diff --git a/CMake/BuildConfigurations/Default.cmake b/CMake/BuildConfigurations/Default.cmake index 4faffa7f12..700e7efd48 100644 --- a/CMake/BuildConfigurations/Default.cmake +++ b/CMake/BuildConfigurations/Default.cmake @@ -1,23 +1,24 @@ set(MITK_CONFIG_PACKAGES ACVD Qt5 BLUEBERRY ) set(MITK_CONFIG_PLUGINS org.mitk.gui.qt.mitkworkbench.intro org.mitk.gui.qt.datamanager org.mitk.gui.qt.stdmultiwidgeteditor org.mitk.gui.qt.dicombrowser org.mitk.gui.qt.imagenavigator org.mitk.gui.qt.measurementtoolbox org.mitk.gui.qt.properties org.mitk.gui.qt.segmentation org.mitk.gui.qt.volumevisualization org.mitk.planarfigure org.mitk.gui.qt.moviemaker org.mitk.gui.qt.pointsetinteraction org.mitk.gui.qt.remeshing org.mitk.gui.qt.viewnavigator org.mitk.gui.qt.imagecropper + org.mitk.gui.qt.pixelvalue ) diff --git a/CMake/BuildConfigurations/FlowBenchSegmentation.cmake b/CMake/BuildConfigurations/FlowBenchSegmentation.cmake index 1bfc32cafe..9731309ef7 100644 --- a/CMake/BuildConfigurations/FlowBenchSegmentation.cmake +++ b/CMake/BuildConfigurations/FlowBenchSegmentation.cmake @@ -1,14 +1,13 @@ set(MITK_CONFIG_PACKAGES Qt5 BLUEBERRY ) set(MITK_BUILD_APP_FlowBench ON CACHE BOOL "Build MITK FlowBench" FORCE) set(MITK_CONFIG_PLUGINS org.mitk.gui.qt.stdmultiwidgeteditor org.mitk.gui.qt.imagenavigator org.mitk.gui.qt.properties - org.mitk.gui.qt.multilabelsegmentation org.mitk.gui.qt.flow.segmentation ) diff --git a/CMake/BuildConfigurations/WorkbenchRelease.cmake b/CMake/BuildConfigurations/WorkbenchRelease.cmake index a0742477e2..db7bf09cd6 100644 --- a/CMake/BuildConfigurations/WorkbenchRelease.cmake +++ b/CMake/BuildConfigurations/WorkbenchRelease.cmake @@ -1,29 +1,28 @@ include(${CMAKE_CURRENT_LIST_DIR}/Default.cmake) set(MITK_CONFIG_PACKAGES ${MITK_CONFIG_PACKAGES} MatchPoint ) set(MITK_CONFIG_PLUGINS ${MITK_CONFIG_PLUGINS} - org.mitk.gui.qt.multilabelsegmentation org.mitk.matchpoint.core.helper org.mitk.gui.qt.matchpoint.algorithm.browser org.mitk.gui.qt.matchpoint.algorithm.control org.mitk.gui.qt.matchpoint.mapper org.mitk.gui.qt.matchpoint.framereg org.mitk.gui.qt.matchpoint.visualizer org.mitk.gui.qt.matchpoint.evaluator org.mitk.gui.qt.matchpoint.manipulator ) if(NOT MITK_USE_SUPERBUILD) set(BUILD_CoreCmdApps ON CACHE BOOL "" FORCE) set(BUILD_MatchPointCmdApps ON CACHE BOOL "" FORCE) endif() set(MITK_VTK_DEBUG_LEAKS OFF CACHE BOOL "Enable VTK Debug Leaks" FORCE) find_package(Doxygen REQUIRED) # Ensure that the in-application help can be build set(BLUEBERRY_QT_HELP_REQUIRED ON CACHE BOOL "Required Qt help documentation in plug-ins" FORCE) diff --git a/CMake/Whitelists/FlowBenchSegmentation.cmake b/CMake/Whitelists/FlowBenchSegmentation.cmake index 36bf724a76..60c1587601 100644 --- a/CMake/Whitelists/FlowBenchSegmentation.cmake +++ b/CMake/Whitelists/FlowBenchSegmentation.cmake @@ -1,56 +1,55 @@ set(enabled_modules Core CppMicroServices DICOM DICOMPM DataTypesExt AlgorithmsExt DICOMQI Multilabel SceneSerializationBase DICOMPMIO DICOMImageIO ContourModel DICOMSegIO LegacyGL MapperExt SceneSerialization LegacyIO IOExt MultilabelIO AppUtil QtWidgets QtWidgetsExt Segmentation SegmentationUI PlanarFigure Annotation SurfaceInterpolation GraphAlgorithms ImageExtraction ImageStatistics ) set(enabled_plugins org.blueberry.core.commands org.blueberry.core.expressions org.blueberry.core.runtime org.blueberry.ui.qt org.blueberry.ui.qt.help org.blueberry.ui.qt.log org.mitk.core.ext org.mitk.core.services org.mitk.gui.common org.mitk.gui.qt.application org.mitk.gui.qt.common org.mitk.gui.qt.datamanager org.mitk.gui.qt.ext org.mitk.gui.qt.flow.segmentation org.mitk.gui.qt.flowapplication org.mitk.gui.qt.imagenavigator -org.mitk.gui.qt.multilabelsegmentation org.mitk.gui.qt.properties org.mitk.gui.qt.segmentation org.mitk.gui.qt.stdmultiwidgeteditor org.mitk.planarfigure ) diff --git a/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox b/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox index e86649fb1c..018001bdbb 100644 --- a/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox +++ b/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox @@ -1,64 +1,63 @@ /** \page PluginListPage MITK Plugin Manuals The plugins and bundles provide much of the extended functionality of MITK. Each encapsulates a solution to a problem and associated features. This way one can easily assemble the necessary capabilites for a workflow without adding a lot of bloat, by combining plugins as needed. */ diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp index d503701503..e14078520e 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp @@ -1,202 +1,212 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "SimpleRenderWindowView.h" #include #include "org_mitk_example_gui_customviewer_views_Activator.h" #include #include #include #include #include #include #include /** * \brief Helper class adapted from QmitkAbstractRenderEditor by defining the correct plugin context. * * This helper class adapted from QmitkAbstractRenderEditor provides the rendering manager interface. */ // //! [SimpleRenderWindowViewHelper] class AbstractRenderWindowViewPrivate { public: AbstractRenderWindowViewPrivate() : m_RenderingManagerInterface(mitk::MakeRenderingManagerInterface(mitk::RenderingManager::GetInstance())), m_PrefServiceTracker(org_mitk_example_gui_customviewer_views_Activator::GetPluginContext()) // //! [SimpleRenderWindowViewHelper] { m_PrefServiceTracker.open(); } ~AbstractRenderWindowViewPrivate() { delete m_RenderingManagerInterface; } mitk::IRenderingManager *m_RenderingManagerInterface; ctkServiceTracker m_PrefServiceTracker; berry::IBerryPreferences::Pointer m_Prefs; }; const std::string SimpleRenderWindowView::VIEW_ID = "org.mitk.customviewer.views.simplerenderwindowview"; SimpleRenderWindowView::SimpleRenderWindowView() : m_RenderWindow(nullptr), d(new AbstractRenderWindowViewPrivate) { } SimpleRenderWindowView::~SimpleRenderWindowView() { } QmitkRenderWindow *SimpleRenderWindowView::GetActiveQmitkRenderWindow() const { return m_RenderWindow; } QHash SimpleRenderWindowView::GetRenderWindows() const { QHash wnds; wnds.insert("axial", m_RenderWindow); return wnds; } QHash SimpleRenderWindowView::GetQmitkRenderWindows() const { QHash wnds; wnds.insert("axial", m_RenderWindow); return wnds; } QmitkRenderWindow *SimpleRenderWindowView::GetRenderWindow(const QString &id) const { if (id == "axial") { return m_RenderWindow; } return nullptr; } QmitkRenderWindow *SimpleRenderWindowView::GetQmitkRenderWindow(const QString &id) const { if (id == "axial") { return m_RenderWindow; } return nullptr; } QmitkRenderWindow *SimpleRenderWindowView::GetQmitkRenderWindow(const mitk::BaseRenderer::ViewDirection &viewDirection) const { if (viewDirection == mitk::BaseRenderer::ViewDirection::AXIAL) { return m_RenderWindow; } return 0; } void SimpleRenderWindowView::SetFocus() { m_RenderWindow->setFocus(); } // //! [SimpleRenderWindowViewCreatePartControl] void SimpleRenderWindowView::CreateQtPartControl(QWidget *parent) { QVBoxLayout *layout = new QVBoxLayout(parent); layout->setContentsMargins(0, 0, 0, 0); m_RenderWindow = new QmitkRenderWindow(parent); layout->addWidget(m_RenderWindow); mitk::DataStorage::Pointer ds = this->GetDataStorage(); m_RenderWindow->GetRenderer()->SetDataStorage(ds); this->RequestUpdate(); } // //! [SimpleRenderWindowViewCreatePartControl] mitk::IRenderingManager *SimpleRenderWindowView::GetRenderingManager() const { // we use the global rendering manager here. This should maybe replaced // by a local one, managing only the render windows specific for the view return d->m_RenderingManagerInterface; } void SimpleRenderWindowView::RequestUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->RequestUpdateAll(requestType); } void SimpleRenderWindowView::ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->ForceImmediateUpdateAll(requestType); } +void SimpleRenderWindowView::SetReferenceGeometry(const mitk::TimeGeometry* /*referenceGeometry*/, bool /*resetCamera*/) +{ + // not implemented +} + +bool SimpleRenderWindowView::HasCoupledRenderWindows() const +{ + return false; +} + mitk::SliceNavigationController *SimpleRenderWindowView::GetTimeNavigationController() const { if (GetRenderingManager()) return GetRenderingManager()->GetTimeNavigationController(); return nullptr; } mitk::Point3D SimpleRenderWindowView::GetSelectedPosition(const QString& /*id*/) const { const mitk::PlaneGeometry* pg = m_RenderWindow->GetSliceNavigationController()->GetCurrentPlaneGeometry(); if (pg) { return pg->GetCenter(); } else { return mitk::Point3D(); } } void SimpleRenderWindowView::SetSelectedPosition(const mitk::Point3D&, const QString&) { } mitk::TimePointType SimpleRenderWindowView::GetSelectedTimePoint(const QString& /*id*/) const { auto timeNavigator = this->GetTimeNavigationController(); if (nullptr != timeNavigator) { return timeNavigator->GetSelectedTimePoint(); } return 0; } void SimpleRenderWindowView::EnableDecorations(bool enable, const QStringList& decorations) { if (decorations.isEmpty() || decorations.contains(DECORATION_MENU)) { m_RenderWindow->ActivateMenuWidget(enable); } } bool SimpleRenderWindowView::IsDecorationEnabled(const QString& decoration) const { if (decoration == DECORATION_MENU) { return m_RenderWindow->GetActivateMenuWidgetFlag(); } return false; } QStringList SimpleRenderWindowView::GetDecorations() const { QStringList decorations; decorations << DECORATION_MENU; return decorations; } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.h b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.h index 7ef01d3d9a..ac3b152408 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.h +++ b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.h @@ -1,147 +1,157 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef SimpleRenderWindowView_H_ #define SimpleRenderWindowView_H_ #include #include #include class QmitkRenderWindow; class AbstractRenderWindowViewPrivate; /** * \brief A view class suited for the ViewerPerspective within the custom viewer plug-in. * * This view class contributes data node rendering functionality to the ViewerPerspective. * Being a subclass of QmitkAbstractView, this class yields access to the data storage and * thus is interconnected with the mitk::QmitkDataManagerView present in the same perspective. * As a subclass of mitk::IRenderWindowPart, this class provides an instance of QmitkRenderWindow. * A SimpleRenderWindowView instance is part of the ViewerPerspective for data visualization. */ // //! [SimpleRenderWindowViewDeclaration] class SimpleRenderWindowView : public QmitkAbstractView, public mitk::IRenderWindowPart // //! [SimpleRenderWindowViewDeclaration] { Q_OBJECT public: /** * Standard constructor. */ SimpleRenderWindowView(); ~SimpleRenderWindowView() override; /** * String based view identifier. */ static const std::string VIEW_ID; berryObjectMacro(SimpleRenderWindowView); // ------------------- mitk::IRenderWindowPart ---------------------- /** * \see mitk::IRenderWindowPart::GetActiveQmitkRenderWindow() */ QmitkRenderWindow *GetActiveQmitkRenderWindow() const override; QHash GetRenderWindows() const; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindows() */ QHash GetQmitkRenderWindows() const override; QmitkRenderWindow *GetRenderWindow(const QString &id) const; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindow(QString) */ QmitkRenderWindow *GetQmitkRenderWindow(const QString &id) const override; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindow(mitk::BaseRenderer::ViewDirection) */ QmitkRenderWindow *GetQmitkRenderWindow(const mitk::BaseRenderer::ViewDirection &viewDirection) const override; /** * \see mitk::QmitkAbstractRenderEditor::GetRenderingManager() */ mitk::IRenderingManager *GetRenderingManager() const override; /** * \see mitk::QmitkAbstractRenderEditor::RequestUpdate() */ void RequestUpdate( mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) override; /** * \see mitk::QmitkAbstractRenderEditor::ForceImmediateUpdate() */ void ForceImmediateUpdate(mitk::RenderingManager::RequestType) override; /** - * \see mitk::QmitkAbstractRenderEditor::GetTimeNavigationController() + * \see mitk::IRenderWindowPart::SetReferenceGeometry() + */ + void SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) override; + + /** + * \see mitk::IRenderWindowPart::HasCoupledRenderWindows + */ + bool HasCoupledRenderWindows() const override; + + /** + * \see mitk::IRenderWindowPart::GetTimeNavigationController() */ mitk::SliceNavigationController *GetTimeNavigationController() const override; /** * \see mitk::IRenderWindowPart::GetSelectionPosition() */ mitk::Point3D GetSelectedPosition(const QString& id = QString()) const override; /** * \see mitk::IRenderWindowPart::SetSelectedPosition() */ void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()) override; /** * \see mitk::IRenderWindowPart::GetSelectedTimePoint() */ mitk::TimePointType GetSelectedTimePoint(const QString& id = QString()) const override; /** * \see mitk::IRenderWindowPart::EnableDecorations() */ void EnableDecorations(bool enable, const QStringList& decorations = QStringList()) override; /** * \see mitk::IRenderWindowPart::IsDecorationEnabled() */ bool IsDecorationEnabled(const QString& decoration) const override; /** * \see mitk::IRenderWindowPart::GetDecorations() */ QStringList GetDecorations() const override; protected: void SetFocus() override; /** * Creates the QmitkRenderWindow whose renderer is being connected to the view's data storage. */ void CreateQtPartControl(QWidget *parent) override; private: /** * The view's render window. */ QmitkRenderWindow *m_RenderWindow; QScopedPointer d; }; #endif /*SimpleRenderWindowView_H_*/ diff --git a/Modules/AppUtil/src/mitkBaseApplication.cpp b/Modules/AppUtil/src/mitkBaseApplication.cpp index 0b8cfb0814..6f7254574e 100644 --- a/Modules/AppUtil/src/mitkBaseApplication.cpp +++ b/Modules/AppUtil/src/mitkBaseApplication.cpp @@ -1,885 +1,889 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { void outputQtMessage(QtMsgType type, const QMessageLogContext&, const QString& msg) { auto message = msg.toStdString(); switch (type) { case QtDebugMsg: MITK_DEBUG << message; break; case QtInfoMsg: MITK_INFO << message; break; case QtWarningMsg: MITK_WARN << message; break; case QtCriticalMsg: MITK_ERROR << message; break; case QtFatalMsg: MITK_ERROR << message; abort(); default: MITK_INFO << message; break; } } } namespace mitk { const QString BaseApplication::ARG_APPLICATION = "BlueBerry.application"; const QString BaseApplication::ARG_CLEAN = "BlueBerry.clean"; const QString BaseApplication::ARG_CONSOLELOG = "BlueBerry.consoleLog"; const QString BaseApplication::ARG_DEBUG = "BlueBerry.debug"; const QString BaseApplication::ARG_FORCE_PLUGIN_INSTALL = "BlueBerry.forcePlugins"; const QString BaseApplication::ARG_HOME = "BlueBerry.home"; const QString BaseApplication::ARG_NEWINSTANCE = "BlueBerry.newInstance"; const QString BaseApplication::ARG_NO_LAZY_REGISTRY_CACHE_LOADING = "BlueBerry.noLazyRegistryCacheLoading"; const QString BaseApplication::ARG_NO_REGISTRY_CACHE = "BlueBerry.noRegistryCache"; const QString BaseApplication::ARG_PLUGIN_CACHE = "BlueBerry.plugin_cache_dir"; const QString BaseApplication::ARG_PLUGIN_DIRS = "BlueBerry.plugin_dirs"; const QString BaseApplication::ARG_PRELOAD_LIBRARY = "BlueBerry.preloadLibrary"; const QString BaseApplication::ARG_PRODUCT = "BlueBerry.product"; const QString BaseApplication::ARG_PROVISIONING = "BlueBerry.provisioning"; const QString BaseApplication::ARG_REGISTRY_MULTI_LANGUAGE = "BlueBerry.registryMultiLanguage"; const QString BaseApplication::ARG_SPLASH_IMAGE = "BlueBerry.splashscreen"; const QString BaseApplication::ARG_STORAGE_DIR = "BlueBerry.storageDir"; const QString BaseApplication::ARG_XARGS = "xargs"; const QString BaseApplication::ARG_LOG_QT_MESSAGES = "Qt.logMessages"; const QString BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET = "Segmentation.labelSetPreset"; const QString BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS = "Segmentation.labelSuggestions"; const QString BaseApplication::PROP_APPLICATION = "blueberry.application"; const QString BaseApplication::PROP_FORCE_PLUGIN_INSTALL = BaseApplication::ARG_FORCE_PLUGIN_INSTALL; const QString BaseApplication::PROP_NEWINSTANCE = BaseApplication::ARG_NEWINSTANCE; const QString BaseApplication::PROP_NO_LAZY_REGISTRY_CACHE_LOADING = BaseApplication::ARG_NO_LAZY_REGISTRY_CACHE_LOADING; const QString BaseApplication::PROP_NO_REGISTRY_CACHE = BaseApplication::ARG_NO_REGISTRY_CACHE; const QString BaseApplication::PROP_PRODUCT = "blueberry.product"; const QString BaseApplication::PROP_REGISTRY_MULTI_LANGUAGE = BaseApplication::ARG_REGISTRY_MULTI_LANGUAGE; class SplashCloserCallback : public QRunnable { public: SplashCloserCallback(QSplashScreen* splashscreen) : m_Splashscreen(splashscreen) { } void run() override { this->m_Splashscreen->close(); } private: QSplashScreen *m_Splashscreen; // Owned by BaseApplication::Impl }; struct BaseApplication::Impl { ctkProperties m_FWProps; QCoreApplication *m_QApp; int m_Argc; char **m_Argv; #ifdef Q_OS_MAC std::vector m_Argv_macOS; #endif QString m_AppName; QString m_OrgaName; QString m_OrgaDomain; bool m_SingleMode; bool m_SafeMode; QSplashScreen *m_Splashscreen; SplashCloserCallback *m_SplashscreenClosingCallback; bool m_LogQtMessages; QStringList m_PreloadLibs; QString m_ProvFile; Impl(int argc, char **argv) : m_Argc(argc), m_Argv(argv), #ifdef Q_OS_MAC m_Argv_macOS(), #endif m_SingleMode(false), m_SafeMode(true), m_Splashscreen(nullptr), m_SplashscreenClosingCallback(nullptr), m_LogQtMessages(false) { #ifdef Q_OS_MAC /* On macOS the process serial number is passed as an command line argument (-psn_) in certain circumstances. This option causes a Poco exception. We remove it, if present. */ m_Argv_macOS.reserve(argc + 1); const char psn[] = "-psn"; for (int i = 0; i < argc; ++i) { if (0 == strncmp(argv[i], psn, sizeof(psn) - 1)) continue; m_Argv_macOS.push_back(argv[i]); } m_Argv_macOS.push_back(nullptr); m_Argc = static_cast(m_Argv_macOS.size() - 1); m_Argv = m_Argv_macOS.data(); #endif } ~Impl() { delete m_SplashscreenClosingCallback; delete m_Splashscreen; delete m_QApp; } QVariant getProperty(const QString &property) const { auto iter = m_FWProps.find(property); return m_FWProps.end() != iter ? iter.value() : QVariant(); } void handleBooleanOption(const std::string &name, const std::string &) { if (ARG_LOG_QT_MESSAGES.toStdString() == name) { m_LogQtMessages = true; return; } auto fwKey = QString::fromStdString(name); // Translate some keys to proper framework properties if (ARG_CONSOLELOG == fwKey) fwKey = ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG; // For all other options we use the command line option name as the // framework property key. m_FWProps[fwKey] = true; } void handlePreloadLibraryOption(const std::string &, const std::string &value) { m_PreloadLibs.push_back(QString::fromStdString(value)); } void handleClean(const std::string &, const std::string &) { m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN] = ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT; } void initializeCTKPluginFrameworkProperties(Poco::Util::LayeredConfiguration &configuration) { // Add all configuration key/value pairs as framework properties Poco::Util::LayeredConfiguration::Keys keys; Poco::Util::LayeredConfiguration::Keys keyStack; configuration.keys(keyStack); std::vector keyChain; while (!keyStack.empty()) { const auto currSubKey = keyStack.back(); if (!keyChain.empty() && keyChain.back() == currSubKey) { keyChain.pop_back(); keyStack.pop_back(); continue; } Poco::Util::LayeredConfiguration::Keys subKeys; configuration.keys(currSubKey, subKeys); if (subKeys.empty()) { std::string finalKey; keyStack.pop_back(); for (const auto& key : keyChain) finalKey += key + '.'; finalKey += currSubKey; keys.push_back(finalKey); } else { keyChain.push_back(currSubKey); for (const auto& key : subKeys) keyStack.push_back(key); } } for (const auto& key : keys) { if (configuration.hasProperty(key)) { // .ini and command line options overwrite already inserted keys auto qKey = QString::fromStdString(key); m_FWProps[qKey] = QString::fromStdString(configuration.getString(key)); } } } void parseProvisioningFile(const QString &filePath) { // Skip parsing if the file path is empty if (filePath.isEmpty()) return; auto consoleLog = this->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool(); // Read initial plugins from a provisioning file QFileInfo provFile(filePath); QStringList pluginsToStart; if (provFile.exists()) { MITK_INFO(consoleLog) << "Using provisioning file: " << qPrintable(provFile.absoluteFilePath()); ProvisioningInfo provInfo(provFile.absoluteFilePath()); // It can still happen that the encoding is not compatible with the fromUtf8 function (i.e. when // manipulating the LANG variable). The QStringList in provInfo is empty then. if (provInfo.getPluginDirs().empty()) { MITK_ERROR << "Cannot search for provisioning file, the retrieved directory list is empty.\n" << "This can happen if there are some special non-ASCII characters in the install path."; } else { for(const auto& pluginPath : provInfo.getPluginDirs()) ctkPluginFrameworkLauncher::addSearchPath(pluginPath); auto pluginUrlsToStart = provInfo.getPluginsToStart(); for (const auto& url : qAsConst(pluginUrlsToStart)) pluginsToStart.push_back(url.toString()); } } else { MITK_INFO(consoleLog) << "Provisionig file does not exist."; } if (!pluginsToStart.isEmpty()) { m_FWProps[ctkPluginFrameworkLauncher::PROP_PLUGINS] = pluginsToStart; // Use transient start with declared activation policy (this helps when the provisioning file // changes and some plug-ins should not be installed in the application any more). ctkPlugin::StartOptions startOptions(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); m_FWProps[ctkPluginFrameworkLauncher::PROP_PLUGINS_START_OPTIONS] = static_cast(startOptions); } } }; BaseApplication::BaseApplication(int argc, char **argv) : Application(), d(new Impl(argc, argv)) { } BaseApplication::~BaseApplication() { delete d; } void BaseApplication::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); } void BaseApplication::setApplicationName(const QString &name) { if (nullptr != qApp) qApp->setApplicationName(name); d->m_AppName = name; } QString BaseApplication::getApplicationName() const { return nullptr != qApp ? qApp->applicationName() : d->m_AppName; } void BaseApplication::setOrganizationName(const QString &name) { if (nullptr != qApp) qApp->setOrganizationName(name); d->m_OrgaName = name; } QString BaseApplication::getOrganizationName() const { return nullptr != qApp ? qApp->organizationName() : d->m_OrgaName; } void BaseApplication::setOrganizationDomain(const QString &domain) { if (nullptr != qApp) qApp->setOrganizationDomain(domain); d->m_OrgaDomain = domain; } QString BaseApplication::getOrganizationDomain() const { return nullptr != qApp ? qApp->organizationDomain() : d->m_OrgaDomain; } void BaseApplication::setSingleMode(bool singleMode) { if (nullptr != qApp) return; d->m_SingleMode = singleMode; } bool BaseApplication::getSingleMode() const { return d->m_SingleMode; } void BaseApplication::setSafeMode(bool safeMode) { if (nullptr != qApp && nullptr == d->m_QApp) return; d->m_SafeMode = safeMode; nullptr == d->m_QApp && getSingleMode() ? static_cast(d->m_QApp)->setSafeMode(safeMode) : static_cast(d->m_QApp)->setSafeMode(safeMode); } bool BaseApplication::getSafeMode() const { return d->m_SafeMode; } void BaseApplication::setPreloadLibraries(const QStringList &libraryBaseNames) { d->m_PreloadLibs = libraryBaseNames; } QStringList BaseApplication::getPreloadLibraries() const { return d->m_PreloadLibs; } void BaseApplication::setProvisioningFilePath(const QString &filePath) { d->m_ProvFile = filePath; } QString BaseApplication::getProvisioningFilePath() const { auto provFilePath = d->m_ProvFile; // A null QString means look up a default provisioning file if (provFilePath.isNull() && nullptr != qApp) { QFileInfo appFilePath(QCoreApplication::applicationFilePath()); QDir basePath(QCoreApplication::applicationDirPath()); auto provFileName = appFilePath.baseName() + ".provisioning"; QFileInfo provFile(basePath.absoluteFilePath(provFileName)); #ifdef Q_OS_MAC /* * On macOS, if started from the build directory, the .provisioning file is located at: * * The executable path is: * * In this case we have to cdUp threetimes. * * During packaging the MitkWorkbench.provisioning file is placed at the same * level like the executable. Nothing has to be done. */ if (!provFile.exists()) { basePath.cdUp(); basePath.cdUp(); basePath.cdUp(); provFile = basePath.absoluteFilePath(provFileName); } #endif if (provFile.exists()) { provFilePath = provFile.absoluteFilePath(); } #ifdef CMAKE_INTDIR else { basePath.cdUp(); provFile.setFile(basePath.absoluteFilePath(provFileName)); if (provFile.exists()) provFilePath = provFile.absoluteFilePath(); } #endif } return provFilePath; } void BaseApplication::initializeQt() { if (nullptr != qApp) return; +#ifdef Q_OS_LINUX + qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--single-process"); // See T29332 +#endif + // If parameters have been set before, we have to store them to hand them // through to the application auto appName = this->getApplicationName(); auto orgName = this->getOrganizationName(); auto orgDomain = this->getOrganizationDomain(); // Create a QCoreApplication instance this->getQApplication(); // Provide parameters to QCoreApplication this->setApplicationName(appName); this->setOrganizationName(orgName); this->setOrganizationDomain(orgDomain); if (d->m_LogQtMessages) qInstallMessageHandler(outputQtMessage); QWebEngineUrlScheme qtHelpScheme("qthelp"); qtHelpScheme.setFlags(QWebEngineUrlScheme::LocalScheme | QWebEngineUrlScheme::LocalAccessAllowed); QWebEngineUrlScheme::registerScheme(qtHelpScheme); } void BaseApplication::initialize(Poco::Util::Application &self) { // 1. Call the super-class method Poco::Util::Application::initialize(self); // 2. Initialize the Qt framework (by creating a QCoreApplication) this->initializeQt(); // 3. Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // 4. Load the "default" configuration, which involves parsing // an optional .ini file and parsing any // command line arguments this->loadConfiguration(); // 5. Add configuration data from the command line and the // optional .ini file as CTK plugin // framework properties. d->initializeCTKPluginFrameworkProperties(this->config()); // 6. Initialize splash screen if an image path is provided // in the .ini file this->initializeSplashScreen(qApp); // 7. Set the custom CTK Plugin Framework storage directory QString storageDir = this->getCTKFrameworkStorageDir(); if (!storageDir.isEmpty()) d->m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE] = storageDir; // 8. Set the library search paths and the pre-load library property this->initializeLibraryPaths(); auto preloadLibs = this->getPreloadLibraries(); if (!preloadLibs.isEmpty()) d->m_FWProps[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES] = preloadLibs; // 9. Initialize the CppMicroServices library. // The initializeCppMicroServices() method reuses the // FRAMEWORK_STORAGE property, so we call it after the // getCTKFrameworkStorageDir method. this->initializeCppMicroServices(); // 10. Parse the (optional) provisioning file and set the // correct framework properties. d->parseProvisioningFile(this->getProvisioningFilePath()); // 11. Set the CTK Plugin Framework properties ctkPluginFrameworkLauncher::setFrameworkProperties(d->m_FWProps); } void BaseApplication::uninitialize() { auto pfw = this->getFramework(); if (pfw) { pfw->stop(); // Wait for up to 10 seconds for the CTK plugin framework to stop pfw->waitForStop(10000); } Poco::Util::Application::uninitialize(); } int BaseApplication::getArgc() const { return d->m_Argc; } char **BaseApplication::getArgv() const { return d->m_Argv; } QString BaseApplication::getCTKFrameworkStorageDir() const { QString storageDir; if (this->getSingleMode()) { // 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. storageDir = handleNewAppInstance(static_cast(d->m_QApp), d->m_Argc, d->m_Argv, ARG_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. storageDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/" + this->getOrganizationName() + "/" + this->getApplicationName() + '_'; storageDir += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; } return storageDir; } void BaseApplication::initializeCppMicroServices() { auto storageDir = this->getProperty(ctkPluginConstants::FRAMEWORK_STORAGE).toString(); if (!storageDir.isEmpty()) us::ModuleSettings::SetStoragePath((storageDir + "us" + QDir::separator()).toStdString()); } QCoreApplication *BaseApplication::getQApplication() const { if (nullptr == qApp) { vtkOpenGLRenderWindow::SetGlobalMaximumNumberOfMultiSamples(0); auto defaultFormat = QVTKOpenGLNativeWidget::defaultFormat(); defaultFormat.setSamples(0); QSurfaceFormat::setDefaultFormat(defaultFormat); #ifdef Q_OS_OSX QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); #endif QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); d->m_QApp = this->getSingleMode() ? static_cast(new QmitkSingleApplication(d->m_Argc, d->m_Argv, this->getSafeMode())) : static_cast(new QmitkSafeApplication(d->m_Argc, d->m_Argv, this->getSafeMode())); } return qApp; } void BaseApplication::initializeLibraryPaths() { QStringList suffixes; suffixes << "plugins"; #ifdef Q_OS_WINDOWS suffixes << "bin/plugins"; #ifdef CMAKE_INTDIR suffixes << "bin/" CMAKE_INTDIR "/plugins"; #endif #else suffixes << "lib/plugins"; #ifdef CMAKE_INTDIR suffixes << "lib/" CMAKE_INTDIR "/plugins"; #endif #endif #ifdef Q_OS_MAC suffixes << "../../plugins"; #endif // We add a couple of standard library search paths for plug-ins QDir appDir(QCoreApplication::applicationDirPath()); // Walk one directory up and add bin and lib sub-dirs; this might be redundant appDir.cdUp(); for (const auto& suffix : qAsConst(suffixes)) ctkPluginFrameworkLauncher::addSearchPath(appDir.absoluteFilePath(suffix)); } int BaseApplication::main(const std::vector &args) { // Start the plugin framework and all installed plug-ins according to their auto-start setting QStringList arguments; for (auto const &arg : args) arguments.push_back(QString::fromStdString(arg)); if (nullptr != d->m_Splashscreen) { // A splash screen is displayed. Create the closing callback. d->m_SplashscreenClosingCallback = new SplashCloserCallback(d->m_Splashscreen); } return ctkPluginFrameworkLauncher::run(d->m_SplashscreenClosingCallback, QVariant::fromValue(arguments)).toInt(); } void BaseApplication::defineOptions(Poco::Util::OptionSet &options) { Poco::Util::Option helpOption("help", "h", "print this help text"); helpOption.callback(Poco::Util::OptionCallback(this, &BaseApplication::printHelp)); options.addOption(helpOption); Poco::Util::Option newInstanceOption(ARG_NEWINSTANCE.toStdString(), "", "forces a new instance of this application"); newInstanceOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(newInstanceOption); Poco::Util::Option cleanOption(ARG_CLEAN.toStdString(), "", "cleans the plugin cache"); cleanOption.callback(Poco::Util::OptionCallback(d, &Impl::handleClean)); options.addOption(cleanOption); Poco::Util::Option productOption(ARG_PRODUCT.toStdString(), "", "the id of the product to be launched"); productOption.argument("").binding(PROP_PRODUCT.toStdString()); options.addOption(productOption); Poco::Util::Option appOption(ARG_APPLICATION.toStdString(), "", "the id of the application extension to be executed"); appOption.argument("").binding(PROP_APPLICATION.toStdString()); options.addOption(appOption); Poco::Util::Option provOption(ARG_PROVISIONING.toStdString(), "", "the location of a provisioning file"); provOption.argument("").binding(ARG_PROVISIONING.toStdString()); options.addOption(provOption); Poco::Util::Option storageDirOption(ARG_STORAGE_DIR.toStdString(), "", "the location for storing persistent application data"); storageDirOption.argument("").binding(ctkPluginConstants::FRAMEWORK_STORAGE.toStdString()); options.addOption(storageDirOption); Poco::Util::Option consoleLogOption(ARG_CONSOLELOG.toStdString(), "", "log messages to the console"); consoleLogOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(consoleLogOption); Poco::Util::Option debugOption(ARG_DEBUG.toStdString(), "", "enable debug mode"); debugOption.argument("", false).binding(ctkPluginFrameworkLauncher::PROP_DEBUG.toStdString()); options.addOption(debugOption); Poco::Util::Option forcePluginOption(ARG_FORCE_PLUGIN_INSTALL.toStdString(), "", "force installing plug-ins with same symbolic name"); forcePluginOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(forcePluginOption); Poco::Util::Option preloadLibsOption(ARG_PRELOAD_LIBRARY.toStdString(), "", "preload a library"); preloadLibsOption.argument("") .repeatable(true) .callback(Poco::Util::OptionCallback(d, &Impl::handlePreloadLibraryOption)); options.addOption(preloadLibsOption); Poco::Util::Option noRegistryCacheOption(ARG_NO_REGISTRY_CACHE.toStdString(), "", "do not use a cache for the registry"); noRegistryCacheOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(noRegistryCacheOption); Poco::Util::Option noLazyRegistryCacheLoadingOption(ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString(), "", "do not use lazy cache loading for the registry"); noLazyRegistryCacheLoadingOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(noLazyRegistryCacheLoadingOption); Poco::Util::Option registryMultiLanguageOption(ARG_REGISTRY_MULTI_LANGUAGE.toStdString(), "", "enable multi-language support for the registry"); registryMultiLanguageOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(registryMultiLanguageOption); Poco::Util::Option splashScreenOption(ARG_SPLASH_IMAGE.toStdString(), "", "optional picture to use as a splash screen"); splashScreenOption.argument("").binding(ARG_SPLASH_IMAGE.toStdString()); options.addOption(splashScreenOption); Poco::Util::Option xargsOption(ARG_XARGS.toStdString(), "", "Extended argument list"); xargsOption.argument("").binding(ARG_XARGS.toStdString()); options.addOption(xargsOption); Poco::Util::Option logQtMessagesOption(ARG_LOG_QT_MESSAGES.toStdString(), "", "log Qt messages"); logQtMessagesOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(logQtMessagesOption); Poco::Util::Option labelSetPresetOption(ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), "", "use this label set preset for new segmentations"); labelSetPresetOption.argument("").binding(ARG_SEGMENTATION_LABELSET_PRESET.toStdString()); options.addOption(labelSetPresetOption); Poco::Util::Option labelSuggestionsOption(ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), "", "use this list of predefined suggestions for segmentation labels"); labelSuggestionsOption.argument("").binding(ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString()); options.addOption(labelSuggestionsOption); Poco::Util::Application::defineOptions(options); } QSharedPointer BaseApplication::getFramework() const { return ctkPluginFrameworkLauncher::getPluginFramework(); } ctkPluginContext *BaseApplication::getFrameworkContext() const { auto framework = getFramework(); return framework ? framework->getPluginContext() : nullptr; } void BaseApplication::initializeSplashScreen(QCoreApplication * application) const { auto pixmapFileNameProp = d->getProperty(ARG_SPLASH_IMAGE); if (!pixmapFileNameProp.isNull()) { auto pixmapFileName = pixmapFileNameProp.toString(); QFileInfo checkFile(pixmapFileName); if (checkFile.exists() && checkFile.isFile()) { QPixmap pixmap(checkFile.absoluteFilePath()); d->m_Splashscreen = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint); d->m_Splashscreen->show(); application->processEvents(); } } } QHash BaseApplication::getFrameworkProperties() const { return d->m_FWProps; } int BaseApplication::run() { this->init(d->m_Argc, d->m_Argv); return Application::run(); } void BaseApplication::setProperty(const QString &property, const QVariant &value) { d->m_FWProps[property] = value; } QVariant BaseApplication::getProperty(const QString &property) const { return d->getProperty(property); } void BaseApplication::installTranslator(QTranslator* translator) { this->getQApplication()->installTranslator(translator); } bool BaseApplication::isRunning() { auto app = dynamic_cast(this->getQApplication()); if (nullptr != app) app->isRunning(); mitkThrow() << "Method not implemented."; } void BaseApplication::sendMessage(const QByteArray msg) { auto app = dynamic_cast(this->getQApplication()); if (nullptr != app) app->sendMessage(msg); mitkThrow() << "Method not implemented."; } } diff --git a/Modules/ContourModel/Algorithms/mitkContourModelUtils.h b/Modules/ContourModel/Algorithms/mitkContourModelUtils.h index 50272c7dd5..e97d315291 100644 --- a/Modules/ContourModel/Algorithms/mitkContourModelUtils.h +++ b/Modules/ContourModel/Algorithms/mitkContourModelUtils.h @@ -1,152 +1,155 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkContourModelUtils_h #define mitkContourModelUtils_h #include #include #include #include namespace mitk { /** * \brief Helpful methods for working with contours and images * * */ class MITKCONTOURMODEL_EXPORT ContourModelUtils : public itk::Object { public: mitkClassMacroItkParent(ContourModelUtils, itk::Object); /** \brief Projects a contour onto an image point by point. Converts from world to index coordinates. \param slice \param contourIn3D */ static ContourModel::Pointer ProjectContourTo2DSlice(const Image *slice, const ContourModel *contourIn3D); /** \brief Projects a slice index coordinates of a contour back into world coordinates. \param sliceGeometry \param contourIn2D */ static ContourModel::Pointer BackProjectContourFrom2DSlice(const BaseGeometry *sliceGeometry, const ContourModel *contourIn2D); /** \brief Fill a contour in a 2D slice with a specified pixel value. This version always uses the contour of time step 0 and fills the image. \deprecated Ths function is deprecated. Use FillContourInSlice2() (in conjunction e.g. with TransferLabelContent()) instead. \pre sliceImage points to a valid instance \pre projectedContour points to a valid instance */ [[deprecated]] static void FillContourInSlice(const ContourModel *projectedContour, Image *sliceImage, const Image* workingImage, int paintingPixelValue = 1); /** \brief Fill a contour in a 2D slice with a specified pixel value. This overloaded version uses the contour at the passed contourTimeStep to fill the passed image slice. \deprecated Ths function is deprecated. Use FillContourInSlice2() (in conjunction e.g. with TransferLabelContent()) instead. \pre sliceImage points to a valid instance \pre projectedContour points to a valid instance */ [[deprecated]] static void FillContourInSlice(const ContourModel *projectedContour, TimeStepType contourTimeStep, Image *sliceImage, const Image* workingImage, int paintingPixelValue = 1); /** \brief Fill a contour in a 2D slice with a specified pixel value. This version always uses the contour of time step 0 and fills the image. \param projectedContour Pointer to the contour that should be projected. \param sliceImage Pointer to the image which content should be altered by adding the contour with the specified paintingPixelValue. + \param paintingPixelValue \pre sliceImage points to a valid instance \pre projectedContour points to a valid instance */ static void FillContourInSlice2(const ContourModel* projectedContour, Image* sliceImage, int paintingPixelValue = 1); /** \brief Fill a contour in a 2D slice with a specified pixel value. This overloaded version uses the contour at the passed contourTimeStep to fill the passed image slice. \param projectedContour Pointer to the contour that should be projected. + \param contourTimeStep \param sliceImage Pointer to the image which content should be altered by + \param paintingPixelValue adding the contour with the specified paintingPixelValue. \pre sliceImage points to a valid instance \pre projectedContour points to a valid instance */ static void FillContourInSlice2(const ContourModel* projectedContour, TimeStepType contourTimeStep, Image* sliceImage, int paintingPixelValue = 1); /** \brief Fills the paintingPixelValue into every pixel of resultImage as indicated by filledImage. If a LableSet image is specified it also by incorporating the rules of LabelSet images when filling the content. \param filledImage Pointer to the image content that should be checked to decied of a pixel in resultImage should be filled with paintingPixelValue or not. \param resultImage Pointer to the image content that should be overwritten guided by the content of filledImage. \param image Pointer to an mitk image that allows to define the LabelSet image which states steer the filling process. If an LabelSet instance is passed its states (e.g. locked labels etc...) will be used. If nullptr or an normal image is passed, then simply any pixel position indicated by filledImage will be overwritten. \param paintingPixelValue the pixelvalue/label that should be used in the result image when filling. \param fillForegroundThreshold The threshold value that decides if a pixel in the filled image counts as foreground (>=fillForegroundThreshold) or not. \deprecated Ths function is deprecated. Use TransferLabelContent() instead. */ [[deprecated]] static void FillSliceInSlice(vtkSmartPointer filledImage, vtkSmartPointer resultImage, const Image* image, int paintingPixelValue, double fillForegroundThreshold = 1.0); /** \brief Move the contour in time step 0 to to a new contour model at the given time step. */ static ContourModel::Pointer MoveZerothContourTimeStep(const ContourModel *contour, TimeStepType timeStep); /** \brief Retrieves the active pixel value of a (labelset) image. If the image is basic image, the pixel value 1 (one) will be returned. If the image is actually a labelset image, the pixel value of the active label of the active layer will be returned. \param workingImage The (labelset) image to retrieve the active pixel value of. */ static int GetActivePixelValue(const Image* workingImage); protected: ContourModelUtils(); ~ContourModelUtils() override; }; } #endif diff --git a/Modules/Core/include/Colortables/Turbo.h b/Modules/Core/include/Colortables/Turbo.h new file mode 100644 index 0000000000..807f5c8045 --- /dev/null +++ b/Modules/Core/include/Colortables/Turbo.h @@ -0,0 +1,85 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef _lut_Turbo_h_ +#define _lut_Turbo_h_ + +// The Turbo Colormap was developed by Anton Mikhailov at Google in 2019. +// It has been released unter the Apache 2.0 license. + +static const int Turbo[256][3] = { + { 48, 18, 59}, { 50, 21, 67}, { 51, 24, 74}, { 52, 27, 81}, + { 53, 30, 88}, { 54, 33, 95}, { 55, 36, 102}, { 56, 39, 109}, + { 57, 42, 115}, { 58, 45, 121}, { 59, 47, 128}, { 60, 50, 134}, + { 61, 53, 139}, { 62, 56, 145}, { 63, 59, 151}, { 63, 62, 156}, + { 64, 64, 162}, { 65, 67, 167}, { 65, 70, 172}, { 66, 73, 177}, + { 66, 75, 181}, { 67, 78, 186}, { 68, 81, 191}, { 68, 84, 195}, + { 68, 86, 199}, { 69, 89, 203}, { 69, 92, 207}, { 69, 94, 211}, + { 70, 97, 214}, { 70, 100, 218}, { 70, 102, 221}, { 70, 105, 224}, + { 70, 107, 227}, { 71, 110, 230}, { 71, 113, 233}, { 71, 115, 235}, + { 71, 118, 238}, { 71, 120, 240}, { 71, 123, 242}, { 70, 125, 244}, + { 70, 128, 246}, { 70, 130, 248}, { 70, 133, 250}, { 70, 135, 251}, + { 69, 138, 252}, { 69, 140, 253}, { 68, 143, 254}, { 67, 145, 254}, + { 66, 148, 255}, { 65, 150, 255}, { 64, 153, 255}, { 62, 155, 254}, + { 61, 158, 254}, { 59, 160, 253}, { 58, 163, 252}, { 56, 165, 251}, + { 55, 168, 250}, { 53, 171, 248}, { 51, 173, 247}, { 49, 175, 245}, + { 47, 178, 244}, { 46, 180, 242}, { 44, 183, 240}, { 42, 185, 238}, + { 40, 188, 235}, { 39, 190, 233}, { 37, 192, 231}, { 35, 195, 228}, + { 34, 197, 226}, { 32, 199, 223}, { 31, 201, 221}, { 30, 203, 218}, + { 28, 205, 216}, { 27, 208, 213}, { 26, 210, 210}, { 26, 212, 208}, + { 25, 213, 205}, { 24, 215, 202}, { 24, 217, 200}, { 24, 219, 197}, + { 24, 221, 194}, { 24, 222, 192}, { 24, 224, 189}, { 25, 226, 187}, + { 25, 227, 185}, { 26, 228, 182}, { 28, 230, 180}, { 29, 231, 178}, + { 31, 233, 175}, { 32, 234, 172}, { 34, 235, 170}, { 37, 236, 167}, + { 39, 238, 164}, { 42, 239, 161}, { 44, 240, 158}, { 47, 241, 155}, + { 50, 242, 152}, { 53, 243, 148}, { 56, 244, 145}, { 60, 245, 142}, + { 63, 246, 138}, { 67, 247, 135}, { 70, 248, 132}, { 74, 248, 128}, + { 78, 249, 125}, { 82, 250, 122}, { 85, 250, 118}, { 89, 251, 115}, + { 93, 252, 111}, { 97, 252, 108}, {101, 253, 105}, {105, 253, 102}, + {109, 254, 98}, {113, 254, 95}, {117, 254, 92}, {121, 254, 89}, + {125, 255, 86}, {128, 255, 83}, {132, 255, 81}, {136, 255, 78}, + {139, 255, 75}, {143, 255, 73}, {146, 255, 71}, {150, 254, 68}, + {153, 254, 66}, {156, 254, 64}, {159, 253, 63}, {161, 253, 61}, + {164, 252, 60}, {167, 252, 58}, {169, 251, 57}, {172, 251, 56}, + {175, 250, 55}, {177, 249, 54}, {180, 248, 54}, {183, 247, 53}, + {185, 246, 53}, {188, 245, 52}, {190, 244, 52}, {193, 243, 52}, + {195, 241, 52}, {198, 240, 52}, {200, 239, 52}, {203, 237, 52}, + {205, 236, 52}, {208, 234, 52}, {210, 233, 53}, {212, 231, 53}, + {215, 229, 53}, {217, 228, 54}, {219, 226, 54}, {221, 224, 55}, + {223, 223, 55}, {225, 221, 55}, {227, 219, 56}, {229, 217, 56}, + {231, 215, 57}, {233, 213, 57}, {235, 211, 57}, {236, 209, 58}, + {238, 207, 58}, {239, 205, 58}, {241, 203, 58}, {242, 201, 58}, + {244, 199, 58}, {245, 197, 58}, {246, 195, 58}, {247, 193, 58}, + {248, 190, 57}, {249, 188, 57}, {250, 186, 57}, {251, 184, 56}, + {251, 182, 55}, {252, 179, 54}, {252, 177, 54}, {253, 174, 53}, + {253, 172, 52}, {254, 169, 51}, {254, 167, 50}, {254, 164, 49}, + {254, 161, 48}, {254, 158, 47}, {254, 155, 45}, {254, 153, 44}, + {254, 150, 43}, {254, 147, 42}, {254, 144, 41}, {253, 141, 39}, + {253, 138, 38}, {252, 135, 37}, {252, 132, 35}, {251, 129, 34}, + {251, 126, 33}, {250, 123, 31}, {249, 120, 30}, {249, 117, 29}, + {248, 114, 28}, {247, 111, 26}, {246, 108, 25}, {245, 105, 24}, + {244, 102, 23}, {243, 99, 21}, {242, 96, 20}, {241, 93, 19}, + {240, 91, 18}, {239, 88, 17}, {237, 85, 16}, {236, 83, 15}, + {235, 80, 14}, {234, 78, 13}, {232, 75, 12}, {231, 73, 12}, + {229, 71, 11}, {228, 69, 10}, {226, 67, 10}, {225, 65, 9}, + {223, 63, 8}, {221, 61, 8}, {220, 59, 7}, {218, 57, 7}, + {216, 55, 6}, {214, 53, 6}, {212, 51, 5}, {210, 49, 5}, + {208, 47, 5}, {206, 45, 4}, {204, 43, 4}, {202, 42, 4}, + {200, 40, 3}, {197, 38, 3}, {195, 37, 3}, {193, 35, 2}, + {190, 33, 2}, {188, 32, 2}, {185, 30, 2}, {183, 29, 2}, + {180, 27, 1}, {178, 26, 1}, {175, 24, 1}, {172, 23, 1}, + {169, 22, 1}, {167, 20, 1}, {164, 19, 1}, {161, 18, 1}, + {158, 16, 1}, {155, 15, 1}, {152, 14, 1}, {149, 13, 1}, + {146, 11, 1}, {142, 10, 1}, {139, 9, 2}, {136, 8, 2}, + {133, 7, 2}, {129, 6, 2}, {126, 5, 2}, {122, 4, 3}}; + +#endif diff --git a/Modules/Core/include/mitkBaseRenderer.h b/Modules/Core/include/mitkBaseRenderer.h index 7ed6b171f7..150e690082 100644 --- a/Modules/Core/include/mitkBaseRenderer.h +++ b/Modules/Core/include/mitkBaseRenderer.h @@ -1,467 +1,482 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKBASERENDERER_H #define MITKBASERENDERER_H #include #include #include #include #include #include #include #include #include #include #include #include #include namespace mitk { class Mapper; class BaseLocalStorageHandler; #pragma GCC visibility push(default) itkEventMacroDeclaration(RendererResetEvent, itk::AnyEvent); #pragma GCC visibility pop /* * \brief Organizes the rendering process * * A BaseRenderer contains a reference to a given vtkRenderWindow * and a corresponding vtkRenderer. * The BaseRenderer defines which mapper should be used (2D / 3D) * and which view direction should be rendered. * * All existing BaseRenderer are stored in a static variable * that can be accessed / modified via the static functions. * VtkPropRenderer is a concrete implementation of a BaseRenderer. */ class MITKCORE_EXPORT BaseRenderer : public itk::Object { public: typedef std::map BaseRendererMapType; static BaseRendererMapType baseRendererMap; - static BaseRenderer* GetInstance(vtkRenderWindow* renderWindow); - static void AddInstance(vtkRenderWindow* renderWindow, BaseRenderer* baseRenderer); - static void RemoveInstance(vtkRenderWindow* renderWindow); - - static BaseRenderer* GetByName(const std::string& name); - static vtkRenderWindow* GetRenderWindowByName(const std::string& name); - - mitkClassMacroItkParent(BaseRenderer, itk::Object); - - BaseRenderer(const char* name = nullptr, vtkRenderWindow* renderWindow = nullptr); - /** * \brief Defines which kind of mapper (e.g. 2D or 3D) should be used. */ enum StandardMapperSlot { Standard2D = 1, Standard3D = 2 }; /** * \brief Defines which view direction should be rendered. */ enum class ViewDirection { AXIAL = 0, SAGITTAL, CORONAL, THREE_D }; + static BaseRenderer* GetInstance(vtkRenderWindow* renderWindow); + static void AddInstance(vtkRenderWindow* renderWindow, BaseRenderer* baseRenderer); + static void RemoveInstance(vtkRenderWindow* renderWindow); + + static BaseRenderer* GetByName(const std::string& name); + static vtkRenderWindow* GetRenderWindowByName(const std::string& name); + + /** + * \brief Get a map of specific RenderWindows + */ + static BaseRendererMapType GetSpecificRenderWindows(MapperSlotId mapper); + + /** + * \brief Convenience function: Get a map of all 2D RenderWindows + */ + static BaseRendererMapType GetAll2DRenderWindows(); + + /** + * \brief Convenience function: Get a map of all 3D RenderWindows + */ + static BaseRendererMapType GetAll3DRenderWindows(); + + mitkClassMacroItkParent(BaseRenderer, itk::Object); + + BaseRenderer(const char* name = nullptr, vtkRenderWindow* renderWindow = nullptr); + void RemoveAllLocalStorages(); void RegisterLocalStorageHandler(BaseLocalStorageHandler* lsh); void UnregisterLocalStorageHandler(BaseLocalStorageHandler* lsh); virtual void SetDataStorage(DataStorage* storage); virtual DataStorage::Pointer GetDataStorage() const { return m_DataStorage.GetPointer(); } vtkRenderWindow* GetRenderWindow() const { return m_RenderWindow; } vtkRenderer* GetVtkRenderer() const { return m_VtkRenderer; } /** * \brief Get the dispatcher, which handles events for this base renderer. */ Dispatcher::Pointer GetDispatcher() const; /** * \brief Set a new size for the render window. */ virtual void Resize(int w, int h); /** * \brief Initialize the base renderer with a vtk render window. * Set the new renderer for the camera controller. */ virtual void InitRenderer(vtkRenderWindow* renderwindow); /** * \brief Set the initial size for the render window. */ virtual void InitSize(int w, int h); virtual void DrawOverlayMouse(Point2D&) { MITK_INFO << "BaseRenderer::DrawOverlayMouse() should be in concret implementation OpenGLRenderer." << std::endl; } /** * \brief Set the world time geometry using the given TimeGeometry. * * Setting a new world time geometry updates the current world geometry and the * curent world plane geometry, using the currently selected slice and timestep. */ virtual void SetWorldTimeGeometry(const mitk::TimeGeometry* geometry); itkGetConstObjectMacro(WorldTimeGeometry, TimeGeometry); /** * \brief Get the current time-extracted 3D-geometry. */ itkGetConstObjectMacro(CurrentWorldGeometry, BaseGeometry); /** * \brief Get the current slice-extracted 2D-geometry. */ itkGetConstObjectMacro(CurrentWorldPlaneGeometry, PlaneGeometry); virtual bool SetWorldGeometryToDataStorageBounds() { return false; } /** * \brief Set the slice that should be used for geometry extraction. * * The slice defines the current slice-extracted 2D-geometry (CurrentWorldPlaneGeometry). * Setting a new slice will update the current world geometry and the * curent world plane geometry. */ virtual void SetSlice(unsigned int slice); itkGetConstMacro(Slice, unsigned int); /** * \brief Set the timestep that should be used for geometry extraction. * * The timestep defines the current time-extracted 3D-geometry (CurrentWorldGeometry). * Setting a new timestep will update the current world geometry and the * curent world plane geometry. */ virtual void SetTimeStep(unsigned int timeStep); itkGetConstMacro(TimeStep, unsigned int); /** * \brief Get the timestep of a BaseData object which * exists at the time of the currently displayed content. * * Returns -1 if there is no data at the current time. */ TimeStepType GetTimeStep(const BaseData* data) const; /** * \brief Get the time in ms of the currently display content (geometry). */ ScalarType GetTime() const; /** * \brief Set the world time geometry using the geometry of the given event. * * The function is triggered by a SliceNavigationController::GeometrySendEvent. */ virtual void SetGeometry(const itk::EventObject& geometrySliceEvent); /** * \brief Set the current world plane geometry using the existing current world geometry. * * The function is triggered by a SliceNavigationController::GeometryUpdateEvent. */ virtual void UpdateGeometry(const itk::EventObject& geometrySliceEvent); /** * \brief Set the current slice using "SetSlice" and update the current world geometry * and the current world plane geometry. * * The function is triggered by a SliceNavigationController::GeometrySliceEvent. */ virtual void SetGeometrySlice(const itk::EventObject& geometrySliceEvent); /** * \brief Set the current time using "SetTimeStep" and update the current world geometry * and the current world plane geometry. * * The function is triggered by a TimeNavigationController::TimeEvent. */ virtual void SetGeometryTime(const itk::EventObject& geometryTimeEvent); itkGetObjectMacro(CurrentWorldPlaneGeometryNode, DataNode); /** * \brief Modify the update time of the current world plane geometry and force reslicing. */ void SendUpdateSlice(); /** * \brief Get timestamp of the update time of the current world plane geometry. */ itkGetMacro(CurrentWorldPlaneGeometryUpdateTime, unsigned long); /** * \brief Get timestamp of the update time of the current timestep. */ itkGetMacro(TimeStepUpdateTime, unsigned long); /** * \brief Pick a world coordinate (x,y,z) given a display coordinate (x,y). * * \warning Not implemented; has to be overwritten in subclasses. */ virtual void PickWorldPoint(const Point2D& diplayPosition, Point3D& worldPosition) const = 0; /** * \brief Determines the object (mitk::DataNode) closest to the current * position by means of picking. * * \warning Implementation currently empty for 2D rendering; intended to be * implemented for 3D renderers. */ virtual DataNode* PickObject(const Point2D& /*displayPosition*/, Point3D& /*worldPosition*/) const { return nullptr; } /** * \brief Get the currently used mapperID. */ itkGetMacro(MapperID, MapperSlotId); itkGetConstMacro(MapperID, MapperSlotId); /** * \brief Set the used mapperID. */ virtual void SetMapperID(MapperSlotId id); virtual int* GetSize() const; virtual int* GetViewportSize() const; void SetSliceNavigationController(SliceNavigationController* SlicenavigationController); itkGetObjectMacro(CameraController, CameraController); itkGetObjectMacro(SliceNavigationController, SliceNavigationController); itkGetObjectMacro(CameraRotationController, CameraRotationController); itkGetMacro(EmptyWorldGeometry, bool); /** * \brief Getter/Setter for defining if the displayed region should be shifted * or rescaled if the render window is resized. */ itkGetMacro(KeepDisplayedRegion, bool); itkSetMacro(KeepDisplayedRegion, bool); /** * \brief Return the name of the base renderer */ const char* GetName() const { return m_Name.c_str(); } /** * \brief Return the size in x-direction of the base renderer. */ int GetSizeX() const { return this->GetSize()[0]; } /** * \brief Return the size in y-direction of the base renderer. */ int GetSizeY() const { return this->GetSize()[1]; } /** * \brief Return the bounds of the bounding box of the * current world geometry (time-extracted 3D-geometry). * * If the geometry is empty, the bounds are set to zero. */ const double* GetBounds() const; void RequestUpdate(); void ForceImmediateUpdate(); /** * \brief Return the number of mappers which are visible and have * level-of-detail rendering enabled. */ unsigned int GetNumberOfVisibleLODEnabledMappers() const; /** * \brief Convert a display point to the 3D world index * using the geometry of the renderWindow. */ void DisplayToWorld(const Point2D& displayPoint, Point3D& worldIndex) const; /** * \brief Convert a display point to the 2D world index, mapped onto the display plane * using the geometry of the renderWindow. */ void DisplayToPlane(const Point2D& displayPoint, Point2D& planePointInMM) const; /** * \brief Convert a 3D world index to the display point * using the geometry of the renderWindow. */ void WorldToDisplay(const Point3D& worldIndex, Point2D& displayPoint) const; /** * \brief Convert a 3D world index to the point on the viewport * using the geometry of the renderWindow. */ void WorldToView(const Point3D& worldIndex, Point2D& viewPoint) const; /** * \brief Convert a 2D plane coordinate to the display point * using the geometry of the renderWindow. */ void PlaneToDisplay(const Point2D& planePointInMM, Point2D& displayPoint) const; /** * \brief Convert a 2D plane coordinate to the point on the viewport * using the geometry of the renderWindow. */ void PlaneToView(const Point2D& planePointInMM, Point2D& viewPoint) const; double GetScaleFactorMMPerDisplayUnit() const; Point2D GetDisplaySizeInMM() const; Point2D GetViewportSizeInMM() const; Point2D GetOriginInMM() const; itkGetConstMacro(ConstrainZoomingAndPanning, bool) virtual void SetConstrainZoomingAndPanning(bool constrain); protected: ~BaseRenderer() override; virtual void Update() = 0; vtkRenderWindow* m_RenderWindow; vtkRenderer* m_VtkRenderer; MapperSlotId m_MapperID; DataStorage::Pointer m_DataStorage; unsigned long m_LastUpdateTime; CameraController::Pointer m_CameraController; CameraRotationController::Pointer m_CameraRotationController; SliceNavigationController::Pointer m_SliceNavigationController; void UpdateCurrentGeometries(); virtual void SetCurrentWorldPlaneGeometry(const PlaneGeometry* geometry2d); virtual void SetCurrentWorldGeometry(const BaseGeometry *geometry); private: /** * \brief Pointer to the current TimeGeometry. * * This WorldTimeGeometry is used to extract a SlicedGeometry3D, * using the current timestep (set via SetTimeStep). * The time-extracted 3D-geometry is used as the "CurrentWorldgeometry". * It will be set using the "SetCurrentWorldGeometry"-function. * A PlaneGeometry can further be extracted using the current slice (set via SetSlice). * The slice-extracted 2D-geometry is used as the "CurrentWorldPlaneGeometry". * It will be set using the "SetCurrentWorldPlaneGeometry"-function. */ TimeGeometry::ConstPointer m_WorldTimeGeometry; /** * \brief Pointer to the current time-extracted 3D-geometry. * * This CurrentWorldGeometry is used to define the bounds for this * BaseRenderer. * It will be set using the "SetCurrentWorldGeometry"-function. */ BaseGeometry::ConstPointer m_CurrentWorldGeometry; /** * \brief Pointer to the current slice-extracted 2D-geometry. * * This CurrentWorldPlaneGeometry is used to define the maximal * area (2D manifold) to be rendered in case we are doing 2D-rendering. * It will be set using the "SetCurrentWorldPlaneGeometry"-function. */ PlaneGeometry::Pointer m_CurrentWorldPlaneGeometry; unsigned int m_Slice; unsigned int m_TimeStep; itk::TimeStamp m_CurrentWorldPlaneGeometryUpdateTime; itk::TimeStamp m_TimeStepUpdateTime; BindDispatcherInteractor* m_BindDispatcherInteractor; bool m_KeepDisplayedRegion; protected: void PrintSelf(std::ostream& os, itk::Indent indent) const override; PlaneGeometryData::Pointer m_CurrentWorldPlaneGeometryData; DataNode::Pointer m_CurrentWorldPlaneGeometryNode; unsigned long m_CurrentWorldPlaneGeometryTransformTime; std::string m_Name; double m_Bounds[6]; bool m_EmptyWorldGeometry; typedef std::set LODEnabledMappersType; unsigned int m_NumberOfVisibleLODEnabledMappers; std::list m_RegisteredLocalStorageHandlers; bool m_ConstrainZoomingAndPanning; }; } // namespace mitk #endif // MITKBASERENDERER_H diff --git a/Modules/Core/include/mitkChannelDescriptor.h b/Modules/Core/include/mitkChannelDescriptor.h index 0480b64b60..b18ffdf3b3 100644 --- a/Modules/Core/include/mitkChannelDescriptor.h +++ b/Modules/Core/include/mitkChannelDescriptor.h @@ -1,78 +1,76 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKCHANNELDESCRIPTOR_H #define MITKCHANNELDESCRIPTOR_H -#include "mitkPixelType.h" +#include #include namespace mitk { /** \brief An object which holds all essential information about a single channel of an Image. The channel descriptor is designed to be used only as a part of the ImageDescriptor. A consequence to this is that the ChannelDescriptor does not hold the geometry information, only the PixelType. The pixel type is the single information that can differ among an image with multiple channels. */ class MITKCORE_EXPORT ChannelDescriptor { public: ChannelDescriptor(mitk::PixelType type, size_t numOfElements, bool allocate = false); ~ChannelDescriptor(); /** \brief Get the type of channel's elements */ PixelType GetPixelType() const { return m_PixelType; } /** \brief Get the size in bytes of the channel */ size_t GetSize() const { return m_Size; } /** \brief Get the pointer to the actual data of the channel \warning Such access to the image's data is not safe and will be replaced \todo new memory management design */ unsigned char *GetData() const { return m_Data; } protected: friend class Image; friend class ImageAccessorBase; void SetData(void *dataPtr) { if (dataPtr == nullptr) { m_Data = (unsigned char *)dataPtr; } } - void AllocateData(); - /** Name of the channel */ std::string m_Name; /** The type of each element of the channel \sa PixelType */ PixelType m_PixelType; /** Size of the channel in bytes */ size_t m_Size; /** Pointer to the data of the channel \warning Not safe \todo Replace in new memory management design */ unsigned char *m_Data; }; } // end namespace mitk #endif // MITKCHANNELDESCRIPTOR_H diff --git a/Modules/Core/include/mitkLevelWindow.h b/Modules/Core/include/mitkLevelWindow.h index 6855dc4ce4..fa27d9287c 100644 --- a/Modules/Core/include/mitkLevelWindow.h +++ b/Modules/Core/include/mitkLevelWindow.h @@ -1,263 +1,263 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #define LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #include "mitkNumericTypes.h" #include namespace mitk { class Image; /** * @brief The LevelWindow class Class to store level/window values. * * Current min and max value are stored in m_LowerWindowBound and m_UpperWindowBound. * m_DefaultLevel amd m_DefaultWindow store the initial Level/Window values for the image. * m_DefaultRangeMin and m_DefaultRangeMax store the initial minrange and maxrange for the image. * * The finite maximum and minimum of valid value range is stored in m_RangeMin and m_RangeMax. * If deduced from an image by default the minimum or maximum of it statistics is used. If one * of these values are infinite the 2nd extrimum (which is guaranteed to be finite), will be used. * * See documentation of SetAuto for information on how the level window is initialized from an image. * * @ingroup DataManagement * * @note If you want to apply the mitk::LevelWindow to an mitk::Image, make sure * to use the mitk::LevelWindowProperty and set the mitk::RenderingModeProperty * to a mode which supports level window (e.g. LEVELWINDOW_COLOR). * Make sure to check the documentation of the mitk::RenderingModeProperty. For a * code example how to use the mitk::LevelWindowProperty check the * mitkImageVtkMapper2DLevelWindowTest.cpp in Core/Code/Testing. */ class MITKCORE_EXPORT LevelWindow { public: LevelWindow(ScalarType level = 127.5, ScalarType window = 255.0); LevelWindow(const mitk::LevelWindow &levWin); virtual ~LevelWindow(); /*! * \brief method that returns the level value, i.e. the center of * the current grey value interval */ ScalarType GetLevel() const; /*! * \brief returns the current window size, i.e the range size of the current grey value interval */ ScalarType GetWindow() const; /*! * \brief method returns the default level value for the image */ ScalarType GetDefaultLevel() const; /*! * \brief returns the default window size for the image */ ScalarType GetDefaultWindow() const; /*! * \brief Resets the level and the window value to the default values */ void ResetDefaultLevelWindow(); /*! * Returns the minimum Value of the window */ ScalarType GetLowerWindowBound() const; /*! * Returns the upper window bound value of the window */ ScalarType GetUpperWindowBound() const; /*! * To set the level and the window value */ void SetLevelWindow(ScalarType level, ScalarType window, bool expandRangesIfNecessary = true); /*! - * Set the lower and upper bound of the window + * Set the lower and upper bound of the window, restricted to the range from -10^300 to 10^300. Higher/lower values are clamped to these boundaries. */ void SetWindowBounds(ScalarType lowerBound, ScalarType upperBound, bool expandRangesIfNecessary = true); /*! * sets the window to its maximum Size in scaleRange */ void SetToMaxWindowSize(); /*! * Set the range minimum and maximum value */ void SetRangeMinMax(ScalarType min, ScalarType max); /*! * Get the range minimum value */ ScalarType GetRangeMin() const; /*! * Get the range maximum value */ ScalarType GetRangeMax() const; /*! * Get the default range minimum value */ ScalarType GetDefaultLowerBound() const; /*! * Get the default range maximum value */ ScalarType GetDefaultUpperBound() const; /*! * \brief the default min and max range for image will be reset */ void ResetDefaultRangeMinMax(); /**! * \brief returns the size of the grey value range */ ScalarType GetRange() const; /*! * set the default level and window value */ void SetDefaultLevelWindow(ScalarType level, ScalarType window); /*! * set the default Boundaries */ void SetDefaultBoundaries(ScalarType low, ScalarType up); /**! * \brief sets level/window to optimize the contrast of the given Image */ void SetAuto(const Image *image, bool tryPicTags = true, bool guessByCentralSlice = true, unsigned selectedComponent = 0); /**! * \brief sets level/window to the min/max greyvalues of the given Image */ void SetToImageRange(const Image *image); /** * If a level window is set to fixed, the set and get methods won't accept * modifications to the level window settings anymore. This behaviour can * be turned of by setting fixed to false; */ void SetFixed(bool fixed); /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool GetFixed() const; /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool IsFixed() const; /*! * \brief equality operator implementation that allows to compare two level windows */ virtual bool operator==(const LevelWindow &levWin) const; /*! * \brief non equality operator implementation that allows to compare two level windows */ virtual bool operator!=(const LevelWindow &levWin) const; /*! * \brief implementation necessary because operator made * private in itk::Object */ virtual LevelWindow &operator=(const LevelWindow &levWin); /*! * \brief Shows if floating values are accepted */ bool IsFloatingValues() const; /*! * \brief Sets the floating image value */ void SetFloatingValues(bool value); protected: /*! * lower bound of current window */ ScalarType m_LowerWindowBound; /*! * upper bound of current window */ ScalarType m_UpperWindowBound; /*! * minimum gray value of the window */ ScalarType m_RangeMin; /*! * maximum gray value of the window */ ScalarType m_RangeMax; /*! * default minimum gray value of the window */ ScalarType m_DefaultLowerBound; /*! * default maximum gray value of the window */ ScalarType m_DefaultUpperBound; /*! * Image with floating values */ bool m_IsFloatingImage; /*! * Defines whether the level window settings may be changed after * initialization or not. */ bool m_Fixed; /*! * confidence tests * * if m_LowerWindowBound > m_UpperWindowBound, then the values for m_LowerWindowBound and m_UpperWindowBound will be * exchanged * * if m_LowerWindowBound < m_RangeMin, m_LowerWindowBound will be set to m_RangeMin. m_UpperWindowBound will be * decreased the same as m_LowerWindowBound will be increased, but minimum value for m_UpperWindowBound is also * m_RangeMin. * * if m_UpperWindowBound > m_RangeMax, m_UpperWindowBound will be set to m_RangeMax. m_LowerWindowBound will be * increased the same as m_UpperWindowBound will be decreased, but maximum value for m_LowerWindowBound is also * m_RangeMax. * */ inline void EnsureConsistency(); }; } // namespace mitk #endif /* LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C */ diff --git a/Modules/Core/include/mitkLookupTable.h b/Modules/Core/include/mitkLookupTable.h index 5ab7de7dba..8646564eca 100644 --- a/Modules/Core/include/mitkLookupTable.h +++ b/Modules/Core/include/mitkLookupTable.h @@ -1,274 +1,277 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkLookupTable_h #define mitkLookupTable_h #include "mitkCommon.h" #include #include #include #include #include class vtkColorTransferFunction; class vtkPiecewiseFunction; namespace mitk { /** * @brief The LookupTable class mitk wrapper for a vtkLookupTable * @ingroup DataManagement * * This class can be used to color images with a LookupTable, such as the * vtkLookupTable. * @note If you want to use this as a property for an mitk::Image, make sure * to use the mitk::LookupTableProperty and set the mitk::RenderingModeProperty * to a mode which supports lookup tables (e.g. LOOKUPTABLE_COLOR). Make * sure to check the documentation of the mitk::RenderingModeProperty. For a * code example how to use the mitk::LookupTable check the * mitkImageVtkMapper2DLookupTableTest.cpp in Core/Code/Testing. */ class MITKCORE_EXPORT LookupTable : public itk::DataObject { public: /** * @brief RawLookupTableType raw lookuptable typedef for convenience. */ typedef unsigned char RawLookupTableType; mitkClassMacroItkParent(LookupTable, itk::DataObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * @brief GetVtkLookupTable Getter for the internally wrapped vtkLookupTable. */ virtual vtkSmartPointer GetVtkLookupTable() const; /** * @brief GetRawLookupTable Getter for the raw lookuptable array. */ virtual RawLookupTableType *GetRawLookupTable() const; /** * @brief SetVtkLookupTable Setter for the internal lookuptable. * @param lut The lookuptable. */ virtual void SetVtkLookupTable(vtkSmartPointer lut); /** * @brief ChangeOpacityForAll Set the opacity for all table values. * @param opacity Opacity between 0.0 and 1.0. */ virtual void ChangeOpacityForAll(float opacity); /** * @brief ChangeOpacity Set the opacity for a specific table index. * @param index The lookuptable index. * @param opacity Opacity between 0.0 and 1.0. */ virtual void ChangeOpacity(int index, float opacity); /** * @brief GetColor convenience method wrapping the vtkLookupTable::GetColor() method. * * Map one value through the lookup table and return the color as an RGB array of doubles between 0 and 1. * @param value The value you want to map. * @param rgb RGB values between 0 and 1. */ virtual void GetColor(double value, double rgb[3]); /** * @brief GetTableValue convenience method wrapping the vtkLookupTable::GetTableValue() method. * @param index The index you want to get. * @param rgba RGB values between 0 and 1. */ virtual void GetTableValue(int index, double rgba[4]); /** * @brief SetTableValue convenience method wrapping the vtkLookupTable::SetTableValue() method. * @param index The index you want to set. * @param rgba RGB values between 0 and 1. */ virtual void SetTableValue(int index, double rgba[4]); itkSetMacro(Window, float); itkSetMacro(Level, float); itkSetMacro(Opacity, float); /** * @brief equality operator implementation */ virtual bool operator==(const mitk::LookupTable &LookupTable) const; /** * @brief non equality operator implementation */ virtual bool operator!=(const LookupTable &LookupTable) const; /** * @brief implementation necessary because operator made * private in itk::Object */ virtual LookupTable &operator=(const LookupTable &LookupTable); /** * @brief Updates the output information of the current object by calling * updateOutputInformation of the data objects source object. */ void UpdateOutputInformation() override; /** * @brief Sets the requested Region to the largest possible region. * This method is not implemented, since this is the default * behavior of the itk pipeline and we do not support the * requested-region mechanism for lookup-tables */ void SetRequestedRegionToLargestPossibleRegion() override; /** * @brief Checks, if the requested region lies outside of the buffered region by * calling verifyRequestedRegion(). */ bool RequestedRegionIsOutsideOfTheBufferedRegion() override; /** * @brief Checks if the requested region is completely contained in * the buffered region. Since we always want to process the lookup * table as a whole, this method always returns true */ bool VerifyRequestedRegion() override; /** * @brief This method has no effect for lookup tables, since we do * not support the region-mechanism */ void SetRequestedRegion(const itk::DataObject *data) override; LookupTable(); ~LookupTable() override; /** * \deprecatedSince{2014_03} Please use CreateColorTransferFunction() instead */ DEPRECATED(void CreateColorTransferFunction(vtkColorTransferFunction *&colorFunction)); /** * \deprecatedSince{2014_03} Please use CreateOpacityTransferFunction() instead */ DEPRECATED(void CreateOpacityTransferFunction(vtkPiecewiseFunction *&opacityFunction)); /** * \deprecatedSince{2014_03} Please use CreateGradientTransferFunction() instead */ DEPRECATED(void CreateGradientTransferFunction(vtkPiecewiseFunction *&gradientFunction)); vtkSmartPointer CreateColorTransferFunction(); vtkSmartPointer CreateOpacityTransferFunction(); vtkSmartPointer CreateGradientTransferFunction(); /** * @brief The LookupTableType enum for different predefined lookup tables. * * \li GRAYSCALE Our default level-window (sometimes referred to as window-level by other sources) setup for a test * image looks like this: * \image html ExampleLevelWindowColor.png * \li INVERSE_GRAYSCALE Inverse LookupTable of GRAYSCALE. * \li HOT_IRON A LookupTable for red colors. * \li JET A LookupTable for JET color rendering. * \li LEGACY_BINARY A LookupTable for binary images. * \li LEGACY_RAINBOW_COLOR A rainbow-like LookupTable. * \li MULTILABEL A LookupTable for multilabel images. * \li PET_COLOR A LookupTable for PET color rendering. * \li PET_20 A LookupTable for PET_20 color rendering. + * \li TURBO An improved rainbow LookupTable for visualization. * * The different LookupTableTypes can be applied in the MitkWorkbench via right-clicking * on an image and choosing a color map. */ enum LookupTableType { GRAYSCALE, INVERSE_GRAYSCALE, HOT_IRON, JET, JET_TRANSPARENT, PLASMA, INFERNO, VIRIDIS, MAGMA, LEGACY_BINARY, LEGACY_RAINBOW_COLOR, MULTILABEL, PET_COLOR, - PET_20 + PET_20, + TURBO }; static std::vector typenameList; /** * @brief Set the look-up table type by enum (or integer). * @details Returns if the given type doesn't exist. Only changes the type if it is different * from the current one. */ virtual void SetType(const LookupTableType type); /** * @brief Set the look-up table type by string. * @details Returns if the given type doesn't exist. Only changes the type if it is different * from the current one. */ virtual void SetType(const std::string &typeName); /** * @brief Return the current look-up table type. */ virtual LookupTableType GetActiveType() const; /** * @brief Return the current look-up table type as a string. */ virtual std::string GetActiveTypeAsString() const; protected: void PrintSelf(std::ostream &os, itk::Indent indent) const override; LookupTable(const LookupTable &other); virtual void BuildGrayScaleLookupTable(); virtual void BuildLegacyBinaryLookupTable(); virtual void BuildLegacyRainbowColorLookupTable(); virtual void BuildInverseGrayScaleLookupTable(); virtual void BuildHotIronLookupTable(); virtual void BuildPlasmaLookupTable(); virtual void BuildInfernoLookupTable(); virtual void BuildViridisLookupTable(); virtual void BuildMagmaLookupTable(); virtual void BuildJetLookupTable(bool transparent = false); virtual void BuildPETColorLookupTable(); virtual void BuildPET20LookupTable(); virtual void BuildMultiLabelLookupTable(); + virtual void BuildTurboLookupTable(); vtkSmartPointer m_LookupTable; float m_Window; float m_Level; float m_Opacity; LookupTableType m_Type; private: itk::LightObject::Pointer InternalClone() const override; }; } // namespace mitk #endif /* mitkLookupTable_h */ diff --git a/Modules/Core/include/mitkMemoryUtilities.h b/Modules/Core/include/mitkMemoryUtilities.h index 33e94a49bc..84fdc6c66f 100644 --- a/Modules/Core/include/mitkMemoryUtilities.h +++ b/Modules/Core/include/mitkMemoryUtilities.h @@ -1,91 +1,39 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MEMORY_UTILITIES_H_ #define _MITK_MEMORY_UTILITIES_H_ #include #include namespace mitk { - class MITKCORE_EXPORT MemoryUtilities + namespace MemoryUtilities { - public: /** * Returns the memory usage of the current process in bytes. - * On linux, this refers to the virtual memory allocated by + * On Linux, this refers to the virtual memory allocated by * the process (the VIRT column in top). - * On windows, this refery to the size in bytes of the working + * On Windows, this refers to the size in bytes of the working * set pages (the "Speicherauslastung" column in the task manager). */ - static size_t GetProcessMemoryUsage(); + MITKCORE_EXPORT size_t GetProcessMemoryUsage(); /** * Returns the total size of physical memory in bytes */ - static size_t GetTotalSizeOfPhysicalRam(); - - /** - * Allocates an array of a given number of elements. Each element - * has a size of sizeof(ElementType). The function returns nullptr, if the array - * could not be allocated. - * @param numberOfElements the number of elements of the array - * @param noThrow if set to false, an exception is thrown if memory allocation - * fails. If set to true, a itk::MemoryAllocationError is thrown - * @returns a pointer to the allocated array. If noThrow == true, nullptr is returned - * if memory allocation failed. - */ - template - static ElementType *AllocateElements(size_t numberOfElements, bool noThrow = false) - { - // Encapsulate all image memory allocation here to throw an - // exception when memory allocation fails even when the compiler - // does not do this by default. - ElementType *data = nullptr; - try - { - data = new ElementType[numberOfElements]; - } - catch (...) - { - data = nullptr; - } - if ((data == nullptr) && (noThrow == false)) - { - throw itk::MemoryAllocationError(__FILE__, __LINE__, "Failed to allocate memory.", ITK_LOCATION); - } - return data; - } - - /** - * Deletes an array of elements previously allocated by AllocateElements. - * @param elements the array to delete. Not that nullptr is an accepted value. - */ - template - static void DeleteElements(ElementType *elements) - { - if (elements != nullptr) - { - delete[] elements; - } - } - - protected: -#ifndef _MSC_VER - static int ReadStatmFromProcFS( - int *size, int *res, int *shared, int *text, int *sharedLibs, int *stack, int *dirtyPages); -#endif - }; -} // end of namespace mitk + MITKCORE_EXPORT size_t GetTotalSizeOfPhysicalRam(); + } +} #endif diff --git a/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp b/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp index 49ec3e82ff..9b7199b15b 100644 --- a/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp +++ b/Modules/Core/src/DataManagement/mitkChannelDescriptor.cpp @@ -1,56 +1,22 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkChannelDescriptor.h" -#include "mitkMemoryUtilities.h" + +#include mitk::ChannelDescriptor::ChannelDescriptor(mitk::PixelType type, size_t numOfElements, bool /*allocate*/) : m_PixelType(type), m_Size(numOfElements), m_Data(nullptr) { - // MITK_INFO << "Entering ChannelDescriptor constructor."; } mitk::ChannelDescriptor::~ChannelDescriptor() { - // TODO: The following line should be correct but leads to an error. - // Solution might be: Hold PixelType on stack, return copy and implement - // copy constructor as well as assignment operator. - // delete m_PixelType; -} - -/* -void mitk::ChannelDescriptor::Initialize(mitk::PixelType &type, size_t numOfElements, bool allocate) -{ - if( m_PixelType.GetPixelTypeId() != type.GetPixelTypeId() ) - { - MITK_WARN << "Changing pixel type for channel: " << - m_PixelType.GetItkTypeAsString() << " -> " << - type.GetItkTypeAsString(); - } - - m_PixelType = type; - - m_Size = numOfElements * m_PixelType.GetSize(); - - if( allocate ) - { - this->AllocateData(); - } -} -*/ - -void mitk::ChannelDescriptor::AllocateData() -{ - if (m_Data == nullptr) - { - m_Data = mitk::MemoryUtilities::AllocateElements(m_Size); - } } diff --git a/Modules/Core/src/DataManagement/mitkImageDataItem.cpp b/Modules/Core/src/DataManagement/mitkImageDataItem.cpp index 407ea0a0ee..f52c165603 100644 --- a/Modules/Core/src/DataManagement/mitkImageDataItem.cpp +++ b/Modules/Core/src/DataManagement/mitkImageDataItem.cpp @@ -1,334 +1,333 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkImageDataItem.h" -#include "mitkMemoryUtilities.h" +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include mitk::ImageDataItem::ImageDataItem(const ImageDataItem &aParent, const mitk::ImageDescriptor::Pointer desc, int timestep, unsigned int dimension, void *data, bool manageMemory, size_t offset) : m_Data(static_cast(aParent.m_Data) + offset), m_PixelType(new mitk::PixelType(aParent.GetPixelType())), m_ManageMemory(false), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(offset), m_IsComplete(false), m_Size(0), m_Parent(&aParent), m_Dimension(dimension), m_Timestep(timestep) { // compute size // const unsigned int *dims = desc->GetDimensions(); for (unsigned int i = 0; i < dimension; i++) { m_Dimensions[i] = desc->GetDimensions()[i]; } this->ComputeItemSize(m_Dimensions, dimension); if (data != nullptr && data != m_Data) { memcpy(m_Data, data, m_Size); if (manageMemory) { delete[](unsigned char *) data; } } m_ReferenceCount = 0; } mitk::ImageDataItem::~ImageDataItem() { if (m_VtkImageData != nullptr) { m_VtkImageData->Delete(); } if (m_VtkImageReadAccessor != nullptr) { delete m_VtkImageReadAccessor; } if (m_VtkImageWriteAccessor != nullptr) { delete m_VtkImageWriteAccessor; } if (m_Parent.IsNull()) { if (m_ManageMemory) delete[] m_Data; } delete m_PixelType; } mitk::ImageDataItem::ImageDataItem(const mitk::ImageDescriptor::Pointer desc, int timestep, void *data, bool manageMemory) : m_Data(static_cast(data)), m_PixelType(new mitk::PixelType(desc->GetChannelDescriptor(0).GetPixelType())), m_ManageMemory(manageMemory), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(0), m_IsComplete(false), m_Size(0), m_Dimension(desc->GetNumberOfDimensions()), m_Timestep(timestep) { // compute size const unsigned int *dimensions = desc->GetDimensions(); for (unsigned int i = 0; i < m_Dimension; i++) { m_Dimensions[i] = dimensions[i]; } this->ComputeItemSize(m_Dimensions, m_Dimension); if (m_Data == nullptr) { - m_Data = mitk::MemoryUtilities::AllocateElements(m_Size); + m_Data = new unsigned char[m_Size]; m_ManageMemory = true; } m_ReferenceCount = 0; } mitk::ImageDataItem::ImageDataItem(const mitk::PixelType &type, int timestep, unsigned int dimension, unsigned int *dimensions, void *data, bool manageMemory) : m_Data(static_cast(data)), m_PixelType(new mitk::PixelType(type)), m_ManageMemory(manageMemory), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(0), m_IsComplete(false), m_Size(0), m_Parent(nullptr), m_Dimension(dimension), m_Timestep(timestep) { for (unsigned int i = 0; i < m_Dimension; i++) { m_Dimensions[i] = dimensions[i]; } this->ComputeItemSize(dimensions, dimension); if (m_Data == nullptr) { - m_Data = mitk::MemoryUtilities::AllocateElements(m_Size); + m_Data = new unsigned char[m_Size]; m_ManageMemory = true; } m_ReferenceCount = 0; } mitk::ImageDataItem::ImageDataItem(const ImageDataItem &other) : itk::LightObject(), m_Data(other.m_Data), m_PixelType(new mitk::PixelType(*other.m_PixelType)), m_ManageMemory(other.m_ManageMemory), m_VtkImageData(nullptr), m_VtkImageReadAccessor(nullptr), m_VtkImageWriteAccessor(nullptr), m_Offset(other.m_Offset), m_IsComplete(other.m_IsComplete), m_Size(other.m_Size), m_Parent(other.m_Parent), m_Dimension(other.m_Dimension), m_Timestep(other.m_Timestep) { // copy m_Data ?? for (int i = 0; i < MAX_IMAGE_DIMENSIONS; ++i) m_Dimensions[i] = other.m_Dimensions[i]; } itk::LightObject::Pointer mitk::ImageDataItem::InternalClone() const { Self::Pointer newGeometry = new Self(*this); newGeometry->UnRegister(); return newGeometry.GetPointer(); } void mitk::ImageDataItem::ComputeItemSize(const unsigned int *dimensions, unsigned int dimension) { m_Size = m_PixelType->GetSize(); for (unsigned int i = 0; i < dimension; i++) { m_Size *= *(dimensions + i); } } void mitk::ImageDataItem::ConstructVtkImageData(ImageConstPointer iP) const { vtkImageData *inData = vtkImageData::New(); vtkDataArray *scalars = nullptr; const unsigned int *dims = m_Dimensions; const unsigned int dim = m_Dimension; unsigned long size = 0; if (dim == 1) { inData->SetDimensions(dims[0] - 1, 1, 1); size = dims[0]; inData->SetOrigin(((mitk::ScalarType)dims[0]) / 2.0, 0, 0); } else if (dim == 2) { inData->SetDimensions(dims[0], dims[1], 1); size = dims[0] * dims[1]; inData->SetOrigin(((mitk::ScalarType)dims[0]) / 2.0f, ((mitk::ScalarType)dims[1]) / 2.0f, 0); } else if (dim >= 3) { inData->SetDimensions(dims[0], dims[1], dims[2]); size = dims[0] * dims[1] * dims[2]; // Test // inData->SetOrigin( (float) dims[0] / 2.0f, (float) dims[1] / 2.0f, (float) dims[2] / 2.0f ); inData->SetOrigin(0, 0, 0); } else { inData->Delete(); return; } if (m_Timestep >= 0) { SlicedGeometry3D *geom3d; geom3d = iP->GetSlicedGeometry(m_Timestep); const mitk::Vector3D vspacing = geom3d->GetSpacing(); double dspacing[3] = {vspacing[0], vspacing[1], vspacing[2]}; inData->SetSpacing(dspacing); } if (m_PixelType->GetComponentType() == itk::IOComponentEnum::CHAR) { scalars = vtkCharArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::UCHAR) { scalars = vtkUnsignedCharArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::SHORT) { scalars = vtkShortArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::USHORT) { scalars = vtkUnsignedShortArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::INT) { scalars = vtkIntArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::UINT) { scalars = vtkUnsignedIntArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::LONG) { scalars = vtkLongArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::ULONG) { scalars = vtkUnsignedLongArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::FLOAT) { scalars = vtkFloatArray::New(); } else if (m_PixelType->GetComponentType() == itk::IOComponentEnum::DOUBLE) { scalars = vtkDoubleArray::New(); } else { inData->Delete(); return; } m_VtkImageData = inData; // set mitk imageDataItem void array to vtk scalar values scalars->SetNumberOfComponents(m_PixelType->GetNumberOfComponents()); scalars->SetVoidArray(m_Data, size * m_PixelType->GetNumberOfComponents(), 1); m_VtkImageData->GetPointData()->SetScalars(scalars); scalars->Delete(); } void mitk::ImageDataItem::Modified() const { if (m_VtkImageData) m_VtkImageData->Modified(); } mitk::ImageVtkReadAccessor *mitk::ImageDataItem::GetVtkImageAccessor(mitk::ImageDataItem::ImageConstPointer iP) const { if (m_VtkImageData == nullptr) { ConstructVtkImageData(iP); } if (m_VtkImageReadAccessor == nullptr) { m_VtkImageReadAccessor = new ImageVtkReadAccessor(iP, this, m_VtkImageData); } return m_VtkImageReadAccessor; } mitk::ImageVtkWriteAccessor *mitk::ImageDataItem::GetVtkImageAccessor(ImagePointer iP) { if (m_VtkImageData == nullptr) { ConstructVtkImageData(iP.GetPointer()); } if (m_VtkImageWriteAccessor == nullptr) { m_VtkImageWriteAccessor = new ImageVtkWriteAccessor(iP, this, m_VtkImageData); } return m_VtkImageWriteAccessor; } diff --git a/Modules/Core/src/DataManagement/mitkLevelWindow.cpp b/Modules/Core/src/DataManagement/mitkLevelWindow.cpp index 131eec028f..c3d8841919 100644 --- a/Modules/Core/src/DataManagement/mitkLevelWindow.cpp +++ b/Modules/Core/src/DataManagement/mitkLevelWindow.cpp @@ -1,507 +1,510 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkLevelWindow.h" #include "mitkImage.h" #include "mitkImageSliceSelector.h" #include "mitkImageStatisticsHolder.h" #include void mitk::LevelWindow::EnsureConsistency() { // Check if total range is ok { if (m_RangeMin > m_RangeMax) std::swap(m_RangeMin, m_RangeMax); if (m_RangeMin == m_RangeMax) m_RangeMin = m_RangeMax - 1; } // Check if current window is ok { if (m_LowerWindowBound > m_UpperWindowBound) std::swap(m_LowerWindowBound, m_UpperWindowBound); if (m_LowerWindowBound <= m_RangeMin) m_LowerWindowBound = m_RangeMin; if (m_UpperWindowBound <= m_RangeMin) m_UpperWindowBound = m_RangeMin + 1; if (m_LowerWindowBound >= m_RangeMax) m_LowerWindowBound = m_RangeMax - 1; if (m_UpperWindowBound >= m_RangeMax) m_UpperWindowBound = m_RangeMax; if (m_LowerWindowBound == m_UpperWindowBound) { m_UpperWindowBound += 0.5; m_LowerWindowBound -= 0.5; m_UpperWindowBound = std::min(m_UpperWindowBound, m_RangeMax); m_LowerWindowBound = std::max(m_LowerWindowBound, m_RangeMin); } } } mitk::LevelWindow::LevelWindow(mitk::ScalarType level, mitk::ScalarType window) : m_LowerWindowBound(level - window / 2.0), m_UpperWindowBound(level + window / 2.0), m_RangeMin(-2048.0), m_RangeMax(4096.0), m_DefaultLowerBound(-2048.0), m_DefaultUpperBound(4096.0), m_IsFloatingImage(false), m_Fixed(false) { SetDefaultLevelWindow(level, window); SetLevelWindow(level, window, true); } mitk::LevelWindow::LevelWindow(const mitk::LevelWindow &levWin) : m_LowerWindowBound(levWin.GetLowerWindowBound()), m_UpperWindowBound(levWin.GetUpperWindowBound()), m_RangeMin(levWin.GetRangeMin()), m_RangeMax(levWin.GetRangeMax()), m_DefaultLowerBound(levWin.GetDefaultLowerBound()), m_DefaultUpperBound(levWin.GetDefaultUpperBound()), m_IsFloatingImage(levWin.IsFloatingValues()), m_Fixed(levWin.GetFixed()) { } mitk::LevelWindow::~LevelWindow() { } mitk::ScalarType mitk::LevelWindow::GetLevel() const { return (m_UpperWindowBound - m_LowerWindowBound) / 2.0 + m_LowerWindowBound; } mitk::ScalarType mitk::LevelWindow::GetWindow() const { return (m_UpperWindowBound - m_LowerWindowBound); } mitk::ScalarType mitk::LevelWindow::GetDefaultLevel() const { return ((m_DefaultUpperBound + m_DefaultLowerBound) / 2.0); } mitk::ScalarType mitk::LevelWindow::GetDefaultWindow() const { return ((m_DefaultUpperBound - m_DefaultLowerBound)); } void mitk::LevelWindow::ResetDefaultLevelWindow() { SetLevelWindow(GetDefaultLevel(), GetDefaultWindow()); } mitk::ScalarType mitk::LevelWindow::GetLowerWindowBound() const { return m_LowerWindowBound; } mitk::ScalarType mitk::LevelWindow::GetUpperWindowBound() const { return m_UpperWindowBound; } void mitk::LevelWindow::SetDefaultLevelWindow(mitk::ScalarType level, mitk::ScalarType window) { SetDefaultBoundaries((level - (window / 2.0)), (level + (window / 2.0))); } void mitk::LevelWindow::SetLevelWindow(mitk::ScalarType level, mitk::ScalarType window, bool expandRangesIfNecessary) { SetWindowBounds((level - (window / 2.0)), (level + (window / 2.0)), expandRangesIfNecessary); } void mitk::LevelWindow::SetWindowBounds(mitk::ScalarType lowerBound, mitk::ScalarType upperBound, bool expandRangesIfNecessary) { if (IsFixed()) return; + upperBound = std::clamp(upperBound, -1e300, 1e300); + lowerBound = std::clamp(lowerBound, -1e300, 1e300); + m_LowerWindowBound = lowerBound; m_UpperWindowBound = upperBound; if (expandRangesIfNecessary) { /* if caller is sure he wants exactly that level/window, we make sure the limits match */ if (m_LowerWindowBound > m_UpperWindowBound) std::swap(m_LowerWindowBound, m_UpperWindowBound); if (m_LowerWindowBound < m_RangeMin) { m_RangeMin = m_LowerWindowBound; } if (m_UpperWindowBound > m_RangeMax) { m_RangeMax = m_UpperWindowBound; } } EnsureConsistency(); } void mitk::LevelWindow::SetRangeMinMax(mitk::ScalarType min, mitk::ScalarType max) { if (IsFixed()) return; m_RangeMin = min; m_RangeMax = max; EnsureConsistency(); } void mitk::LevelWindow::SetDefaultBoundaries(mitk::ScalarType low, mitk::ScalarType up) { if (IsFixed()) return; m_DefaultLowerBound = low; m_DefaultUpperBound = up; // Check if default window is ok { if (m_DefaultLowerBound > m_DefaultUpperBound) std::swap(m_DefaultLowerBound, m_DefaultUpperBound); if (m_DefaultLowerBound == m_DefaultUpperBound) m_DefaultLowerBound--; } EnsureConsistency(); } void mitk::LevelWindow::SetToMaxWindowSize() { SetWindowBounds(m_RangeMin, m_RangeMax); } mitk::ScalarType mitk::LevelWindow::GetRangeMin() const { return m_RangeMin; } mitk::ScalarType mitk::LevelWindow::GetRangeMax() const { return m_RangeMax; } mitk::ScalarType mitk::LevelWindow::GetRange() const { return m_RangeMax - m_RangeMin; } mitk::ScalarType mitk::LevelWindow::GetDefaultUpperBound() const { return m_DefaultUpperBound; } mitk::ScalarType mitk::LevelWindow::GetDefaultLowerBound() const { return m_DefaultLowerBound; } void mitk::LevelWindow::ResetDefaultRangeMinMax() { SetRangeMinMax(m_DefaultLowerBound, m_DefaultUpperBound); } /*! This method initializes a mitk::LevelWindow from an mitk::Image. The algorithm is as follows: Default to taking the central image slice for quick analysis. Compute the smallest (minValue), second smallest (min2ndValue), second largest (max2ndValue), and largest (maxValue) data value by traversing the pixel values only once. In the same scan it also computes the count of minValue values and maxValue values. After that a basic histogram with specific information about the extremes is complete. If minValue == maxValue, the center slice is uniform and the above scan is repeated for the complete image, not just one slice Next, special cases of images with only 1, 2 or 3 distinct data values have hand assigned level window ranges. Next the level window is set relative to the inner range IR = lengthOf([min2ndValue, max2ndValue]) For count(minValue) > 20% the smallest values are frequent and should be distinct from the min2ndValue and larger values (minValue may be std:min, may signify something special) hence the lower end of the level window is set to min2ndValue - 0.5 * IR For count(minValue) <= 20% the smallest values are not so important and can blend with the next ones => min(level window) = min2ndValue And analog for max(level window): count(max2ndValue) > 20%: max(level window) = max2ndValue + 0.5 * IR count(max2ndValue) < 20%: max(level window) = max2ndValue In both 20%+ cases the level window bounds are clamped to the [minValue, maxValue] range In consequence the level window maximizes contrast with minimal amount of computation and does do useful things if the data contains std::min or std:max values or has only 1 or 2 or 3 data values. */ void mitk::LevelWindow::SetAuto(const mitk::Image *image, bool /*tryPicTags*/, bool guessByCentralSlice, unsigned selectedComponent) { if (IsFixed()) return; if (image == nullptr || !image->IsInitialized()) return; if (itk::IOComponentEnum::FLOAT == image->GetPixelType().GetComponentType() || itk::IOComponentEnum::DOUBLE == image->GetPixelType().GetComponentType()) { m_IsFloatingImage = true; } else { m_IsFloatingImage = false; } const mitk::Image *wholeImage = image; ScalarType minValue = 0.0; ScalarType maxValue = 0.0; ScalarType min2ndValue = 0.0; ScalarType max2ndValue = 0.0; mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New(); if (guessByCentralSlice) { sliceSelector->SetInput(image); sliceSelector->SetSliceNr(image->GetDimension(2) / 2); sliceSelector->SetTimeNr(image->GetDimension(3) / 2); sliceSelector->SetChannelNr(image->GetDimension(4) / 2); sliceSelector->Update(); image = sliceSelector->GetOutput(); if (image == nullptr || !image->IsInitialized()) return; minValue = image->GetStatistics()->GetScalarValueMin(0, selectedComponent); maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(); min2ndValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(); max2ndValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(); if (minValue == maxValue) { // guessByCentralSlice seems to have failed, lets look at all data image = wholeImage; minValue = image->GetStatistics()->GetScalarValueMin(0, selectedComponent); maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(); min2ndValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(); max2ndValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(); } } else { const_cast(image)->Update(); minValue = image->GetStatistics()->GetScalarValueMin(0, selectedComponent); maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(0); min2ndValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(0); max2ndValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(0); for (unsigned int i = 1; i < image->GetDimension(3); ++i) { ScalarType minValueTemp = image->GetStatistics()->GetScalarValueMin(i, selectedComponent); if (minValue > minValueTemp) minValue = minValueTemp; ScalarType maxValueTemp = image->GetStatistics()->GetScalarValueMaxNoRecompute(i); if (maxValue < maxValueTemp) maxValue = maxValueTemp; ScalarType min2ndValueTemp = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(i); if (min2ndValue > min2ndValueTemp) min2ndValue = min2ndValueTemp; ScalarType max2ndValueTemp = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(i); if (max2ndValue > max2ndValueTemp) max2ndValue = max2ndValueTemp; } } // Fix for bug# 344 Level Window wird bei Eris Cut bildern nicht richtig gesetzt if (image->GetPixelType().GetPixelType() == itk::IOPixelEnum::SCALAR && image->GetPixelType().GetComponentType() == itk::IOComponentEnum::INT && image->GetPixelType().GetBpe() >= 8) { // the windows compiler complains about ambiguous 'pow' call, therefore static casting to (double, int) if (minValue == -(pow((double)2.0, static_cast(image->GetPixelType().GetBpe() / 2)))) { minValue = min2ndValue; } } // End fix //// uniform image if (minValue == maxValue) { minValue = maxValue - 1; } else { // Due to bug #8690 level window now is no longer of fixed range by default but the range adapts according to // levelwindow interaction // This is done because the range should be a little bit larger from the beginning so that the scale doesn't start // to resize right from the beginning double additionalRange = 0.15 * (maxValue - minValue); minValue -= additionalRange; maxValue += additionalRange; } if (!std::isfinite(minValue)) { minValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(0); } if (!std::isfinite(maxValue)) { maxValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(0); } SetRangeMinMax(minValue, maxValue); SetDefaultBoundaries(minValue, maxValue); size_t numPixelsInDataset = image->GetDimensions()[0]; for (decltype(image->GetDimension()) k = 1; k < image->GetDimension(); ++k) numPixelsInDataset *= image->GetDimensions()[k]; const auto minCount = image->GetStatistics()->GetCountOfMinValuedVoxelsNoRecompute(); const auto maxCount = image->GetStatistics()->GetCountOfMaxValuedVoxelsNoRecompute(); const auto minCountFraction = minCount / static_cast(numPixelsInDataset); const auto maxCountFraction = maxCount / static_cast(numPixelsInDataset); //// binary image if (min2ndValue == maxValue) { // noop; full range is fine } //// triple value image, put middle value in center of gray level ramp else if (min2ndValue == max2ndValue) { ScalarType minDelta = std::min(min2ndValue - minValue, maxValue - min2ndValue); minValue = min2ndValue - minDelta; maxValue = min2ndValue + minDelta; } // now we can assume more than three distict scalar values else { ScalarType innerRange = max2ndValue - min2ndValue; if (minCountFraction > 0.2) //// lots of min values -> make different from rest, but not miles away { ScalarType halfInnerRangeGapMinValue = min2ndValue - innerRange / 2.0; minValue = std::max(minValue, halfInnerRangeGapMinValue); } else //// few min values -> focus on innerRange { minValue = min2ndValue; } if (maxCountFraction > 0.2) //// lots of max values -> make different from rest { ScalarType halfInnerRangeGapMaxValue = max2ndValue + innerRange / 2.0; maxValue = std::min(maxValue, halfInnerRangeGapMaxValue); } else //// few max values -> focus on innerRange { maxValue = max2ndValue; } } SetWindowBounds(minValue, maxValue); SetDefaultLevelWindow((maxValue - minValue) / 2 + minValue, maxValue - minValue); } void mitk::LevelWindow::SetToImageRange(const mitk::Image *image) { if (IsFixed()) return; if (image == nullptr || !image->IsInitialized()) return; ScalarType minValue = image->GetStatistics()->GetScalarValueMin(0); if (!std::isfinite(minValue)) { minValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(0); } ScalarType maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(0); if (!std::isfinite(maxValue)) { maxValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(0); } SetRangeMinMax(minValue, maxValue); SetDefaultBoundaries(minValue, maxValue); SetWindowBounds(minValue, maxValue); SetDefaultLevelWindow((maxValue - minValue) / 2 + minValue, maxValue - minValue); } void mitk::LevelWindow::SetFixed(bool fixed) { m_Fixed = fixed; } bool mitk::LevelWindow::GetFixed() const { return m_Fixed; } bool mitk::LevelWindow::IsFixed() const { return m_Fixed; } bool mitk::LevelWindow::IsFloatingValues() const { return m_IsFloatingImage; } void mitk::LevelWindow::SetFloatingValues(bool value) { m_IsFloatingImage = value; } bool mitk::LevelWindow::operator==(const mitk::LevelWindow &levWin) const { return mitk::Equal(this->m_RangeMin, levWin.m_RangeMin, mitk::sqrteps) && mitk::Equal(this->m_RangeMax, levWin.m_RangeMax, mitk::sqrteps) && mitk::Equal(this->m_DefaultLowerBound, levWin.m_DefaultLowerBound, mitk::sqrteps) && mitk::Equal(this->m_DefaultUpperBound, levWin.m_DefaultUpperBound, mitk::sqrteps) && mitk::Equal(this->m_LowerWindowBound, levWin.m_LowerWindowBound, mitk::sqrteps) && mitk::Equal(this->m_UpperWindowBound, levWin.m_UpperWindowBound, mitk::sqrteps) && m_Fixed == levWin.IsFixed() && m_IsFloatingImage == levWin.IsFloatingValues(); } bool mitk::LevelWindow::operator!=(const mitk::LevelWindow &levWin) const { return !((*this) == levWin); } mitk::LevelWindow &mitk::LevelWindow::operator=(const mitk::LevelWindow &levWin) { if (this == &levWin) { return *this; } else { m_RangeMin = levWin.GetRangeMin(); m_RangeMax = levWin.GetRangeMax(); m_LowerWindowBound = levWin.GetLowerWindowBound(); m_UpperWindowBound = levWin.GetUpperWindowBound(); m_DefaultLowerBound = levWin.GetDefaultLowerBound(); m_DefaultUpperBound = levWin.GetDefaultUpperBound(); m_Fixed = levWin.GetFixed(); m_IsFloatingImage = levWin.IsFloatingValues(); return *this; } } diff --git a/Modules/Core/src/DataManagement/mitkLookupTable.cpp b/Modules/Core/src/DataManagement/mitkLookupTable.cpp index 3022e09869..f8e21faa15 100644 --- a/Modules/Core/src/DataManagement/mitkLookupTable.cpp +++ b/Modules/Core/src/DataManagement/mitkLookupTable.cpp @@ -1,647 +1,666 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkLookupTable.h" #include #include #include #include #include #include #include #include #include #include #include #include +#include #include std::vector mitk::LookupTable::typenameList = { "Grayscale", "Inverse Grayscale", "Hot Iron", "Jet", "Jet Transparent", "Plasma", "Inferno", "Viridis", "Magma", "Legacy Binary", "Legacy Rainbow Color", "Multilabel", "PET Color", - "PET 20" + "PET 20", + "Turbo" }; mitk::LookupTable::LookupTable() : m_LookupTable(vtkSmartPointer::New()) , m_Window(0.0) , m_Level(0.0) , m_Opacity(1.0) , m_Type(mitk::LookupTable::GRAYSCALE) { this->BuildGrayScaleLookupTable(); } mitk::LookupTable::LookupTable(const LookupTable &other) : itk::DataObject() , m_LookupTable(vtkSmartPointer::New()) , m_Window(other.m_Window) , m_Level(other.m_Level) , m_Opacity(other.m_Opacity) , m_Type(other.m_Type) { m_LookupTable->DeepCopy(other.m_LookupTable); } mitk::LookupTable::~LookupTable() { } void mitk::LookupTable::SetVtkLookupTable(vtkSmartPointer lut) { if ((!lut) || (m_LookupTable == lut)) { return; } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::SetType(const mitk::LookupTable::LookupTableType type) { if (m_Type == type) return; switch (type) { case (mitk::LookupTable::GRAYSCALE): this->BuildGrayScaleLookupTable(); break; case (mitk::LookupTable::INVERSE_GRAYSCALE): this->BuildInverseGrayScaleLookupTable(); break; case (mitk::LookupTable::HOT_IRON): this->BuildHotIronLookupTable(); break; case (mitk::LookupTable::JET): this->BuildJetLookupTable(); break; case (mitk::LookupTable::JET_TRANSPARENT): this->BuildJetLookupTable(true); break; case (mitk::LookupTable::PLASMA): this->BuildPlasmaLookupTable(); break; case (mitk::LookupTable::INFERNO): this->BuildInfernoLookupTable(); break; case (mitk::LookupTable::VIRIDIS): this->BuildViridisLookupTable(); break; case (mitk::LookupTable::MAGMA): this->BuildMagmaLookupTable(); break; case (mitk::LookupTable::LEGACY_BINARY): this->BuildLegacyBinaryLookupTable(); break; case (mitk::LookupTable::MULTILABEL): this->BuildMultiLabelLookupTable(); break; case (mitk::LookupTable::PET_COLOR): this->BuildPETColorLookupTable(); break; case (mitk::LookupTable::PET_20): this->BuildPET20LookupTable(); break; + case (mitk::LookupTable::TURBO): + this->BuildTurboLookupTable(); + break; case (mitk::LookupTable::LEGACY_RAINBOW_COLOR): this->BuildLegacyRainbowColorLookupTable(); break; default: MITK_ERROR << "non-existing colormap"; return; } m_Type = type; } void mitk::LookupTable::SetType(const std::string &typeName) { for (size_t i = 0; i < typenameList.size(); ++i) { if (typenameList.at(i) == typeName) { this->SetType(static_cast(i)); } } } mitk::LookupTable::LookupTableType mitk::LookupTable::GetActiveType() const { return m_Type; } std::string mitk::LookupTable::GetActiveTypeAsString() const { if (static_cast(m_Type) < typenameList.size()) { return typenameList.at(m_Type); } return ""; } void mitk::LookupTable::ChangeOpacityForAll(float opacity) { int noValues = m_LookupTable->GetNumberOfTableValues(); double rgba[4]; for (int i = 0; i < noValues; i++) { m_LookupTable->GetTableValue(i, rgba); rgba[3] = opacity; m_LookupTable->SetTableValue(i, rgba); } this->Modified(); // need to call modified, since LookupTableProperty seems to be unchanged so no widget-update is // executed } void mitk::LookupTable::ChangeOpacity(int index, float opacity) { int noValues = m_LookupTable->GetNumberOfTableValues(); if (index > noValues) { MITK_INFO << "could not change opacity. index exceed size of lut ... " << std::endl; return; } double rgba[4]; m_LookupTable->GetTableValue(index, rgba); rgba[3] = opacity; m_LookupTable->SetTableValue(index, rgba); this->Modified(); // need to call modified, since LookupTableProperty seems to be unchanged so no widget-update is // executed } void mitk::LookupTable::GetColor(double value, double rgb[3]) { this->GetVtkLookupTable()->GetColor(value, rgb); } void mitk::LookupTable::GetTableValue(int index, double rgba[4]) { this->GetVtkLookupTable()->GetTableValue(index, rgba); } void mitk::LookupTable::SetTableValue(int index, double rgba[4]) { this->GetVtkLookupTable()->SetTableValue(index, rgba); } vtkSmartPointer mitk::LookupTable::GetVtkLookupTable() const { return m_LookupTable; } mitk::LookupTable::RawLookupTableType *mitk::LookupTable::GetRawLookupTable() const { return m_LookupTable->GetPointer(0); } bool mitk::LookupTable::operator==(const mitk::LookupTable &other) const { if (m_LookupTable == other.GetVtkLookupTable()) return true; vtkLookupTable *olut = other.GetVtkLookupTable(); if (olut == nullptr) return false; bool equal = (m_LookupTable->GetNumberOfColors() == olut->GetNumberOfColors()) && (m_LookupTable->GetTableRange()[0] == olut->GetTableRange()[0]) && (m_LookupTable->GetTableRange()[1] == olut->GetTableRange()[1]) && (m_LookupTable->GetHueRange()[0] == olut->GetHueRange()[0]) && (m_LookupTable->GetHueRange()[1] == olut->GetHueRange()[1]) && (m_LookupTable->GetSaturationRange()[0] == olut->GetSaturationRange()[0]) && (m_LookupTable->GetSaturationRange()[1] == olut->GetSaturationRange()[1]) && (m_LookupTable->GetValueRange()[0] == olut->GetValueRange()[0]) && (m_LookupTable->GetValueRange()[1] == olut->GetValueRange()[1]) && (m_LookupTable->GetAlphaRange()[0] == olut->GetAlphaRange()[0]) && (m_LookupTable->GetAlphaRange()[1] == olut->GetAlphaRange()[1]) && (m_LookupTable->GetRamp() == olut->GetRamp()) && (m_LookupTable->GetScale() == olut->GetScale()) && (m_LookupTable->GetAlpha() == olut->GetAlpha()) && (m_LookupTable->GetTable()->GetNumberOfTuples() == olut->GetTable()->GetNumberOfTuples()); if (equal == false) return false; for (vtkIdType i = 0; i < m_LookupTable->GetNumberOfTableValues(); i++) { bool tvequal = (m_LookupTable->GetTableValue(i)[0] == olut->GetTableValue(i)[0]) && (m_LookupTable->GetTableValue(i)[1] == olut->GetTableValue(i)[1]) && (m_LookupTable->GetTableValue(i)[2] == olut->GetTableValue(i)[2]) && (m_LookupTable->GetTableValue(i)[3] == olut->GetTableValue(i)[3]); if (tvequal == false) return false; } return true; } bool mitk::LookupTable::operator!=(const mitk::LookupTable &other) const { return !(*this == other); } mitk::LookupTable &mitk::LookupTable::operator=(const mitk::LookupTable &LookupTable) { if (this == &LookupTable) { return *this; } else { m_LookupTable = LookupTable.GetVtkLookupTable(); return *this; } } void mitk::LookupTable::UpdateOutputInformation() { if (this->GetSource()) { this->GetSource()->UpdateOutputInformation(); } } void mitk::LookupTable::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::LookupTable::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::LookupTable::VerifyRequestedRegion() { // normally we should check if the requested region lies within the // largest possible region. Since for lookup-tables we assume, that the // requested region is always the largest possible region, we can always // return true! return true; } void mitk::LookupTable::SetRequestedRegion(const itk::DataObject *) { // not implemented, since we always want to have the RequestedRegion // to be set to LargestPossibleRegion } vtkSmartPointer mitk::LookupTable::CreateColorTransferFunction() { vtkSmartPointer colorFunction = vtkSmartPointer::New(); mitk::LookupTable::RawLookupTableType *rawLookupTable = this->GetRawLookupTable(); int num_of_values = m_LookupTable->GetNumberOfTableValues(); auto cols = new double[3 * num_of_values]; double *colsHead = cols; for (int i = 0; i < num_of_values; ++i) { *cols = static_cast(*rawLookupTable) / 255.0; ++cols; ++rawLookupTable; *cols = static_cast(*rawLookupTable) / 255.0; ++cols; ++rawLookupTable; *cols = static_cast(*rawLookupTable) / 255.0; ++cols; ++rawLookupTable; ++rawLookupTable; } colorFunction->BuildFunctionFromTable( m_LookupTable->GetTableRange()[0], m_LookupTable->GetTableRange()[1], num_of_values, colsHead); return colorFunction; } void mitk::LookupTable::CreateColorTransferFunction(vtkColorTransferFunction *&colorFunction) { colorFunction = this->CreateColorTransferFunction(); } vtkSmartPointer mitk::LookupTable::CreateOpacityTransferFunction() { vtkSmartPointer opacityFunction = vtkSmartPointer::New(); mitk::LookupTable::RawLookupTableType *rgba = this->GetRawLookupTable(); int num_of_values = m_LookupTable->GetNumberOfTableValues(); auto alphas = new double[num_of_values]; double *alphasHead = alphas; rgba += 3; for (int i = 0; i < num_of_values; ++i) { *alphas = static_cast(*rgba) / 255.0; ++alphas; rgba += 4; } opacityFunction->BuildFunctionFromTable( m_LookupTable->GetTableRange()[0], m_LookupTable->GetTableRange()[1], num_of_values, alphasHead); return opacityFunction; } void mitk::LookupTable::CreateOpacityTransferFunction(vtkPiecewiseFunction *&opacityFunction) { opacityFunction = this->CreateOpacityTransferFunction(); } vtkSmartPointer mitk::LookupTable::CreateGradientTransferFunction() { vtkSmartPointer gradientFunction = vtkSmartPointer::New(); mitk::LookupTable::RawLookupTableType *rgba = this->GetRawLookupTable(); int num_of_values = m_LookupTable->GetNumberOfTableValues(); auto alphas = new double[num_of_values]; double *alphasHead = alphas; rgba += 3; for (int i = 0; i < num_of_values; ++i) { *alphas = static_cast(*rgba) / 255.0; ++alphas; rgba += 4; } gradientFunction->BuildFunctionFromTable( m_LookupTable->GetTableRange()[0], m_LookupTable->GetTableRange()[1], num_of_values, alphasHead); return gradientFunction; } void mitk::LookupTable::CreateGradientTransferFunction(vtkPiecewiseFunction *&gradientFunction) { gradientFunction = this->CreateGradientTransferFunction(); } void mitk::LookupTable::PrintSelf(std::ostream &os, itk::Indent indent) const { os << indent; m_LookupTable->PrintHeader(os, vtkIndent()); } itk::LightObject::Pointer mitk::LookupTable::InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); result->UnRegister(); return result; } void mitk::LookupTable::BuildGrayScaleLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetRampToLinear(); lut->SetSaturationRange(0.0, 0.0); lut->SetHueRange(0.0, 0.0); lut->SetValueRange(0.0, 1.0); lut->Build(); m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildLegacyBinaryLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetRampToLinear(); lut->SetSaturationRange(0.0, 0.0); lut->SetHueRange(0.0, 0.0); lut->SetValueRange(0.0, 1.0); lut->Build(); lut->SetTableValue(0, 0.0, 0.0, 0.0, 0.0); m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildInverseGrayScaleLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetTableRange(0, 1); lut->SetSaturationRange(0, 0); lut->SetHueRange(0, 0); lut->SetValueRange(1, 0); lut->SetAlphaRange(1, 0); lut->Build(); m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildHotIronLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue( i, (double)HotIron[i][0] / 255.0, (double)HotIron[i][1] / 255.0, (double)HotIron[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildJetLookupTable(bool transparent) { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->Build(); int i = 0; if (transparent) { // Lowest intensity is transparent lut->SetTableValue(0, (double)Jet[0][0] / 255.0, (double)Jet[0][1] / 255.0, (double)Jet[0][2] / 255.0, 0.0); i = 1; } for (; i < 256; i++) { lut->SetTableValue(i, (double)Jet[i][0] / 255.0, (double)Jet[i][1] / 255.0, (double)Jet[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildPETColorLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->SetTableRange((m_Level - m_Window / 2.0), (m_Level + m_Window / 2.0)); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue( i, (double)PETColor[i][0] / 255.0, (double)PETColor[i][1] / 255.0, (double)PETColor[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildPET20LookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->SetTableRange((m_Level - m_Window / 2.0), (m_Level + m_Window / 2.0)); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue(i, (double)PET20[i][0] / 255.0, (double)PET20[i][1] / 255.0, (double)PET20[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } +void mitk::LookupTable::BuildTurboLookupTable() +{ + auto lut = vtkSmartPointer::New(); + lut->SetNumberOfTableValues(256); + lut->SetTableRange((m_Level - m_Window / 2.0), (m_Level + m_Window / 2.0)); + lut->Build(); + + for (int i = 0; i < 256; ++i) + lut->SetTableValue(i, (double)Turbo[i][0] / 255.0, (double)Turbo[i][1] / 255.0, (double)Turbo[i][2] / 255.0, 1.0); + + m_LookupTable = lut; + this->Modified(); +} + void mitk::LookupTable::BuildMultiLabelLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(65536); lut->SetTableRange(0, 65536); lut->Build(); lut->SetTableValue(0, 0.0, 0.0, 0.0, 0.0); // background for (int i = 0; i < 25; i++) { lut->SetTableValue(i+1, Multilabel[i][0], Multilabel[i][1], Multilabel[i][2], 0.4); } for (int i = 26; i < 65536; i++) { if (i % 12 == 0) lut->SetTableValue(i, 1.0, 0.0, 0.0, 0.4); else if (i % 12 == 1) lut->SetTableValue(i, 0.0, 1.0, 0.0, 0.4); else if (i % 12 == 2) lut->SetTableValue(i, 0.0, 0.0, 1.0, 0.4); else if (i % 12 == 3) lut->SetTableValue(i, 1.0, 1.0, 0.0, 0.4); else if (i % 12 == 4) lut->SetTableValue(i, 0.0, 1.0, 1.0, 0.4); else if (i % 12 == 5) lut->SetTableValue(i, 1.0, 0.0, 1.0, 0.4); else if (i % 12 == 6) lut->SetTableValue(i, 1.0, 0.5, 0.0, 0.4); else if (i % 12 == 7) lut->SetTableValue(i, 0.0, 1.0, 0.5, 0.4); else if (i % 12 == 8) lut->SetTableValue(i, 0.5, 0.0, 1.0, 0.4); else if (i % 12 == 9) lut->SetTableValue(i, 1.0, 1.0, 0.5, 0.4); else if (i % 12 == 10) lut->SetTableValue(i, 0.5, 1.0, 1.0, 0.4); else if (i % 12 == 11) lut->SetTableValue(i, 1.0, 0.5, 1.0, 0.4); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildLegacyRainbowColorLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetRampToLinear(); lut->SetHueRange(0.6667, 0.0); lut->SetTableRange(0.0, 20.0); lut->Build(); m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildPlasmaLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue( i, (double)Plasma[i][0] / 255.0, (double)Plasma[i][1] / 255.0, (double)Plasma[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildInfernoLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue( i, (double)Inferno[i][0] / 255.0, (double)Inferno[i][1] / 255.0, (double)Inferno[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildViridisLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue( i, (double)Viridis[i][0] / 255.0, (double)Viridis[i][1] / 255.0, (double)Viridis[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::BuildMagmaLookupTable() { vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues(256); lut->Build(); for (int i = 0; i < 256; i++) { lut->SetTableValue( i, (double)Magma[i][0] / 255.0, (double)Magma[i][1] / 255.0, (double)Magma[i][2] / 255.0, 1.0); } m_LookupTable = lut; this->Modified(); } diff --git a/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp b/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp index c089328d1f..ef9d70abc2 100755 --- a/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp +++ b/Modules/Core/src/DataManagement/mitkMemoryUtilities.cpp @@ -1,115 +1,98 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkMemoryUtilities.h" +#include -#include #if _MSC_VER #include #include #elif defined(__APPLE__) -#include -#include +#include #include #include #else #include #include +#include #endif -/** - * Returns the memory usage of the current process in bytes. - * On linux, this refers to the virtual memory allocated by - * the process (the VIRT column in top). - * On windows, this refery to the size in bytes of the working - * set pages (the "Speicherauslastung" column in the task manager). - */ size_t mitk::MemoryUtilities::GetProcessMemoryUsage() { -#if _MSC_VER size_t size = 0; + +#if _MSC_VER DWORD pid = GetCurrentProcessId(); PROCESS_MEMORY_COUNTERS pmc; + HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); - if (hProcess == nullptr) - return 0; - if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) + + if (hProcess != nullptr) { - size = pmc.WorkingSetSize; + if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)) != 0) + size = pmc.WorkingSetSize; + + CloseHandle(hProcess); } - CloseHandle(hProcess); - return size; #elif defined(__APPLE__) - struct task_basic_info t_info; - mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; - task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); - size_t size = t_info.virtual_size; - return size; + task_vm_info taskInfo; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + + if (task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast(&taskInfo), &count) == KERN_SUCCESS) + size = taskInfo.resident_size - taskInfo.reusable; // That's what Chromium reports as process memory #else - int size, res, shared, text, sharedLibs, stack, dirtyPages; - if (!ReadStatmFromProcFS(&size, &res, &shared, &text, &sharedLibs, &stack, &dirtyPages)) - return (size_t)size * getpagesize(); - else - return 0; + std::ifstream statm("/proc/self/statm"); + + if (statm.is_open()) + { + size_t resident = 0; + size_t shared = 0; + + statm >> size >> resident >> shared; + + statm.close(); + + if (shared < resident) + size = resident - shared; // That's what the GNOME System Monitor reports as process memory + } #endif - return 0; + + return size; } -/** - * Returns the total size of physical memory in bytes - */ size_t mitk::MemoryUtilities::GetTotalSizeOfPhysicalRam() { #if _MSC_VER MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); - GlobalMemoryStatusEx(&statex); - return (size_t)statex.ullTotalPhys; + + if (GlobalMemoryStatusEx(&statex) != 0) + return statex.ullTotalPhys; #elif defined(__APPLE__) int mib[2]; - int64_t physical_memory; mib[0] = CTL_HW; mib[1] = HW_MEMSIZE; + + int64_t physical_memory; size_t length = sizeof(int64_t); + sysctl(mib, 2, &physical_memory, &length, nullptr, 0); + return physical_memory; #else struct sysinfo info; + if (!sysinfo(&info)) return info.totalram * info.mem_unit; - else - return 0; #endif -} -#ifndef _MSC_VER -#ifndef __APPLE__ -int mitk::MemoryUtilities::ReadStatmFromProcFS( - int *size, int *res, int *shared, int *text, int *sharedLibs, int *stack, int *dirtyPages) -{ - int ret = 0; - FILE *f; - f = fopen("/proc/self/statm", "r"); - if (f) - { - size_t ignored = fscanf(f, "%d %d %d %d %d %d %d", size, res, shared, text, sharedLibs, stack, dirtyPages); - ++ignored; - fclose(f); - } - else - { - ret = -1; - } - return ret; + return 0; } -#endif -#endif diff --git a/Modules/Core/src/DataManagement/mitkSurface.cpp b/Modules/Core/src/DataManagement/mitkSurface.cpp index fcc8f6ff98..9fc0cdf7f8 100644 --- a/Modules/Core/src/DataManagement/mitkSurface.cpp +++ b/Modules/Core/src/DataManagement/mitkSurface.cpp @@ -1,509 +1,508 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkSurface.h" #include "mitkInteractionConst.h" #include "mitkSurfaceOperation.h" #include #include static vtkSmartPointer DeepCopy(vtkPolyData *other) { if (other == nullptr) return nullptr; vtkSmartPointer copy = vtkSmartPointer::New(); copy->DeepCopy(other); return copy; } static void Update(vtkPolyData * /*polyData*/) { // if (polyData != nullptr) // polyData->Update(); //VTK6_TODO vtk pipeline } mitk::Surface::Surface() : m_CalculateBoundingBox(false) { this->InitializeEmpty(); } mitk::Surface::Surface(const mitk::Surface &other) : BaseData(other), m_LargestPossibleRegion(other.m_LargestPossibleRegion), m_RequestedRegion(other.m_RequestedRegion), m_CalculateBoundingBox(other.m_CalculateBoundingBox) { if (!other.m_PolyDatas.empty()) { m_PolyDatas.resize(other.m_PolyDatas.size()); std::transform(other.m_PolyDatas.cbegin(), other.m_PolyDatas.cend(), m_PolyDatas.begin(), DeepCopy); } else { this->InitializeEmpty(); } } void mitk::Surface::Swap(mitk::Surface &other) { std::swap(m_PolyDatas, other.m_PolyDatas); std::swap(m_LargestPossibleRegion, other.m_LargestPossibleRegion); std::swap(m_RequestedRegion, other.m_RequestedRegion); std::swap(m_CalculateBoundingBox, other.m_CalculateBoundingBox); } mitk::Surface &mitk::Surface::operator=(Surface other) { this->Swap(other); return *this; } mitk::Surface::~Surface() { this->ClearData(); } void mitk::Surface::ClearData() { m_PolyDatas.clear(); Superclass::ClearData(); } const mitk::Surface::RegionType &mitk::Surface::GetLargestPossibleRegion() const { m_LargestPossibleRegion.SetIndex(3, 0); m_LargestPossibleRegion.SetSize(3, GetTimeGeometry()->CountTimeSteps()); return m_LargestPossibleRegion; } const mitk::Surface::RegionType &mitk::Surface::GetRequestedRegion() const { return m_RequestedRegion; } void mitk::Surface::InitializeEmpty() { if (!m_PolyDatas.empty()) this->ClearData(); Superclass::InitializeTimeGeometry(); m_PolyDatas.push_back(nullptr); m_Initialized = true; } void mitk::Surface::SetVtkPolyData(vtkPolyData *polyData, unsigned int t) { this->Expand(t + 1); if (m_PolyDatas[t] != nullptr) { if (m_PolyDatas[t].GetPointer() == polyData) return; } m_PolyDatas[t].TakeReference(polyData); if (polyData != nullptr) polyData->Register(nullptr); m_CalculateBoundingBox = true; this->Modified(); this->UpdateOutputInformation(); } bool mitk::Surface::IsEmptyTimeStep(unsigned int t) const { if (!IsInitialized()) return false; vtkPolyData *polyData = this->GetVtkPolyData(t); - return polyData == nullptr || (polyData->GetNumberOfLines() == 0 && polyData->GetNumberOfPolys() == 0 && - polyData->GetNumberOfStrips() == 0 && polyData->GetNumberOfVerts() == 0); + return polyData == nullptr; } vtkPolyData *mitk::Surface::GetVtkPolyData(unsigned int t) const { if (t < m_PolyDatas.size()) { if (m_PolyDatas[t] == nullptr && this->GetSource().IsNotNull()) { RegionType requestedRegion; requestedRegion.SetIndex(3, t); requestedRegion.SetSize(3, 1); this->m_RequestedRegion = requestedRegion; this->GetSource()->Update(); } return m_PolyDatas[t].GetPointer(); } return nullptr; } void mitk::Surface::UpdateOutputInformation() { if (this->GetSource().IsNotNull()) this->GetSource()->UpdateOutputInformation(); if (m_CalculateBoundingBox == true && !m_PolyDatas.empty()) this->CalculateBoundingBox(); else this->GetTimeGeometry()->Update(); } void mitk::Surface::CalculateBoundingBox() { TimeGeometry *timeGeometry = this->GetTimeGeometry(); if (timeGeometry->CountTimeSteps() != m_PolyDatas.size()) mitkThrow() << "Number of geometry time steps is inconsistent with number of poly data pointers."; for (unsigned int i = 0; i < m_PolyDatas.size(); ++i) { vtkPolyData *polyData = m_PolyDatas[i].GetPointer(); double bounds[6] = {0}; if (polyData != nullptr && polyData->GetNumberOfPoints() > 0) { // polyData->Update(); //VTK6_TODO vtk pipeline polyData->ComputeBounds(); polyData->GetBounds(bounds); } BaseGeometry::Pointer geometry = timeGeometry->GetGeometryForTimeStep(i); if (geometry.IsNull()) mitkThrow() << "Time-sliced geometry is invalid (equals nullptr)."; geometry->SetFloatBounds(bounds); } timeGeometry->Update(); m_CalculateBoundingBox = false; } void mitk::Surface::SetRequestedRegionToLargestPossibleRegion() { m_RequestedRegion = GetLargestPossibleRegion(); } bool mitk::Surface::RequestedRegionIsOutsideOfTheBufferedRegion() { RegionType::IndexValueType end = m_RequestedRegion.GetIndex(3) + m_RequestedRegion.GetSize(3); if (static_cast(m_PolyDatas.size()) < end) return true; for (RegionType::IndexValueType t = m_RequestedRegion.GetIndex(3); t < end; ++t) { if (m_PolyDatas[t] == nullptr) return true; } return false; } bool mitk::Surface::VerifyRequestedRegion() { if (m_RequestedRegion.GetIndex(3) >= 0 && m_RequestedRegion.GetIndex(3) + m_RequestedRegion.GetSize(3) <= m_PolyDatas.size()) return true; return false; } void mitk::Surface::SetRequestedRegion(const itk::DataObject *data) { const auto *surface = dynamic_cast(data); if (surface != nullptr) m_RequestedRegion = surface->GetRequestedRegion(); else mitkThrow() << "Data object used to get requested region is not a mitk::Surface."; } void mitk::Surface::SetRequestedRegion(Surface::RegionType *region) { if (region == nullptr) mitkThrow() << "Requested region is invalid (equals nullptr)"; m_RequestedRegion = *region; } void mitk::Surface::CopyInformation(const itk::DataObject *data) { Superclass::CopyInformation(data); const auto *surface = dynamic_cast(data); if (surface == nullptr) mitkThrow() << "Data object used to get largest possible region is not a mitk::Surface."; m_LargestPossibleRegion = surface->GetLargestPossibleRegion(); } void mitk::Surface::Update() { using ::Update; if (this->GetSource().IsNull()) std::for_each(m_PolyDatas.begin(), m_PolyDatas.end(), Update); Superclass::Update(); } void mitk::Surface::Expand(unsigned int timeSteps) { if (timeSteps > m_PolyDatas.size()) { Superclass::Expand(timeSteps); m_PolyDatas.resize(timeSteps); m_CalculateBoundingBox = true; } } void mitk::Surface::ExecuteOperation(Operation *operation) { switch (operation->GetOperationType()) { case OpSURFACECHANGED: { auto *surfaceOperation = dynamic_cast(operation); if (surfaceOperation == nullptr) break; unsigned int timeStep = surfaceOperation->GetTimeStep(); if (m_PolyDatas[timeStep] != nullptr) { vtkPolyData *updatedPolyData = surfaceOperation->GetVtkPolyData(); if (updatedPolyData != nullptr) { this->SetVtkPolyData(updatedPolyData, timeStep); this->CalculateBoundingBox(); this->Modified(); } } break; } default: return; } } unsigned int mitk::Surface::GetSizeOfPolyDataSeries() const { return m_PolyDatas.size(); } void mitk::Surface::Graft(const DataObject *data) { const auto *surface = dynamic_cast(data); if (surface == nullptr) mitkThrow() << "Data object used to graft surface is not a mitk::Surface."; this->CopyInformation(data); m_PolyDatas.clear(); for (unsigned int i = 0; i < surface->GetSizeOfPolyDataSeries(); ++i) { m_PolyDatas.push_back(vtkSmartPointer::New()); m_PolyDatas.back()->DeepCopy(surface->GetVtkPolyData(i)); } } void mitk::Surface::PrintSelf(std::ostream &os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "\nNumber PolyDatas: " << m_PolyDatas.size() << "\n"; unsigned int count = 0; for (auto it = m_PolyDatas.begin(); it != m_PolyDatas.end(); ++it) { os << "\n"; if (*it != nullptr) { os << indent << "PolyData at time step " << count << ":\n"; os << indent << "Number of cells: " << (*it)->GetNumberOfCells() << "\n"; os << indent << "Number of points: " << (*it)->GetNumberOfPoints() << "\n\n"; os << indent << "VTKPolyData:\n"; (*it)->Print(os); } else { os << indent << "Empty PolyData at time step " << count << "\n"; } ++count; } } bool mitk::Equal(vtkPolyData *leftHandSide, vtkPolyData *rightHandSide, mitk::ScalarType eps, bool verbose) { if ((leftHandSide == nullptr) || (rightHandSide == nullptr)) { MITK_ERROR << "mitk::Equal( vtkPolyData* leftHandSide, vtkPolyData* rightHandSide, mitk::ScalarType eps, bool " "verbose ) does not work for nullptr pointer input."; return false; } return Equal(*leftHandSide, *rightHandSide, eps, verbose); } bool mitk::Equal(vtkPolyData &leftHandSide, vtkPolyData &rightHandSide, mitk::ScalarType eps, bool verbose) { bool noDifferenceFound = true; if (!mitk::Equal(leftHandSide.GetNumberOfCells(), rightHandSide.GetNumberOfCells(), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Number of cells not equal"; noDifferenceFound = false; } if (!mitk::Equal(leftHandSide.GetNumberOfVerts(), rightHandSide.GetNumberOfVerts(), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Number of vertices not equal"; noDifferenceFound = false; } if (!mitk::Equal(leftHandSide.GetNumberOfLines(), rightHandSide.GetNumberOfLines(), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Number of lines not equal"; noDifferenceFound = false; } if (!mitk::Equal(leftHandSide.GetNumberOfPolys(), rightHandSide.GetNumberOfPolys(), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Number of polys not equal"; noDifferenceFound = false; } if (!mitk::Equal(leftHandSide.GetNumberOfStrips(), rightHandSide.GetNumberOfStrips(), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Number of strips not equal"; noDifferenceFound = false; } { unsigned int numberOfPointsRight = rightHandSide.GetPoints()->GetNumberOfPoints(); unsigned int numberOfPointsLeft = leftHandSide.GetPoints()->GetNumberOfPoints(); if (!mitk::Equal(numberOfPointsLeft, numberOfPointsRight, eps, verbose)) { if (verbose) MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Number of points not equal"; noDifferenceFound = false; } else { for (unsigned int i(0); i < numberOfPointsRight; i++) { bool pointFound = false; double pointOne[3]; rightHandSide.GetPoints()->GetPoint(i, pointOne); for (unsigned int j(0); j < numberOfPointsLeft; j++) { double pointTwo[3]; leftHandSide.GetPoints()->GetPoint(j, pointTwo); double x = pointOne[0] - pointTwo[0]; double y = pointOne[1] - pointTwo[1]; double z = pointOne[2] - pointTwo[2]; double distance = x * x + y * y + z * z; if (distance < eps) { pointFound = true; break; } } if (!pointFound) { if (verbose) { MITK_INFO << "[Equal( vtkPolyData*, vtkPolyData* )] Right hand side point with id " << i << " and coordinates ( " << std::setprecision(12) << pointOne[0] << " ; " << pointOne[1] << " ; " << pointOne[2] << " ) could not be found in left hand side with epsilon " << eps << "."; } noDifferenceFound = false; break; } } } } return noDifferenceFound; } bool mitk::Equal(mitk::Surface *leftHandSide, mitk::Surface *rightHandSide, mitk::ScalarType eps, bool verbose) { if ((leftHandSide == nullptr) || (rightHandSide == nullptr)) { MITK_ERROR << "mitk::Equal( mitk::Surface* leftHandSide, mitk::Surface* rightHandSide, mitk::ScalarType eps, bool " "verbose ) does not work with nullptr pointer input."; return false; } return Equal(*leftHandSide, *rightHandSide, eps, verbose); } bool mitk::Equal(mitk::Surface &leftHandSide, mitk::Surface &rightHandSide, mitk::ScalarType eps, bool verbose) { bool noDifferenceFound = true; if (!mitk::Equal(leftHandSide.GetSizeOfPolyDataSeries(), rightHandSide.GetSizeOfPolyDataSeries(), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( mitk::surface&, mitk::surface& )] Size of PolyData series not equal."; return false; } // No mitk::Equal for TimeGeometry implemented. // if( ! mitk::Equal( leftHandSide->GetTimeGeometry(), rightHandSide->GetTimeGeometry(), eps, verbose ) ) //{ // if(verbose) // MITK_INFO << "[Equal( mitk::surface&, mitk::surface& )] Time sliced geometries not equal"; // noDifferenceFound = false; //} for (unsigned int i(0); i < rightHandSide.GetSizeOfPolyDataSeries(); i++) { if (!mitk::Equal(*leftHandSide.GetVtkPolyData(i), *rightHandSide.GetVtkPolyData(i), eps, verbose)) { if (verbose) MITK_INFO << "[Equal( mitk::surface&, mitk::surface& )] Poly datas not equal."; noDifferenceFound = false; } } return noDifferenceFound; } diff --git a/Modules/Core/src/IO/mitkIOUtil.cpp b/Modules/Core/src/IO/mitkIOUtil.cpp index 2e05ce7d71..17ff57df47 100644 --- a/Modules/Core/src/IO/mitkIOUtil.cpp +++ b/Modules/Core/src/IO/mitkIOUtil.cpp @@ -1,1015 +1,1015 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkIOUtil.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // ITK #include // VTK #include #include #include #include #include static std::string GetLastErrorStr() { #ifdef US_PLATFORM_POSIX return std::string(strerror(errno)); #else // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, nullptr); std::string errMsg((LPCTSTR)lpMsgBuf); LocalFree(lpMsgBuf); return errMsg; #endif } #ifdef US_PLATFORM_WINDOWS #include #include // make the posix flags point to the obsolete bsd types on windows #define S_IRUSR S_IREAD #define S_IWUSR S_IWRITE #else #include #include #include #endif #include #include static const char validLetters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // A cross-platform version of the mkstemps function static int mkstemps_compat(char *tmpl, int suffixlen) { static unsigned long long value = 0; int savedErrno = errno; // Lower bound on the number of temporary files to attempt to generate. #define ATTEMPTS_MIN (62 * 62 * 62) /* The number of times to attempt to generate a temporary file. To conform to POSIX, this must be no smaller than TMP_MAX. */ #if ATTEMPTS_MIN < TMP_MAX const unsigned int attempts = TMP_MAX; #else const unsigned int attempts = ATTEMPTS_MIN; #endif const int len = strlen(tmpl); if ((len - suffixlen) < 6 || strncmp(&tmpl[len - 6 - suffixlen], "XXXXXX", 6)) { errno = EINVAL; return -1; } /* This is where the Xs start. */ char *XXXXXX = &tmpl[len - 6 - suffixlen]; /* Get some more or less random data. */ #ifdef US_PLATFORM_WINDOWS { SYSTEMTIME stNow; FILETIME ftNow; // get system time GetSystemTime(&stNow); stNow.wMilliseconds = 500; if (!SystemTimeToFileTime(&stNow, &ftNow)) { errno = -1; return -1; } unsigned long long randomTimeBits = ((static_cast(ftNow.dwHighDateTime) << 32) | static_cast(ftNow.dwLowDateTime)); value = randomTimeBits ^ static_cast(GetCurrentThreadId()); } #else { struct timeval tv; gettimeofday(&tv, nullptr); unsigned long long randomTimeBits = ((static_cast(tv.tv_usec) << 32) | static_cast(tv.tv_sec)); value = randomTimeBits ^ static_cast(getpid()); } #endif for (unsigned int count = 0; count < attempts; value += 7777, ++count) { unsigned long long v = value; /* Fill in the random bits. */ XXXXXX[0] = validLetters[v % 62]; v /= 62; XXXXXX[1] = validLetters[v % 62]; v /= 62; XXXXXX[2] = validLetters[v % 62]; v /= 62; XXXXXX[3] = validLetters[v % 62]; v /= 62; XXXXXX[4] = validLetters[v % 62]; v /= 62; XXXXXX[5] = validLetters[v % 62]; int fd = open(tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); if (fd >= 0) { errno = savedErrno; return fd; } else if (errno != EEXIST) { return -1; } } /* We got out of the loop because we ran out of combinations to try. */ errno = EEXIST; return -1; } // A cross-platform version of the POSIX mkdtemp function static char *mkdtemps_compat(char *tmpl, int suffixlen) { static unsigned long long value = 0; int savedErrno = errno; // Lower bound on the number of temporary dirs to attempt to generate. #define ATTEMPTS_MIN (62 * 62 * 62) /* The number of times to attempt to generate a temporary dir. To conform to POSIX, this must be no smaller than TMP_MAX. */ #if ATTEMPTS_MIN < TMP_MAX const unsigned int attempts = TMP_MAX; #else const unsigned int attempts = ATTEMPTS_MIN; #endif const int len = strlen(tmpl); if ((len - suffixlen) < 6 || strncmp(&tmpl[len - 6 - suffixlen], "XXXXXX", 6)) { errno = EINVAL; return nullptr; } /* This is where the Xs start. */ char *XXXXXX = &tmpl[len - 6 - suffixlen]; /* Get some more or less random data. */ #ifdef US_PLATFORM_WINDOWS { SYSTEMTIME stNow; FILETIME ftNow; // get system time GetSystemTime(&stNow); stNow.wMilliseconds = 500; if (!SystemTimeToFileTime(&stNow, &ftNow)) { errno = -1; return nullptr; } unsigned long long randomTimeBits = ((static_cast(ftNow.dwHighDateTime) << 32) | static_cast(ftNow.dwLowDateTime)); value = randomTimeBits ^ static_cast(GetCurrentThreadId()); } #else { struct timeval tv; gettimeofday(&tv, nullptr); unsigned long long randomTimeBits = ((static_cast(tv.tv_usec) << 32) | static_cast(tv.tv_sec)); value = randomTimeBits ^ static_cast(getpid()); } #endif unsigned int count = 0; for (; count < attempts; value += 7777, ++count) { unsigned long long v = value; /* Fill in the random bits. */ XXXXXX[0] = validLetters[v % 62]; v /= 62; XXXXXX[1] = validLetters[v % 62]; v /= 62; XXXXXX[2] = validLetters[v % 62]; v /= 62; XXXXXX[3] = validLetters[v % 62]; v /= 62; XXXXXX[4] = validLetters[v % 62]; v /= 62; XXXXXX[5] = validLetters[v % 62]; #ifdef US_PLATFORM_WINDOWS int fd = _mkdir(tmpl); //, _S_IREAD | _S_IWRITE | _S_IEXEC); #else int fd = mkdir(tmpl, S_IRUSR | S_IWUSR | S_IXUSR); #endif if (fd >= 0) { errno = savedErrno; return tmpl; } else if (errno != EEXIST) { return nullptr; } } /* We got out of the loop because we ran out of combinations to try. */ errno = EEXIST; return nullptr; } //#endif //************************************************************** // mitk::IOUtil method definitions namespace mitk { struct IOUtil::Impl { struct FixedReaderOptionsFunctor : public ReaderOptionsFunctorBase { FixedReaderOptionsFunctor(const IFileReader::Options &options) : m_Options(options) {} bool operator()(LoadInfo &loadInfo) const override { IFileReader *reader = loadInfo.m_ReaderSelector.GetSelected().GetReader(); if (reader) { reader->SetOptions(m_Options); } return false; } private: const IFileReader::Options &m_Options; }; struct FixedWriterOptionsFunctor : public WriterOptionsFunctorBase { FixedWriterOptionsFunctor(const IFileReader::Options &options) : m_Options(options) {} bool operator()(SaveInfo &saveInfo) const override { IFileWriter *writer = saveInfo.m_WriterSelector.GetSelected().GetWriter(); if (writer) { writer->SetOptions(m_Options); } return false; } private: const IFileWriter::Options &m_Options; }; static BaseData::Pointer LoadBaseDataFromFile(const std::string &path, const ReaderOptionsFunctorBase* optionsCallback = nullptr); }; BaseData::Pointer IOUtil::Impl::LoadBaseDataFromFile(const std::string &path, const ReaderOptionsFunctorBase *optionsCallback) { std::vector baseDataList = Load(path, optionsCallback); // The Load(path) call above should throw an exception if nothing could be loaded assert(!baseDataList.empty()); return baseDataList.front(); } #ifdef US_PLATFORM_WINDOWS std::string IOUtil::GetProgramPath() { char path[512]; std::size_t index = std::string(path, GetModuleFileName(nullptr, path, 512)).find_last_of('\\'); return std::string(path, index); } #elif defined(US_PLATFORM_APPLE) #include std::string IOUtil::GetProgramPath() { char path[512]; uint32_t size = sizeof(path); if (_NSGetExecutablePath(path, &size) == 0) { std::size_t index = std::string(path).find_last_of('/'); std::string strPath = std::string(path, index); // const char* execPath = strPath.c_str(); // mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch(execPath,false); return strPath; } return std::string(); } #else #include #include #include std::string IOUtil::GetProgramPath() { std::stringstream ss; ss << "/proc/" << getpid() << "/exe"; char proc[512] = {0}; ssize_t ch = readlink(ss.str().c_str(), proc, 512); if (ch == -1) return std::string(); std::size_t index = std::string(proc).find_last_of('/'); return std::string(proc, index); } #endif char IOUtil::GetDirectorySeparator() { #ifdef US_PLATFORM_WINDOWS return '\\'; #else return '/'; #endif } std::string IOUtil::GetTempPath() { static std::string result; if (result.empty()) { #ifdef US_PLATFORM_WINDOWS char tempPathTestBuffer[1]; DWORD bufferLength = GetTempPathA(1, tempPathTestBuffer); if (bufferLength == 0) { mitkThrow() << GetLastErrorStr(); } std::vector tempPath(bufferLength); bufferLength = GetTempPathA(bufferLength, &tempPath[0]); if (bufferLength == 0) { mitkThrow() << GetLastErrorStr(); } result.assign(tempPath.begin(), tempPath.begin() + static_cast(bufferLength)); #else result = "/tmp/"; #endif } return result; } std::string IOUtil::CreateTemporaryFile(const std::string &templateName, std::string path) { std::ofstream tmpOutputStream; std::string returnValue = CreateTemporaryFile(tmpOutputStream, templateName, path); tmpOutputStream.close(); return returnValue; } std::string IOUtil::CreateTemporaryFile(std::ofstream &f, const std::string &templateName, std::string path) { return CreateTemporaryFile(f, std::ios_base::out | std::ios_base::trunc, templateName, path); } std::string IOUtil::CreateTemporaryFile(std::ofstream &f, std::ios_base::openmode mode, const std::string &templateName, std::string path) { if (path.empty()) { path = GetTempPath(); } path += templateName; std::vector dst_path(path.begin(), path.end()); dst_path.push_back('\0'); std::size_t lastX = path.find_last_of('X'); std::size_t firstX = path.find_last_not_of('X', lastX); int firstNonX = firstX == std::string::npos ? -1 : firstX - 1; while (lastX != std::string::npos && (lastX - firstNonX) < 6) { lastX = path.find_last_of('X', firstX); firstX = path.find_last_not_of('X', lastX); firstNonX = firstX == std::string::npos ? -1 : firstX - 1; } std::size_t suffixlen = lastX == std::string::npos ? path.size() : path.size() - lastX - 1; int fd = mkstemps_compat(&dst_path[0], suffixlen); if (fd != -1) { path.assign(dst_path.begin(), dst_path.end() - 1); f.open(path.c_str(), mode | std::ios_base::out | std::ios_base::trunc); close(fd); } else { mitkThrow() << "Creating temporary file " << &dst_path[0] << " failed: " << GetLastErrorStr(); } return path; } std::string IOUtil::CreateTemporaryDirectory(const std::string &templateName, std::string path) { if (path.empty()) { path = GetTempPath(); } path += GetDirectorySeparator() + templateName; std::vector dst_path(path.begin(), path.end()); dst_path.push_back('\0'); std::size_t lastX = path.find_last_of('X'); std::size_t firstX = path.find_last_not_of('X', lastX); int firstNonX = firstX == std::string::npos ? -1 : firstX - 1; while (lastX != std::string::npos && (lastX - firstNonX) < 6) { lastX = path.find_last_of('X', firstX); firstX = path.find_last_not_of('X', lastX); firstNonX = firstX == std::string::npos ? -1 : firstX - 1; } std::size_t suffixlen = lastX == std::string::npos ? path.size() : path.size() - lastX - 1; if (mkdtemps_compat(&dst_path[0], suffixlen) == nullptr) { mitkThrow() << "Creating temporary directory " << &dst_path[0] << " failed: " << GetLastErrorStr(); } path.assign(dst_path.begin(), dst_path.end() - 1); return path; } DataStorage::SetOfObjects::Pointer IOUtil::Load(const std::string &path, DataStorage &storage, const ReaderOptionsFunctorBase *optionsCallback) { std::vector paths; paths.push_back(path); return Load(paths, storage, optionsCallback); } DataStorage::SetOfObjects::Pointer IOUtil::Load(const std::string &path, const IFileReader::Options &options, DataStorage &storage) { std::vector loadInfos; loadInfos.push_back(LoadInfo(path)); DataStorage::SetOfObjects::Pointer nodeResult = DataStorage::SetOfObjects::New(); Impl::FixedReaderOptionsFunctor optionsCallback(options); std::string errMsg = Load(loadInfos, nodeResult, &storage, &optionsCallback); if (!errMsg.empty()) { mitkThrow() << errMsg; } return nodeResult; } std::vector IOUtil::Load(const std::string &path, const ReaderOptionsFunctorBase *optionsCallback) { std::vector paths; paths.push_back(path); return Load(paths, optionsCallback); } std::vector IOUtil::Load(const std::string &path, const IFileReader::Options &options) { std::vector loadInfos; loadInfos.push_back(LoadInfo(path)); Impl::FixedReaderOptionsFunctor optionsCallback(options); std::string errMsg = Load(loadInfos, nullptr, nullptr, &optionsCallback); if (!errMsg.empty()) { mitkThrow() << errMsg; } return loadInfos.front().m_Output; } DataStorage::SetOfObjects::Pointer IOUtil::Load(const std::vector &paths, DataStorage &storage, const ReaderOptionsFunctorBase *optionsCallback) { DataStorage::SetOfObjects::Pointer nodeResult = DataStorage::SetOfObjects::New(); std::vector loadInfos; for (const auto &loadInfo : paths) { loadInfos.emplace_back(loadInfo); } std::string errMsg = Load(loadInfos, nodeResult, &storage, optionsCallback); if (!errMsg.empty()) { mitkThrow() << errMsg; } return nodeResult; } std::vector IOUtil::Load(const std::vector &paths, const ReaderOptionsFunctorBase *optionsCallback) { std::vector result; std::vector loadInfos; for (const auto &loadInfo : paths) { loadInfos.emplace_back(loadInfo); } std::string errMsg = Load(loadInfos, nullptr, nullptr, optionsCallback); if (!errMsg.empty()) { mitkThrow() << errMsg; } for (std::vector::const_iterator iter = loadInfos.begin(), iterEnd = loadInfos.end(); iter != iterEnd; ++iter) { result.insert(result.end(), iter->m_Output.begin(), iter->m_Output.end()); } return result; } std::string IOUtil::Load(std::vector &loadInfos, DataStorage::SetOfObjects *nodeResult, DataStorage *ds, const ReaderOptionsFunctorBase *optionsCallback) { if (loadInfos.empty()) { return "No input files given"; } int filesToRead = loadInfos.size(); mitk::ProgressBar::GetInstance()->AddStepsToDo(2 * filesToRead); std::string errMsg; std::map usedReaderItems; std::vector< std::string > read_files; for (auto &loadInfo : loadInfos) { if(std::find(read_files.begin(), read_files.end(), loadInfo.m_Path) != read_files.end()) continue; std::vector readers = loadInfo.m_ReaderSelector.Get(); if (readers.empty()) { if (!itksys::SystemTools::FileExists(Utf8Util::Local8BitToUtf8(loadInfo.m_Path).c_str())) { errMsg += "File '" + loadInfo.m_Path + "' does not exist\n"; } else { errMsg += "No reader available for '" + loadInfo.m_Path + "'\n"; } continue; } bool callOptionsCallback = readers.size() > 1 || !readers.front().GetReader()->GetOptions().empty(); // check if we already used a reader which should be re-used std::vector currMimeTypes = loadInfo.m_ReaderSelector.GetMimeTypes(); std::string selectedMimeType; for (std::vector::const_iterator mimeTypeIter = currMimeTypes.begin(), mimeTypeIterEnd = currMimeTypes.end(); mimeTypeIter != mimeTypeIterEnd; ++mimeTypeIter) { std::map::const_iterator oldSelectedItemIter = usedReaderItems.find(mimeTypeIter->GetName()); if (oldSelectedItemIter != usedReaderItems.end()) { // we found an already used item for a mime-type which is contained // in the current reader set, check all current readers if there service // id equals the old reader for (std::vector::const_iterator currReaderItem = readers.begin(), currReaderItemEnd = readers.end(); currReaderItem != currReaderItemEnd; ++currReaderItem) { if (currReaderItem->GetMimeType().GetName() == mimeTypeIter->GetName() && currReaderItem->GetServiceId() == oldSelectedItemIter->second.GetServiceId() && currReaderItem->GetConfidenceLevel() >= oldSelectedItemIter->second.GetConfidenceLevel()) { // okay, we used the same reader already, re-use its options selectedMimeType = mimeTypeIter->GetName(); callOptionsCallback = false; loadInfo.m_ReaderSelector.Select(oldSelectedItemIter->second.GetServiceId()); loadInfo.m_ReaderSelector.GetSelected().GetReader()->SetOptions( oldSelectedItemIter->second.GetReader()->GetOptions()); break; } } if (!selectedMimeType.empty()) break; } } if (callOptionsCallback && optionsCallback) { callOptionsCallback = (*optionsCallback)(loadInfo); if (!callOptionsCallback && !loadInfo.m_Cancel) { usedReaderItems.erase(selectedMimeType); FileReaderSelector::Item selectedItem = loadInfo.m_ReaderSelector.GetSelected(); usedReaderItems.insert(std::make_pair(selectedItem.GetMimeType().GetName(), selectedItem)); } } if (loadInfo.m_Cancel) { errMsg += "Reading operation(s) cancelled."; break; } IFileReader *reader = loadInfo.m_ReaderSelector.GetSelected().GetReader(); if (reader == nullptr) { errMsg += "Unexpected nullptr reader."; break; } reader->SetProperties(loadInfo.m_Properties); // Do the actual reading try { DataStorage::SetOfObjects::Pointer nodes; if (ds != nullptr) { nodes = reader->Read(*ds); std::vector< std::string > new_files = reader->GetReadFiles(); read_files.insert( read_files.end(), new_files.begin(), new_files.end() ); } else { nodes = DataStorage::SetOfObjects::New(); std::vector baseData = reader->Read(); for (auto iter = baseData.begin(); iter != baseData.end(); ++iter) { if (iter->IsNotNull()) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(*iter); nodes->InsertElement(nodes->Size(), node); } } std::vector< std::string > new_files = reader->GetReadFiles(); read_files.insert( read_files.end(), new_files.begin(), new_files.end() ); } for (DataStorage::SetOfObjects::ConstIterator nodeIter = nodes->Begin(), nodeIterEnd = nodes->End(); nodeIter != nodeIterEnd; ++nodeIter) { const mitk::DataNode::Pointer &node = nodeIter->Value(); mitk::BaseData::Pointer data = node->GetData(); if (data.IsNull()) { continue; } data->SetProperty("path", mitk::StringProperty::New(Utf8Util::Local8BitToUtf8(loadInfo.m_Path))); loadInfo.m_Output.push_back(data); if (nodeResult) { nodeResult->push_back(nodeIter->Value()); } } if (loadInfo.m_Output.empty() || (nodeResult && nodeResult->Size() == 0)) { errMsg += "Unknown read error occurred reading " + loadInfo.m_Path; } } catch (const std::exception &e) { errMsg += "Exception occurred when reading file " + loadInfo.m_Path + ":\n" + e.what() + "\n\n"; } mitk::ProgressBar::GetInstance()->Progress(2); --filesToRead; } if (!errMsg.empty()) { MITK_ERROR << errMsg; } mitk::ProgressBar::GetInstance()->Progress(2 * filesToRead); return errMsg; } std::vector IOUtil::Load(const us::ModuleResource &usResource, std::ios_base::openmode mode) { us::ModuleResourceStream resStream(usResource, mode); mitk::CoreServicePointer mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider()); std::vector mimetypes = mimeTypeProvider->GetMimeTypesForFile(usResource.GetResourcePath()); std::vector data; if (mimetypes.empty()) { mitkThrow() << "No mimetype for resource stream: " << usResource.GetResourcePath(); return data; } mitk::FileReaderRegistry fileReaderRegistry; std::vector> refs = fileReaderRegistry.GetReferences(mimetypes[0]); if (refs.empty()) { mitkThrow() << "No reader available for resource stream: " << usResource.GetResourcePath(); return data; } mitk::IFileReader *reader = fileReaderRegistry.GetReader(refs[0]); reader->SetInput(usResource.GetResourcePath(), &resStream); data = reader->Read(); return data; } BaseData::Pointer IOUtil::Load(const std::string& path, const PropertyList* properties) { LoadInfo loadInfo(path); loadInfo.m_Properties = properties; std::vector loadInfos; loadInfos.push_back(loadInfo); auto errMsg = Load(loadInfos, nullptr, nullptr, nullptr); if (!errMsg.empty()) mitkThrow() << errMsg; return loadInfos.front().m_Output.front(); } void IOUtil::Save(const BaseData *data, const std::string &path, bool setPathProperty) { Save(data, path, IFileWriter::Options(), setPathProperty); } void IOUtil::Save(const BaseData *data, const std::string &path, const IFileWriter::Options &options, bool setPathProperty) { Save(data, std::string(), path, options, setPathProperty); } void IOUtil::Save(const BaseData *data, const std::string &mimeType, const std::string &path, bool addExtension, bool setPathProperty) { Save(data, mimeType, path, IFileWriter::Options(), addExtension, setPathProperty); } void IOUtil::Save(const BaseData *data, const std::string &mimeType, const std::string &path, const IFileWriter::Options &options, bool addExtension, bool setPathProperty) { if ((data == nullptr) || (data->IsEmpty())) - mitkThrow() << "BaseData cannotbe null or empty for save methods in IOUtil.h."; + mitkThrow() << "BaseData cannot be null or empty for save methods in IOUtil.h."; std::string errMsg; if (options.empty()) { errMsg = Save(data, mimeType, path, nullptr, addExtension, setPathProperty); } else { Impl::FixedWriterOptionsFunctor optionsCallback(options); errMsg = Save(data, mimeType, path, &optionsCallback, addExtension, setPathProperty); } if (!errMsg.empty()) { mitkThrow() << errMsg; } } void IOUtil::Save(std::vector &saveInfos, bool setPathProperty) { std::string errMsg = Save(saveInfos, nullptr, setPathProperty); if (!errMsg.empty()) { mitkThrow() << errMsg; } } std::string IOUtil::Save(const BaseData *data, const std::string &mimeTypeName, const std::string &path, WriterOptionsFunctorBase *optionsCallback, bool addExtension, bool setPathProperty) { if (path.empty()) { return "No output filename given"; } mitk::CoreServicePointer mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider()); MimeType mimeType = mimeTypeProvider->GetMimeTypeForName(mimeTypeName); SaveInfo saveInfo(data, mimeType, path); std::string ext = Utf8Util::Utf8ToLocal8Bit(itksys::SystemTools::GetFilenameExtension(Utf8Util::Local8BitToUtf8(path))); if (saveInfo.m_WriterSelector.IsEmpty()) { return std::string("No suitable writer found for the current data of type ") + data->GetNameOfClass() + (mimeType.IsValid() ? (std::string(" and mime-type ") + mimeType.GetName()) : std::string()) + (ext.empty() ? std::string() : (std::string(" with extension ") + ext)); } // Add an extension if not already specified if (ext.empty() && addExtension) { ext = saveInfo.m_MimeType.GetExtensions().empty() ? std::string() : "." + saveInfo.m_MimeType.GetExtensions().front(); saveInfo.m_Path += ext; } std::vector infos; infos.push_back(saveInfo); return Save(infos, optionsCallback, setPathProperty); } std::string IOUtil::Save(std::vector &saveInfos, WriterOptionsFunctorBase *optionsCallback, bool setPathProperty) { if (saveInfos.empty()) { return "No data for saving available"; } int filesToWrite = saveInfos.size(); mitk::ProgressBar::GetInstance()->AddStepsToDo(2 * filesToWrite); std::string errMsg; std::set usedSaveInfos; for (auto &saveInfo : saveInfos) { const std::string baseDataType = saveInfo.m_BaseData->GetNameOfClass(); std::vector writers = saveInfo.m_WriterSelector.Get(); // Error out if no compatible Writer was found if (writers.empty()) { errMsg += std::string("No writer available for ") + baseDataType + " data.\n"; continue; } bool callOptionsCallback = writers.size() > 1 || !writers[0].GetWriter()->GetOptions().empty(); // check if we already used a writer for this base data type // which should be re-used auto oldSaveInfoIter = usedSaveInfos.find(saveInfo); if (oldSaveInfoIter != usedSaveInfos.end()) { // we previously saved a base data object of the same data with the same mime-type, // check if the same writer is contained in the current writer set and if the // confidence level matches FileWriterSelector::Item oldSelectedItem = oldSaveInfoIter->m_WriterSelector.Get(oldSaveInfoIter->m_WriterSelector.GetSelectedId()); for (std::vector::const_iterator currWriterItem = writers.begin(), currWriterItemEnd = writers.end(); currWriterItem != currWriterItemEnd; ++currWriterItem) { if (currWriterItem->GetServiceId() == oldSelectedItem.GetServiceId() && currWriterItem->GetConfidenceLevel() >= oldSelectedItem.GetConfidenceLevel()) { // okay, we used the same writer already, re-use its options callOptionsCallback = false; saveInfo.m_WriterSelector.Select(oldSaveInfoIter->m_WriterSelector.GetSelectedId()); saveInfo.m_WriterSelector.GetSelected().GetWriter()->SetOptions(oldSelectedItem.GetWriter()->GetOptions()); break; } } } if (callOptionsCallback && optionsCallback) { callOptionsCallback = (*optionsCallback)(saveInfo); if (!callOptionsCallback && !saveInfo.m_Cancel) { usedSaveInfos.erase(saveInfo); usedSaveInfos.insert(saveInfo); } } if (saveInfo.m_Cancel) { errMsg += "Writing operation(s) cancelled."; break; } IFileWriter *writer = saveInfo.m_WriterSelector.GetSelected().GetWriter(); if (writer == nullptr) { errMsg += "Unexpected nullptr writer."; break; } // Do the actual writing try { writer->SetOutputLocation(saveInfo.m_Path); writer->Write(); } catch (const std::exception &e) { errMsg += std::string("Exception occurred when writing to ") + saveInfo.m_Path + ":\n" + e.what() + "\n"; } if (setPathProperty) saveInfo.m_BaseData->GetPropertyList()->SetStringProperty("path", Utf8Util::Local8BitToUtf8(saveInfo.m_Path).c_str()); mitk::ProgressBar::GetInstance()->Progress(2); --filesToWrite; } if (!errMsg.empty()) { MITK_ERROR << errMsg; } mitk::ProgressBar::GetInstance()->Progress(2 * filesToWrite); return errMsg; } IOUtil::SaveInfo::SaveInfo(const BaseData *baseData, const MimeType &mimeType, const std::string &path) : m_BaseData(baseData), m_WriterSelector(baseData, mimeType.GetName(), path), m_MimeType(mimeType.IsValid() ? mimeType // use the original mime-type : (m_WriterSelector.IsEmpty() ? mimeType // no writer found, use the original invalid mime-type : m_WriterSelector.GetDefault().GetMimeType() // use the found default mime-type )), m_Path(path), m_Cancel(false) { } bool IOUtil::SaveInfo::operator<(const IOUtil::SaveInfo &other) const { int r = strcmp(m_BaseData->GetNameOfClass(), other.m_BaseData->GetNameOfClass()); if (r == 0) { return m_WriterSelector.GetSelected().GetMimeType() < other.m_WriterSelector.GetSelected().GetMimeType(); } return r < 0; } IOUtil::LoadInfo::LoadInfo(const std::string &path) : m_Path(path), m_ReaderSelector(path), m_Cancel(false), m_Properties(nullptr) { } } diff --git a/Modules/Core/src/Rendering/mitkBaseRenderer.cpp b/Modules/Core/src/Rendering/mitkBaseRenderer.cpp index 69a07fbffd..e692289a1d 100644 --- a/Modules/Core/src/Rendering/mitkBaseRenderer.cpp +++ b/Modules/Core/src/Rendering/mitkBaseRenderer.cpp @@ -1,732 +1,756 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkBaseRenderer.h" #include "mitkMapper.h" #include "mitkResliceMethodProperty.h" // Geometries #include "mitkSlicedGeometry3D.h" #include "mitkVtkLayerController.h" #include "mitkInteractionConst.h" #include "mitkProperties.h" #include "mitkWeakPointerProperty.h" // VTK #include #include #include #include #include namespace mitk { itkEventMacroDefinition(RendererResetEvent, itk::AnyEvent); } mitk::BaseRenderer::BaseRendererMapType mitk::BaseRenderer::baseRendererMap; mitk::BaseRenderer *mitk::BaseRenderer::GetInstance(vtkRenderWindow *renWin) { for (auto mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) { if ((*mapit).first == renWin) return (*mapit).second; } return nullptr; } void mitk::BaseRenderer::AddInstance(vtkRenderWindow *renWin, BaseRenderer *baseRenderer) { if (renWin == nullptr || baseRenderer == nullptr) return; // ensure that no BaseRenderer is managed twice mitk::BaseRenderer::RemoveInstance(renWin); baseRendererMap.insert(BaseRendererMapType::value_type(renWin, baseRenderer)); } void mitk::BaseRenderer::RemoveInstance(vtkRenderWindow *renWin) { auto mapit = baseRendererMap.find(renWin); if (mapit != baseRendererMap.end()) baseRendererMap.erase(mapit); } mitk::BaseRenderer *mitk::BaseRenderer::GetByName(const std::string &name) { for (auto mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) { if ((*mapit).second->m_Name == name) return (*mapit).second; } return nullptr; } vtkRenderWindow *mitk::BaseRenderer::GetRenderWindowByName(const std::string &name) { for (auto mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) { if ((*mapit).second->m_Name == name) return (*mapit).first; } return nullptr; } +mitk::BaseRenderer::BaseRendererMapType mitk::BaseRenderer::GetSpecificRenderWindows(MapperSlotId mapper) +{ + BaseRendererMapType allRenderWindows; + for (auto mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) + { + if (mapper == mapit->second->GetMapperID()) + { + allRenderWindows.insert(BaseRendererMapType::value_type(mapit->first, mapit->second)); + } + } + + return allRenderWindows; +} + +mitk::BaseRenderer::BaseRendererMapType mitk::BaseRenderer::GetAll2DRenderWindows() +{ + return GetSpecificRenderWindows(BaseRenderer::Standard2D); +} + +mitk::BaseRenderer::BaseRendererMapType mitk::BaseRenderer::GetAll3DRenderWindows() +{ + return GetSpecificRenderWindows(BaseRenderer::Standard3D); +} + mitk::BaseRenderer::BaseRenderer(const char *name, vtkRenderWindow *renWin) : m_RenderWindow(nullptr), m_VtkRenderer(nullptr), m_MapperID(StandardMapperSlot::Standard2D), m_DataStorage(nullptr), m_LastUpdateTime(0), m_CameraController(nullptr), m_CameraRotationController(nullptr), m_SliceNavigationController(nullptr), m_WorldTimeGeometry(nullptr), m_CurrentWorldGeometry(nullptr), m_CurrentWorldPlaneGeometry(nullptr), m_Slice(0), m_TimeStep(), m_CurrentWorldPlaneGeometryUpdateTime(), m_TimeStepUpdateTime(), m_KeepDisplayedRegion(true), m_CurrentWorldPlaneGeometryData(nullptr), m_CurrentWorldPlaneGeometryNode(nullptr), m_CurrentWorldPlaneGeometryTransformTime(0), m_Name(name), m_EmptyWorldGeometry(true), m_NumberOfVisibleLODEnabledMappers(0) { m_Bounds[0] = 0; m_Bounds[1] = 0; m_Bounds[2] = 0; m_Bounds[3] = 0; m_Bounds[4] = 0; m_Bounds[5] = 0; if (name != nullptr) { m_Name = name; } else { m_Name = "unnamed renderer"; itkWarningMacro(<< "Created unnamed renderer. Bad for serialization. Please choose a name."); } if (renWin != nullptr) { m_RenderWindow = renWin; m_RenderWindow->Register(nullptr); } else { itkWarningMacro(<< "Created mitkBaseRenderer without vtkRenderWindow present."); } // instances.insert( this ); // adding this BaseRenderer to the List of all BaseRenderer m_BindDispatcherInteractor = new mitk::BindDispatcherInteractor(GetName()); WeakPointerProperty::Pointer rendererProp = WeakPointerProperty::New((itk::Object *)this); m_CurrentWorldPlaneGeometry = mitk::PlaneGeometry::New(); m_CurrentWorldPlaneGeometryData = mitk::PlaneGeometryData::New(); m_CurrentWorldPlaneGeometryData->SetPlaneGeometry(m_CurrentWorldPlaneGeometry); m_CurrentWorldPlaneGeometryNode = mitk::DataNode::New(); m_CurrentWorldPlaneGeometryNode->SetData(m_CurrentWorldPlaneGeometryData); m_CurrentWorldPlaneGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp); m_CurrentWorldPlaneGeometryNode->GetPropertyList()->SetProperty("layer", IntProperty::New(1000)); m_CurrentWorldPlaneGeometryNode->SetProperty("reslice.thickslices", mitk::ResliceMethodProperty::New()); m_CurrentWorldPlaneGeometryNode->SetProperty("reslice.thickslices.num", mitk::IntProperty::New(1)); m_CurrentWorldPlaneGeometryTransformTime = m_CurrentWorldPlaneGeometryNode->GetVtkTransform()->GetMTime(); m_SliceNavigationController = mitk::SliceNavigationController::New(); m_SliceNavigationController->SetRenderer(this); m_SliceNavigationController->ConnectGeometrySendEvent(this); m_SliceNavigationController->ConnectGeometryUpdateEvent(this); m_SliceNavigationController->ConnectGeometrySliceEvent(this); m_SliceNavigationController->ConnectGeometryTimeEvent(this); m_CameraRotationController = mitk::CameraRotationController::New(); m_CameraRotationController->SetRenderWindow(m_RenderWindow); m_CameraRotationController->AcquireCamera(); m_CameraController = mitk::CameraController::New(); m_CameraController->SetRenderer(this); m_VtkRenderer = vtkRenderer::New(); m_VtkRenderer->SetMaximumNumberOfPeels(16); if (AntiAliasing::FastApproximate == RenderingManager::GetInstance()->GetAntiAliasing()) m_VtkRenderer->UseFXAAOn(); if (nullptr == mitk::VtkLayerController::GetInstance(m_RenderWindow)) mitk::VtkLayerController::AddInstance(m_RenderWindow, m_VtkRenderer); mitk::VtkLayerController::GetInstance(m_RenderWindow)->InsertSceneRenderer(m_VtkRenderer); } mitk::BaseRenderer::~BaseRenderer() { if (m_VtkRenderer != nullptr) { m_VtkRenderer->Delete(); m_VtkRenderer = nullptr; } if (m_CameraController.IsNotNull()) m_CameraController->SetRenderer(nullptr); mitk::VtkLayerController::RemoveInstance(m_RenderWindow); RemoveAllLocalStorages(); m_DataStorage = nullptr; if (m_BindDispatcherInteractor != nullptr) { delete m_BindDispatcherInteractor; } if (m_RenderWindow != nullptr) { m_RenderWindow->Delete(); m_RenderWindow = nullptr; } } void mitk::BaseRenderer::RemoveAllLocalStorages() { this->InvokeEvent(RendererResetEvent()); std::list::iterator it; for (it = m_RegisteredLocalStorageHandlers.begin(); it != m_RegisteredLocalStorageHandlers.end(); ++it) (*it)->ClearLocalStorage(this, false); m_RegisteredLocalStorageHandlers.clear(); } void mitk::BaseRenderer::RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh) { m_RegisteredLocalStorageHandlers.push_back(lsh); } void mitk::BaseRenderer::UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh) { m_RegisteredLocalStorageHandlers.remove(lsh); } void mitk::BaseRenderer::SetDataStorage(DataStorage *storage) { if (storage != m_DataStorage && storage != nullptr) { m_DataStorage = storage; m_BindDispatcherInteractor->SetDataStorage(m_DataStorage); this->Modified(); } } mitk::Dispatcher::Pointer mitk::BaseRenderer::GetDispatcher() const { return m_BindDispatcherInteractor->GetDispatcher(); } void mitk::BaseRenderer::Resize(int w, int h) { m_RenderWindow->SetSize(w, h); } void mitk::BaseRenderer::InitRenderer(vtkRenderWindow *renderwindow) { if (m_RenderWindow != renderwindow) { if (m_RenderWindow != nullptr) { m_RenderWindow->Delete(); } m_RenderWindow = renderwindow; if (m_RenderWindow != nullptr) { m_RenderWindow->Register(nullptr); } } RemoveAllLocalStorages(); if (m_CameraController.IsNotNull()) { m_CameraController->SetRenderer(this); } } void mitk::BaseRenderer::InitSize(int w, int h) { m_RenderWindow->SetSize(w, h); } void mitk::BaseRenderer::SetWorldTimeGeometry(const mitk::TimeGeometry* geometry) { if (m_WorldTimeGeometry == geometry) { return; } m_WorldTimeGeometry = geometry; this->UpdateCurrentGeometries(); } void mitk::BaseRenderer::SetSlice(unsigned int slice) { if (m_Slice == slice) { return; } m_Slice = slice; this->UpdateCurrentGeometries(); } void mitk::BaseRenderer::SetTimeStep(unsigned int timeStep) { if (m_TimeStep == timeStep) { return; } m_TimeStep = timeStep; m_TimeStepUpdateTime.Modified(); this->UpdateCurrentGeometries(); } mitk::TimeStepType mitk::BaseRenderer::GetTimeStep(const mitk::BaseData* data) const { if ((data == nullptr) || (data->IsInitialized() == false)) { return -1; } return data->GetTimeGeometry()->TimePointToTimeStep(GetTime()); } mitk::ScalarType mitk::BaseRenderer::GetTime() const { if (m_WorldTimeGeometry.IsNull()) { return 0; } else { ScalarType timeInMS = m_WorldTimeGeometry->TimeStepToTimePoint(GetTimeStep()); if (timeInMS == itk::NumericTraits::NonpositiveMin()) return 0; else return timeInMS; } } void mitk::BaseRenderer::SetGeometry(const itk::EventObject& geometrySendEvent) { const auto* sendEvent = dynamic_cast(&geometrySendEvent); if (nullptr == sendEvent) { return; } SetWorldTimeGeometry(sendEvent->GetTimeGeometry()); } void mitk::BaseRenderer::UpdateGeometry(const itk::EventObject& geometryUpdateEvent) { const auto* updateEvent = dynamic_cast(&geometryUpdateEvent); if (nullptr == updateEvent) { return; } if (m_CurrentWorldGeometry.IsNull()) { return; } const auto* slicedWorldGeometry = dynamic_cast(m_CurrentWorldGeometry.GetPointer()); if (slicedWorldGeometry) { PlaneGeometry* geometry2D = slicedWorldGeometry->GetPlaneGeometry(m_Slice); SetCurrentWorldPlaneGeometry(geometry2D); // calls Modified() } } void mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject& geometrySliceEvent) { const auto* sliceEvent = dynamic_cast(&geometrySliceEvent); if (nullptr == sliceEvent) { return; } this->SetSlice(sliceEvent->GetPos()); } void mitk::BaseRenderer::SetGeometryTime(const itk::EventObject& geometryTimeEvent) { const auto* timeEvent = dynamic_cast(&geometryTimeEvent); if (nullptr == timeEvent) { return; } this->SetTimeStep(timeEvent->GetPos()); } void mitk::BaseRenderer::SendUpdateSlice() { m_CurrentWorldPlaneGeometryUpdateTime.Modified(); } void mitk::BaseRenderer::SetMapperID(MapperSlotId id) { if (m_MapperID != id) { bool useDepthPeeling = Standard3D == id; m_VtkRenderer->SetUseDepthPeeling(useDepthPeeling); m_VtkRenderer->SetUseDepthPeelingForVolumes(useDepthPeeling); m_MapperID = id; this->Modified(); } } int* mitk::BaseRenderer::GetSize() const { return m_RenderWindow->GetSize(); } int* mitk::BaseRenderer::GetViewportSize() const { return m_VtkRenderer->GetSize(); } const double* mitk::BaseRenderer::GetBounds() const { return m_Bounds; } void mitk::BaseRenderer::RequestUpdate() { SetConstrainZoomingAndPanning(true); RenderingManager::GetInstance()->RequestUpdate(m_RenderWindow); } void mitk::BaseRenderer::ForceImmediateUpdate() { RenderingManager::GetInstance()->ForceImmediateUpdate(m_RenderWindow); } unsigned int mitk::BaseRenderer::GetNumberOfVisibleLODEnabledMappers() const { return m_NumberOfVisibleLODEnabledMappers; } void mitk::BaseRenderer::SetSliceNavigationController(mitk::SliceNavigationController *SlicenavigationController) { if (SlicenavigationController == nullptr) return; // copy worldgeometry SlicenavigationController->SetInputWorldTimeGeometry(SlicenavigationController->GetCreatedWorldGeometry()); SlicenavigationController->Update(); // set new m_SliceNavigationController = SlicenavigationController; m_SliceNavigationController->SetRenderer(this); if (m_SliceNavigationController.IsNotNull()) { m_SliceNavigationController->ConnectGeometrySendEvent(this); m_SliceNavigationController->ConnectGeometryUpdateEvent(this); m_SliceNavigationController->ConnectGeometrySliceEvent(this); m_SliceNavigationController->ConnectGeometryTimeEvent(this); } } void mitk::BaseRenderer::DisplayToWorld(const Point2D& displayPoint, Point3D& worldIndex) const { if (m_MapperID == BaseRenderer::Standard2D) { double display[3], * world; // For the right z-position in display coordinates, take the focal point, convert it to display and use it for // correct depth. double* displayCoord; double cameraFP[4]; // Get camera focal point and position. Convert to display (screen) // coordinates. We need a depth value for z-buffer. this->GetVtkRenderer()->GetActiveCamera()->GetFocalPoint(cameraFP); cameraFP[3] = 0.0; this->GetVtkRenderer()->SetWorldPoint(cameraFP[0], cameraFP[1], cameraFP[2], cameraFP[3]); this->GetVtkRenderer()->WorldToDisplay(); displayCoord = this->GetVtkRenderer()->GetDisplayPoint(); // now convert the display point to world coordinates display[0] = displayPoint[0]; display[1] = displayPoint[1]; display[2] = displayCoord[2]; this->GetVtkRenderer()->SetDisplayPoint(display); this->GetVtkRenderer()->DisplayToWorld(); world = this->GetVtkRenderer()->GetWorldPoint(); for (int i = 0; i < 3; i++) { worldIndex[i] = world[i] / world[3]; } } else if (m_MapperID == BaseRenderer::Standard3D) { // Seems to be the same code as above, but subclasses may contain different implementations. PickWorldPoint(displayPoint, worldIndex); } return; } void mitk::BaseRenderer::DisplayToPlane(const Point2D &displayPoint, Point2D &planePointInMM) const { if (m_MapperID == BaseRenderer::Standard2D) { Point3D worldPoint; this->DisplayToWorld(displayPoint, worldPoint); m_CurrentWorldPlaneGeometry->Map(worldPoint, planePointInMM); } else if (m_MapperID == BaseRenderer::Standard3D) { MITK_WARN << "No conversion possible with 3D mapper."; return; } return; } void mitk::BaseRenderer::WorldToDisplay(const Point3D &worldIndex, Point2D &displayPoint) const { double world[4], *display; world[0] = worldIndex[0]; world[1] = worldIndex[1]; world[2] = worldIndex[2]; world[3] = 1.0; this->GetVtkRenderer()->SetWorldPoint(world); this->GetVtkRenderer()->WorldToDisplay(); display = this->GetVtkRenderer()->GetDisplayPoint(); displayPoint[0] = display[0]; displayPoint[1] = display[1]; return; } void mitk::BaseRenderer::WorldToView(const mitk::Point3D &worldIndex, mitk::Point2D &viewPoint) const { double world[4], *view; world[0] = worldIndex[0]; world[1] = worldIndex[1]; world[2] = worldIndex[2]; world[3] = 1.0; this->GetVtkRenderer()->SetWorldPoint(world); this->GetVtkRenderer()->WorldToView(); view = this->GetVtkRenderer()->GetViewPoint(); this->GetVtkRenderer()->ViewToNormalizedViewport(view[0], view[1], view[2]); viewPoint[0] = view[0] * this->GetViewportSize()[0]; viewPoint[1] = view[1] * this->GetViewportSize()[1]; return; } void mitk::BaseRenderer::PlaneToDisplay(const Point2D &planePointInMM, Point2D &displayPoint) const { Point3D worldPoint; m_CurrentWorldPlaneGeometry->Map(planePointInMM, worldPoint); this->WorldToDisplay(worldPoint, displayPoint); return; } void mitk::BaseRenderer::PlaneToView(const Point2D &planePointInMM, Point2D &viewPoint) const { Point3D worldPoint; m_CurrentWorldPlaneGeometry->Map(planePointInMM, worldPoint); this->WorldToView(worldPoint,viewPoint); return; } double mitk::BaseRenderer::GetScaleFactorMMPerDisplayUnit() const { if (this->GetMapperID() == BaseRenderer::Standard2D) { // GetParallelScale returns half of the height of the render window in mm. // Divided by the half size of the Display size in pixel givest the mm per pixel. return this->GetVtkRenderer()->GetActiveCamera()->GetParallelScale() * 2.0 / GetViewportSize()[1]; } else return 1.0; } mitk::Point2D mitk::BaseRenderer::GetDisplaySizeInMM() const { Point2D dispSizeInMM; dispSizeInMM[0] = GetSizeX() * GetScaleFactorMMPerDisplayUnit(); dispSizeInMM[1] = GetSizeY() * GetScaleFactorMMPerDisplayUnit(); return dispSizeInMM; } mitk::Point2D mitk::BaseRenderer::GetViewportSizeInMM() const { Point2D dispSizeInMM; dispSizeInMM[0] = GetViewportSize()[0] * GetScaleFactorMMPerDisplayUnit(); dispSizeInMM[1] = GetViewportSize()[1] * GetScaleFactorMMPerDisplayUnit(); return dispSizeInMM; } mitk::Point2D mitk::BaseRenderer::GetOriginInMM() const { Point2D originPx; originPx[0] = m_VtkRenderer->GetOrigin()[0]; originPx[1] = m_VtkRenderer->GetOrigin()[1]; Point2D displayGeometryOriginInMM; DisplayToPlane(originPx, displayGeometryOriginInMM); // top left of the render window (Origin) return displayGeometryOriginInMM; } void mitk::BaseRenderer::SetConstrainZoomingAndPanning(bool constrain) { m_ConstrainZoomingAndPanning = constrain; if (m_ConstrainZoomingAndPanning) { this->GetCameraController()->AdjustCameraToPlane(); } } void mitk::BaseRenderer::UpdateCurrentGeometries() { if (m_WorldTimeGeometry.IsNull()) { // simply mark the base renderer as modified Modified(); } if (m_TimeStep >= m_WorldTimeGeometry->CountTimeSteps()) { m_TimeStep = m_WorldTimeGeometry->CountTimeSteps() - 1; } auto slicedWorldGeometry = dynamic_cast(m_WorldTimeGeometry->GetGeometryForTimeStep(m_TimeStep).GetPointer()); if (slicedWorldGeometry != nullptr) { if (m_Slice >= slicedWorldGeometry->GetSlices()) { m_Slice = slicedWorldGeometry->GetSlices() - 1; } SetCurrentWorldGeometry(slicedWorldGeometry); SetCurrentWorldPlaneGeometry(slicedWorldGeometry->GetPlaneGeometry(m_Slice)); } } void mitk::BaseRenderer::SetCurrentWorldPlaneGeometry(const mitk::PlaneGeometry* geometry2d) { if (m_CurrentWorldPlaneGeometry == geometry2d) { return; } m_CurrentWorldPlaneGeometry = geometry2d->Clone(); m_CurrentWorldPlaneGeometryData->SetPlaneGeometry(m_CurrentWorldPlaneGeometry); m_CurrentWorldPlaneGeometryUpdateTime.Modified(); Modified(); } void mitk::BaseRenderer::SetCurrentWorldGeometry(const mitk::BaseGeometry* geometry) { if (m_CurrentWorldGeometry == geometry) { return; } m_CurrentWorldGeometry = geometry; if (geometry == nullptr) { m_Bounds[0] = 0; m_Bounds[1] = 0; m_Bounds[2] = 0; m_Bounds[3] = 0; m_Bounds[4] = 0; m_Bounds[5] = 0; m_EmptyWorldGeometry = true; return; } BoundingBox::Pointer boundingBox = m_CurrentWorldGeometry->CalculateBoundingBoxRelativeToTransform(nullptr); const BoundingBox::BoundsArrayType& worldBounds = boundingBox->GetBounds(); m_Bounds[0] = worldBounds[0]; m_Bounds[1] = worldBounds[1]; m_Bounds[2] = worldBounds[2]; m_Bounds[3] = worldBounds[3]; m_Bounds[4] = worldBounds[4]; m_Bounds[5] = worldBounds[5]; if (boundingBox->GetDiagonalLength2() <= mitk::eps) { m_EmptyWorldGeometry = true; } else { m_EmptyWorldGeometry = false; } } void mitk::BaseRenderer::PrintSelf(std::ostream &os, itk::Indent indent) const { os << indent << " MapperID: " << m_MapperID << std::endl; os << indent << " Slice: " << m_Slice << std::endl; os << indent << " TimeStep: " << m_TimeStep << std::endl; os << indent << " CurrentWorldPlaneGeometry: "; if (m_CurrentWorldPlaneGeometry.IsNull()) os << "nullptr" << std::endl; else m_CurrentWorldPlaneGeometry->Print(os, indent); os << indent << " CurrentWorldPlaneGeometryUpdateTime: " << m_CurrentWorldPlaneGeometryUpdateTime << std::endl; os << indent << " CurrentWorldPlaneGeometryTransformTime: " << m_CurrentWorldPlaneGeometryTransformTime << std::endl; Superclass::PrintSelf(os, indent); } diff --git a/Modules/Core/src/Rendering/mitkBaseRendererHelper.cpp b/Modules/Core/src/Rendering/mitkBaseRendererHelper.cpp index 98a3cca372..00f7396b25 100644 --- a/Modules/Core/src/Rendering/mitkBaseRendererHelper.cpp +++ b/Modules/Core/src/Rendering/mitkBaseRendererHelper.cpp @@ -1,62 +1,77 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkBaseRendererHelper.h" #include bool mitk::BaseRendererHelper::IsRendererAlignedWithSegmentation(BaseRenderer* renderer, const TimeGeometry* timeGeometry) { const BaseGeometry* renderWindowGeometry = renderer->GetCurrentWorldGeometry(); if (nullptr == renderWindowGeometry || nullptr == timeGeometry) { return false; } auto viewDirection = renderer->GetSliceNavigationController()->GetViewDirection(); TimeGeometry::Pointer orientedTimeGeometry; - switch (viewDirection) + try { - case mitk::SliceNavigationController::Original: - break; - case mitk::SliceNavigationController::Axial: - { - orientedTimeGeometry = SliceNavigationHelper::CreateOrientedTimeGeometry( - timeGeometry, PlaneGeometry::Axial, false, false, true); - break; - } - case mitk::SliceNavigationController::Coronal: - { - orientedTimeGeometry = SliceNavigationHelper::CreateOrientedTimeGeometry( - timeGeometry, PlaneGeometry::Coronal, false, true, false); - break; + switch (viewDirection) + { + case mitk::SliceNavigationController::Original: + break; + case mitk::SliceNavigationController::Axial: + { + orientedTimeGeometry = SliceNavigationHelper::CreateOrientedTimeGeometry( + timeGeometry, PlaneGeometry::Axial, false, false, true); + break; + } + case mitk::SliceNavigationController::Coronal: + { + orientedTimeGeometry = SliceNavigationHelper::CreateOrientedTimeGeometry( + timeGeometry, PlaneGeometry::Coronal, false, true, false); + break; + } + case mitk::SliceNavigationController::Sagittal: + { + orientedTimeGeometry = SliceNavigationHelper::CreateOrientedTimeGeometry( + timeGeometry, PlaneGeometry::Sagittal, true, true, false); + break; + } + } } - case mitk::SliceNavigationController::Sagittal: + catch (mitk::Exception& e) { - orientedTimeGeometry = SliceNavigationHelper::CreateOrientedTimeGeometry( - timeGeometry, PlaneGeometry::Sagittal, true, true, false); - break; - } + mitkReThrow(e); } if (nullptr == orientedTimeGeometry) { return false; } - const BaseGeometry* workingImageBaseGeometry = orientedTimeGeometry->GetGeometryForTimeStep(0); + auto selectedTimePoint = RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint(); + const BaseGeometry* workingImageBaseGeometry = orientedTimeGeometry->GetGeometryForTimePoint(selectedTimePoint); + if (nullptr == workingImageBaseGeometry) + { + // time point not valid for the time geometry + mitkThrow() << "Cannot extract a base geometry. A time point is selected that is not covered by" + << "the given time geometry. Selected time point: " << selectedTimePoint; + } + bool geometryIsEqual = Equal(*workingImageBaseGeometry->GetBoundingBox(), *renderWindowGeometry->GetBoundingBox(), eps, true); return geometryIsEqual; -} \ No newline at end of file +} diff --git a/Modules/Core/test/mitkSurfaceVtkWriterTest.cpp b/Modules/Core/test/mitkSurfaceVtkWriterTest.cpp index 509e0605fe..ce8cb40262 100644 --- a/Modules/Core/test/mitkSurfaceVtkWriterTest.cpp +++ b/Modules/Core/test/mitkSurfaceVtkWriterTest.cpp @@ -1,71 +1,68 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkIOUtil.h" -#include "mitkSurface.h" -#include "mitkTestingMacros.h" +#include +#include +#include +#include -#include -#include +#include +#include +#include -#include - -/** - * Simple example for a test for the (non-existent) class "ClassName". - * - * argc and argv are the command line parameters which were passed to - * the ADD_TEST command in the CMakeLists.txt file. For the automatic - * tests, argv is either empty for the simple tests or contains the filename - * of a test image for the image tests (see CMakeLists.txt). - */ -int mitkSurfaceVtkWriterTest(int /*argc*/, char *argv[]) +int mitkSurfaceVtkWriterTest(int, char *argv[]) { - // always start with this! MITK_TEST_BEGIN("SurfaceVtkWriter") - // create contour - vtkPolyDataReader *reader = vtkPolyDataReader::New(); - reader->SetFileName(argv[1]); - reader->Update(); - if (reader->GetOutput()) + mitk::Surface::Pointer surface; + + try + { + MITK_TEST_OUTPUT(<< "Load surface from \"" << argv[1] << "\"") + surface = mitk::IOUtil::Load(argv[1]); + } + catch (...) { - mitk::Surface::Pointer surface = mitk::Surface::New(); - surface->SetVtkPolyData(reader->GetOutput()); - surface->Update(); + } - MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(), "Surface creation") + if (surface.IsNotNull()) + { + std::string path; try { - // test for exception handling - mitk::IOUtil::Save(surface, "/usr/bin"); - MITK_TEST_FAILED_MSG(<< "itk::ExceptionObject expected") - } - catch (const mitk::Exception &) - { /* this is expected */ + std::ofstream stream; + path = mitk::IOUtil::CreateTemporaryFile(stream, "XXXXXX.vtp"); } catch (...) { - // this means that a wrong exception (i.e. no itk:Exception) has been thrown - MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]") } - // write your own tests here and use the macros from mitkTestingMacros.h !!! - // do not write to std::cout and do not return from this function yourself! - } + if (!path.empty()) + { + try + { + MITK_TEST_OUTPUT(<< "Save surface as \"" << path << "\"") + mitk::IOUtil::Save(surface, path); + } + catch (const std::exception& e) + { + std::remove(path.c_str()); + MITK_TEST_FAILED_MSG(<< "Caught exception: " << e.what() << " [FAILED]") + } - // Delete reader correctly - reader->Delete(); + mitk::TestManager::GetInstance()->TestPassed(); + } + } - // always end with this! MITK_TEST_END() } diff --git a/Modules/DICOMQI/mitkDICOMPMPropertyHelper.cpp b/Modules/DICOMQI/mitkDICOMPMPropertyHelper.cpp index 1af46da02e..f2a0cc1185 100644 --- a/Modules/DICOMQI/mitkDICOMPMPropertyHelper.cpp +++ b/Modules/DICOMQI/mitkDICOMPMPropertyHelper.cpp @@ -1,56 +1,55 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include #include #include #include #include #include #include #include // us #include #include namespace mitk { void DICOMPMPropertyHelper::DeriveDICOMPMProperties(BaseData *derivedDICOMImage) { PropertyList::Pointer propertyList = derivedDICOMImage->GetPropertyList(); // Add DICOM Tag (0008, 0060) Modality "PM" propertyList->SetProperty(GeneratePropertyNameForDICOMTag(0x0008, 0x0060).c_str(), TemporoSpatialStringProperty::New("PM")); // Add DICOM Tag (0008,103E) Series Description propertyList->SetProperty(GeneratePropertyNameForDICOMTag(0x0008, 0x103E).c_str(), TemporoSpatialStringProperty::New("MITK Parameter Map")); // Add DICOM Tag (0070,0084) Content Creator Name propertyList->SetProperty(GeneratePropertyNameForDICOMTag(0x0070, 0x0084).c_str(), TemporoSpatialStringProperty::New("MITK")); } } // namespace mitk diff --git a/Modules/IGTBase/src/mitkNavigationDataSet.cpp b/Modules/IGTBase/src/mitkNavigationDataSet.cpp index 790296f6cf..62f6206c03 100644 --- a/Modules/IGTBase/src/mitkNavigationDataSet.cpp +++ b/Modules/IGTBase/src/mitkNavigationDataSet.cpp @@ -1,186 +1,186 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkNavigationDataSet.h" #include "mitkPointSet.h" #include "mitkBaseRenderer.h" mitk::NavigationDataSet::NavigationDataSet( unsigned int numberOfTools ) : m_NavigationDataVectors(std::vector >()), m_NumberOfTools(numberOfTools) { } mitk::NavigationDataSet::~NavigationDataSet( ) { } bool mitk::NavigationDataSet::AddNavigationDatas( std::vector navigationDatas ) { // test if tool with given index exist if ( navigationDatas.size() != m_NumberOfTools ) { MITK_WARN("NavigationDataSet") << "Tried to add too many or too few navigation Datas to NavigationDataSet. " << m_NumberOfTools << " required, tried to add " << navigationDatas.size() << "."; return false; } // test for consistent timestamp if ( m_NavigationDataVectors.size() > 0) { for (std::vector::size_type i = 0; i < navigationDatas.size(); i++) if (navigationDatas[i]->GetIGTTimeStamp() <= m_NavigationDataVectors.back()[i]->GetIGTTimeStamp()) { MITK_WARN("NavigationDataSet") << "IGTTimeStamp of new NavigationData should be newer than timestamp of last NavigationData."; return false; } } m_NavigationDataVectors.push_back(navigationDatas); return true; } mitk::NavigationData::Pointer mitk::NavigationDataSet::GetNavigationDataForIndex( unsigned int index, unsigned int toolIndex ) const { if ( index >= m_NavigationDataVectors.size() ) { MITK_WARN("NavigationDataSet") << "There is no NavigationData available at index " << index << "."; return nullptr; } if ( toolIndex >= m_NavigationDataVectors.at(index).size() ) { MITK_WARN("NavigationDataSet") << "There is NavigatitionData available at index " << index << " for tool " << toolIndex << "."; return nullptr; } return m_NavigationDataVectors.at(index).at(toolIndex); } // Method not yet supported, code below compiles but delivers wrong results //mitk::NavigationData::Pointer mitk::NavigationDataSet::GetNavigationDataBeforeTimestamp( // mitk::NavigationData::TimeStampType timestamp, unsigned int toolIndex) const //{ // if ( toolIndex >= m_NavigationDataVectors.size() ) // { // MITK_WARN("NavigationDataSet") << "There is no tool with index " << toolIndex << "."; // return nullptr; // } // // std::vector::const_iterator it; // // // iterate through all NavigationData objects of the given tool index // // till the timestamp of the NavigationData is greater then the given timestamp // for (it = m_NavigationDataVectors.at(toolIndex).begin(); // it != m_NavigationDataVectors.at(toolIndex).end(); ++it) // { // if ( (*it)->GetIGTTimeStamp() > timestamp) { break; } // } // // // first element was greater than timestamp -> return null // if ( it == m_NavigationDataVectors.at(toolIndex).begin() ) // { // MITK_WARN("NavigationDataSet") << "No NavigationData was recorded before given timestamp."; // return nullptr; // } // // // return last element smaller than the given timestamp // return *(it-1); //} std::vector< mitk::NavigationData::Pointer > mitk::NavigationDataSet::GetDataStreamForTool(unsigned int toolIndex) { if (toolIndex >= m_NumberOfTools ) { MITK_WARN("NavigationDataSet") << "Invalid toolIndex: " << m_NumberOfTools << " Tools known, requested index " << toolIndex << ""; return std::vector(); } std::vector< mitk::NavigationData::Pointer > result; for(std::vector >::size_type i = 0; i < m_NavigationDataVectors.size(); i++) result.push_back(m_NavigationDataVectors[i][toolIndex]); return result; } std::vector< mitk::NavigationData::Pointer > mitk::NavigationDataSet::GetTimeStep(unsigned int index) const { return m_NavigationDataVectors[index]; } unsigned int mitk::NavigationDataSet::GetNumberOfTools() const { return m_NumberOfTools; } unsigned int mitk::NavigationDataSet::Size() const { return m_NavigationDataVectors.size(); } // ---> methods necessary for BaseData void mitk::NavigationDataSet::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::NavigationDataSet::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::NavigationDataSet::VerifyRequestedRegion() { return true; } void mitk::NavigationDataSet::SetRequestedRegion(const DataObject * ) { } bool mitk::NavigationDataSet::IsEmpty() const { return (Size() == 0); } void mitk::NavigationDataSet::ConvertNavigationDataToPointSet() const { //iterate over all tools for (unsigned int toolIndex = 0; toolIndex < this->GetNumberOfTools(); ++ toolIndex) { mitk::PointSet::Pointer _tempPointSet = mitk::PointSet::New(); //iterate over all time steps for (unsigned int time = 0; time < m_NavigationDataVectors.size(); time++) { _tempPointSet->InsertPoint(time,m_NavigationDataVectors[time][toolIndex]->GetPosition()); MITK_DEBUG << m_NavigationDataVectors[time][toolIndex]->GetPosition() << " --- " << _tempPointSet->GetPoint(time); } mitk::DataNode::Pointer dn = mitk::DataNode::New(); std::stringstream str; str << "NavigationData Tool " << toolIndex; dn->SetProperty("name", mitk::StringProperty::New(str.str())); dn->SetData(_tempPointSet); - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetDataStorage()->Add(dn); + mitk::RenderingManager::GetInstance()->GetDataStorage()->Add(dn); } } // <--- methods necessary for BaseData // ---> methods for Iterators mitk::NavigationDataSet::NavigationDataSetConstIterator mitk::NavigationDataSet::Begin() const { return m_NavigationDataVectors.cbegin(); } mitk::NavigationDataSet::NavigationDataSetConstIterator mitk::NavigationDataSet::End() const { return m_NavigationDataVectors.cend(); } diff --git a/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.cpp b/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.cpp index 3183529f5b..2225e98a01 100644 --- a/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.cpp @@ -1,296 +1,292 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkInteractiveTransformationWidget.h" // mitk includes #include "mitkRenderingManager.h" #include "mitkBaseRenderer.h" #include "mitkNavigationData.h" // vtk includes #include "vtkMatrix4x4.h" #include "vtkLinearTransform.h" const std::string QmitkInteractiveTransformationWidget::VIEW_ID = "org.mitk.views.interactivetransformationwidget"; QmitkInteractiveTransformationWidget::QmitkInteractiveTransformationWidget(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f), m_Controls(nullptr), m_Geometry(nullptr) { CreateQtPartControl(this); CreateConnections(); m_ResetGeometry = mitk::Geometry3D::New(); this->setWindowTitle("Edit Tool Tip and Tool Orientation"); } QmitkInteractiveTransformationWidget::~QmitkInteractiveTransformationWidget() { } void QmitkInteractiveTransformationWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkInteractiveTransformationWidgetControls; m_Controls->setupUi(parent); } } void QmitkInteractiveTransformationWidget::CreateConnections() { if (m_Controls) { // translations connect(m_Controls->m_XTransSpinBox, static_cast(&QDoubleSpinBox::valueChanged), this, &QmitkInteractiveTransformationWidget::OnXTranslationValueChanged); connect(m_Controls->m_XTransSlider, &QSlider::valueChanged, this, &QmitkInteractiveTransformationWidget::OnXTranslationValueChanged); connect(m_Controls->m_YTransSpinBox, static_cast(&QDoubleSpinBox::valueChanged), this, &QmitkInteractiveTransformationWidget::OnYTranslationValueChanged); connect(m_Controls->m_YTransSlider, &QSlider::valueChanged, this, &QmitkInteractiveTransformationWidget::OnYTranslationValueChanged); connect(m_Controls->m_ZTransSpinBox, static_cast(&QDoubleSpinBox::valueChanged), this, &QmitkInteractiveTransformationWidget::OnZTranslationValueChanged); connect(m_Controls->m_ZTransSlider, &QSlider::valueChanged, this, &QmitkInteractiveTransformationWidget::OnZTranslationValueChanged); // rotations connect(m_Controls->m_XRotSpinBox, static_cast(&QDoubleSpinBox::valueChanged), this, &QmitkInteractiveTransformationWidget::OnXRotationValueChanged); connect(m_Controls->m_XRotSlider, &QSlider::valueChanged, this, &QmitkInteractiveTransformationWidget::OnXRotationValueChanged); connect(m_Controls->m_YRotSpinBox, static_cast(&QDoubleSpinBox::valueChanged), this, &QmitkInteractiveTransformationWidget::OnYRotationValueChanged); connect(m_Controls->m_YRotSlider, &QSlider::valueChanged, this, &QmitkInteractiveTransformationWidget::OnYRotationValueChanged); connect(m_Controls->m_ZRotSpinBox, static_cast(&QDoubleSpinBox::valueChanged), this, &QmitkInteractiveTransformationWidget::OnZRotationValueChanged); connect(m_Controls->m_ZRotSlider, &QSlider::valueChanged, this, &QmitkInteractiveTransformationWidget::OnZRotationValueChanged); connect((QObject*)(m_Controls->m_ResetPB), SIGNAL(clicked()), this, SLOT(OnResetGeometryToIdentity())); connect((QObject*)(m_Controls->m_RevertChanges), SIGNAL(clicked()), this, SLOT(OnRevertChanges())); connect((QObject*)(m_Controls->m_UseManipulatedToolTipPB), SIGNAL(clicked()), this, SLOT(OnApplyManipulatedToolTip())); connect((QObject*)(m_Controls->m_Cancel), SIGNAL(clicked()), this, SLOT(OnCancel())); } } void QmitkInteractiveTransformationWidget::SetToolToEdit(const mitk::NavigationTool::Pointer _tool) { //If there is already a tool, remove it's node first. if (m_ToolToEdit) - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetDataStorage() - ->Remove(m_ToolToEdit->GetDataNode()); + mitk::RenderingManager::GetInstance()->GetDataStorage()->Remove(m_ToolToEdit->GetDataNode()); m_ToolToEdit = _tool->Clone(); - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetDataStorage() - ->Add(m_ToolToEdit->GetDataNode()); + mitk::RenderingManager::GetInstance()->GetDataStorage()->Add(m_ToolToEdit->GetDataNode()); m_ToolToEdit->GetDataNode()->SetName("Tool Tip to be edited"); //change color to red m_ToolToEdit->GetDataNode()->SetProperty("color", mitk::ColorProperty::New(1, 0, 0)); //use the set-function via vtk matrix, 'cause this guarantees a deep copy and not just sharing a pointer. m_Geometry = m_ToolToEdit->GetDataNode()->GetData()->GetGeometry(); m_ResetGeometry->SetIndexToWorldTransformByVtkMatrix(m_Geometry->GetVtkMatrix()); //Remember the original values to be able to reset and abort everything } void QmitkInteractiveTransformationWidget::SetDefaultOffset(const mitk::Point3D _defaultValues) { m_Geometry->SetOrigin(_defaultValues); m_ResetGeometry->SetOrigin(_defaultValues); //Remember the original values to be able to reset and abort everything SetValuesToGUI(m_Geometry->GetIndexToWorldTransform()); } void QmitkInteractiveTransformationWidget::SetDefaultRotation(const mitk::Quaternion _defaultValues) { // Conversion to navigation data / transform mitk::NavigationData::Pointer rotationTransform = mitk::NavigationData::New(m_Geometry->GetIndexToWorldTransform()); rotationTransform->SetOrientation(_defaultValues); m_Geometry->SetIndexToWorldTransform(rotationTransform->GetAffineTransform3D()); //For ResetGeometry, use the set-function via vtk matrix, 'cause this guarantees a deep copy and not just sharing a pointer. m_ResetGeometry->SetIndexToWorldTransformByVtkMatrix(m_Geometry->GetVtkMatrix()); //Remember the original values to be able to reset and abort everything SetValuesToGUI(m_Geometry->GetIndexToWorldTransform()); } void QmitkInteractiveTransformationWidget::SetValuesToGUI(const mitk::AffineTransform3D::Pointer _defaultValues) { //Set toolTip values in gui m_Controls->m_XTransSlider->setValue(_defaultValues->GetOffset()[0]); m_Controls->m_YTransSlider->setValue(_defaultValues->GetOffset()[1]); m_Controls->m_ZTransSlider->setValue(_defaultValues->GetOffset()[2]); //first: some conversion mitk::NavigationData::Pointer transformConversionHelper = mitk::NavigationData::New(_defaultValues); double eulerAlphaDegrees = transformConversionHelper->GetOrientation().rotation_euler_angles()[0] / vnl_math::pi * 180; double eulerBetaDegrees = transformConversionHelper->GetOrientation().rotation_euler_angles()[1] / vnl_math::pi * 180; double eulerGammaDegrees = transformConversionHelper->GetOrientation().rotation_euler_angles()[2] / vnl_math::pi * 180; m_Controls->m_XRotSpinBox->setValue(eulerAlphaDegrees); m_Controls->m_YRotSpinBox->setValue(eulerBetaDegrees); m_Controls->m_ZRotSpinBox->setValue(eulerGammaDegrees); //Update view mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::SetSynchronizedValuesToSliderAndSpinbox(QDoubleSpinBox* _spinbox, QSlider* _slider, double _value) { //block signals to avoid loop between slider and spinbox. Unblock at the end of the function! _spinbox->blockSignals(true); _slider->blockSignals(true); _spinbox->setValue(_value); _slider->setValue(_value); //unblock signals. See above, don't remove this line. Unblock at the end of the function! _spinbox->blockSignals(false);// _slider->blockSignals(false);// } void QmitkInteractiveTransformationWidget::OnXTranslationValueChanged(double v) { //Set values to member variable mitk::Point3D translationParams = m_Geometry->GetOrigin(); translationParams[0] = v; m_Geometry->SetOrigin(translationParams); SetSynchronizedValuesToSliderAndSpinbox(m_Controls->m_XTransSpinBox, m_Controls->m_XTransSlider, v); //Update view mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::OnYTranslationValueChanged(double v) { //Set values to member variable mitk::Point3D translationParams = m_Geometry->GetOrigin(); translationParams[1] = v; m_Geometry->SetOrigin(translationParams); SetSynchronizedValuesToSliderAndSpinbox(m_Controls->m_YTransSpinBox, m_Controls->m_YTransSlider, v); //Update view mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::OnZTranslationValueChanged(double v) { //Set values to member variable mitk::Point3D translationParams = m_Geometry->GetOrigin(); translationParams[2] = v; m_Geometry->SetOrigin(translationParams); SetSynchronizedValuesToSliderAndSpinbox(m_Controls->m_ZTransSpinBox, m_Controls->m_ZTransSlider, v); //Update view mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::OnXRotationValueChanged(double v) { mitk::Vector3D rotationParams; rotationParams[0] = v; rotationParams[1] = m_Controls->m_YRotSpinBox->value(); rotationParams[2] = m_Controls->m_ZRotSpinBox->value(); SetSynchronizedValuesToSliderAndSpinbox(m_Controls->m_XRotSpinBox, m_Controls->m_XRotSlider, v); this->Rotate(rotationParams); } void QmitkInteractiveTransformationWidget::OnYRotationValueChanged(double v) { mitk::Vector3D rotationParams; rotationParams[0] = m_Controls->m_XRotSpinBox->value(); rotationParams[1] = v; rotationParams[2] = m_Controls->m_ZRotSpinBox->value(); SetSynchronizedValuesToSliderAndSpinbox(m_Controls->m_YRotSpinBox, m_Controls->m_YRotSlider, v); this->Rotate(rotationParams); } void QmitkInteractiveTransformationWidget::OnZRotationValueChanged(double v) { mitk::Vector3D rotationParams; rotationParams[0] = m_Controls->m_XRotSpinBox->value(); rotationParams[1] = m_Controls->m_YRotSpinBox->value(); rotationParams[2] = v; SetSynchronizedValuesToSliderAndSpinbox(m_Controls->m_ZRotSpinBox, m_Controls->m_ZRotSlider, v); this->Rotate(rotationParams); } void QmitkInteractiveTransformationWidget::Rotate(mitk::Vector3D rotateVector) { //0: from degrees to radians double radianX = rotateVector[0] * vnl_math::pi / 180; double radianY = rotateVector[1] * vnl_math::pi / 180; double radianZ = rotateVector[2] * vnl_math::pi / 180; //1: from euler angles to quaternion mitk::Quaternion rotation(radianX, radianY, radianZ); //2: Conversion to navigation data / transform mitk::NavigationData::Pointer rotationTransform = mitk::NavigationData::New(m_Geometry->GetIndexToWorldTransform()); rotationTransform->SetOrientation(rotation); m_Geometry->SetIndexToWorldTransform(rotationTransform->GetAffineTransform3D()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::OnResetGeometryToIdentity() { // reset the input to its initial state. m_Geometry->SetIdentity(); //Update Sliders this->SetValuesToGUI(m_Geometry->GetIndexToWorldTransform()); //Refresh view mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::OnRevertChanges() { // reset the input to its initial state. m_Geometry->SetIndexToWorldTransformByVtkMatrix(m_ResetGeometry->GetVtkMatrix()); //Update Sliders this->SetValuesToGUI(m_Geometry->GetIndexToWorldTransform()); //Refresh view mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkInteractiveTransformationWidget::OnApplyManipulatedToolTip() { - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetDataStorage() - ->Remove(m_ToolToEdit->GetDataNode()); + mitk::RenderingManager::GetInstance()->GetDataStorage()->Remove(m_ToolToEdit->GetDataNode()); mitk::AffineTransform3D::Pointer toolTip = m_Geometry->GetIndexToWorldTransform(); emit EditToolTipFinished(toolTip); this->close(); } void QmitkInteractiveTransformationWidget::reject() { OnCancel(); } void QmitkInteractiveTransformationWidget::OnCancel() { QDialog::reject(); - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetDataStorage() - ->Remove(m_ToolToEdit->GetDataNode()); + mitk::RenderingManager::GetInstance()->GetDataStorage()->Remove(m_ToolToEdit->GetDataNode()); emit EditToolTipFinished(nullptr); } diff --git a/Modules/IGTUI/Qmitk/QmitkPolhemusTrackerWidget.cpp b/Modules/IGTUI/Qmitk/QmitkPolhemusTrackerWidget.cpp index 08dc13a22b..89b5715c1e 100644 --- a/Modules/IGTUI/Qmitk/QmitkPolhemusTrackerWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkPolhemusTrackerWidget.cpp @@ -1,295 +1,299 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkPolhemusTrackerWidget.h" #include #include #include #include #include #include #include #include #include "vtkRenderer.h" #include "vtkCamera.h" const std::string QmitkPolhemusTrackerWidget::VIEW_ID = "org.mitk.views.PolhemusTrackerWidget"; QmitkPolhemusTrackerWidget::QmitkPolhemusTrackerWidget(QWidget* parent, Qt::WindowFlags f) : QmitkAbstractTrackingDeviceWidget(parent, f) , m_Controls(nullptr) { } void QmitkPolhemusTrackerWidget::Initialize() { InitializeSuperclassWidget(); CreateQtPartControl(this); SetAdvancedSettingsEnabled(false); on_m_AdvancedSettings_clicked(); //hide advanced settings on setup } QmitkPolhemusTrackerWidget::~QmitkPolhemusTrackerWidget() { delete m_Controls; } void QmitkPolhemusTrackerWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkPolhemusTrackerWidget; m_Controls->setupUi(parent); } } void QmitkPolhemusTrackerWidget::OnToolStorageChanged() { this->m_TrackingDevice = nullptr; MITK_DEBUG<<"Resetting Polhemus Tracking Device, because tool storage changed."; } void QmitkPolhemusTrackerWidget::CreateConnections() { if (m_Controls) { connect((QObject*)(m_Controls->m_hemisphereTracking), SIGNAL(clicked()), this, SLOT(on_m_hemisphereTracking_clicked())); connect((QObject*)(m_Controls->m_ToggleHemisphere), SIGNAL(clicked()), this, SLOT(on_m_ToggleHemisphere_clicked())); connect((QObject*)(m_Controls->m_SetHemisphere), SIGNAL(clicked()), this, SLOT(on_m_SetHemisphere_clicked())); connect((QObject*)(m_Controls->m_GetHemisphere), SIGNAL(clicked()), this, SLOT(on_m_GetHemisphere_clicked())); connect((QObject*)(m_Controls->m_AdjustHemisphere), SIGNAL(clicked()), this, SLOT(on_m_AdjustHemisphere_clicked())); connect((QObject*)(m_Controls->m_AdvancedSettings), SIGNAL(clicked()), this, SLOT(on_m_AdvancedSettings_clicked())); connect((QObject*)(m_Controls->m_ToggleToolTipCalibration), SIGNAL(clicked()), this, SLOT(on_m_ToggleToolTipCalibration_clicked())); } } mitk::TrackingDevice::Pointer QmitkPolhemusTrackerWidget::GetTrackingDevice() { if (m_TrackingDevice.IsNull()) { m_TrackingDevice = mitk::PolhemusTrackingDevice::New(); m_TrackingDevice->SetHemisphereTrackingEnabled(m_Controls->m_hemisphereTracking->isChecked()); } return static_cast(m_TrackingDevice); } QmitkPolhemusTrackerWidget* QmitkPolhemusTrackerWidget::Clone(QWidget* parent) const { QmitkPolhemusTrackerWidget* clonedWidget = new QmitkPolhemusTrackerWidget(parent); clonedWidget->Initialize(); return clonedWidget; } void QmitkPolhemusTrackerWidget::on_m_hemisphereTracking_clicked() { m_TrackingDevice->SetHemisphereTrackingEnabled(m_Controls->m_hemisphereTracking->isChecked()); } void QmitkPolhemusTrackerWidget::on_m_ToggleHemisphere_clicked() { // Index 0 == All Tools == -1 for Polhemus interface; Index 2 == Tool 2 == 1 for Polhemus; etc... m_TrackingDevice->ToggleHemisphere(GetSelectedToolIndex()); MITK_INFO << "Toggle Hemisphere for tool " << m_Controls->m_ToolSelection->currentText().toStdString(); } void QmitkPolhemusTrackerWidget::on_m_SetHemisphere_clicked() { mitk::Vector3D _hemisphere; mitk::FillVector3D(_hemisphere, m_Controls->m_Hemisphere_X->value(), m_Controls->m_Hemisphere_Y->value(), m_Controls->m_Hemisphere_Z->value()); m_TrackingDevice->SetHemisphere(GetSelectedToolIndex(), _hemisphere); //If you set a hemisphere vector which is unequal (0|0|0), this means, that there is no hemisphere tracking any more //disable the checkbox in case it was on before, so that it can be reactivated... if (_hemisphere.GetNorm() != 0) m_Controls->m_hemisphereTracking->setChecked(false); MITK_INFO << "Hemisphere set for tool " << m_Controls->m_ToolSelection->currentText().toStdString(); } void QmitkPolhemusTrackerWidget::on_m_GetHemisphere_clicked() { mitk::Vector3D _hemisphere = m_TrackingDevice->GetHemisphere(GetSelectedToolIndex()); m_Controls->m_Hemisphere_X->setValue(_hemisphere[0]); m_Controls->m_Hemisphere_Y->setValue(_hemisphere[1]); m_Controls->m_Hemisphere_Z->setValue(_hemisphere[2]); QString label; if (m_TrackingDevice->GetHemisphereTrackingEnabled(GetSelectedToolIndex())) { label = "HemisphereTracking is ON for tool "; label.append(m_Controls->m_ToolSelection->currentText()); } else if (GetSelectedToolIndex() == -1) { label = "HemisphereTracking is OFF for at least one tool."; } else { label = "HemisphereTracking is OFF for tool "; label.append(m_Controls->m_ToolSelection->currentText()); } m_Controls->m_StatusLabelHemisphereTracking->setText(label); MITK_INFO << "Updated SpinBox for Hemisphere of tool " << m_Controls->m_ToolSelection->currentText().toStdString(); } void QmitkPolhemusTrackerWidget::on_m_AdjustHemisphere_clicked() { int _tool = GetSelectedToolIndex(); QMessageBox msgBox; QString _text; if (_tool == -1) { _text.append("Adjusting hemisphere for all tools."); msgBox.setText(_text); _text.clear(); _text = tr("Please make sure, that the entire tools (including tool tip AND sensor) are placed in the positive x hemisphere. Press 'Adjust hemisphere' if you are ready."); msgBox.setInformativeText(_text); } else { _text.append("Adjusting hemisphere for tool '"); _text.append(m_Controls->m_ToolSelection->currentText()); _text.append(tr("' at port %2.").arg(_tool)); msgBox.setText(_text); _text.clear(); _text = tr("Please make sure, that the entire tool (including tool tip AND sensor) is placed in the positive x hemisphere. Press 'Adjust hemisphere' if you are ready."); msgBox.setInformativeText(_text); } QPushButton *adjustButton = msgBox.addButton(tr("Adjust hemisphere"), QMessageBox::ActionRole); QPushButton *cancelButton = msgBox.addButton(QMessageBox::Cancel); msgBox.exec(); if (msgBox.clickedButton() == adjustButton) { // adjust m_TrackingDevice->AdjustHemisphere(_tool); MITK_INFO << "Adjusting Hemisphere for tool " << m_Controls->m_ToolSelection->currentText().toStdString(); } else if (msgBox.clickedButton() == cancelButton) { // abort MITK_INFO << "Cancel 'Adjust hemisphere'. No harm done..."; } } void QmitkPolhemusTrackerWidget::on_m_ToggleToolTipCalibration_clicked() { if (m_Controls->m_ToolSelection->currentIndex() != 0) { mitk::PolhemusTool* _tool = dynamic_cast (this->m_TrackingDevice->GetToolByName(m_Controls->m_ToolSelection->currentText().toStdString())); mitk::Point3D tip = _tool->GetToolTipPosition().GetVectorFromOrigin()*(-1.); mitk::Quaternion quat = _tool->GetToolAxisOrientation().inverse(); _tool->SetToolTipPosition(tip, quat); } else { for (int i = 0; i < m_TrackingDevice->GetToolCount(); ++i) { mitk::PolhemusTool* _tool = dynamic_cast (this->m_TrackingDevice->GetTool(i)); mitk::Point3D tip = _tool->GetToolTipPosition().GetVectorFromOrigin()*(-1.); mitk::Quaternion quat = _tool->GetToolAxisOrientation().inverse(); _tool->SetToolTipPosition(tip, quat); } } } void QmitkPolhemusTrackerWidget::OnConnected(bool _success) { if (!_success) { this->m_TrackingDevice = nullptr; return; } SetAdvancedSettingsEnabled(true); if (m_TrackingDevice->GetToolCount() != m_Controls->m_ToolSelection->count()) { m_Controls->m_ToolSelection->clear(); m_Controls->m_ToolSelection->addItem("All Tools"); for (int i = 0; i < m_TrackingDevice->GetToolCount(); ++i) { m_Controls->m_ToolSelection->addItem(m_TrackingDevice->GetTool(i)->GetToolName()); } } } void QmitkPolhemusTrackerWidget::OnStartTracking(bool _success) { if (!_success) return; - //Rotate mitk standard multi widget, so that the view matches the sensor. Positive x == right, y == front, z == down; - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetCameraController()->SetViewToPosterior(); - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetVtkRenderer()->GetActiveCamera()->SetViewUp(0, 0, -1); + auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows(); + for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit) + { + // rotate 3D render windows, so that the view matches the sensor. Positive x == right, y == front, z == down; + mapit->second->GetCameraController()->SetViewToPosterior(); + mapit->second->GetVtkRenderer()->GetActiveCamera()->SetViewUp(0, 0, -1); + } } void QmitkPolhemusTrackerWidget::OnDisconnected(bool _success) { if (!_success) return; SetAdvancedSettingsEnabled(false); } void QmitkPolhemusTrackerWidget::SetAdvancedSettingsEnabled(bool _enable) { m_Controls->m_ToolSelection->setEnabled(_enable); m_Controls->label_toolsToChange->setEnabled(_enable); m_Controls->label_UpdateOnRequest->setEnabled(_enable); m_Controls->m_GetHemisphere->setEnabled(_enable); m_Controls->m_Hemisphere_X->setEnabled(_enable); m_Controls->m_Hemisphere_Y->setEnabled(_enable); m_Controls->m_Hemisphere_Z->setEnabled(_enable); m_Controls->m_SetHemisphere->setEnabled(_enable); m_Controls->m_ToggleHemisphere->setEnabled(_enable); m_Controls->m_AdjustHemisphere->setEnabled(_enable); m_Controls->m_ToggleToolTipCalibration->setEnabled(_enable); } void QmitkPolhemusTrackerWidget::on_m_AdvancedSettings_clicked() { bool _enable = m_Controls->m_AdvancedSettings->isChecked(); m_Controls->m_ToolSelection->setVisible(_enable); m_Controls->label_toolsToChange->setVisible(_enable); m_Controls->label_UpdateOnRequest->setVisible(_enable); m_Controls->m_GetHemisphere->setVisible(_enable); m_Controls->m_Hemisphere_X->setVisible(_enable); m_Controls->m_Hemisphere_Y->setVisible(_enable); m_Controls->m_Hemisphere_Z->setVisible(_enable); m_Controls->m_SetHemisphere->setVisible(_enable); m_Controls->m_ToggleHemisphere->setVisible(_enable); m_Controls->m_AdjustHemisphere->setVisible(_enable); m_Controls->m_ToggleToolTipCalibration->setVisible(_enable); m_Controls->m_StatusLabelHemisphereTracking->setVisible(_enable); } int QmitkPolhemusTrackerWidget::GetSelectedToolIndex() { // Index 0 == All Tools == -1 for Polhemus interface; Index 1 == Tool 1 == 1 for Polhemus Interface; etc... int _index = m_Controls->m_ToolSelection->currentIndex() - 1; if (_index != -1) { //we need to find the internal Polhemus index for this tool. This is stored in the identifier of a navigation tool or as Port in PolhemusTool. mitk::PolhemusTool* _tool = dynamic_cast(m_TrackingDevice->GetToolByName(m_Controls->m_ToolSelection->currentText().toStdString())); _index = _tool->GetToolPort(); } return _index; } diff --git a/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h b/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h index e50f98aeed..419d27c275 100644 --- a/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h +++ b/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h @@ -1,161 +1,182 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKABSTRACTMULTIWIDGET_H #define QMITKABSTRACTMULTIWIDGET_H // mitk qt widgets module #include "MitkQtWidgetsExports.h" // mitk core #include #include #include #include // qt #include // c++ #include #include class QmitkMultiWidgetLayoutManager; class QmitkRenderWindow; class QmitkRenderWindowWidget; namespace mitk { class DataStorage; class InteractionEventHandler; } /** * @brief The 'QmitkAbstractMultiWidget' is a 'QWidget' that can be subclassed to display multiple render windows at once. * Render windows can dynamically be added and removed to change the layout of the multi widget. * A subclass of this multi widget can be used inside a 'QmitkAbstractMultiWidgetEditor'. * * The class uses the 'DisplayActionEventBroadcast' and 'DisplayActionEventHandler' classes to * load a state machine and set an event configuration. * * Using the 'Synchronize' function the user can enable or disable the synchronization of display action events. * See 'DisplayActionEventFunctions'-class for the different synchronized and non-synchronized functions used. */ class MITKQTWIDGETS_EXPORT QmitkAbstractMultiWidget : public QWidget { Q_OBJECT public: using RenderWindowWidgetPointer = std::shared_ptr; using RenderWindowWidgetMap = std::map>; using RenderWindowHash = QHash; using ViewDirection = mitk::BaseRenderer::ViewDirection; QmitkAbstractMultiWidget(QWidget* parent = 0, Qt::WindowFlags f = 0, const QString& multiWidgetName = "multiwidget"); virtual ~QmitkAbstractMultiWidget(); virtual void InitializeMultiWidget() = 0; virtual void MultiWidgetOpened() { } virtual void MultiWidgetClosed() { } virtual void SetDataStorage(mitk::DataStorage* dataStorage); mitk::DataStorage* GetDataStorage() const; int GetRowCount() const; int GetColumnCount() const; virtual void SetLayout(int row, int column); virtual void Synchronize(bool) { }; virtual void SetInteractionScheme(mitk::InteractionSchemeSwitcher::InteractionScheme scheme); mitk::InteractionEventHandler* GetInteractionEventHandler(); void SetDisplayActionEventHandler(std::unique_ptr displayActionEventHandler); mitk::DisplayActionEventHandler* GetDisplayActionEventHandler(); RenderWindowWidgetMap GetRenderWindowWidgets() const; RenderWindowWidgetMap Get2DRenderWindowWidgets() const; RenderWindowWidgetMap Get3DRenderWindowWidgets() const; RenderWindowWidgetPointer GetRenderWindowWidget(int row, int column) const; RenderWindowWidgetPointer GetRenderWindowWidget(const QString& widgetName) const; RenderWindowWidgetPointer GetRenderWindowWidget(const QmitkRenderWindow* renderWindow) const; RenderWindowHash GetRenderWindows() const; QmitkRenderWindow* GetRenderWindow(int row, int column) const; virtual QmitkRenderWindow* GetRenderWindow(const QString& widgetName) const; virtual QmitkRenderWindow* GetRenderWindow(const ViewDirection& viewDirection) const = 0; virtual void SetActiveRenderWindowWidget(RenderWindowWidgetPointer activeRenderWindowWidget); RenderWindowWidgetPointer GetActiveRenderWindowWidget() const; RenderWindowWidgetPointer GetFirstRenderWindowWidget() const; RenderWindowWidgetPointer GetLastRenderWindowWidget() const; virtual QString GetNameFromIndex(int row, int column) const; virtual QString GetNameFromIndex(size_t index) const; unsigned int GetNumberOfRenderWindowWidgets() const; void RequestUpdate(const QString& widgetName); void RequestUpdateAll(); void ForceImmediateUpdate(const QString& widgetName); void ForceImmediateUpdateAll(); + /** + * @brief Set the reference geometry for interaction inside the render windows of the render window part. + * + * The concrete implementation is subclass-specific, no default implementation is provided here. + * + * @param referenceGeometry The reference geometry which is used for updating the + * time geometry inside the render windows. + * @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom). + * If false, the current crosshair position and the camera zoom will be stored and reset + * after the reference geometry has been updated. + */ + virtual void SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) = 0; + + /** + * @brief Returns true if the render windows are coupled; false if not. + * + * Render windows are coupled if the slice navigation controller of the render windows + * are connected which means that always the same geometry is used for the render windows. + */ + virtual bool HasCoupledRenderWindows() const = 0; + virtual void SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) = 0; virtual const mitk::Point3D GetSelectedPosition(const QString& widgetName) const = 0; virtual void SetCrosshairVisibility(bool visible) = 0; virtual bool GetCrosshairVisibility() const = 0; virtual void SetCrosshairGap(unsigned int gapSize) = 0; virtual void ResetCrosshair() = 0; virtual void SetWidgetPlaneMode(int mode) = 0; virtual void ActivateMenuWidget(bool state); virtual bool IsMenuWidgetEnabled() const; QmitkMultiWidgetLayoutManager* GetMultiWidgetLayoutManager() const; signals: void ActiveRenderWindowChanged(); private slots: void OnFocusChanged(itk::Object*, const itk::EventObject& event); protected: virtual void AddRenderWindowWidget(const QString& widgetName, RenderWindowWidgetPointer renderWindowWidget); virtual void RemoveRenderWindowWidget(); private: /** * @brief This function will be called by the function 'SetLayout' and * can be implemented and customized in the subclasses. */ virtual void SetLayoutImpl() = 0; /** * @brief This function will be called by the function 'SetInteractionScheme' and * can be implemented and customized in the subclasses. */ virtual void SetInteractionSchemeImpl() = 0; struct Impl; std::unique_ptr m_Impl; }; #endif // QMITKABSTRACTMULTIWIDGET_H diff --git a/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h b/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h index b049ca84b1..b050374394 100644 --- a/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h +++ b/Modules/QtWidgets/include/QmitkMemoryUsageIndicatorView.h @@ -1,48 +1,48 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#ifndef QMITKMEMORYUSAGEINDICATORVIEW_WIDGET -#define QMITKMEMORYUSAGEINDICATORVIEW_WIDGET +#ifndef QmitkMemoryUsageIndicatorView_h +#define QmitkMemoryUsageIndicatorView_h #include -#include "ui_QmitkMemoryUsageIndicator.h" #include -#include + +#include +#include + +namespace Ui +{ + class QmitkMemoryUsageIndicator; +} /// \ingroup QmitkModule -class MITKQTWIDGETS_EXPORT QmitkMemoryUsageIndicatorView : public QWidget, public Ui::QmitkMemoryUsageIndicator +class MITKQTWIDGETS_EXPORT QmitkMemoryUsageIndicatorView : public QWidget { Q_OBJECT public: - /// constructor - QmitkMemoryUsageIndicatorView(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr); - - /// destructor + QmitkMemoryUsageIndicatorView(QWidget* parent = nullptr); ~QmitkMemoryUsageIndicatorView() override; -protected slots: +private: void UpdateMemoryUsage(); - -protected: std::string FormatMemorySize(size_t size); std::string FormatPercentage(double val); std::string GetMemoryDescription(size_t processSize, float percentage); - QPixmap m_LEDGreen; - QPixmap m_LEDYellow; - QPixmap m_LEDOrange; - QPixmap m_LEDRed; - char m_PreviousState; + Ui::QmitkMemoryUsageIndicator* m_Ui; + size_t m_PreviousState; + std::array, 4> m_States; }; -#endif // QMITKMEMORYUSAGEINDICATORVIEW_WIDGET + +#endif diff --git a/Modules/QtWidgets/include/QmitkMxNMultiWidget.h b/Modules/QtWidgets/include/QmitkMxNMultiWidget.h index f979ff414c..42505725a6 100644 --- a/Modules/QtWidgets/include/QmitkMxNMultiWidget.h +++ b/Modules/QtWidgets/include/QmitkMxNMultiWidget.h @@ -1,92 +1,109 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKMXNMULTIWIDGET_H #define QMITKMXNMULTIWIDGET_H // qt widgets module #include "MitkQtWidgetsExports.h" #include "QmitkAbstractMultiWidget.h" /** * @brief The 'QmitkMxNMultiWidget' is a 'QmitkAbstractMultiWidget' that is used to display multiple render windows at once. * Render windows can dynamically be added and removed to change the layout of the multi widget. This * is done by using the 'SetLayout'-function to define a layout. This will automatically add or remove * the appropriate number of render window widgets. */ class MITKQTWIDGETS_EXPORT QmitkMxNMultiWidget : public QmitkAbstractMultiWidget { Q_OBJECT public: QmitkMxNMultiWidget(QWidget* parent = nullptr, Qt::WindowFlags f = 0, const QString& multiWidgetName = "mxnmulti"); ~QmitkMxNMultiWidget(); void InitializeMultiWidget() override; void Synchronize(bool synchronized) override; QmitkRenderWindow* GetRenderWindow(const QString& widgetName) const override; QmitkRenderWindow* GetRenderWindow(const mitk::BaseRenderer::ViewDirection& viewDirection) const override; void SetActiveRenderWindowWidget(RenderWindowWidgetPointer activeRenderWindowWidget) override; + /** + * @brief Set the reference geometry for interaction inside the active render windows of the MxNMultiWidget. + * + * @param referenceGeometry The reference geometry which is used for updating the + * time geometry inside the active render window. + * @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom). + * If false, the current crosshair position and the camera zoom will be stored and reset + * after the reference geometry has been updated. + */ + void SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) override; + + /** + * @brief Returns true if the render windows are coupled; false if not. + * + * For the MxNMultiWidget the render windows are typically decoupled. + */ + bool HasCoupledRenderWindows() const override; void SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) override; const mitk::Point3D GetSelectedPosition(const QString& widgetName) const override; void SetCrosshairVisibility(bool visible) override; bool GetCrosshairVisibility() const override; void SetCrosshairGap(unsigned int gapSize) override; void ResetCrosshair() override; void SetWidgetPlaneMode(int userMode) override; mitk::SliceNavigationController* GetTimeNavigationController(); void AddPlanesToDataStorage(); void RemovePlanesFromDataStorage(); public Q_SLOTS: // mouse events void wheelEvent(QWheelEvent* e) override; void mousePressEvent(QMouseEvent* e) override; void moveEvent(QMoveEvent* e) override; Q_SIGNALS: void WheelMoved(QWheelEvent *); void Moved(); protected: void RemoveRenderWindowWidget() override; private: void SetLayoutImpl() override; void SetInteractionSchemeImpl() override { } void CreateRenderWindowWidget(); mitk::SliceNavigationController* m_TimeNavigationController; bool m_CrosshairVisibility; }; #endif // QMITKMXNMULTIWIDGET_H diff --git a/Modules/QtWidgets/include/QmitkRenderWindow.h b/Modules/QtWidgets/include/QmitkRenderWindow.h index b92b71d859..fea6d783d1 100644 --- a/Modules/QtWidgets/include/QmitkRenderWindow.h +++ b/Modules/QtWidgets/include/QmitkRenderWindow.h @@ -1,156 +1,163 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKRENDERWINDOW_H #define QMITKRENDERWINDOW_H #include "mitkRenderWindowBase.h" #include "QmitkRenderWindowMenu.h" #include #include #include #include "mitkBaseRenderer.h" #include "mitkInteractionEventConst.h" +#include + class QDragEnterEvent; class QDropEvent; class QInputEvent; class QMouseEvent; /** * \ingroup QmitkModule * \brief MITK implementation of the QVTKWidget */ class MITKQTWIDGETS_EXPORT QmitkRenderWindow : public QVTKOpenGLNativeWidget, public mitk::RenderWindowBase { Q_OBJECT public: QmitkRenderWindow( QWidget *parent = nullptr, const QString &name = "unnamed renderwindow", mitk::VtkPropRenderer *renderer = nullptr); ~QmitkRenderWindow() override; /** * \brief Whether Qt events should be passed to parent (default: true) * * With introduction of the QVTKWidget the behaviour regarding Qt events changed. * QVTKWidget "accepts" Qt events like mouse clicks (i.e. set an "accepted" flag). * When this flag is set, Qt fininshed handling of this event -- otherwise it is * reached through to the widget's parent. * * This reaching through to the parent was implicitly required by QmitkMaterialWidget / QmitkMaterialShowCase. * * The default behaviour of QmitkRenderWindow is now to clear the "accepted" flag * of Qt events after they were handled by QVTKWidget. This way parents can also * handle events. * * If you don't want this behaviour, call SetResendQtEvents(true) on your render window. */ virtual void SetResendQtEvents(bool resend); // Set Layout Index to define the Layout Type void SetLayoutIndex(QmitkRenderWindowMenu::LayoutIndex layoutIndex); // Get Layout Index to define the Layout Type QmitkRenderWindowMenu::LayoutIndex GetLayoutIndex(); // MenuWidget need to update the Layout Design List when Layout had changed void UpdateLayoutDesignList(QmitkRenderWindowMenu::LayoutDesign layoutDesign); void UpdateCrosshairVisibility(bool); void UpdateCrosshairRotationMode(int); // Activate or Deactivate MenuWidget. void ActivateMenuWidget(bool state); bool GetActivateMenuWidgetFlag() { return m_MenuWidgetActivated; } + + void ShowOverlayMessage(bool show); + // Get it from the QVTKWidget parent vtkRenderWindow *GetVtkRenderWindow() override { return this->renderWindow(); } vtkRenderWindowInteractor *GetVtkRenderWindowInteractor() override { return nullptr; } protected: // catch-all event handler bool event(QEvent *e) override; // overloaded move handler void moveEvent(QMoveEvent *event) override; // overloaded show handler void showEvent(QShowEvent *event) override; // overloaded enter handler void enterEvent(QEvent *) override; // overloaded leave handler void leaveEvent(QEvent *) override; // Overloaded resize handler, see decs in QVTKOpenGLWidget. // Basically, we have to ensure the VTK rendering is updated for each change in window size. void resizeGL(int w, int h) override; /// \brief Simply says we accept the event type. void dragEnterEvent(QDragEnterEvent *event) override; /// \brief If the dropped type is application/x-mitk-datanodes we process the request by converting to mitk::DataNode /// pointers and emitting the NodesDropped signal. void dropEvent(QDropEvent *event) override; Q_SIGNALS: void LayoutDesignChanged(QmitkRenderWindowMenu::LayoutDesign); void ResetView(); void CrosshairRotationModeChanged(int); void CrosshairVisibilityChanged(bool); void moved(); /// \brief Emits a signal to say that this window has had the following nodes dropped on it. void NodesDropped(QmitkRenderWindow *thisWindow, std::vector nodes); private Q_SLOTS: void DeferredHideMenu(); private: // Helper Functions to Convert Qt-Events to Mitk-Events mitk::Point2D GetMousePosition(QMouseEvent *me) const; mitk::Point2D GetMousePosition(QWheelEvent *we) const; mitk::InteractionEvent::MouseButtons GetEventButton(QMouseEvent *me) const; mitk::InteractionEvent::MouseButtons GetButtonState(QMouseEvent *me) const; mitk::InteractionEvent::ModifierKeys GetModifiers(QInputEvent *me) const; mitk::InteractionEvent::MouseButtons GetButtonState(QWheelEvent *we) const; std::string GetKeyLetter(QKeyEvent *ke) const; int GetDelta(QWheelEvent *we) const; void UpdateStatusBar(mitk::Point2D pointerPositionOnScreen); bool m_ResendQtEvents; QmitkRenderWindowMenu *m_MenuWidget; bool m_MenuWidgetActivated; QmitkRenderWindowMenu::LayoutIndex m_LayoutIndex; vtkSmartPointer m_InternalRenderWindow; + QmitkSimpleTextOverlayWidget* m_GeometryViolationWarningOverlay; + }; #endif // QMITKRENDERWINDOW_H diff --git a/Modules/QtWidgets/include/QmitkRenderWindowContextDataStorageInspector.h b/Modules/QtWidgets/include/QmitkRenderWindowContextDataStorageInspector.h index 5f07548423..00a5e77477 100644 --- a/Modules/QtWidgets/include/QmitkRenderWindowContextDataStorageInspector.h +++ b/Modules/QtWidgets/include/QmitkRenderWindowContextDataStorageInspector.h @@ -1,91 +1,90 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKRENDERWINDOWCONTEXTDATASTORAGEINSPECTOR_H #define QMITKRENDERWINDOWCONTEXTDATASTORAGEINSPECTOR_H // qt widgets module #include "MitkQtWidgetsExports.h" #include "ui_QmitkRenderWindowContextDataStorageInspector.h" // render window manager module #include #include // qt widgets module #include // mitk core #include /** * The 'QmitkRenderWindowContextDataStorageInspector' offers a GUI to manipulate the base renderer / render windows of the MITK workbench. * * In order to use this widget, a (e.g.) plugin has to set the controlled renderer, which will be forwarded to * a render window view direction controller. */ class MITKQTWIDGETS_EXPORT QmitkRenderWindowContextDataStorageInspector : public QmitkAbstractDataStorageInspector { Q_OBJECT public: QmitkRenderWindowContextDataStorageInspector(QWidget* parent = nullptr, mitk::BaseRenderer* renderer = nullptr); // override from 'QmitkAbstractDataStorageInspector' /** * @brief See 'QmitkAbstractDataStorageInspector' */ QAbstractItemView* GetView() override; /** * @brief See 'QmitkAbstractDataStorageInspector' */ const QAbstractItemView* GetView() const override; /** * @brief See 'QmitkAbstractDataStorageInspector' */ void SetSelectionMode(SelectionMode mode) override; /** * @brief See 'QmitkAbstractDataStorageInspector' */ SelectionMode GetSelectionMode() const override; QItemSelectionModel* GetDataNodeSelectionModel() const; Q_SIGNALS: void ReinitAction(QList selectedNodes); void ResetAction(QList selectedNodes); private Q_SLOTS: void ModelRowsInserted(const QModelIndex& parent, int start, int end); void ResetRenderer(); void OnContextMenuRequested(const QPoint& pos); void OnReinit(); void OnReset(); private: void Initialize() override; void SetUpConnections(); - QList GetSelectedNodes(); Ui::QmitkRenderWindowContextDataStorageInspector m_Controls; std::unique_ptr m_StorageModel; std::unique_ptr m_RenderWindowLayerController; }; #endif // QMITKRENDERWINDOWCONTEXTDATASTORAGEINSPECTOR_H diff --git a/Modules/QtWidgets/include/QmitkStdMultiWidget.h b/Modules/QtWidgets/include/QmitkStdMultiWidget.h index 0f45a0bcae..c9b4e1dceb 100644 --- a/Modules/QtWidgets/include/QmitkStdMultiWidget.h +++ b/Modules/QtWidgets/include/QmitkStdMultiWidget.h @@ -1,151 +1,169 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSTDMULTIWIDGET_H #define QMITKSTDMULTIWIDGET_H // qt widgets module #include "MitkQtWidgetsExports.h" #include "QmitkAbstractMultiWidget.h" /** * @brief The 'QmitkStdMultiWidget' is a 'QmitkAbstractMultiWidget' that is used to display multiple render windows at once. * Render windows are predefined in a 2x2 design with 3 different 2D view planes and a 3D render window. */ class MITKQTWIDGETS_EXPORT QmitkStdMultiWidget : public QmitkAbstractMultiWidget { Q_OBJECT public: QmitkStdMultiWidget( QWidget *parent = nullptr, Qt::WindowFlags f = nullptr, const QString &name = "stdmulti"); ~QmitkStdMultiWidget() override; virtual void InitializeMultiWidget() override; virtual QmitkRenderWindow* GetRenderWindow(const QString& widgetName) const override; virtual QmitkRenderWindow* GetRenderWindow(const mitk::BaseRenderer::ViewDirection& viewDirection) const override; + /** + * @brief Set the reference geometry for interaction inside all render windows of the StdMultiWidget. + * + * @param referenceGeometry The reference geometry which is used for updating the + * time geometry inside all four render windows. + * @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom). + * If false, the current crosshair position and the camera zoom will be stored and reset + * after the reference geometry has been updated. + */ + void SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) override; + + /** + * @brief Returns true if the render windows are coupled; false if not. + * + * For the StdMultiWidget the render windows are typically coupled. + */ + bool HasCoupledRenderWindows() const override; + virtual void SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) override; virtual const mitk::Point3D GetSelectedPosition(const QString& widgetName) const override; virtual void SetCrosshairVisibility(bool) override; virtual bool GetCrosshairVisibility() const override; void SetCrosshairGap(unsigned int gapSize) override; virtual void ResetCrosshair() override; virtual void SetWidgetPlaneMode(int mode) override; mitk::SliceNavigationController* GetTimeNavigationController(); void AddPlanesToDataStorage(); void RemovePlanesFromDataStorage(); /** * @brief Convenience method to get a render window widget. * @param number of the widget (0-3) * @return The render window widget */ QmitkRenderWindow* GetRenderWindow(unsigned int number) const; QmitkRenderWindow* GetRenderWindow1() const; QmitkRenderWindow* GetRenderWindow2() const; QmitkRenderWindow* GetRenderWindow3() const; QmitkRenderWindow* GetRenderWindow4() const; /** * @brief Convenience method to get a widget plane. * @param number of the widget plane (1-3) * @return The widget plane as data node */ mitk::DataNode::Pointer GetWidgetPlane(unsigned int number) const; mitk::DataNode::Pointer GetWidgetPlane1() const; mitk::DataNode::Pointer GetWidgetPlane2() const; mitk::DataNode::Pointer GetWidgetPlane3() const; /** * @brief SetDecorationColor Set the color of the decoration of the 4 widgets. * * This is used to color the frame of the renderwindow and the corner annatation. * For the first 3 widgets, this color is a property of the helper object nodes * which contain the respective plane geometry. For widget 4, this is a member, * since there is no data node for this widget. */ void SetDecorationColor(unsigned int widgetNumber, mitk::Color color); /** * @brief GetDecorationColorForWidget Get the color for annotation, crosshair and rectangle. * @param widgetNumber Number of the renderwindow (0-3). * @return Color in mitk format. */ mitk::Color GetDecorationColor(unsigned int widgetNumber); public Q_SLOTS: // mouse events virtual void mousePressEvent(QMouseEvent*) override; virtual void moveEvent(QMoveEvent* e) override; virtual void wheelEvent(QWheelEvent* e) override; void Fit(); void AddDisplayPlaneSubTree(); void EnsureDisplayContainsPoint(mitk::BaseRenderer *renderer, const mitk::Point3D &p); void SetWidgetPlaneVisibility(const char *widgetName, bool visible, mitk::BaseRenderer *renderer = nullptr); void SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer = nullptr); Q_SIGNALS: void NotifyCrosshairVisibilityChanged(bool visible); void NotifyCrosshairRotationModeChanged(int mode); void WheelMoved(QWheelEvent *); void Moved(); private: virtual void SetLayoutImpl() override; virtual void SetInteractionSchemeImpl() override { } void CreateRenderWindowWidgets(); mitk::SliceNavigationController* m_TimeNavigationController; /** * @brief The 3 helper objects which contain the plane geometry. */ mitk::DataNode::Pointer m_PlaneNode1; mitk::DataNode::Pointer m_PlaneNode2; mitk::DataNode::Pointer m_PlaneNode3; /** * @brief m_ParentNodeForGeometryPlanes This helper object is added to the datastorage * and contains the 3 planes for displaying the image geometry (crosshair and 3D planes). */ mitk::DataNode::Pointer m_ParentNodeForGeometryPlanes; /** * @brief m_DecorationColorWidget4 color for annotation and rectangle of widget 4. * * For other widgets1-3, the color is a property of the respective data node. * There is no node for widget 4, hence, we need an extra member. */ mitk::Color m_DecorationColorWidget4; }; #endif // QMITKSTDMULTIWIDGET_H diff --git a/Modules/QtWidgets/include/mitkRenderWindowLayerUtilities.h b/Modules/QtWidgets/include/mitkRenderWindowLayerUtilities.h index 914c9007a5..637300f3aa 100644 --- a/Modules/QtWidgets/include/mitkRenderWindowLayerUtilities.h +++ b/Modules/QtWidgets/include/mitkRenderWindowLayerUtilities.h @@ -1,75 +1,77 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKRENDERWINDOWLAYERUTILITIES_H #define MITKRENDERWINDOWLAYERUTILITIES_H // qt widgets module #include "MitkQtWidgetsExports.h" // mitk core #include #include #include -#include +#include /** * @brief Render window layer helper functions to retrieve the currently valid layer stack */ namespace mitk { namespace RenderWindowLayerUtilities { typedef std::vector RendererVector; typedef std::map> LayerStack; /** * The base data node of a renderer is supposed to be on layer 0 (zero), which should be the lowest layer in a render window. */ const int BASE_LAYER_INDEX = 0; /** * The top layer index, denoting that no valid (positive) layer index is given and therefore the index should be resolved into the topmost layer index. */ const int TOP_LAYER_INDEX = -1; /** * @brief Return the stack of layers of the given renderer as std::map, which guarantees ordering of the layers. * Stacked layers are only included if they have their "fixedLayer" property set to true and their "layer" property set. * * If "renderer" = nullptr: a layer stack won't be created and an empty "LayerStack" will be returned. * If "withBaseNode" = true: include the base node in the layer stack, if existing. * If "withBaseNode" = false: exclude the base node from the layer stack. * * @param dataStorage Pointer to a data storage instance whose data nodes should be checked and possibly be included. * @param renderer Pointer to the renderer instance for which the layer stack should be generated. * @param withBaseNode Boolean to decide whether the base node should be included in or excluded from the layer stack. */ MITKQTWIDGETS_EXPORT LayerStack GetLayerStack(const DataStorage* dataStorage, const BaseRenderer* renderer, bool withBaseNode); /** * @brief Helper function to get a node predicate that can be used to filter render window specific data nodes. + * The data nodes must have set a 'fixed layer' property for the given renderer. * - * The data nodes must not be 'helper objects'. The must have set a 'fixed layer' property for the given renderer. + * @param renderer Pointer to the renderer instance for which the 'fixed layer' should be true. + * @return The node predicate to filter 'fixed layer' data nodes. */ - MITKQTWIDGETS_EXPORT NodePredicateAnd::Pointer GetRenderWindowPredicate(const BaseRenderer* renderer); + MITKQTWIDGETS_EXPORT NodePredicateBase::Pointer GetRenderWindowPredicate(const BaseRenderer* renderer); /** * @brief Set renderer-specific properties to mark a data node as 'managed by the specific renderer'. * In order for a renderer to manage a data node, the 'fixedLayer' property has to be set for the given renderer. * Additionally, the 'visible' and the 'layer' property are set and allow to individually render a set of nodes * with a specific renderer. * The last two mentioned properties are set so that they initially have the same value as the corresponding * global property. */ MITKQTWIDGETS_EXPORT void SetRenderWindowProperties(mitk::DataNode* dataNode, const BaseRenderer* renderer); } // namespace RenderWindowLayerUtilities } // namespace mitk #endif // MITKRENDERWINDOWLAYERUTILITIES_H diff --git a/Modules/QtWidgets/src/QmitkDataStorageSimpleTreeModel.cpp b/Modules/QtWidgets/src/QmitkDataStorageSimpleTreeModel.cpp index 5cc4153ab6..fa45000ca7 100644 --- a/Modules/QtWidgets/src/QmitkDataStorageSimpleTreeModel.cpp +++ b/Modules/QtWidgets/src/QmitkDataStorageSimpleTreeModel.cpp @@ -1,375 +1,378 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include // qt widgets module #include "QmitkCustomVariants.h" #include "QmitkEnums.h" QmitkDataStorageSimpleTreeModel::QmitkDataStorageSimpleTreeModel(QObject *parent) : QmitkAbstractDataStorageModel(parent) , m_Root(nullptr) { ResetTree(); } QmitkDataStorageSimpleTreeModel::~QmitkDataStorageSimpleTreeModel() { m_Root->Delete(); m_Root = nullptr; } void QmitkDataStorageSimpleTreeModel::ResetTree() { mitk::DataNode::Pointer rootDataNode = mitk::DataNode::New(); rootDataNode->SetName("Data Storage"); m_Root = new TreeItem(rootDataNode, nullptr); } void QmitkDataStorageSimpleTreeModel::DataStorageChanged() { if (m_Root) { m_Root->Delete(); } beginResetModel(); ResetTree(); UpdateModelData(); endResetModel(); } void QmitkDataStorageSimpleTreeModel::NodePredicateChanged() { beginResetModel(); ResetTree(); UpdateModelData(); endResetModel(); } void QmitkDataStorageSimpleTreeModel::NodeAdded(const mitk::DataNode *node) { auto dataStorage = m_DataStorage.Lock(); if (node == nullptr || dataStorage.IsNull() || !dataStorage->Exists(node) || m_Root->Find(node) != nullptr) return; - this->AddNodeInternal(node); + if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)) + { + this->AddNodeInternal(node); + } } void QmitkDataStorageSimpleTreeModel::NodeChanged(const mitk::DataNode *node) { TreeItem *treeItem = m_Root->Find(node); if (treeItem) { TreeItem *parentTreeItem = treeItem->GetParent(); // as the root node should not be removed one should always have a parent item if (!parentTreeItem) return; QModelIndex index = this->createIndex(treeItem->GetIndex(), 0, treeItem); // now emit the dataChanged signal emit dataChanged(index, index); } } void QmitkDataStorageSimpleTreeModel::NodeRemoved(const mitk::DataNode *node) { if (node == nullptr || !m_Root) return; TreeItem *treeItem = m_Root->Find(node); if (!treeItem) return; // return because there is no treeitem containing this node TreeItem *parentTreeItem = treeItem->GetParent(); QModelIndex parentIndex = this->IndexFromTreeItem(parentTreeItem); // emit beginRemoveRows event (QModelIndex is empty because we dont have a tree model) this->beginRemoveRows(parentIndex, treeItem->GetIndex(), treeItem->GetIndex()); // remove node std::vector children = treeItem->GetChildren(); m_TreeItems.remove(treeItem); delete treeItem; //delete in tree if (!children.empty()) { //if not empty we have to rebuild the whole representation, //because the children could be now top level, or at another //source/parent. this->UpdateModelData(); } } QModelIndex QmitkDataStorageSimpleTreeModel::index(int row, int column, const QModelIndex &parent) const { TreeItem *parentItem; if (!parent.isValid() || parent.model() != this) parentItem = m_Root; else parentItem = static_cast(parent.internalPointer()); if (parentItem) { TreeItem *childItem = parentItem->GetChild(row); if (childItem) return createIndex(row, column, childItem); } return QModelIndex(); } QModelIndex QmitkDataStorageSimpleTreeModel::parent(const QModelIndex &child) const { if (!child.isValid() || !m_Root || child.model() != this) return QModelIndex(); TreeItem *childItem = this->TreeItemFromIndex(child); if (!childItem) return QModelIndex(); TreeItem *parentItem = childItem->GetParent(); if (parentItem == m_Root) return QModelIndex(); return this->createIndex(parentItem->GetIndex(), 0, parentItem); } QmitkDataStorageSimpleTreeModel::TreeItem *QmitkDataStorageSimpleTreeModel::TreeItemFromIndex( const QModelIndex &index) const { if (index.isValid() && index.model() == this) { auto item = static_cast(index.internalPointer()); auto finding = std::find(std::begin(m_TreeItems), std::end(m_TreeItems), item); if (finding == std::end(m_TreeItems)) { return nullptr; } return item; } else return m_Root; } int QmitkDataStorageSimpleTreeModel::rowCount(const QModelIndex &parent) const { TreeItem *parentTreeItem = this->TreeItemFromIndex(parent); if (parentTreeItem) return parentTreeItem->GetChildCount(); else return 0; } int QmitkDataStorageSimpleTreeModel::columnCount(const QModelIndex &/*parent*/) const { return 1; } QVariant QmitkDataStorageSimpleTreeModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.model() != this) { return QVariant(); } auto treeItem = this->TreeItemFromIndex(index); if (!treeItem) return QVariant(); mitk::DataNode *dataNode = treeItem->GetDataNode(); QString nodeName = QString::fromStdString(dataNode->GetName()); if (nodeName.isEmpty()) { nodeName = "unnamed"; } if (role == Qt::DisplayRole) return nodeName; else if (role == Qt::ToolTipRole) return nodeName; else if (role == Qt::DecorationRole) { QmitkNodeDescriptor *nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode); return nodeDescriptor->GetIcon(dataNode); } else if (role == QmitkDataNodeRole) { return QVariant::fromValue(mitk::DataNode::Pointer(dataNode)); } else if (role == QmitkDataNodeRawPointerRole) { return QVariant::fromValue(dataNode); } return QVariant(); } bool QmitkDataStorageSimpleTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || index.model() != this) return false; auto treeItem = this->TreeItemFromIndex(index); if (!treeItem) return false; mitk::DataNode *dataNode = treeItem->GetDataNode(); if (!dataNode) return false; if (role == Qt::EditRole && !value.toString().isEmpty()) { dataNode->SetName(value.toString().toStdString().c_str()); } else if (role == Qt::CheckStateRole) { // Please note: value.toInt() returns 2, independentely from the actual checkstate of the index element. // Therefore the checkstate is being estimated again here. QVariant qcheckstate = index.data(Qt::CheckStateRole); int checkstate = qcheckstate.toInt(); bool isVisible = bool(checkstate); dataNode->SetVisibility(!isVisible); } // inform listeners about changes emit dataChanged(index, index); return true; } QVariant QmitkDataStorageSimpleTreeModel::headerData(int /*section*/, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole && m_Root) return QString::fromStdString(m_Root->GetDataNode()->GetName()); return QVariant(); } Qt::ItemFlags QmitkDataStorageSimpleTreeModel::flags(const QModelIndex &index) const { if (index.isValid() && index.model() == this) { auto treeItem = this->TreeItemFromIndex(index); if (!treeItem) return Qt::NoItemFlags; const auto dataNode = treeItem->GetDataNode(); if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(dataNode)) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable; } else { return Qt::NoItemFlags; } } return Qt::NoItemFlags; } mitk::DataNode *QmitkDataStorageSimpleTreeModel::GetParentNode(const mitk::DataNode *node) const { mitk::DataNode *dataNode = nullptr; mitk::DataStorage::SetOfObjects::ConstPointer _Sources = m_DataStorage.Lock()->GetSources(node); if (_Sources->Size() > 0) dataNode = _Sources->front(); return dataNode; } void QmitkDataStorageSimpleTreeModel::AddNodeInternal(const mitk::DataNode *node) { auto dataStorage = m_DataStorage.Lock(); if (node == nullptr || dataStorage.IsNull() || !dataStorage->Exists(node) || m_Root->Find(node) != nullptr) return; // find out if we have a root node TreeItem *parentTreeItem = m_Root; QModelIndex index; mitk::DataNode *parentDataNode = this->GetParentNode(node); if (parentDataNode) // no top level data node { parentTreeItem = m_Root->Find(parentDataNode); // find the corresponding tree item if (!parentTreeItem) { this->NodeAdded(parentDataNode); parentTreeItem = m_Root->Find(parentDataNode); if (!parentTreeItem) return; } // get the index of this parent with the help of the grand parent index = this->createIndex(parentTreeItem->GetIndex(), 0, parentTreeItem); } int firstRowWithASiblingBelow = 0; int nodeLayer = -1; node->GetIntProperty("layer", nodeLayer); for (TreeItem *siblingTreeItem : parentTreeItem->GetChildren()) { int siblingLayer = -1; if (mitk::DataNode *siblingNode = siblingTreeItem->GetDataNode()) { siblingNode->GetIntProperty("layer", siblingLayer); } if (nodeLayer > siblingLayer) { break; } ++firstRowWithASiblingBelow; } beginInsertRows(index, firstRowWithASiblingBelow, firstRowWithASiblingBelow); auto newNode = new TreeItem(const_cast(node)); parentTreeItem->InsertChild(newNode, firstRowWithASiblingBelow); m_TreeItems.push_back(newNode); endInsertRows(); } QModelIndex QmitkDataStorageSimpleTreeModel::IndexFromTreeItem(TreeItem *item) const { if (item == m_Root) return QModelIndex(); else return this->createIndex(item->GetIndex(), 0, item); } void QmitkDataStorageSimpleTreeModel::UpdateModelData() { auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNotNull()) { auto nodeset = m_NodePredicate != nullptr ? dataStorage->GetSubset(m_NodePredicate) : dataStorage->GetAll(); for (const auto& node : *nodeset) { this->AddNodeInternal(node); } } } diff --git a/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui b/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui index 8af3c1c083..1c34f9572c 100644 --- a/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui +++ b/Modules/QtWidgets/src/QmitkMemoryUsageIndicator.ui @@ -1,93 +1,90 @@ MITKQTWIDGETS_EXPORT QmitkMemoryUsageIndicator 0 0 124 22 0 0 32000 32000 Form1 Memory usage in % of physical memory 0 - + + 0 + + + 0 + + + 0 + + 0 - + 0 0 000,00 % - - Qt::AutoText - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true - + 20 20 - - 0 - - - QmitkApplicationBase/image0 - true - - false - mitkCommon.h string qpixmap.h diff --git a/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp b/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp index e5f61ab68d..3ea50ac3f6 100644 --- a/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp +++ b/Modules/QtWidgets/src/QmitkMemoryUsageIndicatorView.cpp @@ -1,146 +1,130 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ /**************************************************************************** ** ui.h extension file, included from the uic-generated form implementation. ** ** If you want to add, delete, or rename functions or slots, use ** Qt Designer to update this file, preserving your code. ** ** You should not define a constructor or destructor in this file. ** Instead, write your code in functions called init() and destroy(). ** These will automatically be called by the form's constructor and ** destructor. *****************************************************************************/ -#include "QmitkMemoryUsageIndicatorView.h" -#include +#include -#include -#include -#include -#include -#include +#include #include -#include -#include -#include "QmitkMemoryUsageIndicatorImagesGreen.xpm" -#include "QmitkMemoryUsageIndicatorImagesOrange.xpm" -#include "QmitkMemoryUsageIndicatorImagesRed.xpm" -#include "QmitkMemoryUsageIndicatorImagesYellow.xpm" +#include + +#include +#include +#include +#include + +#include -QmitkMemoryUsageIndicatorView::QmitkMemoryUsageIndicatorView(QWidget * /*parent*/, Qt::WindowFlags /*f*/) +QmitkMemoryUsageIndicatorView::QmitkMemoryUsageIndicatorView(QWidget*) + : m_Ui(new Ui::QmitkMemoryUsageIndicator), + m_PreviousState(0), + m_States { + std::make_pair(0.0f, QPixmap(QmitkMemoryUsageIndicatorImagesGreen_xpm)), + std::make_pair(50.0f, QPixmap(QmitkMemoryUsageIndicatorImagesYellow_xpm)), + std::make_pair(65.0f, QPixmap(QmitkMemoryUsageIndicatorImagesOrange_xpm)), + std::make_pair(85.0f, QPixmap(QmitkMemoryUsageIndicatorImagesRed_xpm)) + } { - this->setupUi(this); + m_Ui->setupUi(this); + m_Ui->led->setPixmap(m_States[0].second); auto timer = new QTimer(this); - QObject::connect(timer, SIGNAL(timeout()), this, SLOT(UpdateMemoryUsage())); + connect(timer, &QTimer::timeout, this, &QmitkMemoryUsageIndicatorView::UpdateMemoryUsage); timer->start(1000); - m_LEDGreen = QPixmap(QmitkMemoryUsageIndicatorImagesGreen_xpm); - m_LEDYellow = QPixmap(QmitkMemoryUsageIndicatorImagesYellow_xpm); - m_LEDOrange = QPixmap(QmitkMemoryUsageIndicatorImagesOrange_xpm); - m_LEDRed = QPixmap(QmitkMemoryUsageIndicatorImagesRed_xpm); - m_LED->setPixmap(m_LEDGreen); - m_PreviousState = 0; } QmitkMemoryUsageIndicatorView::~QmitkMemoryUsageIndicatorView() { } void QmitkMemoryUsageIndicatorView::UpdateMemoryUsage() { size_t processSize = mitk::MemoryUtilities::GetProcessMemoryUsage(); size_t totalSize = mitk::MemoryUtilities::GetTotalSizeOfPhysicalRam(); - float percentage = ((float)processSize / (float)totalSize) * 100.0; - m_Label->setText(GetMemoryDescription(processSize, percentage).c_str()); - if (percentage < 50.0) - { - if (m_PreviousState != 0) - { - m_LED->setPixmap(m_LEDGreen); - m_PreviousState = 0; - m_LED->update(); - } - } - else if (percentage < 65.0) - { - if (m_PreviousState != 1) - { - m_LED->setPixmap(m_LEDYellow); - m_PreviousState = 1; - m_LED->update(); - } - } - else if (percentage < 80.0) - { - if (m_PreviousState != 2) - { - m_LED->setPixmap(m_LEDOrange); - m_PreviousState = 2; - m_LED->update(); - } - } - else + float percentage = static_cast(processSize) / totalSize * 100.0f; + + m_Ui->label->setText(QString::fromStdString(this->GetMemoryDescription(processSize, percentage))); + + for (size_t i = m_States.size() - 1; i >= 0; --i) { - if (m_PreviousState != 3) + if (percentage >= m_States[i].first) { - m_LED->setPixmap(m_LEDRed); - m_PreviousState = 3; - m_LED->update(); + if (m_PreviousState != i) + { + m_Ui->led->setPixmap(m_States[i].second); + m_PreviousState = i; + } + + break; } } } std::string QmitkMemoryUsageIndicatorView::FormatMemorySize(size_t size) { double val = size; - std::string descriptor("B"); - if (val >= 1000.0) + std::string unit; + + if (val >= 1024.0) { val /= 1024.0; - descriptor = "KB"; + unit = "K"; } - if (val >= 1000.0) + + if (val >= 1024.0) { val /= 1024.0; - descriptor = "MB"; + unit = "M"; } - if (val >= 1000.0) + + if (val >= 1024.0) { val /= 1024.0; - descriptor = "GB"; + unit = "G"; } + + unit += "B"; + std::ostringstream str; str.imbue(std::locale::classic()); - str << std::fixed << std::setprecision(2) << val << " " << descriptor; + str << std::fixed << std::setprecision(2) << val << " " << unit; return str.str(); } std::string QmitkMemoryUsageIndicatorView::FormatPercentage(double val) { std::ostringstream str; str.imbue(std::locale::classic()); - str << std::fixed << std::setprecision(2) << val << " " - << "%"; + str << std::fixed << std::setprecision(2) << val << " " << "%"; return str.str(); } std::string QmitkMemoryUsageIndicatorView::GetMemoryDescription(size_t processSize, float percentage) { std::ostringstream str; str.imbue(std::locale::classic()); str << FormatMemorySize(processSize) << " (" << FormatPercentage(percentage) << ")"; return str.str(); } diff --git a/Modules/QtWidgets/src/QmitkMxNMultiWidget.cpp b/Modules/QtWidgets/src/QmitkMxNMultiWidget.cpp index f66d3c6ad0..4b049ca746 100644 --- a/Modules/QtWidgets/src/QmitkMxNMultiWidget.cpp +++ b/Modules/QtWidgets/src/QmitkMxNMultiWidget.cpp @@ -1,348 +1,382 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMxNMultiWidget.h" #include "QmitkRenderWindowWidget.h" // mitk core #include #include #include // qt #include #include QmitkMxNMultiWidget::QmitkMxNMultiWidget(QWidget* parent, Qt::WindowFlags f/* = 0*/, const QString& multiWidgetName/* = "mxnmulti"*/) : QmitkAbstractMultiWidget(parent, f, multiWidgetName) , m_TimeNavigationController(nullptr) , m_CrosshairVisibility(false) { m_TimeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController(); } QmitkMxNMultiWidget::~QmitkMxNMultiWidget() { auto allRenderWindows = this->GetRenderWindows(); for (auto& renderWindow : allRenderWindows) { m_TimeNavigationController->Disconnect(renderWindow->GetSliceNavigationController()); } } void QmitkMxNMultiWidget::InitializeMultiWidget() { SetLayout(1, 1); SetDisplayActionEventHandler(std::make_unique()); auto displayActionEventHandler = GetDisplayActionEventHandler(); if (nullptr != displayActionEventHandler) { displayActionEventHandler->InitActions(); } } void QmitkMxNMultiWidget::Synchronize(bool synchronized) { if (synchronized) { SetDisplayActionEventHandler(std::make_unique()); } else { SetDisplayActionEventHandler(std::make_unique()); } auto displayActionEventHandler = GetDisplayActionEventHandler(); if (nullptr != displayActionEventHandler) { displayActionEventHandler->InitActions(); } } QmitkRenderWindow* QmitkMxNMultiWidget::GetRenderWindow(const QString& widgetName) const { if ("axial" == widgetName || "sagittal" == widgetName || "coronal" == widgetName || "3d" == widgetName) { return GetActiveRenderWindowWidget()->GetRenderWindow(); } return QmitkAbstractMultiWidget::GetRenderWindow(widgetName); } QmitkRenderWindow* QmitkMxNMultiWidget::GetRenderWindow(const mitk::BaseRenderer::ViewDirection& /*viewDirection*/) const { // currently no mapping between view directions and render windows // simply return the currently active render window return GetActiveRenderWindowWidget()->GetRenderWindow(); } void QmitkMxNMultiWidget::SetActiveRenderWindowWidget(RenderWindowWidgetPointer activeRenderWindowWidget) { auto currentActiveRenderWindowWidget = GetActiveRenderWindowWidget(); if (currentActiveRenderWindowWidget == activeRenderWindowWidget) { return; } // reset the decoration color of the previously active render window widget if (nullptr != currentActiveRenderWindowWidget) { auto decorationColor = currentActiveRenderWindowWidget->GetDecorationColor(); QColor hexColor(decorationColor[0] * 255, decorationColor[1] * 255, decorationColor[2] * 255); currentActiveRenderWindowWidget->setStyleSheet("QmitkRenderWindowWidget { border: 2px solid " + hexColor.name(QColor::HexRgb) + "; }"); } // set the new decoration color of the currently active render window widget if (nullptr != activeRenderWindowWidget) { activeRenderWindowWidget->setStyleSheet("QmitkRenderWindowWidget { border: 2px solid #FF6464; }"); } QmitkAbstractMultiWidget::SetActiveRenderWindowWidget(activeRenderWindowWidget); } +void QmitkMxNMultiWidget::SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) +{ + auto* renderingManager = mitk::RenderingManager::GetInstance(); + mitk::Point3D currentPosition = mitk::Point3D(); + unsigned int imageTimeStep = 0; + if (!resetCamera) + { + // store the current position to set it again later, if the camera should not be reset + currentPosition = this->GetSelectedPosition(""); + + // store the current time step to set it again later, if the camera should not be reset + const auto currentTimePoint = renderingManager->GetTimeNavigationController()->GetSelectedTimePoint(); + if (referenceGeometry->IsValidTimePoint(currentTimePoint)) + { + imageTimeStep = referenceGeometry->TimePointToTimeStep(currentTimePoint); + } + } + + // initialize active render window + renderingManager->InitializeView( + this->GetActiveRenderWindowWidget()->GetRenderWindow()->GetVtkRenderWindow(), referenceGeometry, resetCamera); + + if (!resetCamera) + { + this->SetSelectedPosition(currentPosition, ""); + renderingManager->GetTimeNavigationController()->GetTime()->SetPos(imageTimeStep); + } +} + +bool QmitkMxNMultiWidget::HasCoupledRenderWindows() const +{ + return false; +} + void QmitkMxNMultiWidget::SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) { RenderWindowWidgetPointer renderWindowWidget; - if (widgetName.isNull()) + if (widgetName.isNull() || widgetName.isEmpty()) { renderWindowWidget = GetActiveRenderWindowWidget(); } else { renderWindowWidget = GetRenderWindowWidget(widgetName); } if (nullptr != renderWindowWidget) { renderWindowWidget->GetSliceNavigationController()->SelectSliceByPoint(newPosition); renderWindowWidget->SetCrosshairPosition(newPosition); return; } MITK_ERROR << "Position can not be set for an unknown render window widget."; } const mitk::Point3D QmitkMxNMultiWidget::GetSelectedPosition(const QString& widgetName) const { RenderWindowWidgetPointer renderWindowWidget; - if (widgetName.isNull()) + if (widgetName.isNull() || widgetName.isEmpty()) { renderWindowWidget = GetActiveRenderWindowWidget(); } else { renderWindowWidget = GetRenderWindowWidget(widgetName); } if (nullptr != renderWindowWidget) { return renderWindowWidget->GetCrosshairPosition(); } MITK_ERROR << "Crosshair position can not be retrieved."; return mitk::Point3D(0.0); } void QmitkMxNMultiWidget::SetCrosshairVisibility(bool visible) { // get the specific render window that sent the signal QmitkRenderWindow* renderWindow = qobject_cast(sender()); if (nullptr == renderWindow) { return; } auto renderWindowWidget = this->GetRenderWindowWidget(renderWindow); renderWindowWidget->SetCrosshairVisibility(visible); } bool QmitkMxNMultiWidget::GetCrosshairVisibility() const { // get the specific render window that sent the signal QmitkRenderWindow* renderWindow = qobject_cast(sender()); if (nullptr == renderWindow) { return false; } auto renderWindowWidget = this->GetRenderWindowWidget(renderWindow); return renderWindowWidget->GetCrosshairVisibility(); } void QmitkMxNMultiWidget::SetCrosshairGap(unsigned int gapSize) { auto renderWindowWidgets = this->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->SetCrosshairGap(gapSize); } } void QmitkMxNMultiWidget::ResetCrosshair() { auto dataStorage = GetDataStorage(); if (nullptr == dataStorage) { return; } // get the specific render window that sent the signal QmitkRenderWindow* renderWindow = qobject_cast(sender()); if (nullptr == renderWindow) { return; } mitk::RenderingManager::GetInstance()->InitializeViewByBoundingObjects(renderWindow->GetRenderWindow(), dataStorage); SetWidgetPlaneMode(mitk::InteractionSchemeSwitcher::MITKStandard); } void QmitkMxNMultiWidget::SetWidgetPlaneMode(int userMode) { MITK_DEBUG << "Changing crosshair mode to " << userMode; switch (userMode) { case 0: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKStandard); break; case 1: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKRotationUncoupled); break; case 2: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKRotationCoupled); break; case 3: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKSwivel); break; } } mitk::SliceNavigationController* QmitkMxNMultiWidget::GetTimeNavigationController() { return m_TimeNavigationController; } void QmitkMxNMultiWidget::AddPlanesToDataStorage() { auto renderWindowWidgets = this->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->AddPlanesToDataStorage(); } } void QmitkMxNMultiWidget::RemovePlanesFromDataStorage() { auto renderWindowWidgets = this->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->RemovePlanesFromDataStorage(); } } ////////////////////////////////////////////////////////////////////////// // PUBLIC SLOTS // MOUSE EVENTS ////////////////////////////////////////////////////////////////////////// void QmitkMxNMultiWidget::wheelEvent(QWheelEvent* e) { emit WheelMoved(e); } void QmitkMxNMultiWidget::mousePressEvent(QMouseEvent*) { // nothing here, but necessary for mouse interactions (.xml-configuration files) } void QmitkMxNMultiWidget::moveEvent(QMoveEvent* e) { QWidget::moveEvent(e); // it is necessary to readjust the position of the overlays as the MultiWidget has moved // unfortunately it's not done by QmitkRenderWindow::moveEvent -> must be done here emit Moved(); } void QmitkMxNMultiWidget::RemoveRenderWindowWidget() { auto renderWindowWidgets = this->GetRenderWindowWidgets(); auto iterator = renderWindowWidgets.find(this->GetNameFromIndex(this->GetNumberOfRenderWindowWidgets() - 1)); if (iterator == renderWindowWidgets.end()) { return; } // disconnect each signal of this render window widget RenderWindowWidgetPointer renderWindowWidgetToRemove = iterator->second; m_TimeNavigationController->Disconnect(renderWindowWidgetToRemove->GetSliceNavigationController()); QmitkAbstractMultiWidget::RemoveRenderWindowWidget(); } ////////////////////////////////////////////////////////////////////////// // PRIVATE ////////////////////////////////////////////////////////////////////////// void QmitkMxNMultiWidget::SetLayoutImpl() { int requiredRenderWindowWidgets = GetRowCount() * GetColumnCount(); int existingRenderWindowWidgets = GetRenderWindowWidgets().size(); int difference = requiredRenderWindowWidgets - existingRenderWindowWidgets; while (0 < difference) { // more render window widgets needed CreateRenderWindowWidget(); --difference; } while (0 > difference) { // less render window widgets needed RemoveRenderWindowWidget(); ++difference; } auto firstRenderWindowWidget = GetFirstRenderWindowWidget(); if (nullptr != firstRenderWindowWidget) { SetActiveRenderWindowWidget(firstRenderWindowWidget); } GetMultiWidgetLayoutManager()->SetLayoutDesign(QmitkMultiWidgetLayoutManager::LayoutDesign::DEFAULT); } void QmitkMxNMultiWidget::CreateRenderWindowWidget() { // create the render window widget and connect signal / slot QString renderWindowWidgetName = GetNameFromIndex(GetNumberOfRenderWindowWidgets()); RenderWindowWidgetPointer renderWindowWidget = std::make_shared(this, renderWindowWidgetName, GetDataStorage(), true); renderWindowWidget->SetCornerAnnotationText(renderWindowWidgetName.toStdString()); AddRenderWindowWidget(renderWindowWidgetName, renderWindowWidget); auto renderWindow = renderWindowWidget->GetRenderWindow(); auto layoutManager = GetMultiWidgetLayoutManager(); connect(renderWindow, &QmitkRenderWindow::LayoutDesignChanged, layoutManager, &QmitkMultiWidgetLayoutManager::SetLayoutDesign); connect(renderWindow, &QmitkRenderWindow::ResetView, this, &QmitkMxNMultiWidget::ResetCrosshair); connect(renderWindow, &QmitkRenderWindow::CrosshairVisibilityChanged, this, &QmitkMxNMultiWidget::SetCrosshairVisibility); connect(renderWindow, &QmitkRenderWindow::CrosshairRotationModeChanged, this, &QmitkMxNMultiWidget::SetWidgetPlaneMode); // connect time navigation controller to react on geometry time events with the render window's slice naviation controller m_TimeNavigationController->ConnectGeometryTimeEvent(renderWindow->GetSliceNavigationController()); // reverse connection between the render window's slice navigation controller and the time navigation controller renderWindow->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController); } diff --git a/Modules/QtWidgets/src/QmitkRenderWindow.cpp b/Modules/QtWidgets/src/QmitkRenderWindow.cpp index af81ae89ec..29244be83f 100644 --- a/Modules/QtWidgets/src/QmitkRenderWindow.cpp +++ b/Modules/QtWidgets/src/QmitkRenderWindow.cpp @@ -1,492 +1,505 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRenderWindow.h" #include "mitkInteractionKeyEvent.h" #include "mitkInternalEvent.h" #include "mitkMouseDoubleClickEvent.h" #include "mitkMouseMoveEvent.h" #include "mitkMousePressEvent.h" #include "mitkMouseReleaseEvent.h" #include "mitkMouseWheelEvent.h" #include #include #include #include #include #include #include #include #include #include #include #include "QmitkMimeTypes.h" #include "QmitkRenderWindowMenu.h" QmitkRenderWindow::QmitkRenderWindow(QWidget *parent, const QString &name, mitk::VtkPropRenderer *) : QVTKOpenGLNativeWidget(parent) , m_ResendQtEvents(true) , m_MenuWidget(nullptr) , m_MenuWidgetActivated(false) , m_LayoutIndex(QmitkRenderWindowMenu::LayoutIndex::AXIAL) + , m_GeometryViolationWarningOverlay(nullptr) { m_InternalRenderWindow = vtkSmartPointer::New(); m_InternalRenderWindow->SetMultiSamples(0); m_InternalRenderWindow->SetAlphaBitPlanes(0); setRenderWindow(m_InternalRenderWindow); Initialize(name.toStdString().c_str()); setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setSizePolicy(sizePolicy); + + // setup overlay widget to show a warning message + m_GeometryViolationWarningOverlay = new QmitkSimpleTextOverlayWidget(this); + m_GeometryViolationWarningOverlay->setVisible(false); + m_GeometryViolationWarningOverlay->SetOverlayText( + QStringLiteral("

Interaction is not possible because the " + "render window is not aligned.

")); } QmitkRenderWindow::~QmitkRenderWindow() { Destroy(); // Destroy mitkRenderWindowBase } void QmitkRenderWindow::SetResendQtEvents(bool resend) { m_ResendQtEvents = resend; } void QmitkRenderWindow::SetLayoutIndex(QmitkRenderWindowMenu::LayoutIndex layoutIndex) { m_LayoutIndex = layoutIndex; if (nullptr != m_MenuWidget) { m_MenuWidget->SetLayoutIndex(layoutIndex); } } QmitkRenderWindowMenu::LayoutIndex QmitkRenderWindow::GetLayoutIndex() { if (nullptr != m_MenuWidget) { return m_MenuWidget->GetLayoutIndex(); } else { return QmitkRenderWindowMenu::LayoutIndex::AXIAL; } } void QmitkRenderWindow::UpdateLayoutDesignList(QmitkRenderWindowMenu::LayoutDesign layoutDesign) { if (nullptr != m_MenuWidget) { m_MenuWidget->UpdateLayoutDesignList(layoutDesign); } } void QmitkRenderWindow::UpdateCrosshairVisibility(bool visible) { m_MenuWidget->UpdateCrosshairVisibility(visible); } void QmitkRenderWindow::UpdateCrosshairRotationMode(int mode) { m_MenuWidget->UpdateCrosshairRotationMode(mode); } void QmitkRenderWindow::ActivateMenuWidget(bool state) { if (nullptr == m_MenuWidget) { m_MenuWidget = new QmitkRenderWindowMenu(this, nullptr, m_Renderer); m_MenuWidget->SetLayoutIndex(m_LayoutIndex); } m_MenuWidgetActivated = state; if (m_MenuWidgetActivated) { connect(m_MenuWidget, &QmitkRenderWindowMenu::LayoutDesignChanged, this, &QmitkRenderWindow::LayoutDesignChanged); connect(m_MenuWidget, &QmitkRenderWindowMenu::ResetView, this, &QmitkRenderWindow::ResetView); connect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairVisibilityChanged, this, &QmitkRenderWindow::CrosshairVisibilityChanged); connect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairRotationModeChanged, this, &QmitkRenderWindow::CrosshairRotationModeChanged); } else { disconnect(m_MenuWidget, &QmitkRenderWindowMenu::LayoutDesignChanged, this, &QmitkRenderWindow::LayoutDesignChanged); disconnect(m_MenuWidget, &QmitkRenderWindowMenu::ResetView, this, &QmitkRenderWindow::ResetView); disconnect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairVisibilityChanged, this, &QmitkRenderWindow::CrosshairVisibilityChanged); disconnect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairRotationModeChanged, this, &QmitkRenderWindow::CrosshairRotationModeChanged); m_MenuWidget->hide(); } } +void QmitkRenderWindow::ShowOverlayMessage(bool show) +{ + m_GeometryViolationWarningOverlay->setVisible(show); +} + void QmitkRenderWindow::moveEvent(QMoveEvent *event) { QVTKOpenGLNativeWidget::moveEvent(event); // after a move the overlays need to be positioned emit moved(); } void QmitkRenderWindow::showEvent(QShowEvent *event) { QVTKOpenGLNativeWidget::showEvent(event); // this singleshot is necessary to have the overlays positioned correctly after initial show // simple call of moved() is no use here!! QTimer::singleShot(0, this, SIGNAL(moved())); } bool QmitkRenderWindow::event(QEvent* e) { mitk::InteractionEvent::Pointer mitkEvent = nullptr; mitk::Point2D mousePosition; bool updateStatusBar = false; switch (e->type()) { case QEvent::MouseMove: { auto me = static_cast(e); mousePosition = this->GetMousePosition(me); mitkEvent = mitk::MouseMoveEvent::New(m_Renderer, mousePosition, GetButtonState(me), GetModifiers(me)); updateStatusBar = true; break; } case QEvent::MouseButtonPress: { auto me = static_cast(e); mitkEvent = mitk::MousePressEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); break; } case QEvent::MouseButtonRelease: { auto me = static_cast(e); mitkEvent = mitk::MouseReleaseEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); break; } case QEvent::MouseButtonDblClick: { auto me = static_cast(e); mitkEvent = mitk::MouseDoubleClickEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); break; } case QEvent::Wheel: { auto we = static_cast(e); mousePosition = this->GetMousePosition(we); mitkEvent = mitk::MouseWheelEvent::New(m_Renderer, mousePosition, GetButtonState(we), GetModifiers(we), GetDelta(we)); updateStatusBar = true; break; } case QEvent::KeyPress: { auto ke = static_cast(e); mitkEvent = mitk::InteractionKeyEvent::New(m_Renderer, GetKeyLetter(ke), GetModifiers(ke)); break; } case QEvent::Resize: { if (nullptr != m_MenuWidget) m_MenuWidget->MoveWidgetToCorrectPos(); } default: { break; } } if (mitkEvent != nullptr) { if (this->HandleEvent(mitkEvent.GetPointer())) { return m_ResendQtEvents ? false : true; } } if (updateStatusBar) { this->UpdateStatusBar(mousePosition); } return QVTKOpenGLNativeWidget::event(e); } void QmitkRenderWindow::enterEvent(QEvent *e) { mitk::InternalEvent::Pointer internalEvent = mitk::InternalEvent::New(m_Renderer, nullptr, "EnterRenderWindow"); this->HandleEvent(internalEvent.GetPointer()); if (nullptr != m_MenuWidget) m_MenuWidget->ShowMenu(); QVTKOpenGLNativeWidget::enterEvent(e); } void QmitkRenderWindow::leaveEvent(QEvent *e) { auto statusBar = mitk::StatusBar::GetInstance(); statusBar->DisplayGreyValueText(""); mitk::InternalEvent::Pointer internalEvent = mitk::InternalEvent::New(m_Renderer, nullptr, "LeaveRenderWindow"); this->HandleEvent(internalEvent.GetPointer()); if (nullptr != m_MenuWidget) m_MenuWidget->HideMenu(); QVTKOpenGLNativeWidget::leaveEvent(e); } void QmitkRenderWindow::resizeGL(int w, int h) { QVTKOpenGLNativeWidget::resizeGL(w, h); mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(renderWindow()); } void QmitkRenderWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("application/x-mitk-datanodes")) { event->accept(); } } void QmitkRenderWindow::dropEvent(QDropEvent *event) { QList dataNodeList = QmitkMimeTypes::ToDataNodePtrList(event->mimeData()); if (!dataNodeList.empty()) { emit NodesDropped(this, dataNodeList.toVector().toStdVector()); } } void QmitkRenderWindow::DeferredHideMenu() { MITK_DEBUG << "QmitkRenderWindow::DeferredHideMenu"; if (nullptr != m_MenuWidget) { m_MenuWidget->HideMenu(); } } mitk::Point2D QmitkRenderWindow::GetMousePosition(QMouseEvent *me) const { mitk::Point2D point; point[0] = me->x(); // We need to convert the y component, as the display and vtk have other definitions for the y direction point[1] = m_Renderer->GetSizeY() - me->y(); return point; } mitk::Point2D QmitkRenderWindow::GetMousePosition(QWheelEvent *we) const { mitk::Point2D point; point[0] = we->x(); // We need to convert the y component, as the display and vtk have other definitions for the y direction point[1] = m_Renderer->GetSizeY() - we->y(); return point; } mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetEventButton(QMouseEvent *me) const { mitk::InteractionEvent::MouseButtons eventButton; switch (me->button()) { case Qt::LeftButton: eventButton = mitk::InteractionEvent::LeftMouseButton; break; case Qt::RightButton: eventButton = mitk::InteractionEvent::RightMouseButton; break; case Qt::MidButton: eventButton = mitk::InteractionEvent::MiddleMouseButton; break; default: eventButton = mitk::InteractionEvent::NoButton; break; } return eventButton; } mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QMouseEvent *me) const { mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton; if (me->buttons() & Qt::LeftButton) { buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton; } if (me->buttons() & Qt::RightButton) { buttonState = buttonState | mitk::InteractionEvent::RightMouseButton; } if (me->buttons() & Qt::MidButton) { buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton; } return buttonState; } mitk::InteractionEvent::ModifierKeys QmitkRenderWindow::GetModifiers(QInputEvent *me) const { mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::NoKey; if (me->modifiers() & Qt::ALT) { modifiers = modifiers | mitk::InteractionEvent::AltKey; } if (me->modifiers() & Qt::CTRL) { modifiers = modifiers | mitk::InteractionEvent::ControlKey; } if (me->modifiers() & Qt::SHIFT) { modifiers = modifiers | mitk::InteractionEvent::ShiftKey; } return modifiers; } mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QWheelEvent *we) const { mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton; if (we->buttons() & Qt::LeftButton) { buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton; } if (we->buttons() & Qt::RightButton) { buttonState = buttonState | mitk::InteractionEvent::RightMouseButton; } if (we->buttons() & Qt::MidButton) { buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton; } return buttonState; } std::string QmitkRenderWindow::GetKeyLetter(QKeyEvent *ke) const { // Converting Qt Key Event to string element. std::string key = ""; int tkey = ke->key(); if (tkey < 128) { // standard ascii letter key = (char)toupper(tkey); } else { // special keys switch (tkey) { case Qt::Key_Return: key = mitk::InteractionEvent::KeyReturn; break; case Qt::Key_Enter: key = mitk::InteractionEvent::KeyEnter; break; case Qt::Key_Escape: key = mitk::InteractionEvent::KeyEsc; break; case Qt::Key_Delete: key = mitk::InteractionEvent::KeyDelete; break; case Qt::Key_Up: key = mitk::InteractionEvent::KeyArrowUp; break; case Qt::Key_Down: key = mitk::InteractionEvent::KeyArrowDown; break; case Qt::Key_Left: key = mitk::InteractionEvent::KeyArrowLeft; break; case Qt::Key_Right: key = mitk::InteractionEvent::KeyArrowRight; break; case Qt::Key_F1: key = mitk::InteractionEvent::KeyF1; break; case Qt::Key_F2: key = mitk::InteractionEvent::KeyF2; break; case Qt::Key_F3: key = mitk::InteractionEvent::KeyF3; break; case Qt::Key_F4: key = mitk::InteractionEvent::KeyF4; break; case Qt::Key_F5: key = mitk::InteractionEvent::KeyF5; break; case Qt::Key_F6: key = mitk::InteractionEvent::KeyF6; break; case Qt::Key_F7: key = mitk::InteractionEvent::KeyF7; break; case Qt::Key_F8: key = mitk::InteractionEvent::KeyF8; break; case Qt::Key_F9: key = mitk::InteractionEvent::KeyF9; break; case Qt::Key_F10: key = mitk::InteractionEvent::KeyF10; break; case Qt::Key_F11: key = mitk::InteractionEvent::KeyF11; break; case Qt::Key_F12: key = mitk::InteractionEvent::KeyF12; break; case Qt::Key_End: key = mitk::InteractionEvent::KeyEnd; break; case Qt::Key_Home: key = mitk::InteractionEvent::KeyPos1; break; case Qt::Key_Insert: key = mitk::InteractionEvent::KeyInsert; break; case Qt::Key_PageDown: key = mitk::InteractionEvent::KeyPageDown; break; case Qt::Key_PageUp: key = mitk::InteractionEvent::KeyPageUp; break; case Qt::Key_Space: key = mitk::InteractionEvent::KeySpace; break; } } return key; } int QmitkRenderWindow::GetDelta(QWheelEvent *we) const { return we->delta(); } void QmitkRenderWindow::UpdateStatusBar(mitk::Point2D pointerPositionOnScreen) { mitk::Point3D worldPosition; m_Renderer->ForceImmediateUpdate(); m_Renderer->DisplayToWorld(pointerPositionOnScreen, worldPosition); auto statusBar = mitk::StatusBar::GetInstance(); statusBar->DisplayRendererInfo(worldPosition, m_Renderer->GetTime()); } diff --git a/Modules/QtWidgets/src/QmitkRenderWindowContextDataStorageInspector.cpp b/Modules/QtWidgets/src/QmitkRenderWindowContextDataStorageInspector.cpp index 3758aaaa10..7cfa9f9099 100644 --- a/Modules/QtWidgets/src/QmitkRenderWindowContextDataStorageInspector.cpp +++ b/Modules/QtWidgets/src/QmitkRenderWindowContextDataStorageInspector.cpp @@ -1,157 +1,146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // render window manager UI module #include "QmitkRenderWindowContextDataStorageInspector.h" #include #include +#include +#include +#include + // qt #include #include QmitkRenderWindowContextDataStorageInspector::QmitkRenderWindowContextDataStorageInspector( QWidget* parent /* =nullptr */, mitk::BaseRenderer* renderer /* = nullptr */) : QmitkAbstractDataStorageInspector(parent) { m_Controls.setupUi(this); mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer{ renderer }; // initialize the render window layer controller and the render window view direction controller m_RenderWindowLayerController = std::make_unique(); m_RenderWindowLayerController->SetControlledRenderer(controlledRenderer); m_StorageModel = std::make_unique(this); m_StorageModel->SetControlledRenderer(controlledRenderer); m_Controls.renderWindowTreeView->setModel(m_StorageModel.get()); m_Controls.renderWindowTreeView->setHeaderHidden(true); m_Controls.renderWindowTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers); m_Controls.renderWindowTreeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.renderWindowTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_Controls.renderWindowTreeView->setAlternatingRowColors(true); m_Controls.renderWindowTreeView->setDragEnabled(true); m_Controls.renderWindowTreeView->setDropIndicatorShown(true); m_Controls.renderWindowTreeView->setAcceptDrops(true); m_Controls.renderWindowTreeView->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_Controls.renderWindowTreeView, &QTreeView::customContextMenuRequested, this, &QmitkRenderWindowContextDataStorageInspector::OnContextMenuRequested); SetUpConnections(); if (nullptr == renderer) { return; } m_StorageModel->SetCurrentRenderer(renderer); } QAbstractItemView* QmitkRenderWindowContextDataStorageInspector::GetView() { return m_Controls.renderWindowTreeView; } const QAbstractItemView* QmitkRenderWindowContextDataStorageInspector::GetView() const { return m_Controls.renderWindowTreeView; } void QmitkRenderWindowContextDataStorageInspector::SetSelectionMode(SelectionMode mode) { m_Controls.renderWindowTreeView->setSelectionMode(mode); } QmitkRenderWindowContextDataStorageInspector::SelectionMode QmitkRenderWindowContextDataStorageInspector::GetSelectionMode() const { return m_Controls.renderWindowTreeView->selectionMode(); } QItemSelectionModel* QmitkRenderWindowContextDataStorageInspector::GetDataNodeSelectionModel() const { return m_Controls.renderWindowTreeView->selectionModel(); } void QmitkRenderWindowContextDataStorageInspector::Initialize() { auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) return; m_StorageModel->SetDataStorage(dataStorage); - m_StorageModel->SetNodePredicate(m_NodePredicate); + + mitk::NodePredicateAnd::Pointer noHelperObjects = mitk::NodePredicateAnd::New(); + noHelperObjects->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))); + noHelperObjects->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("hidden object"))); + m_StorageModel->SetNodePredicate(noHelperObjects); m_RenderWindowLayerController->SetDataStorage(dataStorage); m_Connector->SetView(m_Controls.renderWindowTreeView); } void QmitkRenderWindowContextDataStorageInspector::SetUpConnections() { connect(m_StorageModel.get(), &QAbstractItemModel::rowsInserted, this, &QmitkRenderWindowContextDataStorageInspector::ModelRowsInserted); } void QmitkRenderWindowContextDataStorageInspector::ModelRowsInserted(const QModelIndex& parent, int /*start*/, int /*end*/) { m_Controls.renderWindowTreeView->setExpanded(parent, true); } void QmitkRenderWindowContextDataStorageInspector::ResetRenderer() { m_RenderWindowLayerController->ResetRenderer(true, m_StorageModel->GetCurrentRenderer()); m_Controls.renderWindowTreeView->clearSelection(); } void QmitkRenderWindowContextDataStorageInspector::OnContextMenuRequested(const QPoint& pos) { QMenu contextMenu; contextMenu.addAction(tr("Reinit with node"), this, &QmitkRenderWindowContextDataStorageInspector::OnReinit); contextMenu.addAction(tr("Reset to node geometry"), this, &QmitkRenderWindowContextDataStorageInspector::OnReset); contextMenu.exec(this->mapToGlobal(pos)); } void QmitkRenderWindowContextDataStorageInspector::OnReinit() { auto nodes = this->GetSelectedNodes(); emit ReinitAction(nodes); } void QmitkRenderWindowContextDataStorageInspector::OnReset() { auto nodes = this->GetSelectedNodes(); emit ResetAction(nodes); } - -QList QmitkRenderWindowContextDataStorageInspector::GetSelectedNodes() -{ - auto baseRenderer = m_StorageModel->GetCurrentRenderer(); - - QList nodes; - QModelIndexList selectedIndexes = this->GetDataNodeSelectionModel()->selectedIndexes(); - for (const auto& index : qAsConst(selectedIndexes)) - { - QVariant qvariantDataNode = m_StorageModel->data(index, QmitkDataNodeRole); - if (qvariantDataNode.canConvert()) - { - mitk::DataNode* dataNode = qvariantDataNode.value(); - nodes.insert(nodes.size(), dataNode); - } - } - - return nodes; -} diff --git a/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp b/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp index a97f95f694..3d761af13c 100644 --- a/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp +++ b/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp @@ -1,607 +1,628 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // render window manager UI module #include "QmitkRenderWindowDataStorageTreeModel.h" -// mitk core #include +// mitk core +#include + // qt widgets module #include "QmitkCustomVariants.h" #include "QmitkEnums.h" #include "QmitkMimeTypes.h" #include "QmitkNodeDescriptorManager.h" QmitkRenderWindowDataStorageTreeModel::QmitkRenderWindowDataStorageTreeModel(QObject* parent /*= nullptr*/) : QmitkAbstractDataStorageModel(parent) , m_Root(nullptr) { m_RenderWindowLayerController = std::make_unique(); ResetTree(); } void QmitkRenderWindowDataStorageTreeModel::DataStorageChanged() { m_RenderWindowLayerController->SetDataStorage(m_DataStorage.Lock()); ResetTree(); UpdateModelData(); } void QmitkRenderWindowDataStorageTreeModel::NodePredicateChanged() { ResetTree(); UpdateModelData(); } void QmitkRenderWindowDataStorageTreeModel::NodeAdded(const mitk::DataNode* node) { for (const auto renderer : m_ControlledRenderer) { // add the node to each render window mitk::RenderWindowLayerUtilities::SetRenderWindowProperties(const_cast(node), renderer); } auto baseRenderer = m_BaseRenderer.Lock(); - if (baseRenderer.IsNotNull()) + if (baseRenderer.IsNull()) + { + return; + } + + mitk::NodePredicateBase::Pointer renderWindowPredicate = mitk::RenderWindowLayerUtilities::GetRenderWindowPredicate(baseRenderer); + mitk::NodePredicateAnd::Pointer combinedNodePredicate = mitk::NodePredicateAnd::New(); + combinedNodePredicate->AddPredicate(renderWindowPredicate); + if (m_NodePredicate.IsNotNull()) + { + combinedNodePredicate->AddPredicate(m_NodePredicate); + } + if (combinedNodePredicate->CheckNode(node)) { AddNodeInternal(node, baseRenderer); } } void QmitkRenderWindowDataStorageTreeModel::NodeChanged(const mitk::DataNode* node) { auto item = m_Root->Find(node); if (nullptr != item) { auto parentItem = item->GetParent(); // as the root node should not be removed one should always have a parent item if (nullptr == parentItem) { return; } auto index = createIndex(item->GetIndex(), 0, item); emit dataChanged(index, index); } } void QmitkRenderWindowDataStorageTreeModel::NodeRemoved(const mitk::DataNode* node) { RemoveNodeInternal(node); } QModelIndex QmitkRenderWindowDataStorageTreeModel::index(int row, int column, const QModelIndex& parent) const { auto item = GetItemByIndex(parent); if (nullptr != item) { item = item->GetChild(row); } if (nullptr == item) { return QModelIndex(); } return createIndex(row, column, item); } QModelIndex QmitkRenderWindowDataStorageTreeModel::parent(const QModelIndex& parent) const { auto item = GetItemByIndex(parent); if (nullptr != item) { item = item->GetParent(); } if(nullptr == item) { return QModelIndex(); } if (item == m_Root) { return QModelIndex(); } return createIndex(item->GetIndex(), 0, item); } int QmitkRenderWindowDataStorageTreeModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const { auto item = GetItemByIndex(parent); if (nullptr == item) { return 0; } return item->GetChildCount(); } int QmitkRenderWindowDataStorageTreeModel::columnCount(const QModelIndex&/* parent = QModelIndex()*/) const { if (0 == m_Root->GetChildCount()) { // no items stored, no need to display columns return 0; } return 1; } QVariant QmitkRenderWindowDataStorageTreeModel::data(const QModelIndex& index, int role) const { auto baseRenderer = m_BaseRenderer.Lock(); if (baseRenderer.IsNull()) { return QVariant(); } if (!index.isValid() || this != index.model()) { return QVariant(); } auto item = GetItemByIndex(index); if (nullptr == item) { return QVariant(); } auto dataNode = item->GetDataNode(); if (nullptr == dataNode) { return QVariant(); } if (Qt::CheckStateRole == role) { bool visibility = false; dataNode->GetVisibility(visibility, baseRenderer); if (visibility) { return Qt::Checked; } else { return Qt::Unchecked; } } else if (Qt::DisplayRole == role) { return QVariant(QString::fromStdString(dataNode->GetName())); } else if (Qt::ToolTipRole == role) { return QVariant("Name of the data node."); } else if (Qt::DecorationRole == role) { QmitkNodeDescriptor* nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode); return nodeDescriptor->GetIcon(dataNode); } else if (Qt::UserRole == role || QmitkDataNodeRawPointerRole == role) { // user role always returns a reference to the data node, // which can be used to modify the data node in the data storage return QVariant::fromValue(dataNode); } else if (QmitkDataNodeRole == role) { return QVariant::fromValue(mitk::DataNode::Pointer(dataNode)); } return QVariant(); } bool QmitkRenderWindowDataStorageTreeModel::setData(const QModelIndex& index, const QVariant& value, int role /*= Qt::EditRole*/) { auto baseRenderer = m_BaseRenderer.Lock(); if (baseRenderer.IsNull()) { return false; } if (!index.isValid() || this != index.model()) { return false; } auto item = GetItemByIndex(index); if (nullptr == item) { return false; } auto dataNode = item->GetDataNode(); if (nullptr == dataNode) { return false; } if (Qt::EditRole == role && !value.toString().isEmpty()) { dataNode->SetName(value.toString().toStdString().c_str()); emit dataChanged(index, index); return true; } if (Qt::CheckStateRole == role) { Qt::CheckState newCheckState = static_cast(value.toInt()); bool isVisible = newCheckState; dataNode->SetVisibility(isVisible, baseRenderer); emit dataChanged(index, index); mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow()); return true; } return false; } Qt::ItemFlags QmitkRenderWindowDataStorageTreeModel::flags(const QModelIndex& index) const { if (this != index.model()) { return Qt::NoItemFlags; } if (!index.isValid()) { return Qt::ItemIsDropEnabled; } auto item = GetItemByIndex(index); if (nullptr == item) { return Qt::NoItemFlags; } const auto dataNode = item->GetDataNode(); if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(dataNode)) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; } return Qt::NoItemFlags; } Qt::DropActions QmitkRenderWindowDataStorageTreeModel::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction; } Qt::DropActions QmitkRenderWindowDataStorageTreeModel::supportedDragActions() const { return Qt::CopyAction | Qt::MoveAction; } QStringList QmitkRenderWindowDataStorageTreeModel::mimeTypes() const { QStringList types = QAbstractItemModel::mimeTypes(); types << QmitkMimeTypes::DataNodePtrs; return types; } QMimeData* QmitkRenderWindowDataStorageTreeModel::mimeData(const QModelIndexList& indexes) const { QMimeData* mimeData = new QMimeData(); QByteArray encodedData; QDataStream stream(&encodedData, QIODevice::WriteOnly); for (const auto& index : indexes) { if (index.isValid()) { auto dataNode = data(index, QmitkDataNodeRawPointerRole).value(); stream << reinterpret_cast(dataNode); } } mimeData->setData(QmitkMimeTypes::DataNodePtrs, encodedData); return mimeData; } bool QmitkRenderWindowDataStorageTreeModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int /*row*/, int /*column*/, const QModelIndex& parent) { auto baseRenderer = m_BaseRenderer.Lock(); if (baseRenderer.IsNull()) { return false; } if (action == Qt::IgnoreAction) { return true; } if (!data->hasFormat(QmitkMimeTypes::DataNodePtrs)) { return false; } if (!parent.isValid()) { return false; } int layer = -1; auto dataNode = this->data(parent, QmitkDataNodeRawPointerRole).value(); if (nullptr != dataNode) { dataNode->GetIntProperty("layer", layer, baseRenderer); } auto dataNodeList = QmitkMimeTypes::ToDataNodePtrList(data); for (const auto& dataNode : qAsConst(dataNodeList)) { m_RenderWindowLayerController->MoveNodeToPosition(dataNode, layer, baseRenderer); } ResetTree(); UpdateModelData(); AdjustLayerProperty(); return true; } void QmitkRenderWindowDataStorageTreeModel::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer) { m_RenderWindowLayerController->SetControlledRenderer(controlledRenderer); m_ControlledRenderer = controlledRenderer; ResetTree(); auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) { return; } for (const auto& renderer : controlledRenderer) { if (nullptr == renderer) { continue; } auto allDataNodes = dataStorage->GetAll(); for (const auto& dataNode : *allDataNodes) { // add the node to each render window mitk::RenderWindowLayerUtilities::SetRenderWindowProperties(dataNode, renderer); } } } void QmitkRenderWindowDataStorageTreeModel::SetCurrentRenderer(mitk::BaseRenderer* baseRenderer) { if (m_BaseRenderer == baseRenderer) { return; } // base renderer changed // reset tree to build a new renderer-specific item hierarchy m_BaseRenderer = baseRenderer; ResetTree(); UpdateModelData(); } mitk::BaseRenderer::Pointer QmitkRenderWindowDataStorageTreeModel::GetCurrentRenderer() const { return m_BaseRenderer.Lock(); } void QmitkRenderWindowDataStorageTreeModel::ResetTree() { beginResetModel(); if (nullptr != m_Root) { m_Root->Delete(); } mitk::DataNode::Pointer rootDataNode = mitk::DataNode::New(); rootDataNode->SetName("Data Storage"); m_Root = new QmitkDataStorageTreeModelInternalItem(rootDataNode); endResetModel(); } void QmitkRenderWindowDataStorageTreeModel::UpdateModelData() { auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNotNull()) { auto baseRenderer = m_BaseRenderer.Lock(); if (baseRenderer.IsNotNull()) { auto allDataNodes = dataStorage->GetAll(); for (const auto& dataNode : *allDataNodes) { // add the node to each render window mitk::RenderWindowLayerUtilities::SetRenderWindowProperties(dataNode, baseRenderer); } - mitk::NodePredicateAnd::Pointer combinedNodePredicate = mitk::RenderWindowLayerUtilities::GetRenderWindowPredicate(baseRenderer); + mitk::NodePredicateBase::Pointer renderWindowPredicate = mitk::RenderWindowLayerUtilities::GetRenderWindowPredicate(baseRenderer); + mitk::NodePredicateAnd::Pointer combinedNodePredicate = mitk::NodePredicateAnd::New(); + combinedNodePredicate->AddPredicate(renderWindowPredicate); + if (m_NodePredicate.IsNotNull()) + { + combinedNodePredicate->AddPredicate(m_NodePredicate); + } + auto filteredDataNodes = dataStorage->GetSubset(combinedNodePredicate); for (const auto& dataNode : *filteredDataNodes) { AddNodeInternal(dataNode, baseRenderer); } } } } void QmitkRenderWindowDataStorageTreeModel::AdjustLayerProperty() { auto baseRenderer = m_BaseRenderer.Lock(); if (baseRenderer.IsNull()) { return; } std::vector treeAsVector; TreeToVector(m_Root, treeAsVector); int i = treeAsVector.size() - 1; for (auto it = treeAsVector.begin(); it != treeAsVector.end(); ++it) { auto dataNode = (*it)->GetDataNode(); dataNode->SetIntProperty("layer", i, baseRenderer); --i; } } void QmitkRenderWindowDataStorageTreeModel::TreeToVector(QmitkDataStorageTreeModelInternalItem* parent, std::vector& treeAsVector) const { QmitkDataStorageTreeModelInternalItem* item; for (int i = 0; i < parent->GetChildCount(); ++i) { item = parent->GetChild(i); TreeToVector(item, treeAsVector); treeAsVector.push_back(item); } } void QmitkRenderWindowDataStorageTreeModel::AddNodeInternal(const mitk::DataNode* dataNode, const mitk::BaseRenderer* renderer) { if (nullptr == dataNode || m_DataStorage.IsExpired() || nullptr != m_Root->Find(dataNode)) { return; } // find out if we have a root node auto parentItem = m_Root; QModelIndex index; auto parentDataNode = GetParentNode(dataNode); if (nullptr != parentDataNode) // no top level data node { parentItem = m_Root->Find(parentDataNode); if (nullptr == parentItem) { // parent node not contained in the tree; add it NodeAdded(parentDataNode); parentItem = m_Root->Find(parentDataNode); if (nullptr == parentItem) { // could not find and add the parent tree; abort return; } } // get the index of this parent with the help of the grand parent index = createIndex(parentItem->GetIndex(), 0, parentItem); } int firstRowWithASiblingBelow = 0; int nodeLayer = -1; dataNode->GetIntProperty("layer", nodeLayer, renderer); for (const auto& siblingItem : parentItem->GetChildren()) { int siblingLayer = -1; auto siblingNode = siblingItem->GetDataNode(); if (nullptr != siblingNode) { siblingNode->GetIntProperty("layer", siblingLayer, renderer); } if (nodeLayer > siblingLayer) { break; } ++firstRowWithASiblingBelow; } beginInsertRows(index, firstRowWithASiblingBelow, firstRowWithASiblingBelow); auto newNode = new QmitkDataStorageTreeModelInternalItem(const_cast(dataNode)); parentItem->InsertChild(newNode, firstRowWithASiblingBelow); endInsertRows(); } void QmitkRenderWindowDataStorageTreeModel::RemoveNodeInternal(const mitk::DataNode* dataNode) { if (nullptr == dataNode || nullptr == m_Root) { return; } auto item = m_Root->Find(dataNode); if (nullptr == item) { return; } auto parentItem = item->GetParent(); auto parentIndex = GetIndexByItem(parentItem); auto children = item->GetChildren(); beginRemoveRows(parentIndex, item->GetIndex(), item->GetIndex()); parentItem->RemoveChild(item); delete item; endRemoveRows(); if (!children.empty()) { // rebuild tree because children could not be at the top level ResetTree(); UpdateModelData(); } } mitk::DataNode* QmitkRenderWindowDataStorageTreeModel::GetParentNode(const mitk::DataNode* node) const { mitk::DataNode* dataNode = nullptr; auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) { return dataNode; } auto sources = dataStorage->GetSources(node); if (sources->empty()) { return dataNode; } return sources->front(); } QmitkDataStorageTreeModelInternalItem* QmitkRenderWindowDataStorageTreeModel::GetItemByIndex(const QModelIndex& index) const { if (index.isValid()) { return static_cast(index.internalPointer()); } return m_Root; } QModelIndex QmitkRenderWindowDataStorageTreeModel::GetIndexByItem(QmitkDataStorageTreeModelInternalItem* item) const { if (item == m_Root) { return QModelIndex(); } return createIndex(item->GetIndex(), 0, item); } diff --git a/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp b/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp index 5741cf6dfe..31b5213918 100644 --- a/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp +++ b/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp @@ -1,413 +1,414 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRenderWindowWidget.h" #include #include #include // itk #include // vtk #include #include QmitkRenderWindowWidget::QmitkRenderWindowWidget(QWidget* parent/* = nullptr*/, const QString& widgetName/* = ""*/, mitk::DataStorage* dataStorage/* = nullptr*/, bool windowControls/* = false */) : QFrame(parent) , m_WidgetName(widgetName) , m_DataStorage(dataStorage) , m_RenderWindow(nullptr) , m_CrosshairManager(nullptr) , m_UtilityWidget(nullptr) , m_WindowControls(windowControls) { this->InitializeGUI(); } QmitkRenderWindowWidget::~QmitkRenderWindowWidget() { auto sliceNavigationController = m_RenderWindow->GetSliceNavigationController(); if (nullptr != sliceNavigationController) { sliceNavigationController->SetCrosshairEvent.RemoveListener( mitk::MessageDelegate1( this, &QmitkRenderWindowWidget::SetCrosshairPosition)); } } void QmitkRenderWindowWidget::SetDataStorage(mitk::DataStorage* dataStorage) { if (dataStorage == m_DataStorage) { return; } m_DataStorage = dataStorage; if (nullptr != m_RenderWindow) { mitk::BaseRenderer::GetInstance(m_RenderWindow->renderWindow())->SetDataStorage(dataStorage); } m_CrosshairManager->SetDataStorage(m_DataStorage); } mitk::SliceNavigationController* QmitkRenderWindowWidget::GetSliceNavigationController() const { return m_RenderWindow->GetSliceNavigationController(); } void QmitkRenderWindowWidget::RequestUpdate() { mitk::RenderingManager::GetInstance()->RequestUpdate(m_RenderWindow->renderWindow()); } void QmitkRenderWindowWidget::ForceImmediateUpdate() { mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(m_RenderWindow->renderWindow()); } void QmitkRenderWindowWidget::SetGradientBackgroundColors(const mitk::Color& upper, const mitk::Color& lower) { vtkRenderer* vtkRenderer = m_RenderWindow->GetRenderer()->GetVtkRenderer(); if (nullptr == vtkRenderer) { return; } m_GradientBackgroundColors.first = upper; m_GradientBackgroundColors.second = lower; vtkRenderer->SetBackground(lower[0], lower[1], lower[2]); vtkRenderer->SetBackground2(upper[0], upper[1], upper[2]); ShowGradientBackground(true); } void QmitkRenderWindowWidget::ShowGradientBackground(bool show) { m_RenderWindow->GetRenderer()->GetVtkRenderer()->SetGradientBackground(show); } bool QmitkRenderWindowWidget::IsGradientBackgroundOn() const { return m_RenderWindow->GetRenderer()->GetVtkRenderer()->GetGradientBackground(); } void QmitkRenderWindowWidget::SetDecorationColor(const mitk::Color& color) { m_DecorationColor = color; m_CornerAnnotation->GetTextProperty()->SetColor(m_DecorationColor[0], m_DecorationColor[1], m_DecorationColor[2]); QColor hexColor(m_DecorationColor[0] * 255, m_DecorationColor[1] * 255, m_DecorationColor[2] * 255); setStyleSheet("QmitkRenderWindowWidget { border: 2px solid " + hexColor.name(QColor::HexRgb) + "; }"); } void QmitkRenderWindowWidget::ShowColoredRectangle(bool show) { if (show) { setFrameStyle(QFrame::Box | QFrame::Plain); } else { setFrameStyle(NoFrame); } } bool QmitkRenderWindowWidget::IsColoredRectangleVisible() const { return frameStyle() > 0; } void QmitkRenderWindowWidget::ShowCornerAnnotation(bool show) { m_CornerAnnotation->SetVisibility(show); } bool QmitkRenderWindowWidget::IsCornerAnnotationVisible() const { return m_CornerAnnotation->GetVisibility() > 0; } void QmitkRenderWindowWidget::SetCornerAnnotationText(const std::string& cornerAnnotation) { m_CornerAnnotation->SetText(0, cornerAnnotation.c_str()); } std::string QmitkRenderWindowWidget::GetCornerAnnotationText() const { return std::string(m_CornerAnnotation->GetText(0)); } bool QmitkRenderWindowWidget::IsRenderWindowMenuActivated() const { return m_RenderWindow->GetActivateMenuWidgetFlag(); } void QmitkRenderWindowWidget::SetCrosshairVisibility(bool visible) { m_CrosshairManager->SetCrosshairVisibility(visible); this->RequestUpdate(); } bool QmitkRenderWindowWidget::GetCrosshairVisibility() { return m_CrosshairManager->GetCrosshairVisibility(); } void QmitkRenderWindowWidget::SetCrosshairGap(unsigned int gapSize) { m_CrosshairManager->SetCrosshairGap(gapSize); } void QmitkRenderWindowWidget::AddPlanesToDataStorage() { m_CrosshairManager->AddPlanesToDataStorage(); } void QmitkRenderWindowWidget::RemovePlanesFromDataStorage() { m_CrosshairManager->RemovePlanesFromDataStorage(); } void QmitkRenderWindowWidget::InitializeGUI() { m_Layout = new QVBoxLayout(this); m_Layout->setMargin(0); setLayout(m_Layout); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setContentsMargins(0, 0, 0, 0); if (nullptr == m_DataStorage) { return; } mitk::RenderingManager::GetInstance()->SetDataStorage(m_DataStorage); // create render window for this render window widget m_RenderWindow = new QmitkRenderWindow(this, m_WidgetName, nullptr); m_RenderWindow->SetLayoutIndex(mitk::BaseRenderer::ViewDirection::SAGITTAL); auto sliceNavigationController = m_RenderWindow->GetSliceNavigationController(); sliceNavigationController->SetDefaultViewDirection(mitk::SliceNavigationController::Sagittal); if (m_WindowControls) { m_UtilityWidget = new QmitkRenderWindowUtilityWidget(this, m_RenderWindow, m_DataStorage); m_Layout->addWidget(m_UtilityWidget); connect(m_UtilityWidget, &QmitkRenderWindowUtilityWidget::ReinitAction, this, &QmitkRenderWindowWidget::OnReinitAction); connect(m_UtilityWidget, &QmitkRenderWindowUtilityWidget::ResetAction, this, &QmitkRenderWindowWidget::OnResetAction); } m_Layout->addWidget(m_RenderWindow); // set colors and corner annotation InitializeDecorations(); // use crosshair manager m_CrosshairManager = mitk::CrosshairManager::New(m_DataStorage, m_RenderWindow->GetRenderer()); sliceNavigationController->SetCrosshairEvent.AddListener( mitk::MessageDelegate1( this, &QmitkRenderWindowWidget::SetCrosshairPosition)); // finally add observer, after all relevant objects have been created / initialized sliceNavigationController->ConnectGeometrySendEvent(this); mitk::TimeGeometry::ConstPointer timeGeometry = m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeView(m_RenderWindow->GetVtkRenderWindow(), timeGeometry); } void QmitkRenderWindowWidget::InitializeDecorations() { vtkRenderer* vtkRenderer = m_RenderWindow->GetRenderer()->GetVtkRenderer(); if (nullptr == vtkRenderer) { return; } // initialize background color gradients float black[3] = { 0.0f, 0.0f, 0.0f }; SetGradientBackgroundColors(black, black); // initialize annotation text and decoration color setFrameStyle(QFrame::Box | QFrame::Plain); m_CornerAnnotation = vtkSmartPointer::New(); m_CornerAnnotation->SetText(0, "Sagittal"); m_CornerAnnotation->SetMaximumFontSize(12); if (0 == vtkRenderer->HasViewProp(m_CornerAnnotation)) { vtkRenderer->AddViewProp(m_CornerAnnotation); } float white[3] = { 1.0f, 1.0f, 1.0f }; SetDecorationColor(mitk::Color(white)); } void QmitkRenderWindowWidget::SetCrosshairPosition(const mitk::Point3D& newPosition) { m_CrosshairManager->SetCrosshairPosition(newPosition); this->RequestUpdate(); } mitk::Point3D QmitkRenderWindowWidget::GetCrosshairPosition() const { return m_CrosshairManager->GetCrosshairPosition(); } void QmitkRenderWindowWidget::SetGeometry(const itk::EventObject& event) { if (!mitk::SliceNavigationController::GeometrySendEvent(nullptr, 0).CheckEvent(&event)) { return; } auto sliceNavigationController = m_RenderWindow->GetSliceNavigationController(); const auto* inputTimeGeometry = sliceNavigationController->GetInputWorldTimeGeometry(); m_CrosshairManager->ComputeOrientedTimeGeometries(inputTimeGeometry); if (m_WindowControls) { this->ComputeInvertedSliceNavigation(); } } void QmitkRenderWindowWidget::ComputeInvertedSliceNavigation() { auto sliceNavigationController = m_RenderWindow->GetSliceNavigationController(); auto viewDirection = sliceNavigationController->GetViewDirection(); unsigned int axis = 0; switch (viewDirection) { case mitk::SliceNavigationController::Original: return; case mitk::SliceNavigationController::Axial: { axis = 2; break; } case mitk::SliceNavigationController::Coronal: { axis = 1; break; } case mitk::SliceNavigationController::Sagittal: { axis = 0; break; } } const auto* inputTimeGeometry = sliceNavigationController->GetInputWorldTimeGeometry(); const mitk::BaseGeometry* rendererGeometry = m_RenderWindow->GetRenderer()->GetCurrentWorldGeometry(); // todo: check timepoint / timestep mitk::TimeStepType timeStep = sliceNavigationController->GetTime()->GetPos(); mitk::BaseGeometry::ConstPointer geometry = inputTimeGeometry->GetGeometryForTimeStep(timeStep); mitk::AffineTransform3D::MatrixType matrix = geometry->GetIndexToWorldTransform()->GetMatrix(); matrix.GetVnlMatrix().normalize_columns(); mitk::AffineTransform3D::MatrixType::InternalMatrixType inverseMatrix = matrix.GetInverse(); int dominantAxis = itk::Function::Max3(inverseMatrix[0][axis], inverseMatrix[1][axis], inverseMatrix[2][axis]); bool referenceGeometryAxisInverted = inverseMatrix[dominantAxis][axis] < 0; bool rendererZAxisInverted = rendererGeometry->GetAxisVector(2)[axis] < 0; m_UtilityWidget->SetInvertedSliceNavigation(referenceGeometryAxisInverted != rendererZAxisInverted); } void QmitkRenderWindowWidget::OnReinitAction(QList selectedNodes) { if (selectedNodes.empty()) { return; } auto* baseRenderer = mitk::BaseRenderer::GetInstance(m_RenderWindow->renderWindow()); auto boundingBoxPredicate = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false), baseRenderer)); mitk::DataStorage::SetOfObjects::Pointer nodes = mitk::DataStorage::SetOfObjects::New(); for (const auto& dataNode : selectedNodes) { if (boundingBoxPredicate->CheckNode(dataNode)) { nodes->InsertElement(nodes->Size(), dataNode); } } if (nodes->empty()) { return; } if (1 == nodes->Size()) { auto selectedImage = dynamic_cast(nodes->ElementAt(0)->GetData()); if (nullptr != selectedImage) { mitk::RenderingManager::GetInstance()->InitializeView(baseRenderer->GetRenderWindow(), selectedImage->GetTimeGeometry()); return; } } auto boundingGeometry = m_DataStorage->ComputeBoundingGeometry3D(nodes, "visible", baseRenderer); mitk::RenderingManager::GetInstance()->InitializeView(baseRenderer->GetRenderWindow(), boundingGeometry); } void QmitkRenderWindowWidget::OnResetAction(QList selectedNodes) { if (selectedNodes.empty()) { return; } auto selectedImage = dynamic_cast(selectedNodes.front()->GetData()); if (nullptr == selectedImage) { return; } const mitk::TimeGeometry* referenceGeometry = selectedImage->GetTimeGeometry(); if (nullptr == referenceGeometry) { return; } mitk::TimeStepType imageTimeStep = 0; // store the current position to set it again later, if the camera should not be reset mitk::Point3D currentPosition = this->GetCrosshairPosition(); // store the current time step to set it again later, if the camera should not be reset auto* renderingManager = mitk::RenderingManager::GetInstance(); const auto currentTimePoint = renderingManager->GetTimeNavigationController()->GetSelectedTimePoint(); if (referenceGeometry->IsValidTimePoint(currentTimePoint)) { imageTimeStep = referenceGeometry->TimePointToTimeStep(currentTimePoint); } auto* baseRenderer = mitk::BaseRenderer::GetInstance(m_RenderWindow->renderWindow()); renderingManager->InitializeView(baseRenderer->GetRenderWindow(), referenceGeometry, false); // reset position and time step + this->GetSliceNavigationController()->SelectSliceByPoint(currentPosition); this->SetCrosshairPosition(currentPosition); renderingManager->GetTimeNavigationController()->GetTime()->SetPos(imageTimeStep); -} \ No newline at end of file +} diff --git a/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp b/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp index 770dd4567e..ef8fb9e4d0 100644 --- a/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp +++ b/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp @@ -1,550 +1,550 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include // mitk core #include // mitk qt widgets #include // qt #include #include #include #include // itk #include // c++ #include QmitkSliderLevelWindowWidget::QmitkSliderLevelWindowWidget(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f) { m_Manager = mitk::LevelWindowManager::New(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified); m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command); m_IsObserverTagSet = true; setMouseTracking(true); m_Resize = false; m_Bottom = false; m_CtrlPressed = false; m_MouseDown = false; m_Font.setPointSize(6); m_MoveHeight = height() - 25; m_ScaleVisible = true; m_Contextmenu = new QmitkLevelWindowWidgetContextMenu(this); this->hide(); Update(); } QmitkSliderLevelWindowWidget::~QmitkSliderLevelWindowWidget() { if (m_IsObserverTagSet) { m_Manager->RemoveObserver(m_ObserverTag); m_IsObserverTagSet = false; } } void QmitkSliderLevelWindowWidget::SetLevelWindowManager(mitk::LevelWindowManager *levelWindowManager) { if (m_IsObserverTagSet) { m_Manager->RemoveObserver(m_ObserverTag); m_IsObserverTagSet = false; } m_Manager = levelWindowManager; if (m_Manager.IsNotNull()) { itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified); m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command); m_IsObserverTagSet = true; } } void QmitkSliderLevelWindowWidget::OnPropertyModified(const itk::EventObject &) { try { m_LevelWindow = m_Manager->GetLevelWindow(); this->show(); Update(); } catch (...) { try { this->hide(); } catch (...) { } } } void QmitkSliderLevelWindowWidget::paintEvent(QPaintEvent *itkNotUsed(e)) { QPixmap pm(width(), height()); pm.fill(this->palette().color(this->backgroundRole())); QPainter painter(&pm); painter.setFont(m_Font); painter.setPen(this->palette().color(this->foregroundRole())); QColor c(51, 153, 204); QColor cl = c.light(); QColor cd = c.dark(); painter.setBrush(c); painter.drawRect(m_Rect); - float mr = m_LevelWindow.GetRange(); + mitk::ScalarType mr = m_LevelWindow.GetRange(); float smallestLevelableValue = 1e-9; //This check is needed as safe guard. LevelWindow is refactored to only deduce finite ranges //from images, but old scene serialization may contain infinite ranges that overwrite the new //business logic. This roots in two many "jobs" LevelWindow" is used for; see also T24962. //Until LevelWindow and this widget is refactored the check was the minimal invasive fix. if (!std::isfinite(mr)) { mr = m_LevelWindow.GetWindow(); } // avoiding a division by 0 while still enabling small level windows if (mr < smallestLevelableValue) mr = smallestLevelableValue; - float fact = (float)m_MoveHeight / mr; + mitk::ScalarType fact = m_MoveHeight / mr; // begin draw scale if (m_ScaleVisible) { - double minRange = (double)m_LevelWindow.GetRangeMin(); - double maxRange = (double)m_LevelWindow.GetRangeMax(); + mitk::ScalarType minRange = m_LevelWindow.GetRangeMin(); + mitk::ScalarType maxRange = m_LevelWindow.GetRangeMax(); //This check is needed as safe guard. LevelWindow is refactored to only deduce finite ranges //from images, but old scene serialization may contain infinite ranges that overwrite the new //business logic. This roots in two many "jobs" LevelWindow" is used for; see also T24962. //Until LevelWindow and this widget is refactored the check was the minimal invasive fix. if (!std::isfinite(minRange)) { minRange = m_LevelWindow.GetLowerWindowBound(); } //This check is needed as safe guard. LevelWindow is refactored to only deduce finite ranges //from images, but old scene serialization may contain infinite ranges that overwrite the new //business logic. This roots in two many "jobs" LevelWindow" is used for; see also T24962. //Until LevelWindow and this widget is refactored the check was the minimal invasive fix. if (!std::isfinite(maxRange)) { maxRange = m_LevelWindow.GetUpperWindowBound(); } - int yValue = m_MoveHeight + (int)(minRange * fact); + int yValue = m_MoveHeight + static_cast(minRange * fact); QString s = " 0"; if (minRange < 0 && maxRange > 0) { painter.drawLine(5, yValue, 15, yValue); painter.drawText(21, yValue + 3, s); } int count = 1; int k = 5; bool enoughSpace = false; bool enoughSpace2 = false; double dStepSize = pow(10, floor(log10(mr / 100)) + 1); - for (int i = m_MoveHeight + (int)(minRange * fact); i < m_MoveHeight;) // negative + for (int i = m_MoveHeight + static_cast(minRange * fact); i < m_MoveHeight;) // negative { if (-count * dStepSize < minRange) { break; } - yValue = m_MoveHeight + (int)((minRange + count * dStepSize) * fact); + yValue = m_MoveHeight + static_cast((minRange + count * dStepSize) * fact); s = QString::number(-count * dStepSize); if (count % k && ((dStepSize * fact) > 2.5)) { painter.drawLine(8, yValue, 12, yValue); enoughSpace = true; } else if (!(count % k)) { if ((k * dStepSize * fact) > 7) { painter.drawLine(5, yValue, 15, yValue); painter.drawText(21, yValue + 3, s); enoughSpace2 = true; } else { k += 5; } } if (enoughSpace) { i = yValue; count++; } else if (enoughSpace2) { i = yValue; count += k; } else { i = yValue; count = k; } } count = 1; k = 5; enoughSpace = false; enoughSpace2 = false; - for (int i = m_MoveHeight + (int)(minRange * fact); i >= 0;) + for (int i = m_MoveHeight + static_cast(minRange * fact); i >= 0;) { if (count * dStepSize > maxRange) { break; } - yValue = m_MoveHeight + (int)((minRange - count * dStepSize) * fact); + yValue = m_MoveHeight + static_cast((minRange - count * dStepSize) * fact); s = QString::number(count * dStepSize); if (count % k && ((dStepSize * fact) > 2.5)) { if (!(minRange > 0 && (count * dStepSize) < minRange)) painter.drawLine(8, yValue, 12, yValue); enoughSpace = true; } else if (!(count % k)) { if ((k * dStepSize * fact) > 7) { if (!(minRange > 0 && (count * dStepSize) < minRange)) { painter.drawLine(5, yValue, 15, yValue); painter.drawText(21, yValue + 3, s); } enoughSpace2 = true; } else { k += 5; } } if (enoughSpace) { i = yValue; count++; } else if (enoughSpace2) { i = yValue; count += k; } else { i = yValue; count = k; } } } // end draw scale painter.setPen(cl); painter.drawLine(m_Rect.topLeft(), m_Rect.topRight()); painter.drawLine(m_Rect.topLeft(), m_Rect.bottomLeft()); painter.setPen(cd); painter.drawLine(m_Rect.topRight(), m_Rect.bottomRight()); painter.drawLine(m_Rect.bottomRight(), m_Rect.bottomLeft()); painter.end(); QPainter p(this); p.drawPixmap(0, 0, pm); } void QmitkSliderLevelWindowWidget::mouseMoveEvent(QMouseEvent *mouseEvent) { if (!mouseEvent) return; if (m_LevelWindow.IsFixed()) return; if (!m_MouseDown) { if (mouseEvent->pos().y() >= 0 && mouseEvent->pos().y() <= (m_Rect.topLeft().y() + 3)) { setCursor(Qt::SizeVerCursor); m_UpperBound.setRect(m_Rect.topLeft().x(), m_Rect.topLeft().y() - 3, 17, 7); this->setToolTip("Ctrl + left click to change only upper bound"); m_Resize = true; } else if (mouseEvent->pos().y() >= (m_Rect.bottomLeft().y() - 3)) { setCursor(Qt::SizeVerCursor); m_LowerBound.setRect(m_Rect.bottomLeft().x(), m_Rect.bottomLeft().y() - 3, 17, 7); this->setToolTip("Ctrl + left click to change only lower bound"); m_Resize = true; m_Bottom = true; } else { setCursor(Qt::ArrowCursor); this->setToolTip("Left click and mouse move to adjust the slider"); m_Resize = false; m_Bottom = false; } } else { - float fact = (float)m_MoveHeight / m_LevelWindow.GetRange(); + mitk::ScalarType fact = m_MoveHeight / m_LevelWindow.GetRange(); if (m_Leftbutton) { if (m_Resize && !m_CtrlPressed) { - double diff = (mouseEvent->pos().y()) / fact; + mitk::ScalarType diff = (mouseEvent->pos().y()) / fact; diff -= (m_StartPos.y()) / fact; m_StartPos = mouseEvent->pos(); if (diff == 0) return; - float value; + mitk::ScalarType value; if (m_Bottom) value = m_LevelWindow.GetWindow() + ((2 * diff)); else value = m_LevelWindow.GetWindow() - ((2 * diff)); if (value < 0) value = 0; m_LevelWindow.SetLevelWindow(m_LevelWindow.GetLevel(), value); } else if (m_Resize && m_CtrlPressed) { if (!m_Bottom) { - double diff = (mouseEvent->pos().y()) / fact; + mitk::ScalarType diff = (mouseEvent->pos().y()) / fact; diff -= (m_StartPos.y()) / fact; m_StartPos = mouseEvent->pos(); if (diff == 0) return; - float value; + mitk::ScalarType value; value = m_LevelWindow.GetWindow() - ((diff)); if (value < 0) value = 0; - float oldWindow; - float oldLevel; - float newLevel; + mitk::ScalarType oldWindow; + mitk::ScalarType oldLevel; + mitk::ScalarType newLevel; oldWindow = m_LevelWindow.GetWindow(); oldLevel = m_LevelWindow.GetLevel(); newLevel = oldLevel + (value - oldWindow) / 2; if (!((newLevel + value / 2) > m_LevelWindow.GetRangeMax())) m_LevelWindow.SetLevelWindow(newLevel, value); } else { - double diff = (mouseEvent->pos().y()) / fact; + mitk::ScalarType diff = (mouseEvent->pos().y()) / fact; diff -= (m_StartPos.y()) / fact; m_StartPos = mouseEvent->pos(); if (diff == 0) return; - float value; + mitk::ScalarType value; value = m_LevelWindow.GetWindow() + ((diff)); if (value < 0) value = 0; - float oldWindow; - float oldLevel; - float newLevel; + mitk::ScalarType oldWindow; + mitk::ScalarType oldLevel; + mitk::ScalarType newLevel; oldWindow = m_LevelWindow.GetWindow(); oldLevel = m_LevelWindow.GetLevel(); newLevel = oldLevel - (value - oldWindow) / 2; if (!((newLevel - value / 2) < m_LevelWindow.GetRangeMin())) m_LevelWindow.SetLevelWindow(newLevel, value); } } else { - const float minv = m_LevelWindow.GetRangeMin(); + const mitk::ScalarType minv = m_LevelWindow.GetRangeMin(); - const float level = (m_MoveHeight - mouseEvent->pos().y()) / fact + minv; + const mitk::ScalarType level = (m_MoveHeight - mouseEvent->pos().y()) / fact + minv; - double diff = (mouseEvent->pos().x()) / fact; + mitk::ScalarType diff = (mouseEvent->pos().x()) / fact; diff -= (m_StartPos.x()) / fact; m_StartPos = mouseEvent->pos(); - float window; + mitk::ScalarType window; if (m_Bottom) window = m_LevelWindow.GetWindow() + ((2 * diff)); else window = m_LevelWindow.GetWindow() - ((2 * diff)); if (window < 0) window = 0; m_LevelWindow.SetLevelWindow(level, window); } m_Manager->SetLevelWindow(m_LevelWindow); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkSliderLevelWindowWidget::enterEvent(QEvent * /*event*/) { QPoint p = QCursor::pos(); p = this->mapFromGlobal(p); QMouseEvent ev(QEvent::MouseMove, p, Qt::NoButton, Qt::NoButton, Qt::NoModifier); this->mouseMoveEvent(&ev); } void QmitkSliderLevelWindowWidget::mousePressEvent(QMouseEvent *mouseEvent) { if (m_LevelWindow.IsFixed()) return; m_MouseDown = true; m_StartPos = mouseEvent->pos(); if (mouseEvent->button() == Qt::LeftButton) { if (mouseEvent->modifiers() == Qt::ControlModifier || mouseEvent->modifiers() == Qt::ShiftModifier) { m_CtrlPressed = true; } else { m_CtrlPressed = false; } m_Leftbutton = true; } else m_Leftbutton = false; mouseMoveEvent(mouseEvent); } void QmitkSliderLevelWindowWidget::resizeEvent(QResizeEvent *event) { m_MoveHeight = event->size().height() - 25; Update(); } void QmitkSliderLevelWindowWidget::mouseReleaseEvent(QMouseEvent *) { if (m_LevelWindow.IsFixed()) return; m_MouseDown = false; } void QmitkSliderLevelWindowWidget::Update() { int rectWidth; if (m_ScaleVisible) { rectWidth = 17; setMinimumSize(QSize(50, 50)); setMaximumSize(QSize(50, 2000)); setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding)); } else { rectWidth = 26; setMinimumSize(QSize(40, 50)); setMaximumSize(QSize(50, 2000)); setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding)); } - float mr = m_LevelWindow.GetRange(); + mitk::ScalarType mr = m_LevelWindow.GetRange(); if (mr < 1e-9) mr = 1e-9; - float fact = (float)m_MoveHeight / mr; + mitk::ScalarType fact = m_MoveHeight / mr; - float rectHeight = m_LevelWindow.GetWindow() * fact; + mitk::ScalarType rectHeight = m_LevelWindow.GetWindow() * fact; if (rectHeight < 15) rectHeight = 15; if (m_LevelWindow.GetLowerWindowBound() < 0) m_Rect.setRect(2, - (int)(m_MoveHeight - (m_LevelWindow.GetUpperWindowBound() - m_LevelWindow.GetRangeMin()) * fact), + static_cast(m_MoveHeight - (m_LevelWindow.GetUpperWindowBound() - m_LevelWindow.GetRangeMin()) * fact), rectWidth, - (int)rectHeight); + static_cast(rectHeight)); else m_Rect.setRect(2, - (int)(m_MoveHeight - (m_LevelWindow.GetUpperWindowBound() - m_LevelWindow.GetRangeMin()) * fact), + static_cast(m_MoveHeight - (m_LevelWindow.GetUpperWindowBound() - m_LevelWindow.GetRangeMin()) * fact), rectWidth, - (int)rectHeight); + static_cast(rectHeight)); QWidget::repaint(); } void QmitkSliderLevelWindowWidget::contextMenuEvent(QContextMenuEvent *) { m_Contextmenu->SetLevelWindowManager(m_Manager.GetPointer()); auto contextMenu = new QMenu(this); Q_CHECK_PTR(contextMenu); if (m_ScaleVisible) contextMenu->addAction(tr("Hide Scale"), this, SLOT(HideScale())); else contextMenu->addAction(tr("Show Scale"), this, SLOT(ShowScale())); contextMenu->addSeparator(); m_Contextmenu->GetContextMenu(contextMenu); // Fix: Bug #13327 we need to reset the m_MouseDown value // otherwise the cursor is not correctly restored afterwards m_MouseDown = false; } void QmitkSliderLevelWindowWidget::HideScale() { m_ScaleVisible = false; Update(); } void QmitkSliderLevelWindowWidget::ShowScale() { m_ScaleVisible = true; Update(); } void QmitkSliderLevelWindowWidget::SetDataStorage(mitk::DataStorage *ds) { m_Manager->SetDataStorage(ds); } mitk::LevelWindowManager *QmitkSliderLevelWindowWidget::GetManager() { return m_Manager.GetPointer(); } diff --git a/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp b/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp index 3ea503ba4a..8e8abb1b22 100644 --- a/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp +++ b/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp @@ -1,713 +1,746 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #define SMW_INFO MITK_INFO("widget.stdmulti") #include "QmitkStdMultiWidget.h" #include "QmitkRenderWindowWidget.h" // mitk core #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // qt #include #include #include // vtk #include // c++ #include QmitkStdMultiWidget::QmitkStdMultiWidget(QWidget *parent, Qt::WindowFlags f/* = 0*/, const QString &name/* = "stdmulti"*/) : QmitkAbstractMultiWidget(parent, f, name) , m_TimeNavigationController(nullptr) { m_TimeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController(); } QmitkStdMultiWidget::~QmitkStdMultiWidget() { auto allRenderWindows = this->GetRenderWindows(); for (auto& renderWindow : allRenderWindows) { m_TimeNavigationController->Disconnect(renderWindow->GetSliceNavigationController()); } } void QmitkStdMultiWidget::InitializeMultiWidget() { // yellow is default color for widget4 m_DecorationColorWidget4[0] = 1.0f; m_DecorationColorWidget4[1] = 1.0f; m_DecorationColorWidget4[2] = 0.0f; SetLayout(2, 2); // transfer colors in WorldGeometry-Nodes of the associated Renderer mitk::IntProperty::Pointer layer; // of widget 1 m_PlaneNode1 = mitk::BaseRenderer::GetInstance(GetRenderWindow1()->renderWindow())->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode1->SetColor(GetDecorationColor(0)); layer = mitk::IntProperty::New(1000); m_PlaneNode1->SetProperty("layer", layer); // of widget 2 m_PlaneNode2 = mitk::BaseRenderer::GetInstance(GetRenderWindow2()->renderWindow())->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode2->SetColor(GetDecorationColor(1)); layer = mitk::IntProperty::New(1000); m_PlaneNode2->SetProperty("layer", layer); // of widget 3 m_PlaneNode3 = mitk::BaseRenderer::GetInstance(GetRenderWindow3()->renderWindow())->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode3->SetColor(GetDecorationColor(2)); layer = mitk::IntProperty::New(1000); m_PlaneNode3->SetProperty("layer", layer); // the parent node m_ParentNodeForGeometryPlanes = mitk::BaseRenderer::GetInstance(GetRenderWindow4()->renderWindow())->GetCurrentWorldPlaneGeometryNode(); layer = mitk::IntProperty::New(1000); m_ParentNodeForGeometryPlanes->SetProperty("layer", layer); AddDisplayPlaneSubTree(); SetDisplayActionEventHandler(std::make_unique()); auto displayActionEventHandler = GetDisplayActionEventHandler(); if (nullptr != displayActionEventHandler) { displayActionEventHandler->InitActions(); } } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow(const QString& widgetName) const { if ("axial" == widgetName) { return GetRenderWindow1(); } if ("sagittal" == widgetName) { return GetRenderWindow2(); } if ("coronal" == widgetName) { return GetRenderWindow3(); } if ("3d" == widgetName) { return GetRenderWindow4(); } return QmitkAbstractMultiWidget::GetRenderWindow(widgetName); } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow(const mitk::BaseRenderer::ViewDirection& viewDirection) const { return GetRenderWindow(static_cast(viewDirection)); } +void QmitkStdMultiWidget::SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) +{ + auto* renderingManager = mitk::RenderingManager::GetInstance(); + mitk::Point3D currentPosition = mitk::Point3D(); + unsigned int imageTimeStep = 0; + if (!resetCamera) + { + // store the current position to set it again later, if the camera should not be reset + currentPosition = this->GetSelectedPosition(""); + + // store the current time step to set it again later, if the camera should not be reset + const auto currentTimePoint = renderingManager->GetTimeNavigationController()->GetSelectedTimePoint(); + if (referenceGeometry->IsValidTimePoint(currentTimePoint)) + { + imageTimeStep = referenceGeometry->TimePointToTimeStep(currentTimePoint); + } + } + + // initialize render windows + renderingManager->InitializeViews(referenceGeometry, mitk::RenderingManager::REQUEST_UPDATE_ALL, resetCamera); + + if (!resetCamera) + { + this->SetSelectedPosition(currentPosition, ""); + renderingManager->GetTimeNavigationController()->GetTime()->SetPos(imageTimeStep); + } +} + +bool QmitkStdMultiWidget::HasCoupledRenderWindows() const +{ + return true; +} + void QmitkStdMultiWidget::SetSelectedPosition(const mitk::Point3D& newPosition, const QString& /*widgetName*/) { GetRenderWindow1()->GetSliceNavigationController()->SelectSliceByPoint(newPosition); GetRenderWindow2()->GetSliceNavigationController()->SelectSliceByPoint(newPosition); GetRenderWindow3()->GetSliceNavigationController()->SelectSliceByPoint(newPosition); RequestUpdateAll(); } const mitk::Point3D QmitkStdMultiWidget::GetSelectedPosition(const QString& /*widgetName*/) const { const mitk::PlaneGeometry* plane1 = GetRenderWindow1()->GetSliceNavigationController()->GetCurrentPlaneGeometry(); const mitk::PlaneGeometry* plane2 = GetRenderWindow2()->GetSliceNavigationController()->GetCurrentPlaneGeometry(); const mitk::PlaneGeometry* plane3 = GetRenderWindow3()->GetSliceNavigationController()->GetCurrentPlaneGeometry(); mitk::Line3D line; if ((plane1 != nullptr) && (plane2 != nullptr) && (plane1->IntersectionLine(plane2, line))) { mitk::Point3D point; if ((plane3 != nullptr) && (plane3->IntersectionPoint(line, point))) { return point; } } return mitk::Point3D(); } void QmitkStdMultiWidget::SetCrosshairVisibility(bool visible) { if (m_PlaneNode1.IsNotNull()) { m_PlaneNode1->SetVisibility(visible); } if (m_PlaneNode2.IsNotNull()) { m_PlaneNode2->SetVisibility(visible); } if (m_PlaneNode3.IsNotNull()) { m_PlaneNode3->SetVisibility(visible); } emit NotifyCrosshairVisibilityChanged(visible); RequestUpdateAll(); } bool QmitkStdMultiWidget::GetCrosshairVisibility() const { bool crosshairVisibility = true; if (m_PlaneNode1.IsNotNull()) { bool visibilityProperty = false; m_PlaneNode1->GetVisibility(visibilityProperty, nullptr); crosshairVisibility &= visibilityProperty; } if (m_PlaneNode2.IsNotNull()) { bool visibilityProperty = false; crosshairVisibility &= m_PlaneNode2->GetVisibility(visibilityProperty, nullptr); crosshairVisibility &= visibilityProperty; } if (m_PlaneNode3.IsNotNull()) { bool visibilityProperty = false; crosshairVisibility &= m_PlaneNode3->GetVisibility(visibilityProperty, nullptr); crosshairVisibility &= visibilityProperty; } return crosshairVisibility; } void QmitkStdMultiWidget::SetCrosshairGap(unsigned int gapSize) { m_PlaneNode1->SetIntProperty("Crosshair.Gap Size", gapSize); m_PlaneNode2->SetIntProperty("Crosshair.Gap Size", gapSize); m_PlaneNode3->SetIntProperty("Crosshair.Gap Size", gapSize); } void QmitkStdMultiWidget::ResetCrosshair() { auto dataStorage = GetDataStorage(); if (nullptr == dataStorage) { return; } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); SetWidgetPlaneMode(mitk::InteractionSchemeSwitcher::MITKStandard); } void QmitkStdMultiWidget::SetWidgetPlaneMode(int userMode) { MITK_DEBUG << "Changing crosshair mode to " << userMode; switch (userMode) { case 0: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKStandard); break; case 1: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKRotationUncoupled); break; case 2: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKRotationCoupled); break; case 3: SetInteractionScheme(mitk::InteractionSchemeSwitcher::MITKSwivel); break; } emit NotifyCrosshairRotationModeChanged(userMode); } mitk::SliceNavigationController* QmitkStdMultiWidget::GetTimeNavigationController() { return m_TimeNavigationController; } void QmitkStdMultiWidget::AddPlanesToDataStorage() { auto dataStorage = GetDataStorage(); if (nullptr == dataStorage) { return; } if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull()) { dataStorage->Add(m_ParentNodeForGeometryPlanes); dataStorage->Add(m_PlaneNode1, m_ParentNodeForGeometryPlanes); dataStorage->Add(m_PlaneNode2, m_ParentNodeForGeometryPlanes); dataStorage->Add(m_PlaneNode3, m_ParentNodeForGeometryPlanes); } } void QmitkStdMultiWidget::RemovePlanesFromDataStorage() { auto dataStorage = GetDataStorage(); if (nullptr == dataStorage) { return; } if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull()) { dataStorage->Remove(m_PlaneNode1); dataStorage->Remove(m_PlaneNode2); dataStorage->Remove(m_PlaneNode3); dataStorage->Remove(m_ParentNodeForGeometryPlanes); } } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow(unsigned int number) const { switch (number) { case 0: return GetRenderWindow1(); case 1: return GetRenderWindow2(); case 2: return GetRenderWindow3(); case 3: return GetRenderWindow4(); default: MITK_ERROR << "Requested unknown render window"; break; } return nullptr; } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow1() const { return QmitkAbstractMultiWidget::GetRenderWindow(GetNameFromIndex(0, 0)); } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow2() const { return QmitkAbstractMultiWidget::GetRenderWindow(GetNameFromIndex(0, 1)); } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow3() const { return QmitkAbstractMultiWidget::GetRenderWindow(GetNameFromIndex(1, 0)); } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow4() const { return QmitkAbstractMultiWidget::GetRenderWindow(GetNameFromIndex(1, 1)); } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane1() const { return m_PlaneNode1; } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane2() const { return m_PlaneNode2; } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane3() const { return m_PlaneNode3; } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane(unsigned number) const { switch (number) { case 1: return m_PlaneNode1; case 2: return m_PlaneNode2; case 3: return m_PlaneNode3; default: MITK_ERROR << "Requested unknown render window"; break; } return nullptr; } void QmitkStdMultiWidget::SetDecorationColor(unsigned int widgetNumber, mitk::Color color) { switch (widgetNumber) { case 0: if (m_PlaneNode1.IsNotNull()) { m_PlaneNode1->SetColor(color); } break; case 1: if (m_PlaneNode2.IsNotNull()) { m_PlaneNode2->SetColor(color); } break; case 2: if (m_PlaneNode3.IsNotNull()) { m_PlaneNode3->SetColor(color); } break; case 3: m_DecorationColorWidget4 = color; break; default: MITK_ERROR << "Decoration color for unknown widget!"; break; } } mitk::Color QmitkStdMultiWidget::GetDecorationColor(unsigned int widgetNumber) { // The implementation looks a bit messy here, but it avoids // synchronization of the color of the geometry nodes and an // internal member here. // Default colors were chosen for decent visibility. // Feel free to change your preferences in the workbench. float tmp[3] = { 0.0f, 0.0f, 0.0f }; switch (widgetNumber) { case 0: { if (m_PlaneNode1.IsNotNull()) { if (m_PlaneNode1->GetColor(tmp)) { return dynamic_cast(m_PlaneNode1->GetProperty("color"))->GetColor(); } } float red[3] = { 0.753f, 0.0f, 0.0f }; // This is #C00000 in hex return mitk::Color(red); } case 1: { if (m_PlaneNode2.IsNotNull()) { if (m_PlaneNode2->GetColor(tmp)) { return dynamic_cast(m_PlaneNode2->GetProperty("color"))->GetColor(); } } float green[3] = { 0.0f, 0.69f, 0.0f }; // This is #00B000 in hex return mitk::Color(green); } case 2: { if (m_PlaneNode3.IsNotNull()) { if (m_PlaneNode3->GetColor(tmp)) { return dynamic_cast(m_PlaneNode3->GetProperty("color"))->GetColor(); } } float blue[3] = { 0.0, 0.502f, 1.0f }; // This is #0080FF in hex return mitk::Color(blue); } case 3: { return m_DecorationColorWidget4; } default: MITK_ERROR << "Decoration color for unknown widget!"; float black[3] = { 0.0f, 0.0f, 0.0f }; return mitk::Color(black); } } void QmitkStdMultiWidget::mousePressEvent(QMouseEvent*) { // nothing here, but necessary for mouse interactions (.xml-configuration files) } void QmitkStdMultiWidget::moveEvent(QMoveEvent* e) { QWidget::moveEvent(e); // it is necessary to readjust the position of the Annotation as the StdMultiWidget has moved // unfortunately it's not done by QmitkRenderWindow::moveEvent -> must be done here emit Moved(); } void QmitkStdMultiWidget::wheelEvent(QWheelEvent* e) { emit WheelMoved(e); } void QmitkStdMultiWidget::Fit() { vtkSmartPointer vtkrenderer; vtkrenderer = mitk::BaseRenderer::GetInstance(GetRenderWindow1()->renderWindow())->GetVtkRenderer(); if (nullptr != vtkrenderer) { vtkrenderer->ResetCamera(); } vtkrenderer = mitk::BaseRenderer::GetInstance(GetRenderWindow2()->renderWindow())->GetVtkRenderer(); if (nullptr != vtkrenderer) { vtkrenderer->ResetCamera(); } vtkrenderer = mitk::BaseRenderer::GetInstance(GetRenderWindow3()->renderWindow())->GetVtkRenderer(); if (nullptr != vtkrenderer) { vtkrenderer->ResetCamera(); } vtkrenderer = mitk::BaseRenderer::GetInstance(GetRenderWindow4()->renderWindow())->GetVtkRenderer(); if (nullptr != vtkrenderer) { vtkrenderer->ResetCamera(); } mitk::BaseRenderer::GetInstance(GetRenderWindow1()->renderWindow())->GetCameraController()->Fit(); mitk::BaseRenderer::GetInstance(GetRenderWindow2()->renderWindow())->GetCameraController()->Fit(); mitk::BaseRenderer::GetInstance(GetRenderWindow3()->renderWindow())->GetCameraController()->Fit(); mitk::BaseRenderer::GetInstance(GetRenderWindow4()->renderWindow())->GetCameraController()->Fit(); int w = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); vtkObject::SetGlobalWarningDisplay(w); } void QmitkStdMultiWidget::AddDisplayPlaneSubTree() { // add the displayed planes of the multiwidget to a node to which the subtree // @a planesSubTree points ... mitk::PlaneGeometryDataMapper2D::Pointer mapper; // ... of widget 1 mitk::BaseRenderer* renderer1 = mitk::BaseRenderer::GetInstance(GetRenderWindow1()->renderWindow()); m_PlaneNode1 = renderer1->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("name", mitk::StringProperty::New(std::string(renderer1->GetName()) + ".plane")); m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true)); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 2 mitk::BaseRenderer* renderer2 = mitk::BaseRenderer::GetInstance(GetRenderWindow2()->renderWindow()); m_PlaneNode2 = renderer2->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("name", mitk::StringProperty::New(std::string(renderer2->GetName()) + ".plane")); m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true)); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 3 mitk::BaseRenderer *renderer3 = mitk::BaseRenderer::GetInstance(GetRenderWindow3()->renderWindow()); m_PlaneNode3 = renderer3->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("name", mitk::StringProperty::New(std::string(renderer3->GetName()) + ".plane")); m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true)); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper); m_ParentNodeForGeometryPlanes = mitk::DataNode::New(); m_ParentNodeForGeometryPlanes->SetProperty("name", mitk::StringProperty::New("Widgets")); m_ParentNodeForGeometryPlanes->SetProperty("helper object", mitk::BoolProperty::New(true)); } void QmitkStdMultiWidget::EnsureDisplayContainsPoint(mitk::BaseRenderer *renderer, const mitk::Point3D &p) { mitk::Point2D pointOnDisplay; renderer->WorldToDisplay(p, pointOnDisplay); if (pointOnDisplay[0] < renderer->GetVtkRenderer()->GetOrigin()[0] || pointOnDisplay[1] < renderer->GetVtkRenderer()->GetOrigin()[1] || pointOnDisplay[0] > renderer->GetVtkRenderer()->GetOrigin()[0] + renderer->GetViewportSize()[0] || pointOnDisplay[1] > renderer->GetVtkRenderer()->GetOrigin()[1] + renderer->GetViewportSize()[1]) { mitk::Point2D pointOnPlane; renderer->GetCurrentWorldPlaneGeometry()->Map(p, pointOnPlane); renderer->GetCameraController()->MoveCameraToPoint(pointOnPlane); } } void QmitkStdMultiWidget::SetWidgetPlaneVisibility(const char *widgetName, bool visible, mitk::BaseRenderer *renderer) { auto dataStorage = GetDataStorage(); if (nullptr != dataStorage) { mitk::DataNode* dataNode = dataStorage->GetNamedNode(widgetName); if (dataNode != nullptr) { dataNode->SetVisibility(visible, renderer); } } } void QmitkStdMultiWidget::SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer) { if (m_PlaneNode1.IsNotNull()) { m_PlaneNode1->SetVisibility(visible, renderer); } if (m_PlaneNode2.IsNotNull()) { m_PlaneNode2->SetVisibility(visible, renderer); } if (m_PlaneNode3.IsNotNull()) { m_PlaneNode3->SetVisibility(visible, renderer); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } ////////////////////////////////////////////////////////////////////////// // PRIVATE ////////////////////////////////////////////////////////////////////////// void QmitkStdMultiWidget::SetLayoutImpl() { CreateRenderWindowWidgets(); GetMultiWidgetLayoutManager()->SetLayoutDesign(QmitkMultiWidgetLayoutManager::LayoutDesign::DEFAULT); // Initialize views as axial, sagittal, coronal to all data objects in DataStorage auto geo = GetDataStorage()->ComputeBoundingGeometry3D(GetDataStorage()->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); } void QmitkStdMultiWidget::CreateRenderWindowWidgets() { // create axial render window (widget) QString renderWindowWidgetName = GetNameFromIndex(0, 0); RenderWindowWidgetPointer renderWindowWidget1 = std::make_shared(this, renderWindowWidgetName, GetDataStorage()); auto renderWindow1 = renderWindowWidget1->GetRenderWindow(); renderWindow1->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Axial); renderWindowWidget1->SetDecorationColor(GetDecorationColor(0)); renderWindowWidget1->SetCornerAnnotationText("Axial"); renderWindowWidget1->GetRenderWindow()->SetLayoutIndex(ViewDirection::AXIAL); AddRenderWindowWidget(renderWindowWidgetName, renderWindowWidget1); // create sagittal render window (widget) renderWindowWidgetName = GetNameFromIndex(0, 1); RenderWindowWidgetPointer renderWindowWidget2 = std::make_shared(this, renderWindowWidgetName, GetDataStorage()); auto renderWindow2 = renderWindowWidget2->GetRenderWindow(); renderWindow2->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Sagittal); renderWindowWidget2->SetDecorationColor(GetDecorationColor(1)); renderWindowWidget2->setStyleSheet("border: 0px"); renderWindowWidget2->SetCornerAnnotationText("Sagittal"); renderWindowWidget2->GetRenderWindow()->SetLayoutIndex(ViewDirection::SAGITTAL); AddRenderWindowWidget(renderWindowWidgetName, renderWindowWidget2); // create coronal render window (widget) renderWindowWidgetName = GetNameFromIndex(1, 0); RenderWindowWidgetPointer renderWindowWidget3 = std::make_shared(this, renderWindowWidgetName, GetDataStorage()); auto renderWindow3 = renderWindowWidget3->GetRenderWindow(); renderWindow3->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Coronal); renderWindowWidget3->SetDecorationColor(GetDecorationColor(2)); renderWindowWidget3->SetCornerAnnotationText("Coronal"); renderWindowWidget3->GetRenderWindow()->SetLayoutIndex(ViewDirection::CORONAL); AddRenderWindowWidget(renderWindowWidgetName, renderWindowWidget3); // create 3D render window (widget) renderWindowWidgetName = GetNameFromIndex(1, 1); RenderWindowWidgetPointer renderWindowWidget4 = std::make_shared(this, renderWindowWidgetName, GetDataStorage()); auto renderWindow4 = renderWindowWidget4->GetRenderWindow(); renderWindow4->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Original); renderWindowWidget4->SetDecorationColor(GetDecorationColor(3)); renderWindowWidget4->SetCornerAnnotationText("3D"); renderWindowWidget4->GetRenderWindow()->SetLayoutIndex(ViewDirection::THREE_D); mitk::BaseRenderer::GetInstance(renderWindowWidget4->GetRenderWindow()->renderWindow())->SetMapperID(mitk::BaseRenderer::Standard3D); AddRenderWindowWidget(renderWindowWidgetName, renderWindowWidget4); SetActiveRenderWindowWidget(renderWindowWidget1); // connect to the "time navigation controller": send time via sliceNavigationControllers m_TimeNavigationController->ConnectGeometryTimeEvent(renderWindow1->GetSliceNavigationController()); m_TimeNavigationController->ConnectGeometryTimeEvent(renderWindow2->GetSliceNavigationController()); m_TimeNavigationController->ConnectGeometryTimeEvent(renderWindow3->GetSliceNavigationController()); m_TimeNavigationController->ConnectGeometryTimeEvent(renderWindow4->GetSliceNavigationController()); renderWindow1->GetSliceNavigationController()->ConnectGeometrySendEvent( mitk::BaseRenderer::GetInstance(renderWindow4->renderWindow())); // reverse connection between sliceNavigationControllers and timeNavigationController renderWindow1->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController); renderWindow2->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController); renderWindow3->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController); //renderWindow4->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController); auto layoutManager = GetMultiWidgetLayoutManager(); connect(renderWindow1, &QmitkRenderWindow::ResetView, this, &QmitkStdMultiWidget::ResetCrosshair); connect(renderWindow1, &QmitkRenderWindow::CrosshairVisibilityChanged, this, &QmitkStdMultiWidget::SetCrosshairVisibility); connect(renderWindow1, &QmitkRenderWindow::CrosshairRotationModeChanged, this, &QmitkStdMultiWidget::SetWidgetPlaneMode); connect(renderWindow1, &QmitkRenderWindow::LayoutDesignChanged, layoutManager, &QmitkMultiWidgetLayoutManager::SetLayoutDesign); connect(this, &QmitkStdMultiWidget::NotifyCrosshairVisibilityChanged, renderWindow1, &QmitkRenderWindow::UpdateCrosshairVisibility); connect(this, &QmitkStdMultiWidget::NotifyCrosshairRotationModeChanged, renderWindow1, &QmitkRenderWindow::UpdateCrosshairRotationMode); connect(renderWindow2, &QmitkRenderWindow::ResetView, this, &QmitkStdMultiWidget::ResetCrosshair); connect(renderWindow2, &QmitkRenderWindow::CrosshairVisibilityChanged, this, &QmitkStdMultiWidget::SetCrosshairVisibility); connect(renderWindow2, &QmitkRenderWindow::CrosshairRotationModeChanged, this, &QmitkStdMultiWidget::SetWidgetPlaneMode); connect(renderWindow2, &QmitkRenderWindow::LayoutDesignChanged, layoutManager, &QmitkMultiWidgetLayoutManager::SetLayoutDesign); connect(this, &QmitkStdMultiWidget::NotifyCrosshairVisibilityChanged, renderWindow2, &QmitkRenderWindow::UpdateCrosshairVisibility); connect(this, &QmitkStdMultiWidget::NotifyCrosshairRotationModeChanged, renderWindow2, &QmitkRenderWindow::UpdateCrosshairRotationMode); connect(renderWindow3, &QmitkRenderWindow::ResetView, this, &QmitkStdMultiWidget::ResetCrosshair); connect(renderWindow3, &QmitkRenderWindow::CrosshairVisibilityChanged, this, &QmitkStdMultiWidget::SetCrosshairVisibility); connect(renderWindow3, &QmitkRenderWindow::CrosshairRotationModeChanged, this, &QmitkStdMultiWidget::SetWidgetPlaneMode); connect(renderWindow3, &QmitkRenderWindow::LayoutDesignChanged, layoutManager, &QmitkMultiWidgetLayoutManager::SetLayoutDesign); connect(this, &QmitkStdMultiWidget::NotifyCrosshairVisibilityChanged, renderWindow3, &QmitkRenderWindow::UpdateCrosshairVisibility); connect(this, &QmitkStdMultiWidget::NotifyCrosshairRotationModeChanged, renderWindow3, &QmitkRenderWindow::UpdateCrosshairRotationMode); connect(renderWindow4, &QmitkRenderWindow::ResetView, this, &QmitkStdMultiWidget::ResetCrosshair); connect(renderWindow4, &QmitkRenderWindow::CrosshairVisibilityChanged, this, &QmitkStdMultiWidget::SetCrosshairVisibility); connect(renderWindow4, &QmitkRenderWindow::CrosshairRotationModeChanged, this, &QmitkStdMultiWidget::SetWidgetPlaneMode); connect(renderWindow4, &QmitkRenderWindow::LayoutDesignChanged, layoutManager, &QmitkMultiWidgetLayoutManager::SetLayoutDesign); connect(this, &QmitkStdMultiWidget::NotifyCrosshairVisibilityChanged, renderWindow4, &QmitkRenderWindow::UpdateCrosshairVisibility); connect(this, &QmitkStdMultiWidget::NotifyCrosshairRotationModeChanged, renderWindow4, &QmitkRenderWindow::UpdateCrosshairRotationMode); } diff --git a/Modules/QtWidgets/src/mitkRenderWindowLayerUtilities.cpp b/Modules/QtWidgets/src/mitkRenderWindowLayerUtilities.cpp index b387f8265e..e2e8c375ba 100644 --- a/Modules/QtWidgets/src/mitkRenderWindowLayerUtilities.cpp +++ b/Modules/QtWidgets/src/mitkRenderWindowLayerUtilities.cpp @@ -1,88 +1,82 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // render window manager module #include "mitkRenderWindowLayerUtilities.h" // mitk core -#include #include mitk::RenderWindowLayerUtilities::LayerStack mitk::RenderWindowLayerUtilities::GetLayerStack(const DataStorage* dataStorage, const BaseRenderer* renderer, bool withBaseNode) { LayerStack stackedLayers; if (nullptr == dataStorage || nullptr == renderer) { // no nodes to stack or no renderer selected return stackedLayers; } int layer = -1; - NodePredicateAnd::Pointer combinedNodePredicate = GetRenderWindowPredicate(renderer); - DataStorage::SetOfObjects::ConstPointer filteredDataNodes = dataStorage->GetSubset(combinedNodePredicate); + NodePredicateBase::Pointer fixedLayerPredicate = GetRenderWindowPredicate(renderer); + DataStorage::SetOfObjects::ConstPointer filteredDataNodes = dataStorage->GetSubset(fixedLayerPredicate); for (DataStorage::SetOfObjects::ConstIterator it = filteredDataNodes->Begin(); it != filteredDataNodes->End(); ++it) { DataNode::Pointer dataNode = it->Value(); if (dataNode.IsNull()) { continue; } bool layerFound = dataNode->GetIntProperty("layer", layer, renderer); if (layerFound) { if (BASE_LAYER_INDEX != layer|| withBaseNode) { // data node is not on the base layer or the base layer should be included anyway stackedLayers.insert(std::make_pair(layer, dataNode)); } } } return stackedLayers; } -mitk::NodePredicateAnd::Pointer mitk::RenderWindowLayerUtilities::GetRenderWindowPredicate(const BaseRenderer* renderer) +mitk::NodePredicateBase::Pointer mitk::RenderWindowLayerUtilities::GetRenderWindowPredicate(const BaseRenderer* renderer) { - NodePredicateAnd::Pointer renderWindowPredicate = NodePredicateAnd::New(); + NodePredicateBase::Pointer fixedLayerPredicate = + NodePredicateProperty::New("fixedLayer", BoolProperty::New(true), renderer); - NodePredicateProperty::Pointer helperObject = NodePredicateProperty::New("helper object", BoolProperty::New(true)); - NodePredicateProperty::Pointer fixedLayer = NodePredicateProperty::New("fixedLayer", BoolProperty::New(true), renderer); - - renderWindowPredicate->AddPredicate(NodePredicateNot::New(helperObject)); - renderWindowPredicate->AddPredicate(fixedLayer); - - return renderWindowPredicate; + return fixedLayerPredicate; } void mitk::RenderWindowLayerUtilities::SetRenderWindowProperties(mitk::DataNode* dataNode, const BaseRenderer* renderer) { dataNode->SetBoolProperty("fixedLayer", true, renderer); // use visibility of existing renderer or common renderer // common renderer is used if renderer-specific property does not exist bool visible = false; bool visibilityProperty = dataNode->GetVisibility(visible, renderer); if (true == visibilityProperty) { // found a visibility property dataNode->SetVisibility(visible, renderer); } // use layer of existing renderer or common renderer // common renderer is used if renderer-specific property does not exist int layer = -1; bool layerProperty = dataNode->GetIntProperty("layer", layer, renderer); if (true == layerProperty) { // found a layer property dataNode->SetIntProperty("layer", layer, renderer); } } diff --git a/Modules/SceneSerialization/src/mitkSceneIO.cpp b/Modules/SceneSerialization/src/mitkSceneIO.cpp index 888eda6c5c..c96aa37a3e 100644 --- a/Modules/SceneSerialization/src/mitkSceneIO.cpp +++ b/Modules/SceneSerialization/src/mitkSceneIO.cpp @@ -1,575 +1,577 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include #include "mitkBaseDataSerializer.h" #include "mitkPropertyListSerializer.h" #include "mitkSceneIO.h" #include "mitkSceneReader.h" #include "mitkBaseRenderer.h" #include "mitkProgressBar.h" #include "mitkRenderingManager.h" #include "mitkStandaloneDataStorage.h" #include #include #include #include #include #include #include "itksys/SystemTools.hxx" #include mitk::SceneIO::SceneIO() : m_WorkingDirectory(""), m_UnzipErrors(0) { } mitk::SceneIO::~SceneIO() { } std::string mitk::SceneIO::CreateEmptyTempDirectory() { mitk::UIDGenerator uidGen; // std::string returnValue = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + // Poco::Path::separator() + "SceneIOTemp" + uidGen.GetUID(); std::string returnValue = Poco::Path::temp() + "SceneIOTemp" + uidGen.GetUID(); std::string uniquename = returnValue + Poco::Path::separator(); Poco::File tempdir(uniquename); try { bool existsNot = tempdir.createDirectory(); if (!existsNot) { MITK_ERROR << "Warning: Directory already exitsts: " << uniquename << " (choosing another)"; returnValue = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + Poco::Path::separator() + "SceneIOTempDirectory" + uidGen.GetUID(); uniquename = returnValue + Poco::Path::separator(); Poco::File tempdir2(uniquename); if (!tempdir2.createDirectory()) { MITK_ERROR << "Warning: Second directory also already exitsts: " << uniquename; } } } catch (std::exception &e) { MITK_ERROR << "Could not create temporary directory " << uniquename << ":" << e.what(); return ""; } return returnValue; } mitk::DataStorage::Pointer mitk::SceneIO::LoadScene(const std::string &filename, DataStorage *pStorage, bool clearStorageFirst) { mitk::LocaleSwitch localeSwitch("C"); // prepare data storage DataStorage::Pointer storage = pStorage; if (storage.IsNull()) { storage = StandaloneDataStorage::New().GetPointer(); } // test input filename if (filename.empty()) { MITK_ERROR << "No filename given. Not possible to load scene."; return storage; } // test if filename can be read std::ifstream file(filename.c_str(), std::ios::binary); if (!file.good()) { MITK_ERROR << "Cannot open '" << filename << "' for reading"; return storage; } // get new temporary directory m_WorkingDirectory = CreateEmptyTempDirectory(); if (m_WorkingDirectory.empty()) { MITK_ERROR << "Could not create temporary directory. Cannot open scene files."; return storage; } // unzip all filenames contents to temp dir m_UnzipErrors = 0; Poco::Zip::Decompress unzipper(file, Poco::Path(m_WorkingDirectory)); unzipper.EError += Poco::Delegate>( this, &SceneIO::OnUnzipError); unzipper.EOk += Poco::Delegate>( this, &SceneIO::OnUnzipOk); unzipper.decompressAllFiles(); unzipper.EError -= Poco::Delegate>( this, &SceneIO::OnUnzipError); unzipper.EOk -= Poco::Delegate>( this, &SceneIO::OnUnzipOk); if (m_UnzipErrors) { MITK_ERROR << "There were " << m_UnzipErrors << " errors unzipping '" << filename << "'. Will attempt to read whatever could be unzipped."; } // transcode locale-dependent string m_WorkingDirectory = Poco::Path::transcode (m_WorkingDirectory); auto indexFile = m_WorkingDirectory + mitk::IOUtil::GetDirectorySeparator() + "index.xml"; storage = LoadSceneUnzipped(indexFile, storage, clearStorageFirst); // delete temp directory try { Poco::File deleteDir(m_WorkingDirectory); deleteDir.remove(true); // recursive } catch (...) { MITK_ERROR << "Could not delete temporary directory " << m_WorkingDirectory; } // return new data storage, even if empty or uncomplete (return as much as possible but notify calling method) return storage; } mitk::DataStorage::Pointer mitk::SceneIO::LoadSceneUnzipped(const std::string &indexfilename, DataStorage *pStorage, bool clearStorageFirst) { mitk::LocaleSwitch localeSwitch("C"); // prepare data storage DataStorage::Pointer storage = pStorage; if (storage.IsNull()) { storage = StandaloneDataStorage::New().GetPointer(); } if (clearStorageFirst) { try { storage->Remove(storage->GetAll()); } catch (...) { MITK_ERROR << "DataStorage cannot be cleared properly."; } } // test input filename if (indexfilename.empty()) { MITK_ERROR << "No filename given. Not possible to load scene."; return storage; } // transcode locale-dependent string std::string tempfilename; std::string workingDir; itksys::SystemTools::SplitProgramPath(indexfilename, workingDir, tempfilename); // test if index.xml exists // parse index.xml with TinyXML tinyxml2::XMLDocument document; if (tinyxml2::XML_SUCCESS != document.LoadFile(indexfilename.c_str())) { MITK_ERROR << "Could not open/read/parse " << workingDir << mitk::IOUtil::GetDirectorySeparator() << "index.xml\nTinyXML reports: " << document.ErrorStr() << std::endl; return storage; } SceneReader::Pointer reader = SceneReader::New(); if (!reader->LoadScene(document, workingDir, storage)) { MITK_ERROR << "There were errors while loading scene file " << indexfilename << ". Your data may be corrupted"; } // return new data storage, even if empty or uncomplete (return as much as possible but notify calling method) return storage; } bool mitk::SceneIO::SaveScene(DataStorage::SetOfObjects::ConstPointer sceneNodes, const DataStorage *storage, const std::string &filename) { if (!sceneNodes) { MITK_ERROR << "No set of nodes given. Not possible to save scene."; return false; } if (!storage) { MITK_ERROR << "No data storage given. Not possible to save scene."; // \TODO: Technically, it would be possible to // save the nodes without their relation return false; } if (filename.empty()) { MITK_ERROR << "No filename given. Not possible to save scene."; return false; } mitk::LocaleSwitch localeSwitch("C"); try { m_FailedNodes = DataStorage::SetOfObjects::New(); m_FailedProperties = PropertyList::New(); // start XML DOM tinyxml2::XMLDocument document; document.InsertEndChild(document.NewDeclaration()); auto *version = document.NewElement("Version"); version->SetAttribute("Writer", __FILE__); version->SetAttribute("Revision", "$Revision: 17055 $"); version->SetAttribute("FileVersion", 1); document.InsertEndChild(version); // DataStorage::SetOfObjects::ConstPointer sceneNodes = storage->GetSubset( predicate ); if (sceneNodes.IsNull()) { MITK_WARN << "Saving empty scene to " << filename; } else { if (sceneNodes->size() == 0) { MITK_WARN << "Saving empty scene to " << filename; } MITK_INFO << "Storing scene with " << sceneNodes->size() << " objects to " << filename; m_WorkingDirectory = CreateEmptyTempDirectory(); if (m_WorkingDirectory.empty()) { MITK_ERROR << "Could not create temporary directory. Cannot create scene files."; return false; } ProgressBar::GetInstance()->AddStepsToDo(sceneNodes->size()); // find out about dependencies typedef std::map UIDMapType; typedef std::map> SourcesMapType; UIDMapType nodeUIDs; // for dependencies: ID of each node SourcesMapType sourceUIDs; // for dependencies: IDs of a node's parent nodes UIDGenerator nodeUIDGen("OBJECT_"); for (auto iter = sceneNodes->begin(); iter != sceneNodes->end(); ++iter) { DataNode *node = iter->GetPointer(); if (!node) continue; // unlikely event that we get a nullptr pointer as an object for saving. just ignore // generate UIDs for all source objects DataStorage::SetOfObjects::ConstPointer sourceObjects = storage->GetSources(node); for (auto sourceIter = sourceObjects->begin(); sourceIter != sourceObjects->end(); ++sourceIter) { if (std::find(sceneNodes->begin(), sceneNodes->end(), *sourceIter) == sceneNodes->end()) continue; // source is not saved, so don't generate a UID for this source // create a uid for the parent object if (nodeUIDs[*sourceIter].empty()) { nodeUIDs[*sourceIter] = nodeUIDGen.GetUID(); } // store this dependency for writing sourceUIDs[node].push_back(nodeUIDs[*sourceIter]); } if (nodeUIDs[node].empty()) { nodeUIDs[node] = nodeUIDGen.GetUID(); } } // write out objects, dependencies and properties for (auto iter = sceneNodes->begin(); iter != sceneNodes->end(); ++iter) { DataNode *node = iter->GetPointer(); if (node) { auto *nodeElement = document.NewElement("node"); std::string filenameHint(node->GetName()); filenameHint = itksys::SystemTools::MakeCindentifier( filenameHint.c_str()); // escape filename <-- only allow [A-Za-z0-9_], replace everything else with _ // store dependencies auto searchUIDIter = nodeUIDs.find(node); if (searchUIDIter != nodeUIDs.end()) { // store this node's ID nodeElement->SetAttribute("UID", searchUIDIter->second.c_str()); } auto searchSourcesIter = sourceUIDs.find(node); if (searchSourcesIter != sourceUIDs.end()) { // store all source IDs for (auto sourceUIDIter = searchSourcesIter->second.begin(); sourceUIDIter != searchSourcesIter->second.end(); ++sourceUIDIter) { auto *uidElement = document.NewElement("source"); uidElement->SetAttribute("UID", sourceUIDIter->c_str()); nodeElement->InsertEndChild(uidElement); } } // store basedata if (BaseData *data = node->GetData()) { // std::string filenameHint( node->GetName() ); bool error(false); auto *dataElement = SaveBaseData(document, data, filenameHint, error); // returns a reference to a file if (error) { m_FailedNodes->push_back(node); } // store basedata properties PropertyList *propertyList = data->GetPropertyList(); if (propertyList && !propertyList->IsEmpty()) { auto *baseDataPropertiesElement = SavePropertyList(document, propertyList, filenameHint + "-data"); // returns a reference to a file dataElement->InsertEndChild(baseDataPropertiesElement); } nodeElement->InsertEndChild(dataElement); } // store all renderwindow specific propertylists mitk::DataNode::PropertyListKeyNames propertyListKeys = node->GetPropertyListNames(); for (const auto &renderWindowName : propertyListKeys) { PropertyList *propertyList = node->GetPropertyList(renderWindowName); if (propertyList && !propertyList->IsEmpty()) { auto *renderWindowPropertiesElement = SavePropertyList(document, propertyList, filenameHint + "-" + renderWindowName); // returns a reference to a file renderWindowPropertiesElement->SetAttribute("renderwindow", renderWindowName.c_str()); nodeElement->InsertEndChild(renderWindowPropertiesElement); } } // don't forget the renderwindow independent list PropertyList *propertyList = node->GetPropertyList(); if (propertyList && !propertyList->IsEmpty()) { auto *propertiesElement = SavePropertyList(document, propertyList, filenameHint + "-node"); // returns a reference to a file nodeElement->InsertEndChild(propertiesElement); } document.InsertEndChild(nodeElement); } else { MITK_WARN << "Ignoring nullptr node during scene serialization."; } ProgressBar::GetInstance()->Progress(); } // end for all nodes } // end if sceneNodes std::string defaultLocale_WorkingDirectory = Poco::Path::transcode( m_WorkingDirectory ); auto xmlFilename = defaultLocale_WorkingDirectory + Poco::Path::separator() + "index.xml"; if (tinyxml2::XML_SUCCESS != document.SaveFile(xmlFilename.c_str())) { MITK_ERROR << "Could not write scene to " << defaultLocale_WorkingDirectory << Poco::Path::separator() << "index.xml" << "\nTinyXML reports '" << document.ErrorStr() << "'"; return false; } else { try { Poco::File deleteFile(filename.c_str()); if (deleteFile.exists()) { deleteFile.remove(); } // create zip at filename std::ofstream file(filename.c_str(), std::ios::binary | std::ios::out); if (!file.good()) { MITK_ERROR << "Could not open a zip file for writing: '" << filename << "'"; return false; } else { Poco::Zip::Compress zipper(file, true); Poco::Path tmpdir(m_WorkingDirectory); zipper.addRecursive(tmpdir); zipper.close(); } try { Poco::File deleteDir(m_WorkingDirectory); deleteDir.remove(true); // recursive } catch (...) { MITK_ERROR << "Could not delete temporary directory " << m_WorkingDirectory; return false; // ok? } } catch (std::exception &e) { MITK_ERROR << "Could not create ZIP file from " << m_WorkingDirectory << "\nReason: " << e.what(); return false; } return true; } } catch (std::exception &e) { MITK_ERROR << "Caught exception during saving temporary files to disk. Error description: '" << e.what() << "'"; return false; } } tinyxml2::XMLElement *mitk::SceneIO::SaveBaseData(tinyxml2::XMLDocument &doc, BaseData *data, const std::string &filenamehint, bool &error) { assert(data); error = true; // find correct serializer // the serializer must // - create a file containing all information to recreate the BaseData object --> needs to know where to put this // file (and a filename?) // - TODO what to do about writers that creates one file per timestep? auto *element = doc.NewElement("data"); element->SetAttribute("type", data->GetNameOfClass()); // construct name of serializer class std::string serializername(data->GetNameOfClass()); serializername += "Serializer"; std::list thingsThatCanSerializeThis = itk::ObjectFactoryBase::CreateAllInstance(serializername.c_str()); if (thingsThatCanSerializeThis.size() < 1) { MITK_ERROR << "No serializer found for " << data->GetNameOfClass() << ". Skipping object"; } for (auto iter = thingsThatCanSerializeThis.begin(); iter != thingsThatCanSerializeThis.end(); ++iter) { if (auto *serializer = dynamic_cast(iter->GetPointer())) { serializer->SetData(data); serializer->SetFilenameHint(filenamehint); std::string defaultLocale_WorkingDirectory = Poco::Path::transcode( m_WorkingDirectory ); serializer->SetWorkingDirectory(defaultLocale_WorkingDirectory); try { std::string writtenfilename = serializer->Serialize(); element->SetAttribute("file", writtenfilename.c_str()); - error = false; + + if (!writtenfilename.empty()) + error = false; } catch (std::exception &e) { MITK_ERROR << "Serializer " << serializer->GetNameOfClass() << " failed: " << e.what(); } break; } } element->SetAttribute("UID", data->GetUID().c_str()); return element; } tinyxml2::XMLElement *mitk::SceneIO::SavePropertyList(tinyxml2::XMLDocument &doc, PropertyList *propertyList, const std::string &filenamehint) { assert(propertyList); // - TODO what to do about shared properties (same object in two lists or behind several keys)? auto *element = doc.NewElement("properties"); // construct name of serializer class PropertyListSerializer::Pointer serializer = PropertyListSerializer::New(); serializer->SetPropertyList(propertyList); serializer->SetFilenameHint(filenamehint); std::string defaultLocale_WorkingDirectory = Poco::Path::transcode( m_WorkingDirectory ); serializer->SetWorkingDirectory(defaultLocale_WorkingDirectory); try { std::string writtenfilename = serializer->Serialize(); element->SetAttribute("file", writtenfilename.c_str()); PropertyList::Pointer failedProperties = serializer->GetFailedProperties(); if (failedProperties.IsNotNull()) { // move failed properties to global list m_FailedProperties->ConcatenatePropertyList(failedProperties, true); } } catch (std::exception &e) { MITK_ERROR << "Serializer " << serializer->GetNameOfClass() << " failed: " << e.what(); } return element; } const mitk::SceneIO::FailedBaseDataListType *mitk::SceneIO::GetFailedNodes() { return m_FailedNodes.GetPointer(); } const mitk::PropertyList *mitk::SceneIO::GetFailedProperties() { return m_FailedProperties; } void mitk::SceneIO::OnUnzipError(const void * /*pSender*/, std::pair &info) { ++m_UnzipErrors; MITK_ERROR << "Error while unzipping: " << info.second; } void mitk::SceneIO::OnUnzipOk(const void * /*pSender*/, std::pair & /*info*/) { // MITK_INFO << "Unzipped ok: " << info.second.toString(); } diff --git a/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp b/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp index c28b3e54ce..9337bdf315 100644 --- a/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp +++ b/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp @@ -1,463 +1,468 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkSceneReaderV1.h" #include "Poco/Path.h" #include "mitkBaseRenderer.h" #include "mitkIOUtil.h" #include "mitkProgressBar.h" #include "mitkPropertyListDeserializer.h" #include "mitkSerializerMacros.h" #include #include #include #include #include MITK_REGISTER_SERIALIZER(SceneReaderV1) namespace { typedef std::pair> NodesAndParentsPair; bool NodeSortByLayerIsLessThan(const NodesAndParentsPair &left, const NodesAndParentsPair &right) { if (left.first.IsNotNull() && right.first.IsNotNull()) { int leftLayer; int rightLayer; if (left.first->GetIntProperty("layer", leftLayer) && right.first->GetIntProperty("layer", rightLayer)) { return leftLayer < rightLayer; } else { // fall back to name sort return left.first->GetName() < right.first->GetName(); } } // in all other cases, fall back to stupid pointer comparison // this is not reasonable but at least answers the sorting // question clearly return left.first.GetPointer() < right.first.GetPointer(); } // This is a workaround until we are able to save time-related information in an // actual file format of surfaces. void ApplyProportionalTimeGeometryProperties(mitk::BaseData* data) { auto* geometry = dynamic_cast(data->GetTimeGeometry()); if (nullptr == geometry) return; auto properties = data->GetPropertyList(); float value = 0.0f; if (properties->GetFloatProperty("ProportionalTimeGeometry.FirstTimePoint", value)) { if (value == -std::numeric_limits::infinity()) value = std::numeric_limits::lowest(); geometry->SetFirstTimePoint(value); } if (properties->GetFloatProperty("ProportionalTimeGeometry.StepDuration", value)) geometry->SetStepDuration(value); } mitk::PropertyList::Pointer DeserializeProperties(const tinyxml2::XMLElement *propertiesElement, const std::filesystem::path& basePath) { if (propertiesElement == nullptr) return nullptr; std::filesystem::path path(propertiesElement->Attribute("file")); if (path.empty()) return nullptr; if (!basePath.empty()) path = basePath / path; auto deserializer = mitk::PropertyListDeserializer::New(); deserializer->SetFilename(path.string()); deserializer->Deserialize(); return deserializer->GetOutput(); } } bool mitk::SceneReaderV1::LoadScene(tinyxml2::XMLDocument &document, const std::string &workingDirectory, DataStorage *storage) { assert(storage); bool error(false); // TODO prepare to detect errors (such as cycles) from wrongly written or edited xml files // Get number of elements to initialze progress bar // 1. if there is a element, // - construct a name for the appropriate serializer // - try to instantiate this serializer via itk object factory // - if serializer could be created, use it to read the file into a BaseData object // - if successful, call the new node's SetData(..) // create a node for the tag "data" and test if node was created typedef std::vector DataNodeVector; DataNodeVector DataNodes; unsigned int listSize = 0; for (auto *element = document.FirstChildElement("node"); element != nullptr; element = element->NextSiblingElement("node")) { ++listSize; } ProgressBar::GetInstance()->AddStepsToDo(listSize * 2); // Deserialize base data properties before reading the actual data to be // able to provide them as read-only meta data to the data reader. std::map baseDataPropertyLists; for (auto *nodeElement = document.FirstChildElement("node"); nodeElement != nullptr; nodeElement = nodeElement->NextSiblingElement("node")) { const auto *uid = nodeElement->Attribute("UID"); if (uid == nullptr) continue; auto *dataElement = nodeElement->FirstChildElement("data"); if (dataElement != nullptr) { auto properties = DeserializeProperties(dataElement->FirstChildElement("properties"), workingDirectory); if (properties.IsNotNull()) baseDataPropertyLists[uid] = properties; } } for (auto *element = document.FirstChildElement("node"); element != nullptr; element = element->NextSiblingElement("node")) { mitk::PropertyList* properties = nullptr; const auto *uid = element->Attribute("UID"); if (uid != nullptr) { auto iter = baseDataPropertyLists.find(uid); if (iter != baseDataPropertyLists.end()) properties = iter->second; } const auto *dataElement = element->FirstChildElement("data"); auto dataNode = this->LoadBaseDataFromDataTag(dataElement, properties, workingDirectory, error); if (dataNode.IsNull()) continue; auto* baseData = dataNode->GetData(); if (baseData != nullptr && properties != nullptr) { baseData->SetPropertyList(properties); ApplyProportionalTimeGeometryProperties(baseData); } DataNodes.push_back(dataNode); ProgressBar::GetInstance()->Progress(); } // iterate all nodes // first level nodes should be elements auto nit = DataNodes.begin(); for (auto *element = document.FirstChildElement("node"); element != nullptr || nit != DataNodes.end(); element = element->NextSiblingElement("node"), ++nit) { mitk::DataNode::Pointer node = *nit; // 1. check child nodes const char *uida = element->Attribute("UID"); std::string uid(""); if (uida) { uid = uida; m_NodeForID[uid] = node.GetPointer(); m_IDForNode[node.GetPointer()] = uid; } else { MITK_ERROR << "No UID found for current node. Node will have no parents."; error = true; } // 2. if there are nodes, // - instantiate the appropriate PropertyListDeSerializer // - use them to construct PropertyList objects // - add these properties to the node (if necessary, use renderwindow name) bool success = DecorateNodeWithProperties(node, element, workingDirectory); if (!success) { MITK_ERROR << "Could not load properties for node."; error = true; } // remember node for later adding to DataStorage m_OrderedNodePairs.push_back(std::make_pair(node, std::list())); // 3. if there are elements, remember parent objects for (auto *source = element->FirstChildElement("source"); source != nullptr; source = source->NextSiblingElement("source")) { const char *sourceUID = source->Attribute("UID"); if (sourceUID) { m_OrderedNodePairs.back().second.push_back(std::string(sourceUID)); } } ProgressBar::GetInstance()->Progress(); } // end for all // sort our nodes by their "layer" property // (to be inserted in that order) m_OrderedNodePairs.sort(&NodeSortByLayerIsLessThan); // remove all unknown parent UIDs for (auto nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { for (auto parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end();) { if (m_NodeForID.find(*parentsIter) == m_NodeForID.end()) { parentsIter = nodesIter->second.erase(parentsIter); MITK_WARN << "Found a DataNode with unknown parents. Will add it to DataStorage without any parent objects."; error = true; } else { ++parentsIter; } } } // repeat the following loop ... // ... for all created nodes unsigned int lastMapSize(0); while (lastMapSize != m_OrderedNodePairs .size()) // this is to prevent infinite loops; each iteration must at least add one node to DataStorage { lastMapSize = m_OrderedNodePairs.size(); // iterate (layer) ordered nodes backwards // we insert the highest layers first for (auto nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { bool addThisNode(true); // if any parent node is not yet in DataStorage, skip node for now and check later for (auto parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter) { if (!storage->Exists(m_NodeForID[*parentsIter])) { addThisNode = false; break; } } if (addThisNode) { DataStorage::SetOfObjects::Pointer parents = DataStorage::SetOfObjects::New(); for (auto parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter) { parents->push_back(m_NodeForID[*parentsIter]); } // if all parents are found in datastorage (or are unknown), add node to DataStorage storage->Add(nodesIter->first, parents); // remove this node from m_OrderedNodePairs m_OrderedNodePairs.erase(nodesIter); // break this for loop because iterators are probably invalid break; } } } // All nodes that are still in m_OrderedNodePairs at this point are not part of a proper directed graph structure. // We'll add such nodes without any parent information. for (auto nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { storage->Add(nodesIter->first); MITK_WARN << "Encountered node that is not part of a directed graph structure. Will be added to DataStorage " "without parents."; error = true; } return !error; } mitk::DataNode::Pointer mitk::SceneReaderV1::LoadBaseDataFromDataTag(const tinyxml2::XMLElement *dataElement, const PropertyList *properties, const std::string &workingDirectory, bool &error) { DataNode::Pointer node; if (dataElement) { const char *filename = dataElement->Attribute("file"); if (filename && strlen(filename) != 0) { try { auto baseData = IOUtil::Load(workingDirectory + Poco::Path::separator() + filename, properties); node = DataNode::New(); node->SetData(baseData); } catch (std::exception &e) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Exception says: " << e.what(); error = true; } if (node.IsNull()) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Factory returned nullptr object."; error = true; } } + else + { + MITK_ERROR << "File attribute of data tag is empty!"; + error = true; + } const char* dataUID = dataElement->Attribute("UID"); if (!error && dataUID != nullptr) { UIDManipulator manip(node->GetData()); manip.SetUID(dataUID); } } // in case there was no element we create a new empty node (for appending a propertylist later) if (node.IsNull()) { node = DataNode::New(); } return node; } void mitk::SceneReaderV1::ClearNodePropertyListWithExceptions(DataNode &node, PropertyList &propertyList) { // Basically call propertyList.Clear(), but implement exceptions (see bug 19354) BaseData *data = node.GetData(); PropertyList::Pointer propertiesToKeep = PropertyList::New(); if (dynamic_cast(data)) { /* Older scene files (before changes of bug 17547) could contain a RenderingMode property with value "LevelWindow_Color". Since bug 17547 this value has been removed and replaced by the default value LookupTable_LevelWindow_Color. This new default value does only result in "black-to-white" CT images (or others) if there is a corresponding lookup table. Such a lookup table is provided as a default value by the Image mapper. Since that value was never present in older scene files, we do well in not removing the new default value here. Otherwise the mapper would fall back to another default which is all the colors of the rainbow :-( */ BaseProperty::Pointer lutProperty = propertyList.GetProperty("LookupTable"); propertiesToKeep->SetProperty("LookupTable", lutProperty); /* Older scene files (before changes of T14807) may contain multi-component images without the "Image.Displayed Component" property. As the treatment as multi-component image and the corresponding visualization options hinges on that property we should not delete it, if it was added by the mapper. This is a fix for the issue reported in T19919. */ BaseProperty::Pointer compProperty = propertyList.GetProperty("Image.Displayed Component"); if (compProperty.IsNotNull()) { propertiesToKeep->SetProperty("Image.Displayed Component", compProperty); } } propertyList.Clear(); propertyList.ConcatenatePropertyList(propertiesToKeep); } bool mitk::SceneReaderV1::DecorateNodeWithProperties(DataNode *node, const tinyxml2::XMLElement *nodeElement, const std::string &workingDirectory) { assert(node); assert(nodeElement); bool error(false); for (auto *properties = nodeElement->FirstChildElement("properties"); properties != nullptr; properties = properties->NextSiblingElement("properties")) { const char *propertiesfilea(properties->Attribute("file")); std::string propertiesfile(propertiesfilea ? propertiesfilea : ""); const char *renderwindowa(properties->Attribute("renderwindow")); std::string renderwindow(renderwindowa ? renderwindowa : ""); PropertyList::Pointer propertyList = node->GetPropertyList(renderwindow); // DataNode implementation always returns a propertylist ClearNodePropertyListWithExceptions(*node, *propertyList); // use deserializer to construct new properties PropertyListDeserializer::Pointer deserializer = PropertyListDeserializer::New(); deserializer->SetFilename(workingDirectory + Poco::Path::separator() + propertiesfile); bool success = deserializer->Deserialize(); error |= !success; PropertyList::Pointer readProperties = deserializer->GetOutput(); if (readProperties.IsNotNull()) { propertyList->ConcatenatePropertyList(readProperties, true); // true = replace } else { MITK_ERROR << "Property list reader did not return a property list. This is an implementation error. Please tell " "your developer."; error = true; } } return !error; } diff --git a/Modules/Segmentation/Controllers/mitkToolManagerProvider.cpp b/Modules/Segmentation/Controllers/mitkToolManagerProvider.cpp index 010291abfe..25eb76748b 100644 --- a/Modules/Segmentation/Controllers/mitkToolManagerProvider.cpp +++ b/Modules/Segmentation/Controllers/mitkToolManagerProvider.cpp @@ -1,68 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkToolManagerProvider.h" // micro service includes #include #include const char* const mitk::ToolManagerProvider::SEGMENTATION = ""; -const char* const mitk::ToolManagerProvider::MULTILABEL_SEGMENTATION = "org.mitk.views.multilabelsegmentation"; mitk::ToolManagerProvider::ToolManagerProvider() { m_ToolManagers[SEGMENTATION] = ToolManager::New(nullptr); } mitk::ToolManagerProvider::~ToolManagerProvider() { } mitk::ToolManager *mitk::ToolManagerProvider::GetToolManager(const std::string& context) { if (m_ToolManagers.end() == m_ToolManagers.find(context)) m_ToolManagers[context] = ToolManager::New(nullptr); return m_ToolManagers[context].GetPointer(); } mitk::ToolManagerProvider::ProviderMapType mitk::ToolManagerProvider::GetToolManagers() const { return m_ToolManagers; } mitk::ToolManagerProvider *mitk::ToolManagerProvider::GetInstance() { static us::ServiceReference serviceRef; static us::ModuleContext *context = us::GetModuleContext(); if (!serviceRef) { // This is either the first time GetInstance() was called, // or a SingletonOneService instance has not yet been registered. serviceRef = context->GetServiceReference(); } if (serviceRef) { // We have a valid service reference. It always points to the service // with the lowest id (usually the one which was registered first). // This still might return a null pointer, if all SingletonOneService // instances have been unregistered (during unloading of the library, // for example). return context->GetService(serviceRef); } else { // No SingletonOneService instance was registered yet. return nullptr; } } diff --git a/Modules/Segmentation/Controllers/mitkToolManagerProvider.h b/Modules/Segmentation/Controllers/mitkToolManagerProvider.h index 6dee83ab87..f04f993cf9 100644 --- a/Modules/Segmentation/Controllers/mitkToolManagerProvider.h +++ b/Modules/Segmentation/Controllers/mitkToolManagerProvider.h @@ -1,92 +1,91 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_TOOLMANAGERPROVIDER_H #define MITK_TOOLMANAGERPROVIDER_H #include #include #include #include "mitkToolManager.h" #include #include #include #include namespace mitk { class SegmentationModuleActivator; /** \brief Micro Service Singleton to get an instance of mitk::ToolManager \sa ToolManager Implemented as a registry to have implicitly only one instance of ToolManager per context. Context is nothing more than a unique string, for example, use your plugin's id as context. Use this service to make sure your Tools are managed by the object. \note Can only be instantiated by SegmentationModuleActivator. The common way to get the ToolManager is by mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager("my context"); */ class MITKSEGMENTATION_EXPORT ToolManagerProvider : public itk::LightObject { public: mitkClassMacroItkParent(ToolManagerProvider, itk::LightObject); using ProviderMapType = std::map; // Known ToolManager contexts static const char* const SEGMENTATION; - static const char* const MULTILABEL_SEGMENTATION; /** \brief Returns ToolManager object. \param context A unique, non-empty string to retrieve a certain ToolManager instance. For backwards-compatibility, the overload without arguments is returning the classic segmentation ToolManager instance. If a ToolManager instance does not yet exist for a given context, it is created on the fly. */ virtual mitk::ToolManager *GetToolManager(const std::string& context = SEGMENTATION); /** \brief Returns all registered ToolManager objects. */ ProviderMapType GetToolManagers() const; /** \brief Returns an instance of ToolManagerProvider service. */ static mitk::ToolManagerProvider *GetInstance(); // ONLY SegmentationModuleActivator is able to create instances of the service. friend class mitk::SegmentationModuleActivator; protected: itkFactorylessNewMacro(Self); itkCloneMacro(Self); // hide everything ToolManagerProvider(); ~ToolManagerProvider() override; ToolManagerProvider(const ToolManagerProvider &); ToolManagerProvider &operator=(const ToolManagerProvider &); ProviderMapType m_ToolManagers; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::ToolManagerProvider, "org.mitk.services.ToolManagerProvider") #endif diff --git a/Modules/Segmentation/Interactions/mitkEditableContourTool.cpp b/Modules/Segmentation/Interactions/mitkEditableContourTool.cpp index 81db18aa4a..bb384c2487 100644 --- a/Modules/Segmentation/Interactions/mitkEditableContourTool.cpp +++ b/Modules/Segmentation/Interactions/mitkEditableContourTool.cpp @@ -1,459 +1,459 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkEditableContourTool.h" #include mitk::EditableContourTool::EditableContourTool() : FeedbackContourTool("EditableContourTool"), m_AutoConfirm(true), m_AddMode(true) {} mitk::EditableContourTool::~EditableContourTool() { this->ReleaseHelperObjects(); this->ReleaseInteractors(); } void mitk::EditableContourTool::ConnectActionsAndFunctions() { CONNECT_FUNCTION("InitObject", OnInitContour); CONNECT_FUNCTION("AddPoint", OnAddPoint); CONNECT_FUNCTION("CtrlAddPoint", OnAddPoint); CONNECT_FUNCTION("Drawing", OnDrawing); CONNECT_FUNCTION("EndDrawing", OnEndDrawing); CONNECT_FUNCTION("FinishContour", OnFinish); CONNECT_FUNCTION("CtrlMovePoint", OnMouseMoved); } void mitk::EditableContourTool::Activated() { Superclass::Activated(); this->ResetToStartState(); this->EnableContourInteraction(true); } void mitk::EditableContourTool::Deactivated() { - this->ClearSegmentation(); + this->ClearContour(); Superclass::Deactivated(); } void mitk::EditableContourTool::ConfirmSegmentation(bool resetStatMachine) { auto referenceImage = this->GetReferenceData(); auto workingImage = this->GetWorkingData(); if (nullptr != referenceImage && nullptr != workingImage) { std::vector sliceInfos; const auto currentTimePoint = mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint(); TimeStepType workingImageTimeStep = workingImage->GetTimeGeometry()->TimePointToTimeStep(currentTimePoint); auto contour = this->GetContour(); if (nullptr == contour || contour->IsEmpty()) return; auto workingSlice = this->GetAffectedImageSliceAs2DImage(m_PlaneGeometry, workingImage, workingImageTimeStep)->Clone(); sliceInfos.emplace_back(workingSlice, m_PlaneGeometry, workingImageTimeStep); auto projectedContour = ContourModelUtils::ProjectContourTo2DSlice(workingSlice, contour); int activePixelValue = ContourModelUtils::GetActivePixelValue(workingImage); if (!m_AddMode) { activePixelValue = 0; } ContourModelUtils::FillContourInSlice(projectedContour, workingSlice, workingImage, activePixelValue); this->WriteBackSegmentationResults(sliceInfos); } this->ReleaseHelperObjects(); this->ReleaseInteractors(); if (resetStatMachine) this->ResetToStartState(); } -void mitk::EditableContourTool::ClearSegmentation() +void mitk::EditableContourTool::ClearContour() { this->ReleaseHelperObjects(); this->ReleaseInteractors(); this->ResetToStartState(); } bool mitk::EditableContourTool::IsEditingContour() const { return (nullptr != GetContour()) && !this->IsDrawingContour(); }; bool mitk::EditableContourTool::IsDrawingContour() const { return m_PreviewContour.IsNotNull(); }; mitk::Point3D mitk::EditableContourTool::PrepareInitContour(const Point3D& clickedPoint) { //default implementation does nothing return clickedPoint; } void mitk::EditableContourTool::OnInitContour(StateMachineAction *, InteractionEvent *interactionEvent) { auto positionEvent = dynamic_cast(interactionEvent); if (nullptr == positionEvent) return; auto workingDataNode = this->GetWorkingDataNode(); if (nullptr != this->GetContour()) { this->ConfirmSegmentation(false); } if (!IsPositionEventInsideImageRegion(positionEvent, workingDataNode->GetData())) { this->ResetToStartState(); return; } m_LastEventSender = positionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); auto contour = this->CreateNewContour(); m_ContourNode = mitk::DataNode::New(); m_ContourNode->SetData(contour); m_ContourNode->SetName("working contour node"); m_ContourNode->SetProperty("layer", IntProperty::New(100)); m_ContourNode->AddProperty("fixedLayer", BoolProperty::New(true)); m_ContourNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_ContourNode->AddProperty("contour.color", ColorProperty::New(1.0f, 1.0f, 0.0f), nullptr, true); m_ContourNode->AddProperty("contour.points.color", ColorProperty::New(1.0f, 0.0f, 0.1f), nullptr, true); m_ContourNode->AddProperty("contour.controlpoints.show", BoolProperty::New(true), nullptr, true); m_PreviewContour = this->CreateNewContour(); m_PreviewContourNode = mitk::DataNode::New(); m_PreviewContourNode->SetData(m_PreviewContour); m_PreviewContourNode->SetName("active preview node"); m_PreviewContourNode->SetProperty("layer", IntProperty::New(101)); m_PreviewContourNode->AddProperty("fixedLayer", BoolProperty::New(true)); m_PreviewContourNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PreviewContourNode->AddProperty("contour.color", ColorProperty::New(0.1f, 1.0f, 0.1f), nullptr, true); m_PreviewContourNode->AddProperty("contour.width", mitk::FloatProperty::New(4.0f), nullptr, true); m_ClosureContour = this->CreateNewContour(); m_ClosureContourNode = mitk::DataNode::New(); m_ClosureContourNode->SetData(m_ClosureContour); m_ClosureContourNode->SetName("active closure node"); m_ClosureContourNode->SetProperty("layer", IntProperty::New(101)); m_ClosureContourNode->AddProperty("fixedLayer", BoolProperty::New(true)); m_ClosureContourNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_ClosureContourNode->AddProperty("contour.color", ColorProperty::New(0.0f, 1.0f, 0.1f), nullptr, true); m_ClosureContourNode->AddProperty("contour.width", mitk::FloatProperty::New(2.0f), nullptr, true); m_CurrentRestrictedArea = this->CreateNewContour(); auto dataStorage = this->GetToolManager()->GetDataStorage(); dataStorage->Add(m_ContourNode, workingDataNode); dataStorage->Add(m_PreviewContourNode, workingDataNode); dataStorage->Add(m_ClosureContourNode, workingDataNode); m_ReferenceDataSlice = this->GetAffectedReferenceSlice(positionEvent); auto origin = m_ReferenceDataSlice->GetSlicedGeometry()->GetOrigin(); m_ReferenceDataSlice->GetSlicedGeometry()->WorldToIndex(origin, origin); m_ReferenceDataSlice->GetSlicedGeometry()->IndexToWorld(origin, origin); m_ReferenceDataSlice->GetSlicedGeometry()->SetOrigin(origin); // Remember PlaneGeometry to determine if events were triggered in the same plane m_PlaneGeometry = interactionEvent->GetSender()->GetCurrentWorldPlaneGeometry(); // Map click to pixel coordinates auto click = positionEvent->GetPositionInWorld(); click = this->PrepareInitContour(click); this->InitializePreviewContour(click); // Set initial start point contour->AddVertex(click, true); m_PreviewContour->AddVertex(click, false); m_ClosureContour->AddVertex(click); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::EditableContourTool::FinalizePreviewContour(const Point3D& /*clickedPoint*/) { // Remove duplicate first vertex, it's already contained in m_ContourNode m_PreviewContour->RemoveVertexAt(0); m_PreviewContour->SetControlVertexAt(m_PreviewContour->GetNumberOfVertices() - 1); } void mitk::EditableContourTool::InitializePreviewContour(const Point3D& clickedPoint) { //default implementation only clears the preview and sets the start point m_PreviewContour = this->CreateNewContour(); m_PreviewContour->AddVertex(clickedPoint); m_PreviewContourNode->SetData(m_PreviewContour); } void mitk::EditableContourTool::UpdatePreviewContour(const Point3D& clickedPoint) { //default implementation draws just a simple line to position if (m_PreviewContour->GetNumberOfVertices() > 2) { auto contour = this->GetContour(); this->InitializePreviewContour(contour->GetVertexAt(contour->GetNumberOfVertices() - 1)->Coordinates); } if (m_PreviewContour->GetNumberOfVertices() == 2) { m_PreviewContour->RemoveVertexAt(m_PreviewContour->GetNumberOfVertices()-1); } m_PreviewContour->AddVertex(clickedPoint); } void mitk::EditableContourTool::OnAddPoint(StateMachineAction*, InteractionEvent* interactionEvent) { auto positionEvent = dynamic_cast(interactionEvent); if (nullptr == positionEvent) return; if (m_PlaneGeometry.IsNotNull()) { // Check if the point is in the correct slice if (m_PlaneGeometry->DistanceFromPlane(positionEvent->GetPositionInWorld()) > mitk::sqrteps) return; } this->FinalizePreviewContour(positionEvent->GetPositionInWorld()); // Merge contours auto contour = this->GetContour(); contour->Concatenate(m_PreviewContour); this->InitializePreviewContour(positionEvent->GetPositionInWorld()); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::EditableContourTool::OnDrawing(StateMachineAction*, InteractionEvent* interactionEvent) { auto* positionEvent = dynamic_cast(interactionEvent); if (!positionEvent) return; m_PreviewContourNode->SetVisibility(false); auto contour = this->GetContour(); contour->AddVertex(positionEvent->GetPositionInWorld(), false); UpdateClosureContour(positionEvent->GetPositionInWorld()); assert(positionEvent->GetSender()->GetRenderWindow()); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::EditableContourTool::OnEndDrawing(StateMachineAction*, InteractionEvent* interactionEvent) { auto* positionEvent = dynamic_cast(interactionEvent); if (!positionEvent) return; auto contour = this->GetContour(); auto controlVs = contour->GetControlVertices(0); if (!controlVs.empty()) { //add the last control point (after that the draw part start) m_CurrentRestrictedArea->AddVertex(controlVs.back()->Coordinates); } m_PreviewContourNode->SetVisibility(true); contour->SetControlVertexAt(contour->GetNumberOfVertices() - 1); //add the just created/set last control point (with it the draw part ends) m_CurrentRestrictedArea->AddVertex(contour->GetVertexAt(contour->GetNumberOfVertices() - 1)->Coordinates); this->InitializePreviewContour(positionEvent->GetPositionInWorld()); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::EditableContourTool::OnMouseMoved(StateMachineAction*, InteractionEvent* interactionEvent) { auto positionEvent = dynamic_cast(interactionEvent); if (nullptr == positionEvent) return; if (m_PlaneGeometry.IsNotNull()) { // Check if the point is in the correct slice if (m_PlaneGeometry->DistanceFromPlane(positionEvent->GetPositionInWorld()) > mitk::sqrteps) return; } this->UpdatePreviewContour(positionEvent->GetPositionInWorld()); this->UpdateClosureContour(positionEvent->GetPositionInWorld()); RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::EditableContourTool::OnFinish(StateMachineAction *, InteractionEvent *interactionEvent) { auto positionEvent = dynamic_cast(interactionEvent); if (nullptr == positionEvent) return; if (m_PlaneGeometry.IsNotNull()) { // Check if the point is in the correct slice if (m_PlaneGeometry->DistanceFromPlane(positionEvent->GetPositionInWorld()) > mitk::sqrteps) return; } this->FinalizePreviewContour(positionEvent->GetPositionInWorld()); this->FinishTool(); // Merge contours auto contour = this->GetContour(); contour->Concatenate(m_PreviewContour); auto numberOfTimesteps = static_cast(contour->GetTimeSteps()); for (int i = 0; i <= numberOfTimesteps; ++i) contour->Close(i); this->ReleaseHelperObjects(false); if (m_AutoConfirm) { this->ConfirmSegmentation(); } } void mitk::EditableContourTool::ReleaseHelperObjects(bool includeWorkingContour) { this->RemoveHelperObjectsFromDataStorage(includeWorkingContour); if (includeWorkingContour) { m_ContourNode = nullptr; m_CurrentRestrictedArea = nullptr; } m_PreviewContourNode = nullptr; m_PreviewContour = nullptr; m_ClosureContourNode = nullptr; m_ClosureContour = nullptr; } void mitk::EditableContourTool::RemoveHelperObjectsFromDataStorage(bool includeWorkingContour) { auto dataStorage = this->GetToolManager()->GetDataStorage(); if (nullptr == dataStorage) return; if (includeWorkingContour) { if (m_ContourNode.IsNotNull()) dataStorage->Remove(m_ContourNode); } if (m_PreviewContourNode.IsNotNull()) dataStorage->Remove(m_PreviewContourNode); if (m_ClosureContourNode.IsNotNull()) dataStorage->Remove(m_ClosureContourNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } mitk::ContourModel::Pointer mitk::EditableContourTool::CreateNewContour() const { auto workingData = this->GetWorkingData(); if (nullptr == workingData) { this->InteractiveSegmentationBugMessage( "Cannot create new contour. No valid working data is set. Application is in invalid state."); mitkThrow() << "Cannot create new contour. No valid working data is set. Application is in invalid state."; } auto contour = ContourModel::New(); // generate a time geometry that is always visible as the working contour should always be. auto contourTimeGeometry = ProportionalTimeGeometry::New(); contourTimeGeometry->SetStepDuration(std::numeric_limits::max()); contourTimeGeometry->SetTimeStepGeometry(contour->GetTimeGeometry()->GetGeometryForTimeStep(0)->Clone(), 0); contour->SetTimeGeometry(contourTimeGeometry); return contour; } void mitk::EditableContourTool::UpdateClosureContour(mitk::Point3D endpoint) { if (m_ClosureContour->GetNumberOfVertices() > 2) { m_ClosureContour = this->CreateNewContour(); m_ClosureContourNode->SetData(m_ClosureContour); } if (m_ClosureContour->GetNumberOfVertices() == 0) { auto contour = this->GetContour(); m_ClosureContour->AddVertex(contour->GetVertexAt(0)->Coordinates); m_ClosureContour->Update(); } if (m_ClosureContour->GetNumberOfVertices() == 2) { m_ClosureContour->RemoveVertexAt(0); } m_ClosureContour->AddVertexAtFront(endpoint); } void mitk::EditableContourTool::EnableContourInteraction(bool on) { if (m_ContourInteractor.IsNotNull()) { m_ContourInteractor->EnableInteraction(on); } } void mitk::EditableContourTool::ReleaseInteractors() { this->EnableContourInteraction(false); m_ContourInteractor = nullptr; } mitk::ContourModel* mitk::EditableContourTool::GetContour() { if (this->m_ContourNode.IsNotNull()) { return dynamic_cast(this->m_ContourNode->GetData()); } return nullptr; }; const mitk::ContourModel* mitk::EditableContourTool::GetContour() const { if (this->m_ContourNode.IsNotNull()) { return dynamic_cast(this->m_ContourNode->GetData()); } return nullptr; }; \ No newline at end of file diff --git a/Modules/Segmentation/Interactions/mitkEditableContourTool.h b/Modules/Segmentation/Interactions/mitkEditableContourTool.h index 1189e3b406..2ac29f4219 100644 --- a/Modules/Segmentation/Interactions/mitkEditableContourTool.h +++ b/Modules/Segmentation/Interactions/mitkEditableContourTool.h @@ -1,125 +1,125 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkEditbaleContourTool_h_Included #define mitkEditbaleContourTool_h_Included #include namespace mitk { /** * Base class for lasso like tools that allow to draw closed contours with multiple ancor points. * The segments between the ancor points may be freehand contour segments or computed segments * (e.g. straight lines or live wire). Derive from the class to implement the computation of the non-freehand * segments. * @sa LassoTool LivewWireTool2D */ class MITKSEGMENTATION_EXPORT EditableContourTool : public FeedbackContourTool { public: mitkClassMacro(EditableContourTool, FeedbackContourTool); /// \brief Convert current contour to binary segmentations. virtual void ConfirmSegmentation(bool resetStatMachine = true); /// \brief Delete all current contours. - virtual void ClearSegmentation(); + virtual void ClearContour(); itkBooleanMacro(AutoConfirm); itkSetMacro(AutoConfirm, bool); itkGetMacro(AutoConfirm, bool); itkBooleanMacro(AddMode); itkSetMacro(AddMode, bool); itkGetMacro(AddMode, bool); - /* Indicated if a contour is drawn, but not confirmed yet. This the tool is in interactor mode + /* Indicated if a contour is drawn, but not confirmed yet. This tool is in interactor mode to allow users to edit the contour. This state can be reached if AutoConfirm is false, after the finalizing double click before the contour is confirmed.*/ bool IsEditingContour() const; /* Indicate if a contour is currently drawn by the user (state between the initializing double click and the finalizing double click).*/ bool IsDrawingContour() const; protected: EditableContourTool(); ~EditableContourTool() override; void ConnectActionsAndFunctions() override; void Activated() override; void Deactivated() override; virtual Point3D PrepareInitContour(const Point3D& clickedPoint); virtual void FinalizePreviewContour(const Point3D& clickedPoint); virtual void InitializePreviewContour(const Point3D& clickedPoint); virtual void UpdatePreviewContour(const Point3D& clickedPoint); /// \brief Initialize tool. virtual void OnInitContour(StateMachineAction *, InteractionEvent *interactionEvent); /// \brief Add a control point and finish current segment. virtual void OnAddPoint(StateMachineAction *, InteractionEvent *interactionEvent); /// \brief Draw a contour according to the mouse movement when mouse button is pressed and mouse is moved. virtual void OnDrawing(StateMachineAction *, InteractionEvent *interactionEvent); virtual void OnEndDrawing(StateMachineAction *, InteractionEvent *interactionEvent); /// \brief Computation of the preview contour. virtual void OnMouseMoved(StateMachineAction *, InteractionEvent *interactionEvent); /// \brief Finish EditableContour tool. virtual void OnFinish(StateMachineAction *, InteractionEvent *interactionEvent); /// \brief Finish contour interaction. virtual void FinishTool() = 0; void EnableContourInteraction(bool on); void ReleaseInteractors(); virtual void ReleaseHelperObjects(bool includeWorkingContour = true); virtual void RemoveHelperObjectsFromDataStorage(bool includeWorkingContour = true); ContourModel::Pointer CreateNewContour() const; virtual void UpdateClosureContour(mitk::Point3D endpoint); mitk::ContourModel* GetContour(); const mitk::ContourModel* GetContour() const; mitk::DataNode::Pointer m_ContourNode; mitk::ContourModel::Pointer m_PreviewContour; mitk::DataNode::Pointer m_PreviewContourNode; mitk::ContourModel::Pointer m_ClosureContour; mitk::DataNode::Pointer m_ClosureContourNode; mitk::ContourModel::Pointer m_CurrentRestrictedArea; /** Slice of the reference data the tool is currently actively working on to define contours.*/ mitk::Image::Pointer m_ReferenceDataSlice; PlaneGeometry::ConstPointer m_PlaneGeometry; mitk::DataInteractor::Pointer m_ContourInteractor; bool m_AutoConfirm; bool m_AddMode; }; } #endif diff --git a/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp b/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp index f57cc037be..352d148533 100644 --- a/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp +++ b/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp @@ -1,59 +1,58 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkErasePaintbrushTool.h" #include "mitkErasePaintbrushTool.xpm" // us #include #include #include #include namespace mitk { MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, ErasePaintbrushTool, "Paintbrush erasing tool"); } -mitk::ErasePaintbrushTool::ErasePaintbrushTool() : PaintbrushTool(0) +mitk::ErasePaintbrushTool::ErasePaintbrushTool() : PaintbrushTool(false) { - FeedbackContourTool::SetFeedbackContourColor(1.0, 0.0, 0.0); } mitk::ErasePaintbrushTool::~ErasePaintbrushTool() { } const char **mitk::ErasePaintbrushTool::GetXPM() const { return mitkErasePaintbrushTool_xpm; } us::ModuleResource mitk::ErasePaintbrushTool::GetIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Wipe.svg"); return resource; } us::ModuleResource mitk::ErasePaintbrushTool::GetCursorIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Wipe_Cursor.svg"); return resource; } const char *mitk::ErasePaintbrushTool::GetName() const { return "Wipe"; } diff --git a/Modules/Segmentation/Interactions/mitkFillRegionBaseTool.cpp b/Modules/Segmentation/Interactions/mitkFillRegionBaseTool.cpp index 403b705cd7..600bb49236 100644 --- a/Modules/Segmentation/Interactions/mitkFillRegionBaseTool.cpp +++ b/Modules/Segmentation/Interactions/mitkFillRegionBaseTool.cpp @@ -1,149 +1,149 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkFillRegionBaseTool.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkDataStorage.h" #include "mitkITKImageImport.h" #include "mitkImageAccessByItk.h" #include "mitkRenderingManager.h" #include mitk::FillRegionBaseTool::FillRegionBaseTool() : SegTool2D("MouseReleaseOnly") { } mitk::FillRegionBaseTool::~FillRegionBaseTool() { } void mitk::FillRegionBaseTool::ConnectActionsAndFunctions() { CONNECT_FUNCTION("Release", OnClick); } template void DoITKRegionGrowing(const itk::Image* oldSegImage, mitk::Image::Pointer& filledRegionImage, itk::Index seedIndex, mitk::Label::PixelType& seedLabel ) { typedef itk::Image InputImageType; typedef itk::Image OutputImageType; typedef itk::ConnectedThresholdImageFilter RegionGrowingFilterType; seedLabel = oldSegImage->GetPixel(seedIndex); typename OutputImageType::Pointer itkResultImage; filledRegionImage = nullptr; try { typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New(); regionGrower->SetInput(oldSegImage); regionGrower->SetReplaceValue(1); regionGrower->AddSeed(seedIndex); regionGrower->SetLower(seedLabel); regionGrower->SetUpper(seedLabel); regionGrower->Update(); itkResultImage = regionGrower->GetOutput(); } catch (const itk::ExceptionObject&) { return; // can't work } catch (...) { return; } mitk::CastToMitkImage(itkResultImage, filledRegionImage); } void mitk::FillRegionBaseTool::OnClick(StateMachineAction*, InteractionEvent* interactionEvent) { auto positionEvent = dynamic_cast(interactionEvent); if (nullptr == positionEvent) return; auto labelSetImage = dynamic_cast(this->GetWorkingData()); if (nullptr == labelSetImage) { return; } if (!IsPositionEventInsideImageRegion(positionEvent, labelSetImage)) { return; } m_LastEventSender = positionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); auto workingSlice = this->GetAffectedWorkingSlice(positionEvent); auto click = positionEvent->GetPositionInWorld(); m_SeedLabelValue = 0; auto fillImage = this->GenerateFillImage(workingSlice, click, m_SeedLabelValue); if (fillImage.IsNull()) { return; //nothing to fill; } auto label = labelSetImage->GetLabel(m_SeedLabelValue, labelSetImage->GetActiveLayer()); - if (label->GetLocked() && label->GetValue()!=labelSetImage->GetActiveLabel()->GetValue()) + if (label->GetLocked() && label->GetValue()!=labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer())->GetValue()) { ErrorMessage.Send("Label of selected region is locked. Tool operation has no effect."); return; } this->PrepareFilling(workingSlice, click); //as fill region tools should always allow to manipulate active label //(that is what the user expects/knows when using tools so far: //the active label can always be changed even if locked) //we realize that by cloning the relevant label set and changing the lock state //this fillLabelSet is used for the transfer. auto fillLabelSet = labelSetImage->GetActiveLabelSet()->Clone(); - auto activeLabelClone = fillLabelSet->GetLabel(labelSetImage->GetActiveLabel()->GetValue()); + auto activeLabelClone = fillLabelSet->GetLabel(labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer())->GetValue()); if (nullptr != activeLabelClone) { activeLabelClone->SetLocked(false); } TransferLabelContent(fillImage, workingSlice, fillLabelSet, 0, labelSetImage->GetExteriorLabel()->GetValue(), false, { {1, m_FillLabelValue} }, m_MergeStyle); this->WriteBackSegmentationResult(positionEvent, workingSlice); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } mitk::Image::Pointer mitk::FillRegionBaseTool::GenerateFillImage(const Image* workingSlice, Point3D seedPoint, mitk::Label::PixelType& seedLabelValue) const { itk::Index<2> seedIndex; workingSlice->GetGeometry()->WorldToIndex(seedPoint, seedIndex); Image::Pointer fillImage; AccessFixedDimensionByItk_n(workingSlice, DoITKRegionGrowing, 2, (fillImage, seedIndex, seedLabelValue)); return fillImage; } diff --git a/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp b/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp index bde58bce1a..296e8f613c 100644 --- a/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp +++ b/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp @@ -1,59 +1,59 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkFillRegionTool.h" // us #include #include #include #include namespace mitk { MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, FillRegionTool, "Fill tool"); } const char **mitk::FillRegionTool::GetXPM() const { return nullptr; } us::ModuleResource mitk::FillRegionTool::GetIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Fill.svg"); return resource; } us::ModuleResource mitk::FillRegionTool::GetCursorIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Fill_Cursor.svg"); return resource; } const char *mitk::FillRegionTool::GetName() const { return "Fill"; } void mitk::FillRegionTool::PrepareFilling(const Image* /*workingSlice*/, Point3D /*seedPoint*/) { auto labelSetImage = dynamic_cast(this->GetWorkingData()); if (nullptr == labelSetImage) mitkThrow() << "Invalid state of FillRegionTool. Working image is not of correct type."; - m_FillLabelValue = labelSetImage->GetActiveLabel()->GetValue(); + m_FillLabelValue = labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer())->GetValue(); m_MergeStyle = MultiLabelSegmentation::MergeStyle::Merge; }; diff --git a/Modules/Segmentation/Interactions/mitkGrowCutTool.cpp b/Modules/Segmentation/Interactions/mitkGrowCutTool.cpp index 005804c177..370f93641e 100644 --- a/Modules/Segmentation/Interactions/mitkGrowCutTool.cpp +++ b/Modules/Segmentation/Interactions/mitkGrowCutTool.cpp @@ -1,153 +1,147 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGrowCutTool.h" #include "mitkToolManager.h" #include "mitkImageCast.h" #include "mitkTool.h" #include #include #include "mitkGrowCutSegmentationFilter.h" // us #include #include #include #include // ITK #include namespace mitk { MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, GrowCutTool, "GrowCutTool"); } -mitk::GrowCutTool::GrowCutTool() : SegWithPreviewTool(false, "PressMoveReleaseAndPointSetting") +mitk::GrowCutTool::GrowCutTool() : SegWithPreviewTool(true, "PressMoveReleaseAndPointSetting") { this->ResetsToEmptyPreviewOn(); + this->UseSpecialPreviewColorOff(); } mitk::GrowCutTool::~GrowCutTool() {} bool mitk::GrowCutTool::CanHandle(const BaseData *referenceData, const BaseData *workingData) const { if (!Superclass::CanHandle(referenceData, workingData)) return false; auto *image = dynamic_cast(referenceData); if (image == nullptr) return false; return true; } const char **mitk::GrowCutTool::GetXPM() const { return nullptr; } const char *mitk::GrowCutTool::GetName() const { return "GrowCut"; } us::ModuleResource mitk::GrowCutTool::GetIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("GrowCut.svg"); return resource; } void mitk::GrowCutTool::Activated() { Superclass::Activated(); m_DistancePenalty = 0.0; } void mitk::GrowCutTool::Deactivated() { Superclass::Deactivated(); } -bool mitk::GrowCutTool::HasMoreThanTwoSeedLabel() +bool mitk::GrowCutTool::SeedImageIsValid() { if (nullptr == this->GetToolManager()->GetWorkingData(0)) { return false; } auto *workingDataLabelSetImage = dynamic_cast(this->GetToolManager()->GetWorkingData(0)->GetData()); if (nullptr == workingDataLabelSetImage) { return false; } - workingDataLabelSetImage->SetActiveLayer(0); - auto numberOfLabels = workingDataLabelSetImage->GetNumberOfLabels(); + auto numberOfLabels = workingDataLabelSetImage->GetNumberOfLabels(workingDataLabelSetImage->GetActiveLayer()); if (numberOfLabels >= 3) { return true; } return false; } void mitk::GrowCutTool::DoUpdatePreview(const Image *inputAtTimeStep, - const Image * /*oldSegAtTimeStep*/, + const Image * oldSegAtTimeStep, LabelSetImage *previewImage, TimeStepType timeStep) { if (nullptr != inputAtTimeStep && nullptr != previewImage) { mitk::GrowCutSegmentationFilter::Pointer growCutFilter = mitk::GrowCutSegmentationFilter::New(); if (nullptr == this->GetToolManager()->GetWorkingData(0)) { return; } - auto *workingDataLabelSetImage = dynamic_cast(this->GetToolManager()->GetWorkingData(0)->GetData()); - - if (nullptr == workingDataLabelSetImage) - { - return; - } - SeedImageType::Pointer seedImage = SeedImageType::New(); - workingDataLabelSetImage->SetActiveLayer(0); - CastToItkImage(workingDataLabelSetImage, seedImage); + CastToItkImage(oldSegAtTimeStep, seedImage); growCutFilter->SetSeedImage(seedImage); growCutFilter->SetDistancePenalty(m_DistancePenalty); growCutFilter->SetInput(inputAtTimeStep); + growCutFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand); try { growCutFilter->Update(); } catch (...) { mitkThrow() << "itkGrowCutFilter error"; } auto growCutResultImage = mitk::LabelSetImage::New(); growCutResultImage->InitializeByLabeledImage(growCutFilter->GetOutput()); + TransferLabelSetImageContent(growCutResultImage, previewImage, timeStep); } } diff --git a/Modules/Segmentation/Interactions/mitkGrowCutTool.h b/Modules/Segmentation/Interactions/mitkGrowCutTool.h index 4860df13a2..691dd053e3 100644 --- a/Modules/Segmentation/Interactions/mitkGrowCutTool.h +++ b/Modules/Segmentation/Interactions/mitkGrowCutTool.h @@ -1,64 +1,64 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkGrowCutTool_h_Included #define mitkGrowCutTool_h_Included #include "mitkSegWithPreviewTool.h" #include namespace us { class ModuleResource; } namespace mitk { class MITKSEGMENTATION_EXPORT GrowCutTool : public SegWithPreviewTool { public: mitkClassMacro(GrowCutTool, SegWithPreviewTool); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkSetMacro(DistancePenalty, double); itkGetConstMacro(DistancePenalty, double); typedef itk::Image SeedImageType; typedef typename SeedImageType::IndexType IndexType; const char **GetXPM() const override; const char *GetName() const override; us::ModuleResource GetIconResource() const override; bool CanHandle(const BaseData *referenceData, const BaseData *workingData) const override; void Activated() override; void Deactivated() override; - bool HasMoreThanTwoSeedLabel(); + bool SeedImageIsValid(); protected: GrowCutTool(); // purposely hidden ~GrowCutTool() override; void DoUpdatePreview(const Image *inputAtTimeStep, const Image *oldSegAtTimeStep, LabelSetImage *previewImage, TimeStepType timeStep) override; double m_DistancePenalty = 0.0; }; } // namespace mitk #endif diff --git a/Modules/Segmentation/Interactions/mitkPaintbrushTool.cpp b/Modules/Segmentation/Interactions/mitkPaintbrushTool.cpp index 432abb62de..f8301be7f1 100644 --- a/Modules/Segmentation/Interactions/mitkPaintbrushTool.cpp +++ b/Modules/Segmentation/Interactions/mitkPaintbrushTool.cpp @@ -1,572 +1,612 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPaintbrushTool.h" #include "mitkAbstractTransformGeometry.h" #include "mitkBaseRenderer.h" #include "mitkToolManager.h" #include "mitkContourModelUtils.h" #include "mitkLevelWindowProperty.h" #include "mitkImageWriteAccessor.h" int mitk::PaintbrushTool::m_Size = 1; -mitk::PaintbrushTool::PaintbrushTool(int paintingPixelValue) +mitk::PaintbrushTool::PaintbrushTool(bool startWithFillMode) : FeedbackContourTool("PressMoveReleaseWithCTRLInversionAllMouseMoves"), - m_PaintingPixelValue(paintingPixelValue), + m_FillMode(startWithFillMode), m_LastContourSize(0) // other than initial mitk::PaintbrushTool::m_Size (around l. 28) { m_MasterContour = ContourModel::New(); m_MasterContour->Initialize(); m_CurrentPlane = nullptr; } mitk::PaintbrushTool::~PaintbrushTool() { } void mitk::PaintbrushTool::ConnectActionsAndFunctions() { CONNECT_FUNCTION("PrimaryButtonPressed", OnMousePressed); CONNECT_FUNCTION("Move", OnPrimaryButtonPressedMoved); CONNECT_FUNCTION("MouseMove", OnMouseMoved); CONNECT_FUNCTION("Release", OnMouseReleased); CONNECT_FUNCTION("InvertLogic", OnInvertLogic); } void mitk::PaintbrushTool::Activated() { Superclass::Activated(); - FeedbackContourTool::SetFeedbackContourVisible(true); SizeChanged.Send(m_Size); this->GetToolManager()->WorkingDataChanged += mitk::MessageDelegate(this, &mitk::PaintbrushTool::OnToolManagerWorkingDataModified); m_PaintingNode = DataNode::New(); m_PaintingNode->SetProperty("levelwindow", mitk::LevelWindowProperty::New(mitk::LevelWindow(0, m_InternalFillValue))); m_PaintingNode->SetProperty("binary", mitk::BoolProperty::New(true)); m_PaintingNode->SetProperty("outline binary", mitk::BoolProperty::New(true)); m_PaintingNode->SetProperty("name", mitk::StringProperty::New("Paintbrush_Node")); m_PaintingNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PaintingNode->SetProperty("opacity", mitk::FloatProperty::New(0.8)); m_PaintingNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); - m_PaintingNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); + auto allRenderWindows = BaseRenderer::GetAll3DRenderWindows(); + for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit) + { + m_PaintingNode->SetVisibility(false, mapit->second); + } + + this->UpdateFeedbackColor(); + FeedbackContourTool::SetFeedbackContourVisible(true); this->GetToolManager()->GetDataStorage()->Add(m_PaintingNode); } void mitk::PaintbrushTool::Deactivated() { FeedbackContourTool::SetFeedbackContourVisible(false); if (this->GetToolManager()->GetDataStorage()->Exists(m_PaintingNode)) this->GetToolManager()->GetDataStorage()->Remove(m_PaintingNode); m_WorkingSlice = nullptr; m_PaintingSlice = nullptr; m_CurrentPlane = nullptr; m_PaintingNode = nullptr; this->GetToolManager()->WorkingDataChanged -= mitk::MessageDelegate(this, &mitk::PaintbrushTool::OnToolManagerWorkingDataModified); Superclass::Deactivated(); } void mitk::PaintbrushTool::SetSize(int value) { m_Size = value; } mitk::Point2D mitk::PaintbrushTool::upperLeft(mitk::Point2D p) { p[0] -= 0.5; p[1] += 0.5; return p; } void mitk::PaintbrushTool::UpdateContour(const InteractionPositionEvent *positionEvent) { // MITK_INFO<<"Update..."; // examine stateEvent and create a contour that matches the pixel mask that we are going to draw // mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); // const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return; // Get Spacing of current Slice // mitk::Vector3D vSpacing = m_WorkingSlice->GetSlicedGeometry()->GetPlaneGeometry(0)->GetSpacing(); // // Draw a contour in Square according to selected brush size // int radius = (m_Size) / 2; float fradius = static_cast(m_Size) / 2.0f; ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New(); // estimate center point of the brush ( relative to the pixel the mouse points on ) // -- left upper corner for even sizes, // -- midpoint for uneven sizes mitk::Point2D centerCorrection; centerCorrection.Fill(0); // even --> correction of [+0.5, +0.5] bool evenSize = ((m_Size % 2) == 0); if (evenSize) { centerCorrection[0] += 0.5; centerCorrection[1] += 0.5; } // we will compute the control points for the upper left quarter part of a circle contour std::vector quarterCycleUpperRight; std::vector quarterCycleLowerRight; std::vector quarterCycleLowerLeft; std::vector quarterCycleUpperLeft; mitk::Point2D curPoint; bool curPointIsInside = true; curPoint[0] = 0; curPoint[1] = radius; quarterCycleUpperRight.push_back(upperLeft(curPoint)); // to estimate if a pixel is inside the circle, we need to compare against the 'outer radius' // i.e. the distance from the midpoint [0,0] to the border of the pixel [0,radius] // const float outer_radius = static_cast(radius) + 0.5; while (curPoint[1] > 0) { // Move right until pixel is outside circle float curPointX_squared = 0.0f; float curPointY_squared = (curPoint[1] - centerCorrection[1]) * (curPoint[1] - centerCorrection[1]); while (curPointIsInside) { // increment posX and chec curPoint[0]++; curPointX_squared = (curPoint[0] - centerCorrection[0]) * (curPoint[0] - centerCorrection[0]); const float len = sqrt(curPointX_squared + curPointY_squared); if (len > fradius) { // found first Pixel in this horizontal line, that is outside the circle curPointIsInside = false; } } quarterCycleUpperRight.push_back(upperLeft(curPoint)); // Move down until pixel is inside circle while (!curPointIsInside) { // increment posX and chec curPoint[1]--; curPointY_squared = (curPoint[1] - centerCorrection[1]) * (curPoint[1] - centerCorrection[1]); const float len = sqrt(curPointX_squared + curPointY_squared); if (len <= fradius) { // found first Pixel in this horizontal line, that is outside the circle curPointIsInside = true; quarterCycleUpperRight.push_back(upperLeft(curPoint)); } // Quarter cycle is full, when curPoint y position is 0 if (curPoint[1] <= 0) break; } } // QuarterCycle is full! Now copy quarter cycle to other quarters. if (!evenSize) { std::vector::const_iterator it = quarterCycleUpperRight.begin(); while (it != quarterCycleUpperRight.end()) { mitk::Point2D p; p = *it; // the contour points in the lower right corner have same position but with negative y values p[1] *= -1; quarterCycleLowerRight.push_back(p); // the contour points in the lower left corner have same position // but with both x,y negative p[0] *= -1; quarterCycleLowerLeft.push_back(p); // the contour points in the upper left corner have same position // but with x negative p[1] *= -1; quarterCycleUpperLeft.push_back(p); it++; } } else { std::vector::const_iterator it = quarterCycleUpperRight.begin(); while (it != quarterCycleUpperRight.end()) { mitk::Point2D p, q; p = *it; q = p; // the contour points in the lower right corner have same position but with negative y values q[1] *= -1; // correct for moved offset if size even = the midpoint is not the midpoint of the current pixel // but its upper rigt corner q[1] += 1; quarterCycleLowerRight.push_back(q); q = p; // the contour points in the lower left corner have same position // but with both x,y negative q[1] = -1.0f * q[1] + 1; q[0] = -1.0f * q[0] + 1; quarterCycleLowerLeft.push_back(q); // the contour points in the upper left corner have same position // but with x negative q = p; q[0] *= -1; q[0] += 1; quarterCycleUpperLeft.push_back(q); it++; } } // fill contour with poins in right ordering, starting with the upperRight block mitk::Point3D tempPoint; for (unsigned int i = 0; i < quarterCycleUpperRight.size(); i++) { tempPoint[0] = quarterCycleUpperRight[i][0]; tempPoint[1] = quarterCycleUpperRight[i][1]; tempPoint[2] = 0; contourInImageIndexCoordinates->AddVertex(tempPoint); } // the lower right has to be parsed in reverse order for (int i = quarterCycleLowerRight.size() - 1; i >= 0; i--) { tempPoint[0] = quarterCycleLowerRight[i][0]; tempPoint[1] = quarterCycleLowerRight[i][1]; tempPoint[2] = 0; contourInImageIndexCoordinates->AddVertex(tempPoint); } for (unsigned int i = 0; i < quarterCycleLowerLeft.size(); i++) { tempPoint[0] = quarterCycleLowerLeft[i][0]; tempPoint[1] = quarterCycleLowerLeft[i][1]; tempPoint[2] = 0; contourInImageIndexCoordinates->AddVertex(tempPoint); } // the upper left also has to be parsed in reverse order for (int i = quarterCycleUpperLeft.size() - 1; i >= 0; i--) { tempPoint[0] = quarterCycleUpperLeft[i][0]; tempPoint[1] = quarterCycleUpperLeft[i][1]; tempPoint[2] = 0; contourInImageIndexCoordinates->AddVertex(tempPoint); } m_MasterContour = contourInImageIndexCoordinates; } void mitk::PaintbrushTool::OnMousePressed(StateMachineAction *, InteractionEvent *interactionEvent) { if (m_WorkingSlice.IsNull()) return; - auto *positionEvent = dynamic_cast(interactionEvent); + auto* positionEvent = dynamic_cast(interactionEvent); if (!positionEvent) return; - m_WorkingSlice->GetGeometry()->WorldToIndex(positionEvent->GetPositionInWorld(), m_LastPosition); + this->ResetWorkingSlice(positionEvent); + m_WorkingSlice->GetGeometry()->WorldToIndex(positionEvent->GetPositionInWorld(), m_LastPosition); this->m_PaintingNode->SetVisibility(true); m_LastEventSender = positionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); - m_PaintingSlice = nullptr; //force reset of the painting slice. Will be triggered in MouseMoved() by - //CheckIfCurrentSliceHasChanged - m_MasterContour->SetClosed(true); this->MouseMoved(interactionEvent, true); } void mitk::PaintbrushTool::OnMouseMoved(StateMachineAction *, InteractionEvent *interactionEvent) { MouseMoved(interactionEvent, false); } void mitk::PaintbrushTool::OnPrimaryButtonPressedMoved(StateMachineAction *, InteractionEvent *interactionEvent) { MouseMoved(interactionEvent, true); } /** Insert the point to the feedback contour,finish to build the contour and at the same time the painting function */ void mitk::PaintbrushTool::MouseMoved(mitk::InteractionEvent *interactionEvent, bool leftMouseButtonPressed) { auto *positionEvent = dynamic_cast(interactionEvent); - CheckIfCurrentSliceHasChanged(positionEvent); + bool newSlice = CheckIfCurrentSliceHasChanged(positionEvent); + if (newSlice) + { + this->ResetWorkingSlice(positionEvent); + } if (m_LastContourSize != m_Size) { UpdateContour(positionEvent); m_LastContourSize = m_Size; } Point3D worldCoordinates = positionEvent->GetPositionInWorld(); Point3D indexCoordinates; m_WorkingSlice->GetGeometry()->WorldToIndex(worldCoordinates, indexCoordinates); // round to nearest voxel center (abort if this hasn't changed) if (m_Size % 2 == 0) // even { indexCoordinates[0] = std::round(indexCoordinates[0]); indexCoordinates[1] = std::round(indexCoordinates[1]); } else // odd { indexCoordinates[0] = std::round(indexCoordinates[0]); indexCoordinates[1] = std::round(indexCoordinates[1]); } static Point3D lastPos; // uninitialized: if somebody finds out how this can be initialized in a one-liner, tell me if (fabs(indexCoordinates[0] - lastPos[0]) > mitk::eps || fabs(indexCoordinates[1] - lastPos[1]) > mitk::eps || fabs(indexCoordinates[2] - lastPos[2]) > mitk::eps || leftMouseButtonPressed) { lastPos = indexCoordinates; } else { return; } auto contour = ContourModel::New(); contour->SetClosed(true); auto it = m_MasterContour->Begin(); auto end = m_MasterContour->End(); while (it != end) { auto point = (*it)->Coordinates; point[0] += indexCoordinates[0]; point[1] += indexCoordinates[1]; contour->AddVertex(point); ++it; } if (leftMouseButtonPressed) { ContourModelUtils::FillContourInSlice2(contour, m_PaintingSlice, m_InternalFillValue); const double dist = indexCoordinates.EuclideanDistanceTo(m_LastPosition); const double radius = static_cast(m_Size) / 2.0; // if points are >= radius away draw rectangle to fill empty holes // in between the 2 points if (dist > radius) { const mitk::Point3D ¤tPos = indexCoordinates; mitk::Point3D direction; mitk::Point3D vertex; mitk::Point3D normal; direction[0] = indexCoordinates[0] - m_LastPosition[0]; direction[1] = indexCoordinates[1] - m_LastPosition[1]; direction[2] = indexCoordinates[2] - m_LastPosition[2]; direction[0] = direction.GetVnlVector().normalize()[0]; direction[1] = direction.GetVnlVector().normalize()[1]; direction[2] = direction.GetVnlVector().normalize()[2]; // 90 degrees rotation of direction normal[0] = -1.0 * direction[1]; normal[1] = direction[0]; auto gapContour = ContourModel::New(); // upper left corner vertex[0] = m_LastPosition[0] + (normal[0] * radius); vertex[1] = m_LastPosition[1] + (normal[1] * radius); gapContour->AddVertex(vertex); // upper right corner vertex[0] = currentPos[0] + (normal[0] * radius); vertex[1] = currentPos[1] + (normal[1] * radius); gapContour->AddVertex(vertex); // lower right corner vertex[0] = currentPos[0] - (normal[0] * radius); vertex[1] = currentPos[1] - (normal[1] * radius); gapContour->AddVertex(vertex); // lower left corner vertex[0] = m_LastPosition[0] - (normal[0] * radius); vertex[1] = m_LastPosition[1] - (normal[1] * radius); gapContour->AddVertex(vertex); ContourModelUtils::FillContourInSlice2(gapContour, m_PaintingSlice, m_InternalFillValue); } } else { // switched from different renderwindow // no activate hover highlighting. Otherwise undo / redo wont work this->m_PaintingNode->SetVisibility(false); } m_LastPosition = indexCoordinates; // visualize contour ContourModel::Pointer tmp = FeedbackContourTool::BackProjectContourFrom2DSlice(m_WorkingSlice->GetGeometry(), contour); this->UpdateCurrentFeedbackContour(tmp); - assert(positionEvent->GetSender()->GetRenderWindow()); - RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); + if (newSlice) + { + RenderingManager::GetInstance()->RequestUpdateAll(); + } + else + { + assert(positionEvent->GetSender()->GetRenderWindow()); + RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); + } } void mitk::PaintbrushTool::OnMouseReleased(StateMachineAction *, InteractionEvent *interactionEvent) { // When mouse is released write segmentationresult back into image auto *positionEvent = dynamic_cast(interactionEvent); if (!positionEvent) return; DataNode* workingNode(this->GetToolManager()->GetWorkingData(0)); auto workingImage = dynamic_cast(workingNode->GetData()); - int activePixelValue = ContourModelUtils::GetActivePixelValue(workingImage); + Label::PixelType activePixelValue = ContourModelUtils::GetActivePixelValue(workingImage); + if (!m_FillMode) + { + activePixelValue = workingImage->GetExteriorLabel()->GetValue(); + } //as paintbrush tools should always allow to manipulate active label //(that is what the user expects/knows when using tools so far: //the active label can always be changed even if locked) //we realize that by cloning the relevant label set and changing the lock state //this fillLabelSet is used for the transfer. auto fillLabelSet = workingImage->GetActiveLabelSet()->Clone(); - auto activeLabelClone = fillLabelSet->GetLabel(workingImage->GetActiveLabel()->GetValue()); + auto activeLabelClone = fillLabelSet->GetLabel(workingImage->GetActiveLabel(workingImage->GetActiveLayer())->GetValue()); if (nullptr != activeLabelClone) { activeLabelClone->SetLocked(false); } - TransferLabelContent(m_PaintingSlice, m_WorkingSlice, fillLabelSet, 0, workingImage->GetExteriorLabel()->GetValue(), false, { {m_InternalFillValue, m_PaintingPixelValue * activePixelValue} }, mitk::MultiLabelSegmentation::MergeStyle::Merge); + TransferLabelContent(m_PaintingSlice, m_WorkingSlice, fillLabelSet, 0, workingImage->GetExteriorLabel()->GetValue(), false, { {m_InternalFillValue, activePixelValue} }, mitk::MultiLabelSegmentation::MergeStyle::Merge); this->WriteBackSegmentationResult(positionEvent, m_WorkingSlice->Clone()); // deactivate visibility of helper node m_PaintingNode->SetVisibility(false); + m_PaintingNode->SetData(nullptr); + m_PaintingSlice = nullptr; + m_WorkingSlice = nullptr; - RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); + RenderingManager::GetInstance()->RequestUpdateAll(); } -/** - Called when the CTRL key is pressed. Will change the painting pixel value from 0 to 1 or from 1 to 0. - */ -void mitk::PaintbrushTool::OnInvertLogic(StateMachineAction *, InteractionEvent *) +void mitk::PaintbrushTool::UpdateFeedbackColor() { - // Inversion only for 0 and 1 as painting values - if (m_PaintingPixelValue == 1) + mitk::Color currentColor; + if (m_FillMode) + { + FeedbackContourTool::SetFeedbackContourColorDefault(); + currentColor.Set(0.0, 1.0, 0.); + } + else { - m_PaintingPixelValue = 0; FeedbackContourTool::SetFeedbackContourColor(1.0, 0.0, 0.0); + currentColor.Set(1.0, 0.0, 0.); } - else if (m_PaintingPixelValue == 0) + + if (m_PaintingNode.IsNotNull()) { - m_PaintingPixelValue = 1; - FeedbackContourTool::SetFeedbackContourColorDefault(); + m_PaintingNode->SetProperty("color", mitk::ColorProperty::New(currentColor[0], currentColor[1], currentColor[2])); } +} + +/** + Called when the CTRL key is pressed. + */ +void mitk::PaintbrushTool::OnInvertLogic(StateMachineAction *, InteractionEvent *) +{ + m_FillMode = !m_FillMode; + UpdateFeedbackColor(); + mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } -void mitk::PaintbrushTool::CheckIfCurrentSliceHasChanged(const InteractionPositionEvent *event) +bool mitk::PaintbrushTool::CheckIfCurrentSliceHasChanged(const InteractionPositionEvent *event) { const PlaneGeometry* planeGeometry((event->GetSender()->GetCurrentWorldPlaneGeometry())); const auto* abstractTransformGeometry( dynamic_cast(event->GetSender()->GetCurrentWorldPlaneGeometry())); if (nullptr == planeGeometry || nullptr != abstractTransformGeometry) { - return; + return false; } - DataNode* workingNode = this->GetToolManager()->GetWorkingData(0); - if (nullptr == workingNode) - { - return; - } - - Image::Pointer image = dynamic_cast(workingNode->GetData()); - if (nullptr == image) - { - return; - } + bool newPlane = false; if (m_CurrentPlane.IsNull() || m_WorkingSlice.IsNull() //or not the same slice || !mitk::MatrixEqualElementWise(planeGeometry->GetIndexToWorldTransform()->GetMatrix(), m_CurrentPlane->GetIndexToWorldTransform()->GetMatrix()) || !mitk::Equal(planeGeometry->GetIndexToWorldTransform()->GetOffset(), m_CurrentPlane->GetIndexToWorldTransform()->GetOffset())) { m_CurrentPlane = planeGeometry; - m_WorkingSlice = SegTool2D::GetAffectedImageSliceAs2DImage(event, image)->Clone(); + newPlane = true; } - if (m_PaintingSlice.IsNull()) + return newPlane; +} + +void mitk::PaintbrushTool::ResetWorkingSlice(const InteractionPositionEvent* event) +{ + const PlaneGeometry* planeGeometry((event->GetSender()->GetCurrentWorldPlaneGeometry())); + const auto* abstractTransformGeometry( + dynamic_cast(event->GetSender()->GetCurrentWorldPlaneGeometry())); + if (nullptr == planeGeometry || nullptr != abstractTransformGeometry) { - m_PaintingSlice = Image::New(); - m_PaintingSlice->Initialize(m_WorkingSlice); + return; + } - unsigned int byteSize = m_PaintingSlice->GetPixelType().GetSize(); - for (unsigned int dim = 0; dim < m_PaintingSlice->GetDimension(); ++dim) - { - byteSize *= m_PaintingSlice->GetDimension(dim); - } - mitk::ImageWriteAccessor writeAccess(m_PaintingSlice.GetPointer(), m_PaintingSlice->GetVolumeData(0)); - memset(writeAccess.GetData(), 0, byteSize); + m_WorkingSlice = nullptr; + m_PaintingSlice = nullptr; + m_PaintingNode->SetData(nullptr); - m_PaintingNode->SetData(m_PaintingSlice); + DataNode* workingNode = this->GetToolManager()->GetWorkingData(0); + if (nullptr == workingNode) + { + return; } - mitk::Color currentColor; - if (m_PaintingPixelValue == 1) + Image::Pointer image = dynamic_cast(workingNode->GetData()); + if (nullptr == image) { - currentColor.Set(0.0, 1.0, 0.); + return; } - else + + m_WorkingSlice = SegTool2D::GetAffectedImageSliceAs2DImage(event, image)->Clone(); + + m_PaintingSlice = Image::New(); + m_PaintingSlice->Initialize(m_WorkingSlice); + + unsigned int byteSize = m_PaintingSlice->GetPixelType().GetSize(); + for (unsigned int dim = 0; dim < m_PaintingSlice->GetDimension(); ++dim) { - currentColor.Set(1.0, 0.0, 0.); + byteSize *= m_PaintingSlice->GetDimension(dim); } - m_PaintingNode->SetProperty("color", mitk::ColorProperty::New(currentColor[0], currentColor[1], currentColor[2])); + mitk::ImageWriteAccessor writeAccess(m_PaintingSlice.GetPointer(), m_PaintingSlice->GetVolumeData(0)); + memset(writeAccess.GetData(), 0, byteSize); + + m_PaintingNode->SetData(m_PaintingSlice); } void mitk::PaintbrushTool::OnToolManagerWorkingDataModified() { // Here we simply set the current working slice to null. The next time the mouse is moved // within a renderwindow a new slice will be extracted from the new working data m_WorkingSlice = nullptr; m_PaintingSlice = nullptr; } diff --git a/Modules/Segmentation/Interactions/mitkPaintbrushTool.h b/Modules/Segmentation/Interactions/mitkPaintbrushTool.h index 7b931405b9..519e3a1cea 100644 --- a/Modules/Segmentation/Interactions/mitkPaintbrushTool.h +++ b/Modules/Segmentation/Interactions/mitkPaintbrushTool.h @@ -1,106 +1,107 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPaintbrushTool_h_Included #define mitkPaintbrushTool_h_Included #include "mitkCommon.h" #include "mitkFeedbackContourTool.h" #include namespace mitk { class StateMachineAction; class InteractionEvent; class InteractionPositionEvent; /** \brief Paintbrush tool for InteractiveSegmentation \sa FeedbackContourTool \sa ExtractImageFilter \ingroup Interaction \ingroup ToolManagerEtAl Simple paintbrush drawing tool. Right now there are only circular pens of varying size. \warning Only to be instantiated by mitk::ToolManager. $Author: maleike $ */ class MITKSEGMENTATION_EXPORT PaintbrushTool : public FeedbackContourTool { public: // sent when the pen size is changed or should be updated in a GUI. Message1 SizeChanged; mitkClassMacro(PaintbrushTool, FeedbackContourTool); void SetSize(int value); protected: - PaintbrushTool(int paintingPixelValue = 1); // purposely hidden + PaintbrushTool(bool startWithFillMode = true); // purposely hidden ~PaintbrushTool() override; void ConnectActionsAndFunctions() override; void Activated() override; void Deactivated() override; virtual void OnMousePressed(StateMachineAction *, InteractionEvent *); virtual void OnMouseMoved(StateMachineAction *, InteractionEvent *); virtual void OnPrimaryButtonPressedMoved(StateMachineAction *, InteractionEvent *); virtual void MouseMoved(mitk::InteractionEvent *interactionEvent, bool leftMouseButtonPressed); virtual void OnMouseReleased(StateMachineAction *, InteractionEvent *); + void UpdateFeedbackColor(); virtual void OnInvertLogic(StateMachineAction *, InteractionEvent *); /** * \todo This is a possible place where to introduce * different types of pens */ void UpdateContour(const InteractionPositionEvent *); /** * Little helper function. Returns the upper left corner of the given pixel. */ mitk::Point2D upperLeft(mitk::Point2D p); /** - * Checks if the current slice has changed + * Checks if the current slice has changed and updates (if needed m_CurrentPlane). */ - void CheckIfCurrentSliceHasChanged(const InteractionPositionEvent *event); + bool CheckIfCurrentSliceHasChanged(const InteractionPositionEvent *event); - void OnToolManagerWorkingDataModified(); + void ResetWorkingSlice(const InteractionPositionEvent* event); - void ResetPaintingSlice(); + void OnToolManagerWorkingDataModified(); - int m_PaintingPixelValue; + bool m_FillMode; static int m_Size; ContourModel::Pointer m_MasterContour; int m_LastContourSize; const int m_InternalFillValue = 255; Image::Pointer m_WorkingSlice; Image::Pointer m_PaintingSlice; PlaneGeometry::ConstPointer m_CurrentPlane; DataNode::Pointer m_PaintingNode; mitk::Point3D m_LastPosition; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkProcessExecutor.cpp b/Modules/Segmentation/Interactions/mitkProcessExecutor.cpp index cd0aa04854..7f38dae959 100644 --- a/Modules/Segmentation/Interactions/mitkProcessExecutor.cpp +++ b/Modules/Segmentation/Interactions/mitkProcessExecutor.cpp @@ -1,161 +1,165 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkProcessExecutor.h" #include #include #include #include namespace mitk { std::string ProcessExecutor::GetOSDependendExecutableName(const std::string &name) { #if defined(_WIN32) if (itksys::SystemTools::GetFilenameLastExtension(name).empty()) { return name + ".exe"; } return name; #else auto result = itksys::SystemTools::GetFilenamePath(name); if (EnsureCorrectOSPathSeparator(result).empty()) { return "./" + name; } else { return name; } #endif } std::string ProcessExecutor::EnsureCorrectOSPathSeparator(const std::string &path) { std::string ret = path; #ifdef _WIN32 const std::string curSep = "\\"; const char wrongSep = '/'; #else const std::string curSep = "/"; const char wrongSep = '\\'; #endif std::string::size_type pos = ret.find_first_of(wrongSep); while (pos != std::string::npos) { ret.replace(pos, 1, curSep); pos = ret.find_first_of(wrongSep); } return ret; } int ProcessExecutor::GetExitValue() { return this->m_ExitValue; }; bool ProcessExecutor::Execute(const std::string &executionPath, const ArgumentListType &argumentList) { std::vector pArguments_(argumentList.size() + 1); for (ArgumentListType::size_type index = 0; index < argumentList.size(); ++index) { pArguments_[index] = argumentList[index].c_str(); } pArguments_.push_back(nullptr); //terminating null element as required by ITK bool normalExit = false; try { m_ProcessID = itksysProcess_New(); itksysProcess_SetCommand(m_ProcessID, pArguments_.data()); + + /* Place the process in a new process group for seamless interruption when required. */ + itksysProcess_SetOption(m_ProcessID, itksysProcess_Option_CreateProcessGroup, 1); itksysProcess_SetWorkingDirectory(m_ProcessID, executionPath.c_str()); if (this->m_SharedOutputPipes) { itksysProcess_SetPipeShared(m_ProcessID, itksysProcess_Pipe_STDOUT, 1); itksysProcess_SetPipeShared(m_ProcessID, itksysProcess_Pipe_STDERR, 1); } itksysProcess_Execute(m_ProcessID); char *rawOutput = nullptr; int outputLength = 0; while (true) { int dataStatus = itksysProcess_WaitForData(m_ProcessID, &rawOutput, &outputLength, nullptr); if (dataStatus == itksysProcess_Pipe_STDOUT) { std::string data(rawOutput, outputLength); this->InvokeEvent(ExternalProcessStdOutEvent(data)); } else if (dataStatus == itksysProcess_Pipe_STDERR) { std::string data(rawOutput, outputLength); this->InvokeEvent(ExternalProcessStdErrEvent(data)); } else { break; } } itksysProcess_WaitForExit(m_ProcessID, nullptr); auto state = static_cast(itksysProcess_GetState(m_ProcessID)); normalExit = (state == itksysProcess_State_Exited); this->m_ExitValue = itksysProcess_GetExitValue(m_ProcessID); } catch (...) { throw; } return normalExit; }; bool ProcessExecutor::Execute(const std::string &executionPath, const std::string &executableName, ArgumentListType &argumentList) { std::string executableName_OS = GetOSDependendExecutableName(executableName); argumentList.insert(argumentList.begin(), executableName_OS); return Execute(executionPath, argumentList); } void ProcessExecutor::KillProcess() { if (m_ProcessID != nullptr) { - itksysProcess_Kill(m_ProcessID); + itksysProcess_Interrupt(m_ProcessID); + itksysProcess_WaitForExit(m_ProcessID, nullptr); } } ProcessExecutor::ProcessExecutor() { this->m_ExitValue = 0; this->m_SharedOutputPipes = false; } ProcessExecutor::~ProcessExecutor() = default; } // namespace mitk diff --git a/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.cpp b/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.cpp index 0a5b9717bf..da01802ce3 100644 --- a/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.cpp +++ b/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.cpp @@ -1,732 +1,735 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkSegWithPreviewTool.h" #include "mitkToolManager.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkDataStorage.h" #include "mitkRenderingManager.h" #include "mitkImageAccessByItk.h" #include "mitkImageCast.h" #include "mitkLabelSetImage.h" #include "mitkMaskAndCutRoiImageFilter.h" #include "mitkPadImageFilter.h" #include "mitkNodePredicateGeometry.h" #include "mitkSegTool2D.h" mitk::SegWithPreviewTool::SegWithPreviewTool(bool lazyDynamicPreviews): Tool("dummy"), m_LazyDynamicPreviews(lazyDynamicPreviews) { m_ProgressCommand = ToolCommand::New(); } mitk::SegWithPreviewTool::SegWithPreviewTool(bool lazyDynamicPreviews, const char* interactorType, const us::Module* interactorModule) : Tool(interactorType, interactorModule), m_LazyDynamicPreviews(lazyDynamicPreviews) { m_ProgressCommand = ToolCommand::New(); } mitk::SegWithPreviewTool::~SegWithPreviewTool() { } void mitk::SegWithPreviewTool::SetMergeStyle(MultiLabelSegmentation::MergeStyle mergeStyle) { m_MergeStyle = mergeStyle; } void mitk::SegWithPreviewTool::SetOverwriteStyle(MultiLabelSegmentation::OverwriteStyle overwriteStyle) { m_OverwriteStyle = overwriteStyle; } void mitk::SegWithPreviewTool::SetLabelTransferMode(LabelTransferMode LabelTransferMode) { m_LabelTransferMode = LabelTransferMode; } void mitk::SegWithPreviewTool::SetSelectedLabels(const SelectedLabelVectorType& labelsToTransfer) { m_SelectedLabels = labelsToTransfer; } bool mitk::SegWithPreviewTool::CanHandle(const BaseData* referenceData, const BaseData* workingData) const { if (!Superclass::CanHandle(referenceData, workingData)) return false; if (workingData == nullptr) return true; auto* labelSet = dynamic_cast(workingData); if (labelSet != nullptr) return true; auto* image = dynamic_cast(workingData); if (image == nullptr) return false; //if it is a normal image and not a label set image is used as working data //it must have the same pixel type as a label set. return MakeScalarPixelType< DefaultSegmentationDataType >() == image->GetPixelType(); } void mitk::SegWithPreviewTool::Activated() { Superclass::Activated(); this->GetToolManager()->RoiDataChanged += MessageDelegate(this, &SegWithPreviewTool::OnRoiDataChanged); this->GetToolManager()->SelectedTimePointChanged += MessageDelegate(this, &SegWithPreviewTool::OnTimePointChanged); m_ReferenceDataNode = this->GetToolManager()->GetReferenceData(0); m_SegmentationInputNode = m_ReferenceDataNode; m_LastTimePointOfUpdate = RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint(); if (m_PreviewSegmentationNode.IsNull()) { m_PreviewSegmentationNode = DataNode::New(); m_PreviewSegmentationNode->SetProperty("color", ColorProperty::New(0.0, 1.0, 0.0)); m_PreviewSegmentationNode->SetProperty("name", StringProperty::New(std::string(this->GetName())+" preview")); m_PreviewSegmentationNode->SetProperty("opacity", FloatProperty::New(0.3)); m_PreviewSegmentationNode->SetProperty("binary", BoolProperty::New(true)); m_PreviewSegmentationNode->SetProperty("helper object", BoolProperty::New(true)); } if (m_SegmentationInputNode.IsNotNull()) { this->ResetPreviewNode(); this->InitiateToolByInput(); } else { this->GetToolManager()->ActivateTool(-1); } } void mitk::SegWithPreviewTool::Deactivated() { this->GetToolManager()->RoiDataChanged -= MessageDelegate(this, &SegWithPreviewTool::OnRoiDataChanged); this->GetToolManager()->SelectedTimePointChanged -= MessageDelegate(this, &SegWithPreviewTool::OnTimePointChanged); m_SegmentationInputNode = nullptr; m_ReferenceDataNode = nullptr; m_WorkingPlaneGeometry = nullptr; try { if (DataStorage *storage = this->GetToolManager()->GetDataStorage()) { storage->Remove(m_PreviewSegmentationNode); RenderingManager::GetInstance()->RequestUpdateAll(); } } catch (...) { // don't care } if (m_PreviewSegmentationNode.IsNotNull()) { m_PreviewSegmentationNode->SetData(nullptr); } Superclass::Deactivated(); } void mitk::SegWithPreviewTool::ConfirmSegmentation() { bool labelChanged = this->EnsureUpToDateUserDefinedActiveLabel(); if ((m_LazyDynamicPreviews && m_CreateAllTimeSteps) || labelChanged) { // The tool should create all time steps but is currently in lazy mode, // thus ensure that a preview for all time steps is available. this->UpdatePreview(true); } CreateResultSegmentationFromPreview(); RenderingManager::GetInstance()->RequestUpdateAll(); if (!m_KeepActiveAfterAccept) { this->GetToolManager()->ActivateTool(-1); } } void mitk::SegWithPreviewTool::InitiateToolByInput() { //default implementation does nothing. //implement in derived classes to change behavior } mitk::LabelSetImage* mitk::SegWithPreviewTool::GetPreviewSegmentation() { if (m_PreviewSegmentationNode.IsNull()) { return nullptr; } return dynamic_cast(m_PreviewSegmentationNode->GetData()); } const mitk::LabelSetImage* mitk::SegWithPreviewTool::GetPreviewSegmentation() const { if (m_PreviewSegmentationNode.IsNull()) { return nullptr; } return dynamic_cast(m_PreviewSegmentationNode->GetData()); } mitk::DataNode* mitk::SegWithPreviewTool::GetPreviewSegmentationNode() { return m_PreviewSegmentationNode; } const mitk::Image* mitk::SegWithPreviewTool::GetSegmentationInput() const { if (m_SegmentationInputNode.IsNull()) { return nullptr; } return dynamic_cast(m_SegmentationInputNode->GetData()); } const mitk::Image* mitk::SegWithPreviewTool::GetReferenceData() const { if (m_ReferenceDataNode.IsNull()) { return nullptr; } return dynamic_cast(m_ReferenceDataNode->GetData()); } template void ClearBufferProcessing(ImageType* itkImage) { itkImage->FillBuffer(0); } void mitk::SegWithPreviewTool::ResetPreviewContentAtTimeStep(unsigned int timeStep) { auto previewImage = GetImageByTimeStep(this->GetPreviewSegmentation(), timeStep); if (nullptr != previewImage) { AccessByItk(previewImage, ClearBufferProcessing); } } void mitk::SegWithPreviewTool::ResetPreviewContent() { auto previewImage = this->GetPreviewSegmentation(); if (nullptr != previewImage) { auto castedPreviewImage = dynamic_cast(previewImage); if (nullptr == castedPreviewImage) mitkThrow() << "Application is on wrong state / invalid tool implementation. Preview image should always be of type LabelSetImage now."; castedPreviewImage->ClearBuffer(); } } void mitk::SegWithPreviewTool::ResetPreviewNode() { if (m_IsUpdating) { mitkThrow() << "Used tool is implemented incorrectly. ResetPreviewNode is called while preview update is ongoing. Check implementation!"; } itk::RGBPixel previewColor; previewColor[0] = 0.0f; previewColor[1] = 1.0f; previewColor[2] = 0.0f; const auto image = this->GetSegmentationInput(); if (nullptr != image) { LabelSetImage::ConstPointer workingImage = dynamic_cast(this->GetToolManager()->GetWorkingData(0)->GetData()); if (workingImage.IsNotNull()) { auto newPreviewImage = workingImage->Clone(); if (this->GetResetsToEmptyPreview()) { newPreviewImage->ClearBuffer(); } if (newPreviewImage.IsNull()) { MITK_ERROR << "Cannot create preview helper objects. Unable to clone working image"; return; } m_PreviewSegmentationNode->SetData(newPreviewImage); - // Let's paint the feedback node green... auto* activeLayer = newPreviewImage->GetActiveLabelSet(); auto* activeLabel = activeLayer->GetActiveLabel(); - activeLabel->SetColor(previewColor); - activeLayer->UpdateLookupTable(activeLabel->GetValue()); + if (m_UseSpecialPreviewColor) + { + // Let's paint the feedback node green... + activeLabel->SetColor(previewColor); + activeLayer->UpdateLookupTable(activeLabel->GetValue()); + } activeLabel->SetVisible(true); } else { Image::ConstPointer workingImageBin = dynamic_cast(this->GetToolManager()->GetWorkingData(0)->GetData()); if (workingImageBin.IsNotNull()) { Image::Pointer newPreviewImage; if (this->GetResetsToEmptyPreview()) { newPreviewImage = Image::New(); newPreviewImage->Initialize(workingImageBin); } else { auto newPreviewImage = workingImageBin->Clone(); } if (newPreviewImage.IsNull()) { MITK_ERROR << "Cannot create preview helper objects. Unable to clone working image"; return; } m_PreviewSegmentationNode->SetData(newPreviewImage); } else { mitkThrow() << "Tool is an invalid state. Cannot setup preview node. Working data is an unsupported class and should have not been accepted by CanHandle()."; } } m_PreviewSegmentationNode->SetColor(previewColor); m_PreviewSegmentationNode->SetOpacity(0.5); int layer(50); m_ReferenceDataNode->GetIntProperty("layer", layer); m_PreviewSegmentationNode->SetIntProperty("layer", layer + 1); if (DataStorage *ds = this->GetToolManager()->GetDataStorage()) { if (!ds->Exists(m_PreviewSegmentationNode)) ds->Add(m_PreviewSegmentationNode, m_ReferenceDataNode); } } } mitk::SegWithPreviewTool::LabelMappingType mitk::SegWithPreviewTool::GetLabelMapping() const { LabelMappingType labelMapping = { { this->GetUserDefinedActiveLabel(),this->GetUserDefinedActiveLabel() } }; if (LabelTransferMode::SelectedLabels == this->m_LabelTransferMode) { labelMapping.clear(); for (auto label : this->m_SelectedLabels) { labelMapping.push_back({ label, label }); } } else if (LabelTransferMode::AllLabels == this->m_LabelTransferMode) { labelMapping.clear(); const auto labelSet = this->GetPreviewSegmentation()->GetActiveLabelSet(); for (auto labelIter = labelSet->IteratorConstBegin(); labelIter != labelSet->IteratorConstEnd(); ++labelIter) { labelMapping.push_back({ labelIter->second->GetValue(),labelIter->second->GetValue() }); } } return labelMapping; } void mitk::SegWithPreviewTool::TransferImageAtTimeStep(const Image* sourceImage, Image* destinationImage, const TimeStepType timeStep) { try { Image::ConstPointer sourceImageAtTimeStep = this->GetImageByTimeStep(sourceImage, timeStep); if (sourceImageAtTimeStep->GetPixelType() != destinationImage->GetPixelType()) { mitkThrow() << "Cannot transfer images. Tool is in an invalid state, source image and destination image do not have the same pixel type. " << "Source pixel type: " << sourceImage->GetPixelType().GetTypeAsString() << "; destination pixel type: " << destinationImage->GetPixelType().GetTypeAsString(); } if (!Equal(*(sourceImage->GetGeometry(timeStep)), *(destinationImage->GetGeometry(timeStep)), NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, false)) { mitkThrow() << "Cannot transfer images. Tool is in an invalid state, source image and destination image do not have the same geometry."; } if (nullptr != this->GetWorkingPlaneGeometry()) { auto sourceSlice = SegTool2D::GetAffectedImageSliceAs2DImage(this->GetWorkingPlaneGeometry(), sourceImage, timeStep); SegTool2D::WriteBackSegmentationResult(this->GetTargetSegmentationNode(), m_WorkingPlaneGeometry, sourceSlice, timeStep); } else { //take care of the full segmentation volume auto sourceLSImage = dynamic_cast(sourceImage); auto destLSImage = dynamic_cast(destinationImage); auto labelMapping = this->GetLabelMapping(); TransferLabelContent(sourceLSImage, destLSImage, labelMapping, m_MergeStyle, m_OverwriteStyle, timeStep); } } catch (...) { Tool::ErrorMessage("Error accessing single time steps of the original image. Cannot create segmentation."); throw; } } void mitk::SegWithPreviewTool::CreateResultSegmentationFromPreview() { const auto segInput = this->GetSegmentationInput(); auto previewImage = this->GetPreviewSegmentation(); if (nullptr != segInput && nullptr != previewImage) { DataNode::Pointer resultSegmentationNode = GetTargetSegmentationNode(); if (resultSegmentationNode.IsNotNull()) { const auto timePoint = RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint(); auto resultSegmentation = dynamic_cast(resultSegmentationNode->GetData()); // REMARK: the following code in this scope assumes that previewImage and resultSegmentation // are clones of the working image (segmentation provided to the tool). Therefore they have // the same time geometry. if (previewImage->GetTimeSteps() != resultSegmentation->GetTimeSteps()) { mitkThrow() << "Cannot confirm/transfer segmentation. Internal tool state is invalid." << " Preview segmentation and segmentation result image have different time geometries."; } this->TransferPrepare(); if (m_CreateAllTimeSteps) { for (unsigned int timeStep = 0; timeStep < previewImage->GetTimeSteps(); ++timeStep) { this->TransferImageAtTimeStep(previewImage, resultSegmentation, timeStep); } } else { const auto timeStep = resultSegmentation->GetTimeGeometry()->TimePointToTimeStep(timePoint); this->TransferImageAtTimeStep(previewImage, resultSegmentation, timeStep); } // since we are maybe working on a smaller image, pad it to the size of the original image if (m_ReferenceDataNode.GetPointer() != m_SegmentationInputNode.GetPointer()) { PadImageFilter::Pointer padFilter = PadImageFilter::New(); padFilter->SetInput(0, resultSegmentation); padFilter->SetInput(1, dynamic_cast(m_ReferenceDataNode->GetData())); padFilter->SetBinaryFilter(true); padFilter->SetUpperThreshold(1); padFilter->SetLowerThreshold(1); padFilter->Update(); resultSegmentationNode->SetData(padFilter->GetOutput()); } this->EnsureTargetSegmentationNodeInDataStorage(); } } } void mitk::SegWithPreviewTool::OnRoiDataChanged() { DataNode::ConstPointer node = this->GetToolManager()->GetRoiData(0); if (node.IsNotNull()) { MaskAndCutRoiImageFilter::Pointer roiFilter = MaskAndCutRoiImageFilter::New(); Image::Pointer image = dynamic_cast(m_SegmentationInputNode->GetData()); if (image.IsNull()) return; roiFilter->SetInput(image); roiFilter->SetRegionOfInterest(node->GetData()); roiFilter->Update(); DataNode::Pointer tmpNode = DataNode::New(); tmpNode->SetData(roiFilter->GetOutput()); m_SegmentationInputNode = tmpNode; } else m_SegmentationInputNode = m_ReferenceDataNode; this->ResetPreviewNode(); this->InitiateToolByInput(); this->UpdatePreview(); } void mitk::SegWithPreviewTool::OnTimePointChanged() { if (m_IsTimePointChangeAware && m_PreviewSegmentationNode.IsNotNull() && m_SegmentationInputNode.IsNotNull()) { const auto timePoint = RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint(); const bool isStaticSegOnDynamicImage = m_PreviewSegmentationNode->GetData()->GetTimeSteps() == 1 && m_SegmentationInputNode->GetData()->GetTimeSteps() > 1; if (timePoint!=m_LastTimePointOfUpdate && (isStaticSegOnDynamicImage || m_LazyDynamicPreviews)) { //we only need to update either because we are lazzy //or because we have a static segmentation with a dynamic image this->UpdatePreview(); } } } bool mitk::SegWithPreviewTool::EnsureUpToDateUserDefinedActiveLabel() { bool labelChanged = true; const auto workingImage = dynamic_cast(this->GetToolManager()->GetWorkingData(0)->GetData()); if (const auto& labelSetImage = dynamic_cast(workingImage)) { // this is a fix for T28131 / T28986, which should be refactored if T28524 is being worked on auto newLabel = labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer())->GetValue(); labelChanged = newLabel != m_UserDefinedActiveLabel; m_UserDefinedActiveLabel = newLabel; } else { m_UserDefinedActiveLabel = 1; labelChanged = false; } return labelChanged; } void mitk::SegWithPreviewTool::UpdatePreview(bool ignoreLazyPreviewSetting) { const auto inputImage = this->GetSegmentationInput(); auto previewImage = this->GetPreviewSegmentation(); int progress_steps = 200; const auto workingImage = dynamic_cast(this->GetToolManager()->GetWorkingData(0)->GetData()); this->EnsureUpToDateUserDefinedActiveLabel(); this->CurrentlyBusy.Send(true); m_IsUpdating = true; this->UpdatePrepare(); const auto timePoint = RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint(); try { if (nullptr != inputImage && nullptr != previewImage) { m_ProgressCommand->AddStepsToDo(progress_steps); if (previewImage->GetTimeSteps() > 1 && (ignoreLazyPreviewSetting || !m_LazyDynamicPreviews)) { for (unsigned int timeStep = 0; timeStep < previewImage->GetTimeSteps(); ++timeStep) { Image::ConstPointer feedBackImage; Image::ConstPointer currentSegImage; auto previewTimePoint = previewImage->GetTimeGeometry()->TimeStepToTimePoint(timeStep); auto inputTimeStep = inputImage->GetTimeGeometry()->TimePointToTimeStep(previewTimePoint); if (nullptr != this->GetWorkingPlaneGeometry()) { //only extract a specific slice defined by the working plane as feedback image. feedBackImage = SegTool2D::GetAffectedImageSliceAs2DImage(this->GetWorkingPlaneGeometry(), inputImage, inputTimeStep); currentSegImage = SegTool2D::GetAffectedImageSliceAs2DImageByTimePoint(this->GetWorkingPlaneGeometry(), workingImage, previewTimePoint); } else { //work on the whole feedback image feedBackImage = this->GetImageByTimeStep(inputImage, inputTimeStep); currentSegImage = this->GetImageByTimePoint(workingImage, previewTimePoint); } this->DoUpdatePreview(feedBackImage, currentSegImage, previewImage, timeStep); } } else { Image::ConstPointer feedBackImage; Image::ConstPointer currentSegImage; if (nullptr != this->GetWorkingPlaneGeometry()) { feedBackImage = SegTool2D::GetAffectedImageSliceAs2DImageByTimePoint(this->GetWorkingPlaneGeometry(), inputImage, timePoint); currentSegImage = SegTool2D::GetAffectedImageSliceAs2DImageByTimePoint(this->GetWorkingPlaneGeometry(), workingImage, timePoint); } else { feedBackImage = this->GetImageByTimePoint(inputImage, timePoint); currentSegImage = this->GetImageByTimePoint(workingImage, timePoint); } auto timeStep = previewImage->GetTimeGeometry()->TimePointToTimeStep(timePoint); this->DoUpdatePreview(feedBackImage, currentSegImage, previewImage, timeStep); } RenderingManager::GetInstance()->RequestUpdateAll(); } } catch (itk::ExceptionObject & excep) { MITK_ERROR << "Exception caught: " << excep.GetDescription(); m_ProgressCommand->SetProgress(progress_steps); std::string msg = excep.GetDescription(); ErrorMessage.Send(msg); } catch (...) { m_ProgressCommand->SetProgress(progress_steps); m_IsUpdating = false; CurrentlyBusy.Send(false); throw; } this->UpdateCleanUp(); m_LastTimePointOfUpdate = timePoint; m_ProgressCommand->SetProgress(progress_steps); m_IsUpdating = false; CurrentlyBusy.Send(false); } bool mitk::SegWithPreviewTool::IsUpdating() const { return m_IsUpdating; } void mitk::SegWithPreviewTool::UpdatePrepare() { // default implementation does nothing //reimplement in derived classes for special behavior } void mitk::SegWithPreviewTool::UpdateCleanUp() { // default implementation does nothing //reimplement in derived classes for special behavior } void mitk::SegWithPreviewTool::TransferLabelInformation(LabelMappingType& labelMapping, const mitk::LabelSetImage* source, mitk::LabelSetImage* target) { for (const auto& [sourceLabel, targetLabel] : labelMapping) { if (!target->ExistLabel(targetLabel, target->GetActiveLayer())) { if (!source->ExistLabel(sourceLabel, source->GetActiveLayer())) { mitkThrow() << "Cannot prepare segmentation for preview transfer. Preview seems invalid as label is missing. Missing label: " << sourceLabel; } auto clonedLabel = source->GetLabel(sourceLabel, source->GetActiveLayer())->Clone(); clonedLabel->SetValue(targetLabel); target->GetActiveLabelSet()->AddLabel(clonedLabel); } } } void mitk::SegWithPreviewTool::TransferPrepare() { auto labelMapping = this->GetLabelMapping(); DataNode::Pointer resultSegmentationNode = GetTargetSegmentationNode(); if (resultSegmentationNode.IsNotNull()) { auto resultSegmentation = dynamic_cast(resultSegmentationNode->GetData()); if (nullptr == resultSegmentation) { mitkThrow() << "Cannot prepare segmentation for preview transfer. Tool is in invalid state as segmentation is not existing or of right type"; } auto preview = this->GetPreviewSegmentation(); TransferLabelInformation(labelMapping, preview, resultSegmentation); } } mitk::TimePointType mitk::SegWithPreviewTool::GetLastTimePointOfUpdate() const { return m_LastTimePointOfUpdate; } const char* mitk::SegWithPreviewTool::GetGroup() const { return "autoSegmentation"; } mitk::Image::ConstPointer mitk::SegWithPreviewTool::GetImageByTimeStep(const mitk::Image* image, TimeStepType timestep) { return SelectImageByTimeStep(image, timestep); } mitk::Image::Pointer mitk::SegWithPreviewTool::GetImageByTimeStep(mitk::Image* image, TimeStepType timestep) { return SelectImageByTimeStep(image, timestep); } mitk::Image::ConstPointer mitk::SegWithPreviewTool::GetImageByTimePoint(const mitk::Image* image, TimePointType timePoint) { - return SelectImageByTimeStep(image, timePoint); + return SelectImageByTimePoint(image, timePoint); } void mitk::SegWithPreviewTool::EnsureTargetSegmentationNodeInDataStorage() const { auto targetNode = this->GetTargetSegmentationNode(); auto dataStorage = this->GetToolManager()->GetDataStorage(); if (!dataStorage->Exists(targetNode)) { dataStorage->Add(targetNode, this->GetToolManager()->GetReferenceData(0)); } } std::string mitk::SegWithPreviewTool::GetCurrentSegmentationName() { auto workingData = this->GetToolManager()->GetWorkingData(0); return nullptr != workingData ? workingData->GetName() : ""; } mitk::DataNode* mitk::SegWithPreviewTool::GetTargetSegmentationNode() const { return this->GetToolManager()->GetWorkingData(0); } void mitk::SegWithPreviewTool::TransferLabelSetImageContent(const LabelSetImage* source, LabelSetImage* target, TimeStepType timeStep) { mitk::ImageReadAccessor newMitkImgAcc(source); LabelMappingType labelMapping; const auto labelSet = source->GetActiveLabelSet(); for (auto labelIter = labelSet->IteratorConstBegin(); labelIter != labelSet->IteratorConstEnd(); ++labelIter) { labelMapping.push_back({ labelIter->second->GetValue(),labelIter->second->GetValue() }); } TransferLabelInformation(labelMapping, source, target); target->SetVolume(newMitkImgAcc.GetData(), timeStep); } diff --git a/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.h b/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.h index b9462aa25e..f518acf250 100644 --- a/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.h +++ b/Modules/Segmentation/Interactions/mitkSegWithPreviewTool.h @@ -1,287 +1,295 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSegWithPreviewTool_h_Included #define mitkSegWithPreviewTool_h_Included #include "mitkTool.h" #include "mitkCommon.h" #include "mitkDataNode.h" #include "mitkToolCommand.h" #include namespace mitk { /** \brief Base class for any auto segmentation tool that provides a preview of the new segmentation. This tool class implements a lot basic logic to handle auto segmentation tools with preview, Time point and ROI support. Derived classes will ask to update the segmentation preview if needed (e.g. because the ROI or the current time point has changed) or because derived tools indicated the need to update themselves. This class also takes care to properly transfer a confirmed preview into the segementation result. \ingroup ToolManagerEtAl \sa mitk::Tool \sa QmitkInteractiveSegmentation */ class MITKSEGMENTATION_EXPORT SegWithPreviewTool : public Tool { public: mitkClassMacro(SegWithPreviewTool, Tool); void Activated() override; void Deactivated() override; void ConfirmSegmentation(); itkSetMacro(CreateAllTimeSteps, bool); itkGetMacro(CreateAllTimeSteps, bool); itkBooleanMacro(CreateAllTimeSteps); itkSetMacro(KeepActiveAfterAccept, bool); itkGetMacro(KeepActiveAfterAccept, bool); itkBooleanMacro(KeepActiveAfterAccept); itkSetMacro(IsTimePointChangeAware, bool); itkGetMacro(IsTimePointChangeAware, bool); itkBooleanMacro(IsTimePointChangeAware); itkSetMacro(ResetsToEmptyPreview, bool); itkGetMacro(ResetsToEmptyPreview, bool); itkBooleanMacro(ResetsToEmptyPreview); + itkSetMacro(UseSpecialPreviewColor, bool); + itkGetMacro(UseSpecialPreviewColor, bool); + itkBooleanMacro(UseSpecialPreviewColor); + /*itk macro was not used on purpose, to aviod the change of mtime.*/ void SetMergeStyle(MultiLabelSegmentation::MergeStyle mergeStyle); itkGetMacro(MergeStyle, MultiLabelSegmentation::MergeStyle); /*itk macro was not used on purpose, to aviod the change of mtime.*/ void SetOverwriteStyle(MultiLabelSegmentation::OverwriteStyle overwriteStyle); itkGetMacro(OverwriteStyle, MultiLabelSegmentation::OverwriteStyle); enum class LabelTransferMode { ActiveLabel, //Only the active label will be transfered from preview to segmentation. SelectedLabels, //The labels defined as selected labels will be transfered. AllLabels //Transfer all labels of the preview }; /*itk macro was not used on purpose, to aviod the change of mtime.*/ void SetLabelTransferMode(LabelTransferMode LabelTransferMode); itkGetMacro(LabelTransferMode, LabelTransferMode); using SelectedLabelVectorType = std::vector; /** Specifies the labels that should be transfered form preview to the working image, if the segmentation is confirmed. The setting will be used, if LabelTransferMode is set to "SelectedLabels".*/ void SetSelectedLabels(const SelectedLabelVectorType& labelsToTransfer); itkGetMacro(SelectedLabels, SelectedLabelVectorType); bool CanHandle(const BaseData* referenceData, const BaseData* workingData) const override; /** Triggers the actualization of the preview * @param ignoreLazyPreviewSetting If set true UpdatePreview will always * generate the preview for all time steps. If set to false, UpdatePreview * will regard the setting specified by the constructor. * To define the update generation for time steps implement DoUpdatePreview. * To alter what should be done directly before or after the update of the preview, * reimplement UpdatePrepare() or UpdateCleanUp().*/ void UpdatePreview(bool ignoreLazyPreviewSetting = false); /** Indicate if currently UpdatePreview is triggered (true) or not (false).*/ bool IsUpdating() const; /** * @brief Gets the name of the currently selected segmentation node * @return the name of the segmentation node or an empty string if * none is selected */ std::string GetCurrentSegmentationName(); /** * @brief Returns the currently selected segmentation node * @return a mitk::DataNode which contains a segmentation image */ virtual DataNode* GetTargetSegmentationNode() const; /** Returns the image that contains the preview of the current segmentation. * Returns null if the node is not set or does not contain an image.*/ LabelSetImage* GetPreviewSegmentation(); const LabelSetImage* GetPreviewSegmentation() const; DataNode* GetPreviewSegmentationNode(); protected: ToolCommand::Pointer m_ProgressCommand; SegWithPreviewTool(bool lazyDynamicPreviews = false); // purposely hidden SegWithPreviewTool(bool lazyDynamicPreviews, const char* interactorType, const us::Module* interactorModule = nullptr); // purposely hidden ~SegWithPreviewTool() override; const char* GetGroup() const override; /** Helper that extracts the image for the passed timestep, if the image has multiple time steps.*/ static Image::ConstPointer GetImageByTimeStep(const Image* image, TimeStepType timestep); /** Helper that extracts the image for the passed timestep, if the image has multiple time steps.*/ static Image::Pointer GetImageByTimeStep(Image* image, TimeStepType timestep); /** Helper that extracts the image for the passed time point, if the image has multiple time steps.*/ static Image::ConstPointer GetImageByTimePoint(const Image* image, TimePointType timePoint); void EnsureTargetSegmentationNodeInDataStorage() const; /** Member is always called if GetSegmentationInput() has changed * (e.g. because a new ROI was defined, or on activation) to give derived * classes the posibility to initiate their state accordingly. * Reimplement this function to implement special behavior. */ virtual void InitiateToolByInput(); /** This member function offers derived classes the possibility to alter what should happen directly before the update of the preview is performed. It is called by UpdatePreview. Default implementation does nothing.*/ virtual void UpdatePrepare(); /** This member function offers derived classes the possibility to alter what should happen directly after the update of the preview is performed. It is called by UpdatePreview. Default implementation does nothing.*/ virtual void UpdateCleanUp(); /** This member function offers derived classes the possibility to alter what should happen directly before the content of the preview is transfered to the segmentation, when the segmentation is confirmed. It is called by CreateResultSegmentationFromPreview. Default implementation ensure that all labels that will be transfered, exist in the segmentation. If they are not existing before the transfer, the will be added by cloning the label information of the preview.*/ virtual void TransferPrepare(); using LabelMappingType = std::vector >; static void TransferLabelInformation(LabelMappingType& labelMapping, const mitk::LabelSetImage* source, mitk::LabelSetImage* target); /**Helper function that can be used to move the content of an LabelSetImage (the pixels of the active source layer and the labels). This is e.g. helpfull if you generate an LabelSetImage content in DoUpdatePreview and you want to transfer it into the preview image.*/ static void TransferLabelSetImageContent(const LabelSetImage* source, LabelSetImage* target, TimeStepType timeStep); /** This function does the real work. Here the preview for a given * input image should be computed and stored in the also passed * preview image at the passed time step. * It also provides the current/old segmentation at the time point, * which can be used, if the preview depends on the the segmenation so far. */ virtual void DoUpdatePreview(const Image* inputAtTimeStep, const Image* oldSegAtTimeStep, LabelSetImage* previewImage, TimeStepType timeStep) = 0; /** Returns the input that should be used for any segmentation/preview or tool update. * It is either the data of ReferenceDataNode itself or a part of it defined by a ROI mask * provided by the tool manager. Derived classes should regard this as the relevant * input data for any processing. * Returns null if the node is not set or does not contain an image.*/ const Image* GetSegmentationInput() const; /** Returns the image that is provided by the ReferenceDataNode. * Returns null if the node is not set or does not contain an image.*/ const Image* GetReferenceData() const; /** Resets the preview node so it is empty and ready to be filled by the tool @remark Calling this function will generate a new preview image, and the old might be invalidated. Therefore this function should not be used within the scope of UpdatePreview (m_IsUpdating == true).*/ void ResetPreviewNode(); /** Resets the complete content of the preview image. The instance of the preview image and its settings * stay the same.*/ void ResetPreviewContent(); /** Resets only the image content of the specified timeStep of the preview image. If the preview image or the specified time step does not exist, nothing happens.*/ void ResetPreviewContentAtTimeStep(unsigned int timeStep); TimePointType GetLastTimePointOfUpdate() const; itkGetConstMacro(UserDefinedActiveLabel, Label::PixelType); itkSetObjectMacro(WorkingPlaneGeometry, PlaneGeometry); itkGetConstObjectMacro(WorkingPlaneGeometry, PlaneGeometry); private: void TransferImageAtTimeStep(const Image* sourceImage, Image* destinationImage, const TimeStepType timeStep); void CreateResultSegmentationFromPreview(); void OnRoiDataChanged(); void OnTimePointChanged(); /**Internal helper that ensures that the stored active label is up to date. This is a fix for T28131 / T28986. It should be refactored if T28524 is being worked on. On the long run, the active label will be communicated/set by the user/toolmanager as a state of the tool and the tool should react accordingly (like it does for other external state changes). @return indicates if the label has changed (true) or not. */ bool EnsureUpToDateUserDefinedActiveLabel(); LabelMappingType GetLabelMapping() const; /** Node that containes the preview data generated and managed by this class or derived ones.*/ DataNode::Pointer m_PreviewSegmentationNode; /** The reference data recieved from ToolManager::GetReferenceData when tool was activated.*/ DataNode::Pointer m_ReferenceDataNode; /** Node that containes the data that should be used as input for any auto segmentation. It might * be the same like m_ReferenceDataNode (if no ROI is set) or a sub region (if ROI is set).*/ DataNode::Pointer m_SegmentationInputNode; /** Indicates if Accepting the threshold should transfer/create the segmentations of all time steps (true) or only of the currently selected timepoint (false).*/ bool m_CreateAllTimeSteps = false; /** Indicates if the tool should kept active after accepting the segmentation or not.*/ bool m_KeepActiveAfterAccept = false; /** Relevant if the working data / preview image has multiple time steps (dynamic segmentations). * This flag has to be set by derived classes accordingly to there way to generate dynamic previews. * If LazyDynamicPreview is true, the tool generates only the preview for the current time step. * Therefore it always has to update the preview if current time point has changed and it has to (re)compute * all timeframes if ConfirmSegmentation() is called.*/ bool m_LazyDynamicPreviews = false; bool m_IsTimePointChangeAware = true; /** Controls if ResetPreviewNode generates an empty content (true) or clones the current segmentation (false).*/ bool m_ResetsToEmptyPreview = false; + /** Controls if for the preview of the active label a special preview color is used. + * If set to false, coloring will stay in the preview like it is in the working image.*/ + bool m_UseSpecialPreviewColor = true; + TimePointType m_LastTimePointOfUpdate = 0.; bool m_IsUpdating = false; Label::PixelType m_UserDefinedActiveLabel = 1; /** This variable indicates if for the tool a working plane geometry is defined. * If a working plane is defined the tool will only work an the slice of the input * and the segmentation. Thus only the relevant input slice will be passed to * DoUpdatePreview(...) and only the relevant slice of the preview will be transfered when * ConfirmSegmentation() is called.*/ PlaneGeometry::Pointer m_WorkingPlaneGeometry; /** This variable controles how the label pixel content of the preview should be transfered into the segmentation- For more details of the behavior see documentation of MultiLabelSegmentation::MergeStyle. */ MultiLabelSegmentation::MergeStyle m_MergeStyle = MultiLabelSegmentation::MergeStyle::Replace; /** This variable controles how the label pixel content of the preview should be transfered into the segmentation- For more details of the behavior see documentation of MultiLabelSegmentation::OverwriteStyle. */ MultiLabelSegmentation::OverwriteStyle m_OverwriteStyle = MultiLabelSegmentation::OverwriteStyle::RegardLocks; LabelTransferMode m_LabelTransferMode = LabelTransferMode::ActiveLabel; SelectedLabelVectorType m_SelectedLabels = {}; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkTool.cpp b/Modules/Segmentation/Interactions/mitkTool.cpp index 36416c4c88..6ad70a18e1 100644 --- a/Modules/Segmentation/Interactions/mitkTool.cpp +++ b/Modules/Segmentation/Interactions/mitkTool.cpp @@ -1,339 +1,338 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkTool.h" -#include #include "mitkDisplayActionEventBroadcast.h" #include "mitkImageReadAccessor.h" #include "mitkImageWriteAccessor.h" #include "mitkLevelWindowProperty.h" #include "mitkLookupTableProperty.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include #include // us #include #include // itk #include namespace mitk { itkEventMacroDefinition(ToolEvent, itk::ModifiedEvent); } mitk::Tool::Tool(const char *type, const us::Module *interactorModule) : m_EventConfig(""), m_ToolManager(nullptr), m_PredicateImages(NodePredicateDataType::New("Image")), // for reference images m_PredicateDim3(NodePredicateDimension::New(3, 1)), m_PredicateDim4(NodePredicateDimension::New(4, 1)), m_PredicateDimension(mitk::NodePredicateOr::New(m_PredicateDim3, m_PredicateDim4)), m_PredicateImage3D(NodePredicateAnd::New(m_PredicateImages, m_PredicateDimension)), m_PredicateBinary(NodePredicateProperty::New("binary", BoolProperty::New(true))), m_PredicateNotBinary(NodePredicateNot::New(m_PredicateBinary)), m_PredicateSegmentation(NodePredicateProperty::New("segmentation", BoolProperty::New(true))), m_PredicateNotSegmentation(NodePredicateNot::New(m_PredicateSegmentation)), m_PredicateHelper(NodePredicateProperty::New("helper object", BoolProperty::New(true))), m_PredicateNotHelper(NodePredicateNot::New(m_PredicateHelper)), m_PredicateImageColorful(NodePredicateAnd::New(m_PredicateNotBinary, m_PredicateNotSegmentation)), m_PredicateImageColorfulNotHelper(NodePredicateAnd::New(m_PredicateImageColorful, m_PredicateNotHelper)), m_PredicateReference(NodePredicateAnd::New(m_PredicateImage3D, m_PredicateImageColorfulNotHelper)), m_IsSegmentationPredicate( NodePredicateAnd::New(NodePredicateOr::New(m_PredicateBinary, m_PredicateSegmentation), m_PredicateNotHelper)), m_InteractorType(type), m_DisplayInteractionConfigs(), m_InteractorModule(interactorModule) { } mitk::Tool::~Tool() { } bool mitk::Tool::CanHandle(const BaseData* referenceData, const BaseData* /*workingData*/) const { if (referenceData == nullptr) return false; return true; } void mitk::Tool::InitializeStateMachine() { if (m_InteractorType.empty()) return; try { auto isThisModule = nullptr == m_InteractorModule; auto module = isThisModule ? us::GetModuleContext()->GetModule() : m_InteractorModule; LoadStateMachine(m_InteractorType + ".xml", module); SetEventConfig(isThisModule ? "SegmentationToolsConfig.xml" : m_InteractorType + "Config.xml", module); } catch (const std::exception &e) { MITK_ERROR << "Could not load statemachine pattern " << m_InteractorType << ".xml with exception: " << e.what(); } } void mitk::Tool::Notify(InteractionEvent *interactionEvent, bool isHandled) { // to use the state machine pattern, // the event is passed to the state machine interface to be handled if (!isHandled) { this->HandleEvent(interactionEvent, nullptr); } } void mitk::Tool::ConnectActionsAndFunctions() { } bool mitk::Tool::FilterEvents(InteractionEvent *, DataNode *) { return true; } const char *mitk::Tool::GetGroup() const { return "default"; } void mitk::Tool::SetToolManager(ToolManager *manager) { m_ToolManager = manager; } mitk::ToolManager* mitk::Tool::GetToolManager() const { return m_ToolManager; } mitk::DataStorage* mitk::Tool::GetDataStorage() const { if (nullptr != m_ToolManager) { return m_ToolManager->GetDataStorage(); } return nullptr; } void mitk::Tool::Activated() { // As a legacy solution the display interaction of the new interaction framework is disabled here to avoid conflicts // with tools // Note: this only affects InteractionEventObservers (formerly known as Listeners) all DataNode specific interaction // will still be enabled m_DisplayInteractionConfigs.clear(); auto eventObservers = us::GetModuleContext()->GetServiceReferences(); for (const auto& eventObserver : eventObservers) { auto displayActionEventBroadcast = dynamic_cast( us::GetModuleContext()->GetService(eventObserver)); if (nullptr != displayActionEventBroadcast) { // remember the original configuration m_DisplayInteractionConfigs.insert(std::make_pair(eventObserver, displayActionEventBroadcast->GetEventConfig())); // here the alternative configuration is loaded displayActionEventBroadcast->AddEventConfig(m_EventConfig.c_str()); } } } void mitk::Tool::Deactivated() { // Re-enabling InteractionEventObservers that have been previously disabled for legacy handling of Tools // in new interaction framework for (const auto& displayInteractionConfig : m_DisplayInteractionConfigs) { if (displayInteractionConfig.first) { auto displayActionEventBroadcast = static_cast( us::GetModuleContext()->GetService(displayInteractionConfig.first)); if (nullptr != displayActionEventBroadcast) { // here the regular configuration is loaded again displayActionEventBroadcast->SetEventConfig(displayInteractionConfig.second); } } } m_DisplayInteractionConfigs.clear(); } itk::Object::Pointer mitk::Tool::GetGUI(const std::string &toolkitPrefix, const std::string &toolkitPostfix) { itk::Object::Pointer object; std::string classname = this->GetNameOfClass(); std::string guiClassname = toolkitPrefix + classname + toolkitPostfix; std::list allGUIs = itk::ObjectFactoryBase::CreateAllInstance(guiClassname.c_str()); for (auto iter = allGUIs.begin(); iter != allGUIs.end(); ++iter) { if (object.IsNull()) { object = dynamic_cast(iter->GetPointer()); } else { MITK_ERROR << "There is more than one GUI for " << classname << " (several factories claim ability to produce a " << guiClassname << " ) " << std::endl; return nullptr; // people should see and fix this error } } return object; } mitk::NodePredicateBase::ConstPointer mitk::Tool::GetReferenceDataPreference() const { return m_PredicateReference.GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::Tool::GetWorkingDataPreference() const { return m_IsSegmentationPredicate.GetPointer(); } mitk::DataNode::Pointer mitk::Tool::CreateEmptySegmentationNode(const Image *original, const std::string &organName, const mitk::Color &color) const { // we NEED a reference image for size etc. if (!original) return nullptr; // actually create a new empty segmentation PixelType pixelType(mitk::MakeScalarPixelType()); LabelSetImage::Pointer segmentation = LabelSetImage::New(); if (original->GetDimension() == 2) { const unsigned int dimensions[] = {original->GetDimension(0), original->GetDimension(1), 1}; segmentation->Initialize(pixelType, 3, dimensions); segmentation->AddLayer(); } else { segmentation->Initialize(original); } mitk::Label::Pointer label = mitk::Label::New(); label->SetName(organName); label->SetColor(color); label->SetValue(1); segmentation->GetActiveLabelSet()->AddLabel(label); segmentation->GetActiveLabelSet()->SetActiveLabel(1); unsigned int byteSize = sizeof(mitk::Label::PixelType); if (segmentation->GetDimension() < 4) { for (unsigned int dim = 0; dim < segmentation->GetDimension(); ++dim) { byteSize *= segmentation->GetDimension(dim); } mitk::ImageWriteAccessor writeAccess(segmentation.GetPointer(), segmentation->GetVolumeData(0)); memset(writeAccess.GetData(), 0, byteSize); } else { // if we have a time-resolved image we need to set memory to 0 for each time step for (unsigned int dim = 0; dim < 3; ++dim) { byteSize *= segmentation->GetDimension(dim); } for (unsigned int volumeNumber = 0; volumeNumber < segmentation->GetDimension(3); volumeNumber++) { mitk::ImageWriteAccessor writeAccess(segmentation.GetPointer(), segmentation->GetVolumeData(volumeNumber)); memset(writeAccess.GetData(), 0, byteSize); } } if (original->GetTimeGeometry()) { TimeGeometry::Pointer originalGeometry = original->GetTimeGeometry()->Clone(); segmentation->SetTimeGeometry(originalGeometry); } else { Tool::ErrorMessage("Original image does not have a 'Time sliced geometry'! Cannot create a segmentation."); return nullptr; } return CreateSegmentationNode(segmentation, organName, color); } mitk::DataNode::Pointer mitk::Tool::CreateSegmentationNode(Image *image, const std::string &organName, const mitk::Color &color) const { if (!image) return nullptr; // decorate the datatreenode with some properties DataNode::Pointer segmentationNode = DataNode::New(); segmentationNode->SetData(image); // name segmentationNode->SetProperty("name", StringProperty::New(organName)); // visualization properties segmentationNode->SetProperty("binary", BoolProperty::New(true)); segmentationNode->SetProperty("color", ColorProperty::New(color)); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); lut->SetType(mitk::LookupTable::MULTILABEL); mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New(); lutProp->SetLookupTable(lut); segmentationNode->SetProperty("LookupTable", lutProp); segmentationNode->SetProperty("texture interpolation", BoolProperty::New(false)); segmentationNode->SetProperty("layer", IntProperty::New(10)); segmentationNode->SetProperty("levelwindow", LevelWindowProperty::New(LevelWindow(0.5, 1))); segmentationNode->SetProperty("opacity", FloatProperty::New(0.3)); segmentationNode->SetProperty("segmentation", BoolProperty::New(true)); segmentationNode->SetProperty("reslice interpolation", VtkResliceInterpolationProperty::New()); // otherwise -> segmentation appears in 2 // slices sometimes (only visual effect, not // different data) // For MITK-3M3 release, the volume of all segmentations should be shown segmentationNode->SetProperty("showVolume", BoolProperty::New(true)); return segmentationNode; } us::ModuleResource mitk::Tool::GetIconResource() const { // Each specific tool should load its own resource. This one will be invalid return us::ModuleResource(); } us::ModuleResource mitk::Tool::GetCursorIconResource() const { // Each specific tool should load its own resource. This one will be invalid return us::ModuleResource(); } diff --git a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp index f0cb874239..15cb4647b8 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp +++ b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp @@ -1,100 +1,100 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkEditableContourToolGUIBase.h" QmitkEditableContourToolGUIBase::QmitkEditableContourToolGUIBase() : QmitkToolGUI() { m_Controls.setupUi(this); m_Controls.m_Information->hide(); m_Controls.m_AutoCheck->setChecked(true); m_Controls.m_ConfirmButton->hide(); m_Controls.m_AddMode->setChecked(true); - m_Controls.m_SubstractMode->hide(); + m_Controls.m_SubtractMode->hide(); m_Controls.m_AddMode->hide(); m_Controls.m_ClearButton->hide(); connect(m_Controls.m_ConfirmButton, SIGNAL(clicked()), this, SLOT(OnConfirmSegmentation())); - connect(m_Controls.m_ClearButton, SIGNAL(clicked()), this, SLOT(OnClearSegmentation())); + connect(m_Controls.m_ClearButton, SIGNAL(clicked()), this, SLOT(OnClearContour())); connect(this, SIGNAL(NewToolAssociated(mitk::Tool *)), this, SLOT(OnNewToolAssociated(mitk::Tool *))); connect(m_Controls.m_InformationCheckBox, SIGNAL(toggled(bool)), this, SLOT(OnShowInformation(bool))); connect(m_Controls.m_AutoCheck, SIGNAL(toggled(bool)), this, SLOT(OnAutoConfirm(bool))); connect(m_Controls.m_AddMode, SIGNAL(toggled(bool)), this, SLOT(OnAddModeToogled(bool))); } QmitkEditableContourToolGUIBase::~QmitkEditableContourToolGUIBase() { } void QmitkEditableContourToolGUIBase::OnNewToolAssociated(mitk::Tool *tool) { m_NewTool = dynamic_cast(tool); if (m_NewTool.IsNull()) { mitkThrow() << "Tool is in an invalid state. QmitkEditableContourToolGUIBase needs tools based on EditableContourTool."; } const auto autoConfirm = m_NewTool->GetAutoConfirm(); m_Controls.m_AutoCheck->setChecked(autoConfirm); const auto addMode = m_NewTool->GetAddMode(); m_Controls.m_AddMode->setChecked(addMode); this->OnAutoConfirm(autoConfirm); } void QmitkEditableContourToolGUIBase::OnConfirmSegmentation() { if (m_NewTool.IsNotNull()) { m_NewTool->ConfirmSegmentation(); } } -void QmitkEditableContourToolGUIBase::OnClearSegmentation() +void QmitkEditableContourToolGUIBase::OnClearContour() { if (m_NewTool.IsNotNull()) - m_NewTool->ClearSegmentation(); + m_NewTool->ClearContour(); } void QmitkEditableContourToolGUIBase::OnShowInformation(bool on) { m_Controls.m_Information->setVisible(on); } void QmitkEditableContourToolGUIBase::OnAutoConfirm(bool on) { m_Controls.m_ConfirmButton->setVisible(!on); m_Controls.m_ClearButton->setVisible(!on); m_Controls.m_AddMode->setVisible(!on); if (on) { m_Controls.m_AddMode->setChecked(true); } - m_Controls.m_SubstractMode->setVisible(!on); + m_Controls.m_SubtractMode->setVisible(!on); if (m_NewTool.IsNotNull()) { if (on && m_NewTool->IsEditingContour()) { this->OnConfirmSegmentation(); } m_NewTool->SetAutoConfirm(on); } } void QmitkEditableContourToolGUIBase::OnAddModeToogled(bool on) { if (m_NewTool.IsNotNull()) { m_NewTool->SetAddMode(on); } } diff --git a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.h b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.h index 8343107799..3b7640ba99 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.h +++ b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.h @@ -1,59 +1,59 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkEditableContourToolGUIBase_h_Included #define QmitkEditableContourToolGUIBase_h_Included #include "QmitkToolGUI.h" #include "mitkEditableContourTool.h" #include "ui_QmitkEditableContourToolGUIControls.h" #include class QmitkEditableContourToolGUIBaseControls; /** \ingroup org_mitk_gui_qt_interactivesegmentation_internal \brief GUI for mitk::EditableContourTool based classes. \sa mitk::LassoTool */ class MITKSEGMENTATIONUI_EXPORT QmitkEditableContourToolGUIBase : public QmitkToolGUI { Q_OBJECT public: mitkClassMacro(QmitkEditableContourToolGUIBase, QmitkToolGUI); itkFactorylessNewMacro(Self); itkCloneMacro(Self); protected slots : void OnNewToolAssociated(mitk::Tool *); void OnConfirmSegmentation(); - void OnClearSegmentation(); + void OnClearContour(); void OnAutoConfirm(bool on); void OnAddModeToogled(bool on); void OnShowInformation(bool on); protected: QmitkEditableContourToolGUIBase(); ~QmitkEditableContourToolGUIBase() override; Ui::QmitkEditableContourToolGUIControls m_Controls; mitk::EditableContourTool::Pointer m_NewTool; }; #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIControls.ui b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIControls.ui index 4cb2af9f25..2811de9dd2 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIControls.ui +++ b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIControls.ui @@ -1,159 +1,156 @@ QmitkEditableContourToolGUIControls 0 0 421 429 0 0 0 0 - QmitkLiveWireTool2DGUIControls - - - Confirm all previous contour. + QmitkEditableContourToolGUIControls 0 0 0 0 Auto confirm contour true The contour will be added as segmentation for the active label. Add mode true - + - If confirmed the contour will be added as background, thus it will be substracted from the active label. + If confirmed the contour will be added as background, thus it will be subtracted from the active label. - Substract mode + Subtract mode Confirm Segmentation - Clear Segmentation + Clear Contour Qt::Vertical QSizePolicy::Fixed 20 15 Show usage information 0 150 12 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:12pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">The tool is started by a double-click near the object of interest.</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">You can fix preview segments by adding ancor points with a single left mouse button click. When you keep the mouse button pressed, you can manually draw contours (freehand contours) by moving the mouse. To close a contour and finish current segmentation perform a double click.</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">If &quot;Auto confirm&quot; is active and the segmentation is finished, the preview will be directly added as segmentation. From there you are free to start a new contour (double click).</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">If &quot;Auto confirm&quot; is active and the contour is finished, the preview will be directly added as segmentation. From there you are free to start a new contour (double click).</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">If &quot;Auto confirm&quot; is not active, the contour will be still editable after finishing the segmentation. You can move, insert (CTRL+click on the contour segment) and delete (press DEL while ancor is selected) its ancor points. To confirm the segmentation, push the &quot;Confirm Segmentation&quot; button. Please be aware that freehand contour parts are treated differently: You cannot add an ancor point there, also you are not allowed to select/move/delete an ancor point that is at the beginning or end of a freehand contour part. </span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">Push the &quot;Clear Segmentation&quot; button to delete all unconfirmed contours.</span></p></body></html> diff --git a/Modules/SegmentationUI/Qmitk/QmitkGrowCutToolGUI.cpp b/Modules/SegmentationUI/Qmitk/QmitkGrowCutToolGUI.cpp index b4ca6da252..03a607b838 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkGrowCutToolGUI.cpp +++ b/Modules/SegmentationUI/Qmitk/QmitkGrowCutToolGUI.cpp @@ -1,149 +1,149 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkGrowCutToolGUI.h" #include #include // Qt #include #include #include #include #include #include MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkGrowCutToolGUI, "") QmitkGrowCutToolGUI::QmitkGrowCutToolGUI() : QmitkMultiLabelSegWithPreviewToolGUIBase() { auto enableConfirmSegBtnFnc = [this](bool enabled) { return enabled && m_FirstPreviewComputation; }; m_EnableConfirmSegBtnFnc = enableConfirmSegBtnFnc; } QmitkGrowCutToolGUI::~QmitkGrowCutToolGUI() {} void QmitkGrowCutToolGUI::ConnectNewTool(mitk::SegWithPreviewTool *newTool) { Superclass::ConnectNewTool(newTool); newTool->IsTimePointChangeAwareOff(); } void QmitkGrowCutToolGUI::InitializeUI(QBoxLayout *mainLayout) { m_Controls.setupUi(this); this->OnAdvancedSettingsButtonToggled(false); std::function isPreviewAvailable; isPreviewAvailable = [this]() { auto tool = this->GetConnectedToolAs(); if (nullptr != tool) { - return tool->HasMoreThanTwoSeedLabel(); + return tool->SeedImageIsValid(); } return false; }; auto previewAvailable = isPreviewAvailable(); m_Controls.m_previewButton->setEnabled(previewAvailable); m_Controls.m_warningLabel->setVisible(!previewAvailable); mainLayout->addLayout(m_Controls.verticalLayout); connect(m_Controls.m_previewButton, &QPushButton::clicked, this, &QmitkGrowCutToolGUI::OnPreviewBtnClicked); connect(m_Controls.m_advancedSettingsButton, &ctkExpandButton::toggled, this, &QmitkGrowCutToolGUI::OnAdvancedSettingsButtonToggled); connect(m_Controls.m_distancePenaltyDoubleSpinBox, qOverload(&QDoubleSpinBox::valueChanged), this, &QmitkGrowCutToolGUI::SetValueOfDistancePenaltySlider); connect(m_Controls.m_distancePenaltySlider, &QSlider::valueChanged, this, &QmitkGrowCutToolGUI::SetValueOfDistancePenaltyDoubleSpinBox); Superclass::InitializeUI(mainLayout); } void QmitkGrowCutToolGUI::SetValueOfDistancePenaltySlider(double val) { m_Controls.m_distancePenaltySlider->setValue(val * 100); } void QmitkGrowCutToolGUI::SetValueOfDistancePenaltyDoubleSpinBox(int val) { m_Controls.m_distancePenaltyDoubleSpinBox->setValue((static_cast(val) / 100)); } void QmitkGrowCutToolGUI::OnAdvancedSettingsButtonToggled(bool toggled) { m_Controls.m_distancePenaltyLabel->setVisible(toggled); m_Controls.m_distancePenaltyDoubleSpinBox->setVisible(toggled); m_Controls.m_distancePenaltySlider->setVisible(toggled); double distancePenaltyMinium = 0.0; double distancePenaltyMaximum = 1.0; m_Controls.m_distancePenaltyDoubleSpinBox->setMinimum(distancePenaltyMinium); m_Controls.m_distancePenaltyDoubleSpinBox->setMaximum(distancePenaltyMaximum); m_Controls.m_distancePenaltySlider->setMinimum(distancePenaltyMinium); m_Controls.m_distancePenaltySlider->setMaximum(distancePenaltyMaximum * 100); m_Controls.m_distancePenaltyDoubleSpinBox->setSingleStep(0.01); } void QmitkGrowCutToolGUI::OnPreviewBtnClicked() { auto tool = this->GetConnectedToolAs(); if (nullptr != tool) { try { tool->SetDistancePenalty(m_Controls.m_distancePenaltyDoubleSpinBox->value()); tool->UpdatePreview(); } catch (...) { this->setCursor(Qt::ArrowCursor); QMessageBox *messageBox = new QMessageBox(QMessageBox::Critical, nullptr, "itkGrowCutFilter error."); messageBox->exec(); delete messageBox; return; } m_FirstPreviewComputation = true; this->SetLabelSetPreview(tool->GetPreviewSegmentation()); tool->IsTimePointChangeAwareOn(); this->ActualizePreviewLabelVisibility(); } } void QmitkGrowCutToolGUI::EnableWidgets(bool enabled) { Superclass::EnableWidgets(enabled); m_Controls.m_distancePenaltyLabel->setEnabled(enabled); m_Controls.m_distancePenaltyDoubleSpinBox->setEnabled(enabled); m_Controls.m_distancePenaltySlider->setEnabled(enabled); } diff --git a/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp b/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp index 9ac77d0939..48b35ba5f7 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp +++ b/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp @@ -1,1439 +1,1437 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSlicesInterpolator.h" #include "mitkApplyDiffImageOperation.h" #include "mitkColorProperty.h" #include "mitkCoreObjectFactory.h" #include "mitkDiffImageApplier.h" #include "mitkInteractionConst.h" #include "mitkLevelWindowProperty.h" #include "mitkOperationEvent.h" #include "mitkProgressBar.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkSegTool2D.h" #include "mitkSliceNavigationController.h" #include "mitkSurfaceToImageFilter.h" #include "mitkToolManager.h" #include "mitkUndoController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { template itk::SmartPointer GetData(const mitk::DataNode* dataNode) { return nullptr != dataNode ? dynamic_cast(dataNode->GetData()) : nullptr; } } float SURFACE_COLOR_RGB[3] = {0.49f, 1.0f, 0.16f}; const std::map QmitkSlicesInterpolator::createActionToSliceDimension() { std::map actionToSliceDimension; foreach (mitk::SliceNavigationController *slicer, m_ControllerToDeleteObserverTag.keys()) { actionToSliceDimension[new QAction(QString::fromStdString(slicer->GetViewDirectionAsString()), nullptr)] = slicer; } return actionToSliceDimension; } QmitkSlicesInterpolator::QmitkSlicesInterpolator(QWidget *parent, const char * /*name*/) : QWidget(parent), // ACTION_TO_SLICEDIMENSION( createActionToSliceDimension() ), m_Interpolator(mitk::SegmentationInterpolationController::New()), m_SurfaceInterpolator(mitk::SurfaceInterpolationController::GetInstance()), m_ToolManager(nullptr), m_Initialized(false), m_LastSNC(nullptr), m_LastSliceIndex(0), m_2DInterpolationEnabled(false), m_3DInterpolationEnabled(false), m_FirstRun(true) { m_GroupBoxEnableExclusiveInterpolationMode = new QGroupBox("Interpolation", this); QVBoxLayout *vboxLayout = new QVBoxLayout(m_GroupBoxEnableExclusiveInterpolationMode); m_EdgeDetector = mitk::FeatureBasedEdgeDetectionFilter::New(); m_PointScorer = mitk::PointCloudScoringFilter::New(); m_CmbInterpolation = new QComboBox(m_GroupBoxEnableExclusiveInterpolationMode); m_CmbInterpolation->addItem("Disabled"); m_CmbInterpolation->addItem("2-Dimensional"); m_CmbInterpolation->addItem("3-Dimensional"); vboxLayout->addWidget(m_CmbInterpolation); m_BtnApply2D = new QPushButton("Confirm for single slice", m_GroupBoxEnableExclusiveInterpolationMode); vboxLayout->addWidget(m_BtnApply2D); m_BtnApplyForAllSlices2D = new QPushButton("Confirm for all slices", m_GroupBoxEnableExclusiveInterpolationMode); vboxLayout->addWidget(m_BtnApplyForAllSlices2D); m_BtnApply3D = new QPushButton("Confirm", m_GroupBoxEnableExclusiveInterpolationMode); vboxLayout->addWidget(m_BtnApply3D); // T28261 // m_BtnSuggestPlane = new QPushButton("Suggest a plane", m_GroupBoxEnableExclusiveInterpolationMode); // vboxLayout->addWidget(m_BtnSuggestPlane); m_BtnReinit3DInterpolation = new QPushButton("Reinit Interpolation", m_GroupBoxEnableExclusiveInterpolationMode); vboxLayout->addWidget(m_BtnReinit3DInterpolation); m_ChkShowPositionNodes = new QCheckBox("Show Position Nodes", m_GroupBoxEnableExclusiveInterpolationMode); vboxLayout->addWidget(m_ChkShowPositionNodes); this->HideAllInterpolationControls(); connect(m_CmbInterpolation, SIGNAL(currentIndexChanged(int)), this, SLOT(OnInterpolationMethodChanged(int))); connect(m_BtnApply2D, SIGNAL(clicked()), this, SLOT(OnAcceptInterpolationClicked())); connect(m_BtnApplyForAllSlices2D, SIGNAL(clicked()), this, SLOT(OnAcceptAllInterpolationsClicked())); connect(m_BtnApply3D, SIGNAL(clicked()), this, SLOT(OnAccept3DInterpolationClicked())); // T28261 // connect(m_BtnSuggestPlane, SIGNAL(clicked()), this, SLOT(OnSuggestPlaneClicked())); connect(m_BtnReinit3DInterpolation, SIGNAL(clicked()), this, SLOT(OnReinit3DInterpolation())); connect(m_ChkShowPositionNodes, SIGNAL(toggled(bool)), this, SLOT(OnShowMarkers(bool))); connect(m_ChkShowPositionNodes, SIGNAL(toggled(bool)), this, SIGNAL(SignalShowMarkerNodes(bool))); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(m_GroupBoxEnableExclusiveInterpolationMode); this->setLayout(layout); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnInterpolationInfoChanged); InterpolationInfoChangedObserverTag = m_Interpolator->AddObserver(itk::ModifiedEvent(), command); itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnSurfaceInterpolationInfoChanged); SurfaceInterpolationInfoChangedObserverTag = m_SurfaceInterpolator->AddObserver(itk::ModifiedEvent(), command2); auto command3 = itk::ReceptorMemberCommand::New(); command3->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnInterpolationAborted); InterpolationAbortedObserverTag = m_Interpolator->AddObserver(itk::AbortEvent(), command3); // feedback node and its visualization properties m_FeedbackNode = mitk::DataNode::New(); mitk::CoreObjectFactory::GetInstance()->SetDefaultProperties(m_FeedbackNode); m_FeedbackNode->SetProperty("binary", mitk::BoolProperty::New(true)); m_FeedbackNode->SetProperty("outline binary", mitk::BoolProperty::New(true)); m_FeedbackNode->SetProperty("color", mitk::ColorProperty::New(255.0, 255.0, 0.0)); m_FeedbackNode->SetProperty("texture interpolation", mitk::BoolProperty::New(false)); m_FeedbackNode->SetProperty("layer", mitk::IntProperty::New(20)); m_FeedbackNode->SetProperty("levelwindow", mitk::LevelWindowProperty::New(mitk::LevelWindow(0, 1))); m_FeedbackNode->SetProperty("name", mitk::StringProperty::New("Interpolation feedback")); m_FeedbackNode->SetProperty("opacity", mitk::FloatProperty::New(0.8)); m_FeedbackNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_InterpolatedSurfaceNode = mitk::DataNode::New(); m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(SURFACE_COLOR_RGB)); m_InterpolatedSurfaceNode->SetProperty("name", mitk::StringProperty::New("Surface Interpolation feedback")); m_InterpolatedSurfaceNode->SetProperty("opacity", mitk::FloatProperty::New(0.5)); m_InterpolatedSurfaceNode->SetProperty("line width", mitk::FloatProperty::New(4.0f)); m_InterpolatedSurfaceNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_InterpolatedSurfaceNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_InterpolatedSurfaceNode->SetVisibility(false); m_3DContourNode = mitk::DataNode::New(); m_3DContourNode->SetProperty("color", mitk::ColorProperty::New(0.0, 0.0, 0.0)); m_3DContourNode->SetProperty("hidden object", mitk::BoolProperty::New(true)); m_3DContourNode->SetProperty("name", mitk::StringProperty::New("Drawn Contours")); m_3DContourNode->SetProperty("material.representation", mitk::VtkRepresentationProperty::New(VTK_WIREFRAME)); m_3DContourNode->SetProperty("material.wireframeLineWidth", mitk::FloatProperty::New(2.0f)); m_3DContourNode->SetProperty("3DContourContainer", mitk::BoolProperty::New(true)); m_3DContourNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2"))); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); + m_3DContourNode->SetVisibility(false); QWidget::setContentsMargins(0, 0, 0, 0); if (QWidget::layout() != nullptr) { QWidget::layout()->setContentsMargins(0, 0, 0, 0); } // For running 3D Interpolation in background // create a QFuture and a QFutureWatcher connect(&m_Watcher, SIGNAL(started()), this, SLOT(StartUpdateInterpolationTimer())); connect(&m_Watcher, SIGNAL(finished()), this, SLOT(OnSurfaceInterpolationFinished())); connect(&m_Watcher, SIGNAL(finished()), this, SLOT(StopUpdateInterpolationTimer())); m_Timer = new QTimer(this); connect(m_Timer, SIGNAL(timeout()), this, SLOT(ChangeSurfaceColor())); } void QmitkSlicesInterpolator::SetDataStorage(mitk::DataStorage::Pointer storage) { if (m_DataStorage == storage) { return; } if (m_DataStorage.IsNotNull()) { m_DataStorage->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1(this, &QmitkSlicesInterpolator::NodeRemoved) ); } m_DataStorage = storage; m_SurfaceInterpolator->SetDataStorage(storage); if (m_DataStorage.IsNotNull()) { m_DataStorage->RemoveNodeEvent.AddListener( mitk::MessageDelegate1(this, &QmitkSlicesInterpolator::NodeRemoved) ); } } mitk::DataStorage *QmitkSlicesInterpolator::GetDataStorage() { if (m_DataStorage.IsNotNull()) { return m_DataStorage; } else { return nullptr; } } void QmitkSlicesInterpolator::Initialize(mitk::ToolManager *toolManager, const QList &controllers) { Q_ASSERT(!controllers.empty()); if (m_Initialized) { // remove old observers Uninitialize(); } m_ToolManager = toolManager; if (m_ToolManager) { // set enabled only if a segmentation is selected mitk::DataNode *node = m_ToolManager->GetWorkingData(0); QWidget::setEnabled(node != nullptr); // react whenever the set of selected segmentation changes m_ToolManager->WorkingDataChanged += mitk::MessageDelegate(this, &QmitkSlicesInterpolator::OnToolManagerWorkingDataModified); m_ToolManager->ReferenceDataChanged += mitk::MessageDelegate( this, &QmitkSlicesInterpolator::OnToolManagerReferenceDataModified); // connect to the slice navigation controller. after each change, call the interpolator foreach (mitk::SliceNavigationController *slicer, controllers) { // Has to be initialized m_LastSNC = slicer; m_TimePoints.insert(slicer, slicer->GetSelectedTimePoint()); itk::MemberCommand::Pointer deleteCommand = itk::MemberCommand::New(); deleteCommand->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnSliceNavigationControllerDeleted); m_ControllerToDeleteObserverTag.insert(slicer, slicer->AddObserver(itk::DeleteEvent(), deleteCommand)); itk::MemberCommand::Pointer timeChangedCommand = itk::MemberCommand::New(); timeChangedCommand->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnTimeChanged); m_ControllerToTimeObserverTag.insert( slicer, slicer->AddObserver(mitk::SliceNavigationController::TimeGeometryEvent(nullptr, 0), timeChangedCommand)); itk::MemberCommand::Pointer sliceChangedCommand = itk::MemberCommand::New(); sliceChangedCommand->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnSliceChanged); m_ControllerToSliceObserverTag.insert( slicer, slicer->AddObserver(mitk::SliceNavigationController::GeometrySliceEvent(nullptr, 0), sliceChangedCommand)); } ACTION_TO_SLICEDIMENSION = createActionToSliceDimension(); } m_Initialized = true; } void QmitkSlicesInterpolator::Uninitialize() { if (m_ToolManager.IsNotNull()) { m_ToolManager->WorkingDataChanged -= mitk::MessageDelegate(this, &QmitkSlicesInterpolator::OnToolManagerWorkingDataModified); m_ToolManager->ReferenceDataChanged -= mitk::MessageDelegate( this, &QmitkSlicesInterpolator::OnToolManagerReferenceDataModified); } foreach (mitk::SliceNavigationController *slicer, m_ControllerToSliceObserverTag.keys()) { slicer->RemoveObserver(m_ControllerToDeleteObserverTag.take(slicer)); slicer->RemoveObserver(m_ControllerToTimeObserverTag.take(slicer)); slicer->RemoveObserver(m_ControllerToSliceObserverTag.take(slicer)); } ACTION_TO_SLICEDIMENSION.clear(); m_ToolManager = nullptr; m_Initialized = false; } QmitkSlicesInterpolator::~QmitkSlicesInterpolator() { if (m_Initialized) { // remove old observers Uninitialize(); } WaitForFutures(); if (m_DataStorage.IsNotNull()) { m_DataStorage->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1(this, &QmitkSlicesInterpolator::NodeRemoved) ); if (m_DataStorage->Exists(m_3DContourNode)) m_DataStorage->Remove(m_3DContourNode); if (m_DataStorage->Exists(m_InterpolatedSurfaceNode)) m_DataStorage->Remove(m_InterpolatedSurfaceNode); } // remove observer m_Interpolator->RemoveObserver(InterpolationAbortedObserverTag); m_Interpolator->RemoveObserver(InterpolationInfoChangedObserverTag); m_SurfaceInterpolator->RemoveObserver(SurfaceInterpolationInfoChangedObserverTag); delete m_Timer; } /** External enableization... */ void QmitkSlicesInterpolator::setEnabled(bool enable) { QWidget::setEnabled(enable); // Set the gui elements of the different interpolation modi enabled if (enable) { if (m_2DInterpolationEnabled) { this->Show2DInterpolationControls(true); m_Interpolator->Activate2DInterpolation(true); } else if (m_3DInterpolationEnabled) { this->Show3DInterpolationControls(true); this->Show3DInterpolationResult(true); } } // Set all gui elements of the interpolation disabled else { this->HideAllInterpolationControls(); this->Show3DInterpolationResult(false); } } void QmitkSlicesInterpolator::On2DInterpolationEnabled(bool status) { OnInterpolationActivated(status); m_Interpolator->Activate2DInterpolation(status); } void QmitkSlicesInterpolator::On3DInterpolationEnabled(bool status) { On3DInterpolationActivated(status); } void QmitkSlicesInterpolator::OnInterpolationDisabled(bool status) { if (status) { OnInterpolationActivated(!status); On3DInterpolationActivated(!status); this->Show3DInterpolationResult(false); } } void QmitkSlicesInterpolator::HideAllInterpolationControls() { this->Show2DInterpolationControls(false); this->Show3DInterpolationControls(false); } void QmitkSlicesInterpolator::Show2DInterpolationControls(bool show) { m_BtnApply2D->setVisible(show); m_BtnApplyForAllSlices2D->setVisible(show); } void QmitkSlicesInterpolator::Show3DInterpolationControls(bool show) { m_BtnApply3D->setVisible(show); // T28261 // m_BtnSuggestPlane->setVisible(show); m_ChkShowPositionNodes->setVisible(show); m_BtnReinit3DInterpolation->setVisible(show); } void QmitkSlicesInterpolator::OnInterpolationMethodChanged(int index) { switch (index) { case 0: // Disabled m_GroupBoxEnableExclusiveInterpolationMode->setTitle("Interpolation"); this->HideAllInterpolationControls(); this->OnInterpolationActivated(false); this->On3DInterpolationActivated(false); this->Show3DInterpolationResult(false); m_Interpolator->Activate2DInterpolation(false); break; case 1: // 2D m_GroupBoxEnableExclusiveInterpolationMode->setTitle("Interpolation (Enabled)"); this->HideAllInterpolationControls(); this->Show2DInterpolationControls(true); this->OnInterpolationActivated(true); this->On3DInterpolationActivated(false); m_Interpolator->Activate2DInterpolation(true); break; case 2: // 3D m_GroupBoxEnableExclusiveInterpolationMode->setTitle("Interpolation (Enabled)"); this->HideAllInterpolationControls(); this->Show3DInterpolationControls(true); this->OnInterpolationActivated(false); this->On3DInterpolationActivated(true); m_Interpolator->Activate2DInterpolation(false); break; default: MITK_ERROR << "Unknown interpolation method!"; m_CmbInterpolation->setCurrentIndex(0); break; } } void QmitkSlicesInterpolator::OnShowMarkers(bool state) { mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = m_DataStorage->GetSubset(mitk::NodePredicateProperty::New("isContourMarker", mitk::BoolProperty::New(true))); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { it->Value()->SetProperty("helper object", mitk::BoolProperty::New(!state)); } } void QmitkSlicesInterpolator::OnToolManagerWorkingDataModified() { if (m_ToolManager->GetWorkingData(0) != nullptr) { m_Segmentation = dynamic_cast(m_ToolManager->GetWorkingData(0)->GetData()); m_BtnReinit3DInterpolation->setEnabled(true); } else { // If no workingdata is set, remove the interpolation feedback this->GetDataStorage()->Remove(m_FeedbackNode); m_FeedbackNode->SetData(nullptr); this->GetDataStorage()->Remove(m_3DContourNode); m_3DContourNode->SetData(nullptr); this->GetDataStorage()->Remove(m_InterpolatedSurfaceNode); m_InterpolatedSurfaceNode->SetData(nullptr); m_BtnReinit3DInterpolation->setEnabled(false); return; } // Updating the current selected segmentation for the 3D interpolation SetCurrentContourListID(); if (m_2DInterpolationEnabled) { OnInterpolationActivated(true); // re-initialize if needed } this->CheckSupportedImageDimension(); } void QmitkSlicesInterpolator::OnToolManagerReferenceDataModified() { } void QmitkSlicesInterpolator::OnTimeChanged(itk::Object *sender, const itk::EventObject &e) { // Check if we really have a GeometryTimeEvent if (!dynamic_cast(&e)) return; mitk::SliceNavigationController *slicer = dynamic_cast(sender); Q_ASSERT(slicer); const auto timePoint = slicer->GetSelectedTimePoint(); m_TimePoints[slicer] = timePoint; m_SurfaceInterpolator->SetCurrentTimePoint(timePoint); if (m_LastSNC == slicer) { slicer->SendSlice(); // will trigger a new interpolation } } void QmitkSlicesInterpolator::OnSliceChanged(itk::Object *sender, const itk::EventObject &e) { // Check whether we really have a GeometrySliceEvent if (!dynamic_cast(&e)) return; mitk::SliceNavigationController *slicer = dynamic_cast(sender); if (TranslateAndInterpolateChangedSlice(e, slicer)) { slicer->GetRenderer()->RequestUpdate(); } } bool QmitkSlicesInterpolator::TranslateAndInterpolateChangedSlice(const itk::EventObject &e, mitk::SliceNavigationController *slicer) { if (!m_2DInterpolationEnabled) return false; try { const mitk::SliceNavigationController::GeometrySliceEvent &event = dynamic_cast(e); mitk::TimeGeometry *tsg = event.GetTimeGeometry(); if (tsg && m_TimePoints.contains(slicer) && tsg->IsValidTimePoint(m_TimePoints[slicer])) { mitk::SlicedGeometry3D *slicedGeometry = dynamic_cast(tsg->GetGeometryForTimePoint(m_TimePoints[slicer]).GetPointer()); if (slicedGeometry) { m_LastSNC = slicer; mitk::PlaneGeometry *plane = dynamic_cast(slicedGeometry->GetPlaneGeometry(event.GetPos())); if (plane) Interpolate(plane, m_TimePoints[slicer], slicer); return true; } } } catch (const std::bad_cast &) { return false; // so what } return false; } void QmitkSlicesInterpolator::Interpolate(mitk::PlaneGeometry *plane, mitk::TimePointType timePoint, mitk::SliceNavigationController *slicer) { if (m_ToolManager) { mitk::DataNode *node = m_ToolManager->GetWorkingData(0); if (node) { m_Segmentation = dynamic_cast(node->GetData()); if (m_Segmentation) { if (!m_Segmentation->GetTimeGeometry()->IsValidTimePoint(timePoint)) { MITK_WARN << "Cannot interpolate segmentation. Passed time point is not within the time bounds of WorkingImage. Time point: " << timePoint; return; } const auto timeStep = m_Segmentation->GetTimeGeometry()->TimePointToTimeStep(timePoint); int clickedSliceDimension(-1); int clickedSliceIndex(-1); // calculate real slice position, i.e. slice of the image mitk::SegTool2D::DetermineAffectedImageSlice(m_Segmentation, plane, clickedSliceDimension, clickedSliceIndex); mitk::Image::Pointer interpolation = m_Interpolator->Interpolate(clickedSliceDimension, clickedSliceIndex, plane, timeStep); m_FeedbackNode->SetData(interpolation); m_LastSNC = slicer; m_LastSliceIndex = clickedSliceIndex; } } } } void QmitkSlicesInterpolator::OnSurfaceInterpolationFinished() { mitk::Surface::Pointer interpolatedSurface = m_SurfaceInterpolator->GetInterpolationResult(); mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); - if (interpolatedSurface.IsNotNull() && workingNode && - workingNode->IsVisible( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2")))) + if (interpolatedSurface.IsNotNull() && workingNode && workingNode->IsVisible(nullptr)) { m_BtnApply3D->setEnabled(true); // T28261 // m_BtnSuggestPlane->setEnabled(true); m_InterpolatedSurfaceNode->SetData(interpolatedSurface); m_3DContourNode->SetData(m_SurfaceInterpolator->GetContoursAsSurface()); this->Show3DInterpolationResult(true); if (!m_DataStorage->Exists(m_InterpolatedSurfaceNode)) { m_DataStorage->Add(m_InterpolatedSurfaceNode); } if (!m_DataStorage->Exists(m_3DContourNode)) { m_DataStorage->Add(m_3DContourNode, workingNode); } } else if (interpolatedSurface.IsNull()) { m_BtnApply3D->setEnabled(false); // T28261 // m_BtnSuggestPlane->setEnabled(false); if (m_DataStorage->Exists(m_InterpolatedSurfaceNode)) { this->Show3DInterpolationResult(false); } } m_BtnReinit3DInterpolation->setEnabled(true); foreach (mitk::SliceNavigationController *slicer, m_ControllerToTimeObserverTag.keys()) { slicer->GetRenderer()->RequestUpdate(); } } void QmitkSlicesInterpolator::OnAcceptInterpolationClicked() { if (m_Segmentation && m_FeedbackNode->GetData()) { // Make sure that for reslicing and overwriting the same alogrithm is used. We can specify the mode of the vtk // reslicer vtkSmartPointer reslice = vtkSmartPointer::New(); // Set slice as input mitk::Image::Pointer slice = dynamic_cast(m_FeedbackNode->GetData()); reslice->SetInputSlice(slice->GetSliceData()->GetVtkImageAccessor(slice)->GetVtkImageData()); // set overwrite mode to true to write back to the image volume reslice->SetOverwriteMode(true); reslice->Modified(); const auto timePoint = m_LastSNC->GetSelectedTimePoint(); if (!m_Segmentation->GetTimeGeometry()->IsValidTimePoint(timePoint)) { MITK_WARN << "Cannot accept interpolation. Time point selected by SliceNavigationController is not within the time bounds of segmentation. Time point: " << timePoint; return; } mitk::ExtractSliceFilter::Pointer extractor = mitk::ExtractSliceFilter::New(reslice); extractor->SetInput(m_Segmentation); const auto timeStep = m_Segmentation->GetTimeGeometry()->TimePointToTimeStep(timePoint); extractor->SetTimeStep(timeStep); extractor->SetWorldGeometry(m_LastSNC->GetCurrentPlaneGeometry()); extractor->SetVtkOutputRequest(true); extractor->SetResliceTransformByGeometry(m_Segmentation->GetTimeGeometry()->GetGeometryForTimeStep(timeStep)); extractor->Modified(); extractor->Update(); // the image was modified within the pipeline, but not marked so m_Segmentation->Modified(); m_Segmentation->GetVtkImageData()->Modified(); m_FeedbackNode->SetData(nullptr); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSlicesInterpolator::AcceptAllInterpolations(mitk::SliceNavigationController *slicer) { /* * What exactly is done here: * 1. We create an empty diff image for the current segmentation * 2. All interpolated slices are written into the diff image * 3. Then the diffimage is applied to the original segmentation */ if (m_Segmentation) { mitk::Image::Pointer segmentation3D = m_Segmentation; unsigned int timeStep = 0; const auto timePoint = slicer->GetSelectedTimePoint(); if (4 == m_Segmentation->GetDimension()) { const auto* geometry = m_Segmentation->GetTimeGeometry(); if (!geometry->IsValidTimePoint(timePoint)) { MITK_WARN << "Cannot accept all interpolations. Time point selected by passed SliceNavigationController is not within the time bounds of segmentation. Time point: " << timePoint; return; } timeStep = geometry->TimePointToTimeStep(timePoint); auto timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(m_Segmentation); timeSelector->SetTimeNr(timeStep); timeSelector->Update(); segmentation3D = timeSelector->GetOutput(); } // Create an empty diff image for the undo operation auto diffImage = mitk::Image::New(); diffImage->Initialize(segmentation3D); // Create scope for ImageWriteAccessor so that the accessor is destroyed right after use { mitk::ImageWriteAccessor accessor(diffImage); // Set all pixels to zero auto pixelType = mitk::MakeScalarPixelType(); // For legacy purpose support former pixel type of segmentations (before multilabel) if (itk::IOComponentEnum::UCHAR == m_Segmentation->GetImageDescriptor()->GetChannelDescriptor().GetPixelType().GetComponentType()) pixelType = mitk::MakeScalarPixelType(); memset(accessor.GetData(), 0, pixelType.GetSize() * diffImage->GetDimension(0) * diffImage->GetDimension(1) * diffImage->GetDimension(2)); } // Since we need to shift the plane it must be clone so that the original plane isn't altered auto slicedGeometry = m_Segmentation->GetSlicedGeometry(); auto planeGeometry = slicer->GetCurrentPlaneGeometry()->Clone(); int sliceDimension = -1; int sliceIndex = -1; mitk::SegTool2D::DetermineAffectedImageSlice(m_Segmentation, planeGeometry, sliceDimension, sliceIndex); const auto numSlices = m_Segmentation->GetDimension(sliceDimension); mitk::ProgressBar::GetInstance()->AddStepsToDo(numSlices); std::atomic_uint totalChangedSlices; // Reuse interpolation algorithm instance for each slice to cache boundary calculations auto algorithm = mitk::ShapeBasedInterpolationAlgorithm::New(); // Distribute slice interpolations to multiple threads const auto numThreads = std::min(std::thread::hardware_concurrency(), numSlices); std::vector> sliceIndices(numThreads); for (std::remove_const_t sliceIndex = 0; sliceIndex < numSlices; ++sliceIndex) sliceIndices[sliceIndex % numThreads].push_back(sliceIndex); std::vector threads; threads.reserve(numThreads); // This lambda will be executed by the threads auto interpolate = [=, &interpolator = m_Interpolator, &totalChangedSlices](unsigned int threadIndex) { auto clonedPlaneGeometry = planeGeometry->Clone(); auto origin = clonedPlaneGeometry->GetOrigin(); for (auto sliceIndex : sliceIndices[threadIndex]) { slicedGeometry->WorldToIndex(origin, origin); origin[sliceDimension] = sliceIndex; slicedGeometry->IndexToWorld(origin, origin); clonedPlaneGeometry->SetOrigin(origin); auto interpolation = interpolator->Interpolate(sliceDimension, sliceIndex, clonedPlaneGeometry, timeStep, algorithm); if (interpolation.IsNotNull()) { // Setting up the reslicing pipeline which allows us to write the interpolation results back into the image volume auto reslicer = vtkSmartPointer::New(); // Set overwrite mode to true to write back to the image volume reslicer->SetInputSlice(interpolation->GetSliceData()->GetVtkImageAccessor(interpolation)->GetVtkImageData()); reslicer->SetOverwriteMode(true); reslicer->Modified(); auto diffSliceWriter = mitk::ExtractSliceFilter::New(reslicer); diffSliceWriter->SetInput(diffImage); diffSliceWriter->SetTimeStep(0); diffSliceWriter->SetWorldGeometry(clonedPlaneGeometry); diffSliceWriter->SetVtkOutputRequest(true); diffSliceWriter->SetResliceTransformByGeometry(diffImage->GetTimeGeometry()->GetGeometryForTimeStep(0)); diffSliceWriter->Modified(); diffSliceWriter->Update(); ++totalChangedSlices; } mitk::ProgressBar::GetInstance()->Progress(); } }; m_Interpolator->EnableSliceImageCache(); for (std::remove_const_t threadIndex = 0; threadIndex < numThreads; ++threadIndex) threads.emplace_back(interpolate, threadIndex); // Run the interpolation for (auto& thread : threads) thread.join(); m_Interpolator->DisableSliceImageCache(); if (totalChangedSlices > 0) { // Create do/undo operations auto* doOp = new mitk::ApplyDiffImageOperation(mitk::OpTEST, m_Segmentation, diffImage, timeStep); auto* undoOp = new mitk::ApplyDiffImageOperation(mitk::OpTEST, m_Segmentation, diffImage, timeStep); undoOp->SetFactor(-1.0); auto comment = "Confirm all interpolations (" + std::to_string(totalChangedSlices) + ")"; auto* undoStackItem = new mitk::OperationEvent(mitk::DiffImageApplier::GetInstanceForUndo(), doOp, undoOp, comment); mitk::OperationEvent::IncCurrGroupEventId(); mitk::OperationEvent::IncCurrObjectEventId(); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent(undoStackItem); // Apply the changes to the original image mitk::DiffImageApplier::GetInstanceForUndo()->ExecuteOperation(doOp); } m_FeedbackNode->SetData(nullptr); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSlicesInterpolator::FinishInterpolation(mitk::SliceNavigationController *slicer) { // this redirect is for calling from outside if (slicer == nullptr) OnAcceptAllInterpolationsClicked(); else AcceptAllInterpolations(slicer); } void QmitkSlicesInterpolator::OnAcceptAllInterpolationsClicked() { QMenu orientationPopup(this); std::map::const_iterator it; for (it = ACTION_TO_SLICEDIMENSION.begin(); it != ACTION_TO_SLICEDIMENSION.end(); it++) orientationPopup.addAction(it->first); connect(&orientationPopup, SIGNAL(triggered(QAction *)), this, SLOT(OnAcceptAllPopupActivated(QAction *))); orientationPopup.exec(QCursor::pos()); } void QmitkSlicesInterpolator::OnAccept3DInterpolationClicked() { auto referenceImage = GetData(m_ToolManager->GetReferenceData(0)); auto* segmentationDataNode = m_ToolManager->GetWorkingData(0); auto segmentation = GetData(segmentationDataNode); if (referenceImage.IsNull() || segmentation.IsNull()) return; const auto* segmentationGeometry = segmentation->GetTimeGeometry(); const auto timePoint = m_LastSNC->GetSelectedTimePoint(); if (!referenceImage->GetTimeGeometry()->IsValidTimePoint(timePoint) || !segmentationGeometry->IsValidTimePoint(timePoint)) { MITK_WARN << "Cannot accept interpolation. Current time point is not within the time bounds of the patient image and segmentation."; return; } auto interpolatedSurface = GetData(m_InterpolatedSurfaceNode); if (interpolatedSurface.IsNull()) return; auto surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); surfaceToImageFilter->SetImage(referenceImage); surfaceToImageFilter->SetMakeOutputBinary(true); surfaceToImageFilter->SetUShortBinaryPixelType(itk::IOComponentEnum::USHORT == segmentation->GetPixelType().GetComponentType()); surfaceToImageFilter->SetInput(interpolatedSurface); surfaceToImageFilter->Update(); mitk::Image::Pointer interpolatedSegmentation = surfaceToImageFilter->GetOutput(); auto timeStep = interpolatedSegmentation->GetTimeGeometry()->TimePointToTimeStep(timePoint); mitk::ImageReadAccessor readAccessor(interpolatedSegmentation, interpolatedSegmentation->GetVolumeData(timeStep)); const auto* dataPointer = readAccessor.GetData(); if (nullptr == dataPointer) return; timeStep = segmentationGeometry->TimePointToTimeStep(timePoint); segmentation->SetVolume(dataPointer, timeStep, 0); m_CmbInterpolation->setCurrentIndex(0); this->Show3DInterpolationResult(false); std::string name = segmentationDataNode->GetName() + "_3D-interpolation"; mitk::TimeBounds timeBounds; if (1 < interpolatedSurface->GetTimeSteps()) { name += "_t" + std::to_string(timeStep); auto* polyData = vtkPolyData::New(); polyData->DeepCopy(interpolatedSurface->GetVtkPolyData(timeStep)); auto surface = mitk::Surface::New(); surface->SetVtkPolyData(polyData); interpolatedSurface = surface; timeBounds = segmentationGeometry->GetTimeBounds(timeStep); } else { timeBounds = segmentationGeometry->GetTimeBounds(0); } auto* surfaceGeometry = static_cast(interpolatedSurface->GetTimeGeometry()); surfaceGeometry->SetFirstTimePoint(timeBounds[0]); surfaceGeometry->SetStepDuration(timeBounds[1] - timeBounds[0]); // Typical file formats for surfaces do not save any time-related information. As a workaround at least for MITK scene files, we have the // possibility to seralize this information as properties. interpolatedSurface->SetProperty("ProportionalTimeGeometry.FirstTimePoint", mitk::FloatProperty::New(surfaceGeometry->GetFirstTimePoint())); interpolatedSurface->SetProperty("ProportionalTimeGeometry.StepDuration", mitk::FloatProperty::New(surfaceGeometry->GetStepDuration())); auto interpolatedSurfaceDataNode = mitk::DataNode::New(); interpolatedSurfaceDataNode->SetData(interpolatedSurface); interpolatedSurfaceDataNode->SetName(name); interpolatedSurfaceDataNode->SetOpacity(0.7f); std::array rgb; segmentationDataNode->GetColor(rgb.data()); interpolatedSurfaceDataNode->SetColor(rgb.data()); m_DataStorage->Add(interpolatedSurfaceDataNode, segmentationDataNode); } void ::QmitkSlicesInterpolator::OnSuggestPlaneClicked() { if (m_PlaneWatcher.isRunning()) m_PlaneWatcher.waitForFinished(); m_PlaneFuture = QtConcurrent::run(this, &QmitkSlicesInterpolator::RunPlaneSuggestion); m_PlaneWatcher.setFuture(m_PlaneFuture); } void ::QmitkSlicesInterpolator::RunPlaneSuggestion() { if (m_FirstRun) mitk::ProgressBar::GetInstance()->AddStepsToDo(7); else mitk::ProgressBar::GetInstance()->AddStepsToDo(3); m_EdgeDetector->SetSegmentationMask(m_Segmentation); m_EdgeDetector->SetInput(dynamic_cast(m_ToolManager->GetReferenceData(0)->GetData())); m_EdgeDetector->Update(); mitk::UnstructuredGrid::Pointer uGrid = mitk::UnstructuredGrid::New(); uGrid->SetVtkUnstructuredGrid(m_EdgeDetector->GetOutput()->GetVtkUnstructuredGrid()); mitk::ProgressBar::GetInstance()->Progress(); mitk::Surface::Pointer surface = dynamic_cast(m_InterpolatedSurfaceNode->GetData()); vtkSmartPointer vtkpoly = surface->GetVtkPolyData(); vtkSmartPointer vtkpoints = vtkpoly->GetPoints(); vtkSmartPointer vGrid = vtkSmartPointer::New(); vtkSmartPointer verts = vtkSmartPointer::New(); verts->GetPointIds()->SetNumberOfIds(vtkpoints->GetNumberOfPoints()); for (int i = 0; i < vtkpoints->GetNumberOfPoints(); i++) { verts->GetPointIds()->SetId(i, i); } vGrid->Allocate(1); vGrid->InsertNextCell(verts->GetCellType(), verts->GetPointIds()); vGrid->SetPoints(vtkpoints); mitk::UnstructuredGrid::Pointer interpolationGrid = mitk::UnstructuredGrid::New(); interpolationGrid->SetVtkUnstructuredGrid(vGrid); m_PointScorer->SetInput(0, uGrid); m_PointScorer->SetInput(1, interpolationGrid); m_PointScorer->Update(); mitk::UnstructuredGrid::Pointer scoredGrid = mitk::UnstructuredGrid::New(); scoredGrid = m_PointScorer->GetOutput(); mitk::ProgressBar::GetInstance()->Progress(); double spacing = mitk::SurfaceInterpolationController::GetInstance()->GetDistanceImageSpacing(); mitk::UnstructuredGridClusteringFilter::Pointer clusterFilter = mitk::UnstructuredGridClusteringFilter::New(); clusterFilter->SetInput(scoredGrid); clusterFilter->SetMeshing(false); clusterFilter->SetMinPts(4); clusterFilter->Seteps(spacing); clusterFilter->Update(); mitk::ProgressBar::GetInstance()->Progress(); // Create plane suggestion + // TODO: "stdmulti.widget0" needs to be removed, see T29203 + // Currently this feature is disabled, so we don't care, see T28261 mitk::BaseRenderer::Pointer br = mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0")); mitk::PlaneProposer planeProposer; std::vector grids = clusterFilter->GetAllClusters(); planeProposer.SetUnstructuredGrids(grids); mitk::SliceNavigationController::Pointer snc = br->GetSliceNavigationController(); planeProposer.SetSliceNavigationController(snc); planeProposer.SetUseDistances(true); try { planeProposer.CreatePlaneInfo(); } catch (const mitk::Exception &e) { MITK_ERROR << e.what(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FirstRun = false; } void QmitkSlicesInterpolator::OnReinit3DInterpolation() { mitk::NodePredicateProperty::Pointer pred = mitk::NodePredicateProperty::New("3DContourContainer", mitk::BoolProperty::New(true)); mitk::DataStorage::SetOfObjects::ConstPointer contourNodes = m_DataStorage->GetDerivations(m_ToolManager->GetWorkingData(0), pred); if (contourNodes->Size() != 0) { m_BtnApply3D->setEnabled(true); m_3DContourNode = contourNodes->at(0); mitk::Surface::Pointer contours = dynamic_cast(m_3DContourNode->GetData()); if (contours) mitk::SurfaceInterpolationController::GetInstance()->ReinitializeInterpolation(contours); m_BtnReinit3DInterpolation->setEnabled(false); } else { m_BtnApply3D->setEnabled(false); QMessageBox errorInfo; errorInfo.setWindowTitle("Reinitialize surface interpolation"); errorInfo.setIcon(QMessageBox::Information); errorInfo.setText("No contours available for the selected segmentation!"); errorInfo.exec(); } } void QmitkSlicesInterpolator::OnAcceptAllPopupActivated(QAction *action) { try { std::map::const_iterator iter = ACTION_TO_SLICEDIMENSION.find(action); if (iter != ACTION_TO_SLICEDIMENSION.end()) { mitk::SliceNavigationController *slicer = iter->second; AcceptAllInterpolations(slicer); } } catch (...) { /* Showing message box with possible memory error */ QMessageBox errorInfo; errorInfo.setWindowTitle("Interpolation Process"); errorInfo.setIcon(QMessageBox::Critical); errorInfo.setText("An error occurred during interpolation. Possible cause: Not enough memory!"); errorInfo.exec(); // additional error message on std::cerr std::cerr << "Ill construction in " __FILE__ " l. " << __LINE__ << std::endl; } } void QmitkSlicesInterpolator::OnInterpolationActivated(bool on) { m_2DInterpolationEnabled = on; try { if (m_DataStorage.IsNotNull()) { if (on && !m_DataStorage->Exists(m_FeedbackNode)) { m_DataStorage->Add(m_FeedbackNode); } } } catch (...) { // don't care (double add/remove) } if (m_ToolManager) { mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); mitk::DataNode *referenceNode = m_ToolManager->GetReferenceData(0); QWidget::setEnabled(workingNode != nullptr); m_BtnApply2D->setEnabled(on); m_FeedbackNode->SetVisibility(on); if (!on) { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return; } if (workingNode) { mitk::Image *segmentation = dynamic_cast(workingNode->GetData()); if (segmentation) { m_Interpolator->SetSegmentationVolume(segmentation); if (referenceNode) { mitk::Image *referenceImage = dynamic_cast(referenceNode->GetData()); m_Interpolator->SetReferenceVolume(referenceImage); // may be nullptr } } } } UpdateVisibleSuggestion(); } void QmitkSlicesInterpolator::Run3DInterpolation() { m_SurfaceInterpolator->Interpolate(); } void QmitkSlicesInterpolator::StartUpdateInterpolationTimer() { m_Timer->start(500); } void QmitkSlicesInterpolator::StopUpdateInterpolationTimer() { m_Timer->stop(); m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(SURFACE_COLOR_RGB)); - mitk::RenderingManager::GetInstance()->RequestUpdate( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetRenderWindow()); + + mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS); } void QmitkSlicesInterpolator::ChangeSurfaceColor() { float currentColor[3]; m_InterpolatedSurfaceNode->GetColor(currentColor); if (currentColor[2] == SURFACE_COLOR_RGB[2]) { m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 1.0f)); } else { m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(SURFACE_COLOR_RGB)); } m_InterpolatedSurfaceNode->Update(); - mitk::RenderingManager::GetInstance()->RequestUpdate( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetRenderWindow()); + + mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS); } void QmitkSlicesInterpolator::On3DInterpolationActivated(bool on) { m_3DInterpolationEnabled = on; this->CheckSupportedImageDimension(); try { if (m_DataStorage.IsNotNull() && m_ToolManager && m_3DInterpolationEnabled) { mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); - if (workingNode) + if (nullptr != workingNode) { - if ((workingNode->IsVisible(mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2"))))) + if (workingNode->IsVisible(nullptr)) { int ret = QMessageBox::Yes; if (m_SurfaceInterpolator->EstimatePortionOfNeededMemory() > 0.5) { QMessageBox msgBox; msgBox.setText("Due to short handed system memory the 3D interpolation may be very slow!"); msgBox.setInformativeText("Are you sure you want to activate the 3D interpolation?"); msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes); ret = msgBox.exec(); } if (m_Watcher.isRunning()) m_Watcher.waitForFinished(); if (ret == QMessageBox::Yes) { m_Future = QtConcurrent::run(this, &QmitkSlicesInterpolator::Run3DInterpolation); m_Watcher.setFuture(m_Future); } else { m_CmbInterpolation->setCurrentIndex(0); } } } else { QWidget::setEnabled(false); m_ChkShowPositionNodes->setEnabled(m_3DInterpolationEnabled); } } if (!m_3DInterpolationEnabled) { this->Show3DInterpolationResult(false); m_BtnApply3D->setEnabled(m_3DInterpolationEnabled); // T28261 // m_BtnSuggestPlane->setEnabled(m_3DInterpolationEnabled); } } catch (...) { MITK_ERROR << "Error with 3D surface interpolation!"; } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSlicesInterpolator::EnableInterpolation(bool on) { // only to be called from the outside world // just a redirection to OnInterpolationActivated OnInterpolationActivated(on); } void QmitkSlicesInterpolator::Enable3DInterpolation(bool on) { // only to be called from the outside world // just a redirection to OnInterpolationActivated On3DInterpolationActivated(on); } void QmitkSlicesInterpolator::UpdateVisibleSuggestion() { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSlicesInterpolator::OnInterpolationInfoChanged(const itk::EventObject & /*e*/) { // something (e.g. undo) changed the interpolation info, we should refresh our display UpdateVisibleSuggestion(); } void QmitkSlicesInterpolator::OnInterpolationAborted(const itk::EventObject& /*e*/) { m_CmbInterpolation->setCurrentIndex(0); m_FeedbackNode->SetData(nullptr); } void QmitkSlicesInterpolator::OnSurfaceInterpolationInfoChanged(const itk::EventObject & /*e*/) { if (m_3DInterpolationEnabled) { if (m_Watcher.isRunning()) m_Watcher.waitForFinished(); m_Future = QtConcurrent::run(this, &QmitkSlicesInterpolator::Run3DInterpolation); m_Watcher.setFuture(m_Future); } } void QmitkSlicesInterpolator::SetCurrentContourListID() { // New ContourList = hide current interpolation Show3DInterpolationResult(false); if (m_DataStorage.IsNotNull() && m_ToolManager && m_LastSNC) { mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); if (workingNode) { QWidget::setEnabled(true); const auto timePoint = m_LastSNC->GetSelectedTimePoint(); // In case the time is not valid use 0 to access the time geometry of the working node unsigned int time_position = 0; if (!workingNode->GetData()->GetTimeGeometry()->IsValidTimePoint(timePoint)) { MITK_WARN << "Cannot accept interpolation. Time point selected by SliceNavigationController is not within the time bounds of WorkingImage. Time point: " << timePoint; return; } time_position = workingNode->GetData()->GetTimeGeometry()->TimePointToTimeStep(timePoint); mitk::Vector3D spacing = workingNode->GetData()->GetGeometry(time_position)->GetSpacing(); double minSpacing(100); double maxSpacing(0); for (int i = 0; i < 3; i++) { if (spacing[i] < minSpacing) { minSpacing = spacing[i]; } if (spacing[i] > maxSpacing) { maxSpacing = spacing[i]; } } m_SurfaceInterpolator->SetMaxSpacing(maxSpacing); m_SurfaceInterpolator->SetMinSpacing(minSpacing); m_SurfaceInterpolator->SetDistanceImageVolume(50000); mitk::Image *segmentationImage = dynamic_cast(workingNode->GetData()); m_SurfaceInterpolator->SetCurrentInterpolationSession(segmentationImage); m_SurfaceInterpolator->SetCurrentTimePoint(timePoint); if (m_3DInterpolationEnabled) { if (m_Watcher.isRunning()) m_Watcher.waitForFinished(); m_Future = QtConcurrent::run(this, &QmitkSlicesInterpolator::Run3DInterpolation); m_Watcher.setFuture(m_Future); } } else { QWidget::setEnabled(false); } } } void QmitkSlicesInterpolator::Show3DInterpolationResult(bool status) { if (m_InterpolatedSurfaceNode.IsNotNull()) m_InterpolatedSurfaceNode->SetVisibility(status); if (m_3DContourNode.IsNotNull()) - m_3DContourNode->SetVisibility( - status, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); + { + auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows(); + for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit) + { + m_3DContourNode->SetVisibility(status, mapit->second); + } + } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSlicesInterpolator::CheckSupportedImageDimension() { if (m_ToolManager->GetWorkingData(0)) m_Segmentation = dynamic_cast(m_ToolManager->GetWorkingData(0)->GetData()); /*if (m_3DInterpolationEnabled && m_Segmentation && m_Segmentation->GetDimension() != 3) { QMessageBox info; info.setWindowTitle("3D Interpolation Process"); info.setIcon(QMessageBox::Information); info.setText("3D Interpolation is only supported for 3D images at the moment!"); info.exec(); m_CmbInterpolation->setCurrentIndex(0); }*/ } void QmitkSlicesInterpolator::OnSliceNavigationControllerDeleted(const itk::Object *sender, const itk::EventObject & /*e*/) { // Don't know how to avoid const_cast here?! mitk::SliceNavigationController *slicer = dynamic_cast(const_cast(sender)); if (slicer) { m_ControllerToTimeObserverTag.remove(slicer); m_ControllerToSliceObserverTag.remove(slicer); m_ControllerToDeleteObserverTag.remove(slicer); } } void QmitkSlicesInterpolator::WaitForFutures() { if (m_Watcher.isRunning()) { m_Watcher.waitForFinished(); } if (m_PlaneWatcher.isRunning()) { m_PlaneWatcher.waitForFinished(); } } void QmitkSlicesInterpolator::NodeRemoved(const mitk::DataNode* node) { if ((m_ToolManager && m_ToolManager->GetWorkingData(0) == node) || node == m_3DContourNode || node == m_FeedbackNode || node == m_InterpolatedSurfaceNode) { WaitForFutures(); } } diff --git a/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.cpp b/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.cpp index 8179d37041..135bcb9362 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.cpp +++ b/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.cpp @@ -1,353 +1,350 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSurfaceBasedInterpolatorWidget.h" #include "mitkColorProperty.h" #include "mitkInteractionConst.h" #include "mitkOperationEvent.h" #include "mitkProgressBar.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkSegTool2D.h" #include "mitkSliceNavigationController.h" #include "mitkSurfaceToImageFilter.h" #include "mitkUndoController.h" #include "mitkVtkRepresentationProperty.h" #include #include #include #include QmitkSurfaceBasedInterpolatorWidget::QmitkSurfaceBasedInterpolatorWidget(QWidget *parent, const char * /*name*/) : QWidget(parent), m_SurfaceBasedInterpolatorController(mitk::SurfaceBasedInterpolationController::GetInstance()), m_ToolManager(nullptr), m_Activated(false), m_DataStorage(nullptr) { m_Controls.setupUi(this); m_ToolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); m_ToolManager->WorkingDataChanged += mitk::MessageDelegate( this, &QmitkSurfaceBasedInterpolatorWidget::OnToolManagerWorkingDataModified); connect(m_Controls.m_btStart, SIGNAL(toggled(bool)), this, SLOT(OnToggleWidgetActivation(bool))); connect(m_Controls.m_btAccept, SIGNAL(clicked()), this, SLOT(OnAcceptInterpolationClicked())); connect(m_Controls.m_cbShowPositionNodes, SIGNAL(toggled(bool)), this, SLOT(OnShowMarkers(bool))); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSurfaceBasedInterpolatorWidget::OnSurfaceInterpolationInfoChanged); m_SurfaceInterpolationInfoChangedObserverTag = m_SurfaceBasedInterpolatorController->AddObserver(itk::ModifiedEvent(), command); m_InterpolatedSurfaceNode = mitk::DataNode::New(); m_InterpolatedSurfaceNode->SetName("Surface Interpolation feedback"); m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(255.0, 255.0, 0.0)); m_InterpolatedSurfaceNode->SetProperty("opacity", mitk::FloatProperty::New(0.5)); m_InterpolatedSurfaceNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_InterpolatedSurfaceNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_InterpolatedSurfaceNode->SetVisibility(false); m_3DContourNode = mitk::DataNode::New(); m_3DContourNode->SetName("Drawn Contours"); m_3DContourNode->SetProperty("color", mitk::ColorProperty::New(0.0, 0.0, 0.0)); m_3DContourNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_3DContourNode->SetProperty("material.representation", mitk::VtkRepresentationProperty::New(VTK_WIREFRAME)); m_3DContourNode->SetProperty("material.wireframeLineWidth", mitk::FloatProperty::New(2.0f)); m_3DContourNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2"))); - m_3DContourNode->SetVisibility( - false, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); - + m_3DContourNode->SetVisibility(false); connect(&m_Watcher, SIGNAL(started()), this, SLOT(StartUpdateInterpolationTimer())); connect(&m_Watcher, SIGNAL(finished()), this, SLOT(OnSurfaceInterpolationFinished())); connect(&m_Watcher, SIGNAL(finished()), this, SLOT(StopUpdateInterpolationTimer())); m_Timer = new QTimer(this); connect(m_Timer, SIGNAL(timeout()), this, SLOT(ChangeSurfaceColor())); m_Controls.m_btAccept->setEnabled(false); m_Controls.m_cbShowPositionNodes->setEnabled(false); this->setEnabled(false); } void QmitkSurfaceBasedInterpolatorWidget::SetDataStorage(mitk::DataStorage &storage) { m_DataStorage = &storage; } QmitkSurfaceBasedInterpolatorWidget::~QmitkSurfaceBasedInterpolatorWidget() { m_ToolManager->WorkingDataChanged -= mitk::MessageDelegate( this, &QmitkSurfaceBasedInterpolatorWidget::OnToolManagerWorkingDataModified); if (m_DataStorage->Exists(m_3DContourNode)) m_DataStorage->Remove(m_3DContourNode); if (m_DataStorage->Exists(m_InterpolatedSurfaceNode)) m_DataStorage->Remove(m_InterpolatedSurfaceNode); // remove observer m_SurfaceBasedInterpolatorController->RemoveObserver(m_SurfaceInterpolationInfoChangedObserverTag); delete m_Timer; } void QmitkSurfaceBasedInterpolatorWidget::ShowInterpolationResult(bool status) { if (m_InterpolatedSurfaceNode.IsNotNull()) m_InterpolatedSurfaceNode->SetVisibility(status); if (m_3DContourNode.IsNotNull()) - m_3DContourNode->SetVisibility( - status, mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); + { + auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows(); + for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit) + { + m_3DContourNode->SetVisibility(status, mapit->second); + } + } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSurfaceBasedInterpolatorWidget::OnSurfaceInterpolationFinished() { mitk::Surface::Pointer interpolatedSurface = m_SurfaceBasedInterpolatorController->GetInterpolationResult(); if (interpolatedSurface.IsNotNull()) { m_InterpolatedSurfaceNode->SetData(interpolatedSurface); m_3DContourNode->SetData(m_SurfaceBasedInterpolatorController->GetContoursAsSurface()); this->ShowInterpolationResult(true); } else { m_InterpolatedSurfaceNode->SetData(nullptr); m_3DContourNode->SetData(nullptr); this->ShowInterpolationResult(false); } } void QmitkSurfaceBasedInterpolatorWidget::OnShowMarkers(bool state) { mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = m_DataStorage->GetSubset(mitk::NodePredicateProperty::New("isContourMarker", mitk::BoolProperty::New(true))); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { it->Value()->SetProperty("helper object", mitk::BoolProperty::New(!state)); } mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = m_ToolManager->GetTools().size(); for (unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(m_ToolManager->GetToolById(i)); if (manualSegmentationTool) { manualSegmentationTool->SetShowMarkerNodes(state); } } } void QmitkSurfaceBasedInterpolatorWidget::StartUpdateInterpolationTimer() { m_Timer->start(500); } void QmitkSurfaceBasedInterpolatorWidget::StopUpdateInterpolationTimer() { m_Timer->stop(); m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(255.0, 255.0, 0.0)); - mitk::RenderingManager::GetInstance()->RequestUpdate( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetRenderWindow()); + + mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS); } void QmitkSurfaceBasedInterpolatorWidget::ChangeSurfaceColor() { float currentColor[3]; m_InterpolatedSurfaceNode->GetColor(currentColor); float yellow[3] = {255.0, 255.0, 0.0}; if (currentColor[2] == yellow[2]) { m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(255.0, 255.0, 255.0)); } else { m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(yellow)); } m_InterpolatedSurfaceNode->Update(); - mitk::RenderingManager::GetInstance()->RequestUpdate( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetRenderWindow()); + + mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS); } void QmitkSurfaceBasedInterpolatorWidget::OnToolManagerWorkingDataModified() { mitk::DataNode *workingNode = this->m_ToolManager->GetWorkingData(0); if (!workingNode) { this->setEnabled(false); return; } mitk::LabelSetImage *workingImage = dynamic_cast(workingNode->GetData()); // TODO adapt tool manager so that this check is done there, e.g. convenience function // Q_ASSERT(workingImage); if (!workingImage) { this->setEnabled(false); return; } if (workingImage->GetDimension() > 4 || workingImage->GetDimension() < 3) { this->setEnabled(false); return; } m_WorkingImage = workingImage; this->setEnabled(true); } void QmitkSurfaceBasedInterpolatorWidget::OnRunInterpolation() { m_SurfaceBasedInterpolatorController->Interpolate(); } void QmitkSurfaceBasedInterpolatorWidget::OnToggleWidgetActivation(bool enabled) { Q_ASSERT(m_ToolManager); mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); if (!workingNode) return; m_Controls.m_btAccept->setEnabled(enabled); m_Controls.m_cbShowPositionNodes->setEnabled(enabled); if (enabled) m_Controls.m_btStart->setText("Stop"); else m_Controls.m_btStart->setText("Start"); for (unsigned int i = 0; i < m_ToolManager->GetTools().size(); i++) { mitk::SegTool2D *tool = dynamic_cast(m_ToolManager->GetToolById(i)); if (tool) tool->SetEnable3DInterpolation(enabled); } if (enabled) { if (!m_DataStorage->Exists(m_InterpolatedSurfaceNode)) { m_DataStorage->Add(m_InterpolatedSurfaceNode); } if (!m_DataStorage->Exists(m_3DContourNode)) { m_DataStorage->Add(m_3DContourNode); } mitk::Vector3D spacing = m_WorkingImage->GetGeometry(0)->GetSpacing(); double minSpacing(100); double maxSpacing(0); for (int i = 0; i < 3; i++) { if (spacing[i] < minSpacing) { minSpacing = spacing[i]; } else if (spacing[i] > maxSpacing) { maxSpacing = spacing[i]; } } m_SurfaceBasedInterpolatorController->SetWorkingImage(m_WorkingImage); m_SurfaceBasedInterpolatorController->SetActiveLabel(m_WorkingImage->GetActiveLabel()->GetValue()); m_SurfaceBasedInterpolatorController->SetMaxSpacing(maxSpacing); m_SurfaceBasedInterpolatorController->SetMinSpacing(minSpacing); m_SurfaceBasedInterpolatorController->SetDistanceImageVolume(50000); int ret = QMessageBox::Yes; if (m_SurfaceBasedInterpolatorController->EstimatePortionOfNeededMemory() > 0.5) { QMessageBox msgBox; msgBox.setText("Due to short handed system memory the 3D interpolation may be very slow!"); msgBox.setInformativeText("Are you sure you want to activate the 3D interpolation?"); msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes); ret = msgBox.exec(); } if (m_Watcher.isRunning()) m_Watcher.waitForFinished(); if (ret == QMessageBox::Yes) { m_Future = QtConcurrent::run(this, &QmitkSurfaceBasedInterpolatorWidget::OnRunInterpolation); m_Watcher.setFuture(m_Future); } } else { if (m_DataStorage->Exists(m_InterpolatedSurfaceNode)) { m_DataStorage->Remove(m_InterpolatedSurfaceNode); } if (m_DataStorage->Exists(m_3DContourNode)) { m_DataStorage->Remove(m_3DContourNode); } mitk::UndoController::GetCurrentUndoModel()->Clear(); } m_Activated = enabled; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSurfaceBasedInterpolatorWidget::OnAcceptInterpolationClicked() { if (m_InterpolatedSurfaceNode.IsNotNull() && m_InterpolatedSurfaceNode->GetData()) { // m_WorkingImage->SurfaceStamp(dynamic_cast(m_InterpolatedSurfaceNode->GetData()), false); this->ShowInterpolationResult(false); } } void QmitkSurfaceBasedInterpolatorWidget::OnSurfaceInterpolationInfoChanged(const itk::EventObject & /*e*/) { if (m_Activated) { if (m_Watcher.isRunning()) m_Watcher.waitForFinished(); m_Future = QtConcurrent::run(this, &QmitkSurfaceBasedInterpolatorWidget::OnRunInterpolation); m_Watcher.setFuture(m_Future); } } diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp index 2d42898731..7016cc6971 100755 --- a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp +++ b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp @@ -1,683 +1,622 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ //#define MBILOG_ENABLE_DEBUG 1 #include #include "QmitkToolSelectionBox.h" #include "QmitkToolGUI.h" #include "mitkBaseRenderer.h" #include #include #include #include #include #include #include #include "usModuleResource.h" #include "usModuleResourceStream.h" #include "mitkToolManagerProvider.h" QmitkToolSelectionBox::QmitkToolSelectionBox(QWidget *parent, mitk::DataStorage *) : QWidget(parent), m_SelfCall(false), m_DisplayedGroups("default"), m_LayoutColumns(2), m_ShowNames(true), m_GenerateAccelerators(false), m_ToolGUIWidget(nullptr), m_LastToolGUI(nullptr), m_ToolButtonGroup(nullptr), - m_ButtonLayout(nullptr), - m_EnabledMode(EnabledWithReferenceAndWorkingDataVisible) + m_ButtonLayout(nullptr) { QFont currentFont = QWidget::font(); currentFont.setBold(true); QWidget::setFont(currentFont); m_ToolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); // QButtonGroup m_ToolButtonGroup = new QButtonGroup(this); // some features of QButtonGroup m_ToolButtonGroup->setExclusive(false); // mutually exclusive toggle buttons RecreateButtons(); QWidget::setContentsMargins(0, 0, 0, 0); if (layout() != nullptr) { layout()->setContentsMargins(0, 0, 0, 0); } // reactions to signals connect(m_ToolButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(toolButtonClicked(int))); // reactions to ToolManager events m_ToolManager->ActiveToolChanged += mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerToolModified); m_ToolManager->ReferenceDataChanged += mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified); m_ToolManager->WorkingDataChanged += mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified); // show active tool SetOrUnsetButtonForActiveTool(); QWidget::setEnabled(false); } QmitkToolSelectionBox::~QmitkToolSelectionBox() { m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerToolModified); m_ToolManager->ReferenceDataChanged -= mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified); m_ToolManager->WorkingDataChanged -= mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified); } -void QmitkToolSelectionBox::SetEnabledMode(EnabledMode mode) -{ - m_EnabledMode = mode; - SetGUIEnabledAccordingToToolManagerState(); -} - mitk::ToolManager *QmitkToolSelectionBox::GetToolManager() { return m_ToolManager; } void QmitkToolSelectionBox::SetToolManager( mitk::ToolManager &newManager) // no nullptr pointer allowed here, a manager is required { // say bye to the old manager m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerToolModified); m_ToolManager->ReferenceDataChanged -= mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified); m_ToolManager->WorkingDataChanged -= mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified); if (QWidget::isEnabled()) { m_ToolManager->UnregisterClient(); } m_ToolManager = &newManager; RecreateButtons(); // greet the new one m_ToolManager->ActiveToolChanged += mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerToolModified); m_ToolManager->ReferenceDataChanged += mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified); m_ToolManager->WorkingDataChanged += mitk::MessageDelegate(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified); if (QWidget::isEnabled()) { m_ToolManager->RegisterClient(); } // ask the new one what the situation is like SetOrUnsetButtonForActiveTool(); } void QmitkToolSelectionBox::toolButtonClicked(int id) { if (!QWidget::isEnabled()) return; // this method could be triggered from the constructor, when we are still disabled MITK_DEBUG << "toolButtonClicked(" << id << "): id translates to tool ID " << m_ToolIDForButtonID[id]; QToolButton *toolButton = dynamic_cast(m_ToolButtonGroup->buttons().at(id)); if (toolButton) { if ((m_ButtonIDForToolID.find(m_ToolManager->GetActiveToolID()) != m_ButtonIDForToolID.end()) // if we have this tool in our box && (m_ButtonIDForToolID[m_ToolManager->GetActiveToolID()] == id)) // the tool corresponding to this button is already active { // disable this button, disable all tools toolButton->setChecked(false); m_ToolManager->ActivateTool(-1); // disable everything } else { // enable the corresponding tool m_SelfCall = true; m_ToolManager->ActivateTool(m_ToolIDForButtonID[id]); m_SelfCall = false; } } } void QmitkToolSelectionBox::OnToolManagerToolModified() { SetOrUnsetButtonForActiveTool(); } void QmitkToolSelectionBox::SetOrUnsetButtonForActiveTool() { // we want to emit a signal in any case, whether we selected ourselves or somebody else changes "our" tool manager. // --> emit before check on m_SelfCall int id = m_ToolManager->GetActiveToolID(); // don't emit signal for shape model tools bool emitSignal = true; mitk::Tool *tool = m_ToolManager->GetActiveTool(); if (tool && std::string(tool->GetGroup()) == "organ_segmentation") emitSignal = false; if (emitSignal) emit ToolSelected(id); // delete old GUI (if any) if (m_LastToolGUI && m_ToolGUIWidget) { if (m_ToolGUIWidget->layout()) { m_ToolGUIWidget->layout()->removeWidget(m_LastToolGUI); } m_LastToolGUI->setParent(nullptr); delete m_LastToolGUI; // will hopefully notify parent and layouts m_LastToolGUI = nullptr; QLayout *layout = m_ToolGUIWidget->layout(); if (layout) { layout->activate(); } } QToolButton *toolButton(nullptr); if (m_ButtonIDForToolID.find(id) != m_ButtonIDForToolID.end()) // if this tool is in our box { toolButton = dynamic_cast(m_ToolButtonGroup->buttons().at(m_ButtonIDForToolID[id])); } if (toolButton) { // mmueller // uncheck all other buttons QAbstractButton *tmpBtn = nullptr; QList::iterator it; for (int i = 0; i < m_ToolButtonGroup->buttons().size(); ++i) { tmpBtn = m_ToolButtonGroup->buttons().at(i); if (tmpBtn != toolButton) dynamic_cast(tmpBtn)->setChecked(false); } toolButton->setChecked(true); if (m_ToolGUIWidget && tool) { // create and reparent new GUI (if any) itk::Object::Pointer possibleGUI = tool->GetGUI("Qmitk", "GUI").GetPointer(); // prefix and postfix if (possibleGUI.IsNull()) possibleGUI = tool->GetGUI("", "GUI").GetPointer(); QmitkToolGUI *gui = dynamic_cast(possibleGUI.GetPointer()); //! m_LastToolGUI = gui; if (gui) { gui->SetTool(tool); gui->setParent(m_ToolGUIWidget); gui->move(gui->geometry().topLeft()); gui->show(); QLayout *layout = m_ToolGUIWidget->layout(); if (!layout) { layout = new QVBoxLayout(m_ToolGUIWidget); } if (layout) { layout->addWidget(gui); layout->activate(); } } } } else { // disable all buttons QToolButton *selectedToolButton = dynamic_cast(m_ToolButtonGroup->checkedButton()); if (selectedToolButton) { selectedToolButton->setChecked(false); } } } void QmitkToolSelectionBox::OnToolManagerReferenceDataModified() { if (m_SelfCall) return; MITK_DEBUG << "OnToolManagerReferenceDataModified()"; this->UpdateButtonsEnabledState(); - this->SetGUIEnabledAccordingToToolManagerState(); } void QmitkToolSelectionBox::OnToolManagerWorkingDataModified() { if (m_SelfCall) return; MITK_DEBUG << "OnToolManagerWorkingDataModified()"; this->UpdateButtonsEnabledState(); - this->SetGUIEnabledAccordingToToolManagerState(); } -/** - Implementes the logic, which decides, when tools are activated/deactivated. -*/ -void QmitkToolSelectionBox::SetGUIEnabledAccordingToToolManagerState() +void QmitkToolSelectionBox::setEnabled(bool enable) { - mitk::DataNode *referenceNode = m_ToolManager->GetReferenceData(0); - mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); - - bool enabled = true; - - switch (m_EnabledMode) - { - default: - case EnabledWithReferenceAndWorkingDataVisible: - enabled = referenceNode && workingNode && - referenceNode->IsVisible( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))) && - workingNode->IsVisible( - mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))) && - isVisible(); - break; - case EnabledWithReferenceData: - enabled = referenceNode && isVisible(); - break; - case EnabledWithWorkingData: - enabled = workingNode && isVisible(); - break; - case AlwaysEnabled: - enabled = isVisible(); - break; - } + if (QWidget::isEnabled() == enable) + return; - if (QWidget::isEnabled() == enabled) - return; // nothing to change + QWidget::setEnabled(enable); - QWidget::setEnabled(enabled); - if (enabled) + if (enable) { m_ToolManager->RegisterClient(); - int id = m_ToolManager->GetActiveToolID(); + auto id = m_ToolManager->GetActiveToolID(); emit ToolSelected(id); } else { m_ToolManager->ActivateTool(-1); m_ToolManager->UnregisterClient(); emit ToolSelected(-1); } } -/** - External enableization... -*/ -void QmitkToolSelectionBox::setEnabled(bool /*enable*/) -{ - SetGUIEnabledAccordingToToolManagerState(); -} - void QmitkToolSelectionBox::UpdateButtonsEnabledState() { auto buttons = m_ToolButtonGroup->buttons(); const auto refDataNode = m_ToolManager->GetReferenceData(0); const mitk::BaseData* refData = nullptr; if (nullptr != refDataNode) { refData = refDataNode->GetData(); } const auto workingDataNode = m_ToolManager->GetWorkingData(0); const mitk::BaseData* workingData = nullptr; if (nullptr != workingDataNode) { workingData = workingDataNode->GetData(); } for (const auto& button : qAsConst(buttons)) { const auto buttonID = m_ToolButtonGroup->id(button); const auto toolID = m_ToolIDForButtonID[buttonID]; const auto tool = m_ToolManager->GetToolById(toolID); button->setEnabled(tool->CanHandle(refData, workingData)); } } void QmitkToolSelectionBox::RecreateButtons() { if (m_ToolManager.IsNull()) return; QList l = m_ToolButtonGroup->buttons(); // remove all buttons that are there QList::iterator it; QAbstractButton *btn; for (it = l.begin(); it != l.end(); ++it) { btn = *it; m_ToolButtonGroup->removeButton(btn); delete btn; } mitk::ToolManager::ToolVectorTypeConst allPossibleTools = m_ToolManager->GetTools(); mitk::ToolManager::ToolVectorTypeConst allTools; typedef std::pair SortPairType; typedef std::priority_queue SortedToolQueueType; SortedToolQueueType toolPositions; // clear and sort all tools // step one: find name/group of all tools in m_DisplayedGroups string. remember these positions for all tools. for (mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allPossibleTools.begin(); iter != allPossibleTools.end(); ++iter) { const mitk::Tool *tool = *iter; std::string::size_type namePos = m_DisplayedGroups.find(std::string("'") + tool->GetName() + "'"); std::string::size_type groupPos = m_DisplayedGroups.find(std::string("'") + tool->GetGroup() + "'"); if (!m_DisplayedGroups.empty() && namePos == std::string::npos && groupPos == std::string::npos) continue; // skip if (m_DisplayedGroups.empty() && std::string(tool->GetName()).length() > 0) { namePos = static_cast(tool->GetName()[0]); } SortPairType thisPair = std::make_pair(namePos < groupPos ? namePos : groupPos, *iter); toolPositions.push(thisPair); } // step two: sort tools according to previously found positions in m_DisplayedGroups MITK_DEBUG << "Sorting order of tools (lower number --> earlier in button group)"; while (!toolPositions.empty()) { SortPairType thisPair = toolPositions.top(); MITK_DEBUG << "Position " << thisPair.first << " : " << thisPair.second->GetName(); allTools.push_back(thisPair.second); toolPositions.pop(); } std::reverse(allTools.begin(), allTools.end()); MITK_DEBUG << "Sorted tools:"; for (mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allTools.begin(); iter != allTools.end(); ++iter) { MITK_DEBUG << (*iter)->GetName(); } if (m_ButtonLayout == nullptr) m_ButtonLayout = new QGridLayout; int row(0); int column(-1); int currentButtonID(0); m_ButtonIDForToolID.clear(); m_ToolIDForButtonID.clear(); QToolButton *button = nullptr; MITK_DEBUG << "Creating buttons for tools"; // fill group box with buttons for (mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allTools.begin(); iter != allTools.end(); ++iter) { const mitk::Tool *tool = *iter; int currentToolID(m_ToolManager->GetToolID(tool)); ++column; // new line if we are at the maximum columns if (column == m_LayoutColumns) { ++row; column = 0; } button = new QToolButton; button->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum)); // add new button to the group MITK_DEBUG << "Adding button with ID " << currentToolID; m_ToolButtonGroup->addButton(button, currentButtonID); // ... and to the layout MITK_DEBUG << "Adding button in row/column " << row << "/" << column; m_ButtonLayout->addWidget(button, row, column); if (m_LayoutColumns == 1) { button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); } else { button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); } button->setCheckable(true); if (currentToolID == m_ToolManager->GetActiveToolID()) button->setChecked(true); QString label; if (m_GenerateAccelerators) { label += "&"; } label += tool->GetName(); QString tooltip = tool->GetName(); MITK_DEBUG << tool->GetName() << ", " << label.toLocal8Bit().constData() << ", '" << tooltip.toLocal8Bit().constData(); if (m_ShowNames) { button->setText(label); // a label button->setToolTip(tooltip); QFont currentFont = button->font(); currentFont.setBold(false); button->setFont(currentFont); } us::ModuleResource iconResource = tool->GetIconResource(); if (!iconResource.IsValid()) { button->setIcon(QIcon(QPixmap(tool->GetXPM()))); } else { auto isSVG = "svg" == iconResource.GetSuffix(); auto openmode = isSVG ? std::ios_base::in : std::ios_base::binary; us::ModuleResourceStream resourceStream(iconResource, openmode); resourceStream.seekg(0, std::ios::end); std::ios::pos_type length = resourceStream.tellg(); resourceStream.seekg(0, std::ios::beg); char *data = new char[length]; resourceStream.read(data, length); if (isSVG) { button->setIcon(QmitkStyleManager::ThemeIcon(QByteArray::fromRawData(data, length))); } else { QPixmap pixmap; pixmap.loadFromData(QByteArray::fromRawData(data, length)); button->setIcon(QIcon(pixmap)); } delete[] data; if (m_ShowNames) { if (m_LayoutColumns == 1) button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); else button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); button->setIconSize(QSize(24, 24)); } else { button->setToolButtonStyle(Qt::ToolButtonIconOnly); button->setIconSize(QSize(32, 32)); button->setToolTip(tooltip); } } if (m_GenerateAccelerators) { QString firstLetter = QString(tool->GetName()); firstLetter.truncate(1); button->setShortcut( firstLetter); // a keyboard shortcut (just the first letter of the given name w/o any CTRL or something) } m_ButtonIDForToolID[currentToolID] = currentButtonID; m_ToolIDForButtonID[currentButtonID] = currentToolID; MITK_DEBUG << "m_ButtonIDForToolID[" << currentToolID << "] == " << currentButtonID; MITK_DEBUG << "m_ToolIDForButtonID[" << currentButtonID << "] == " << currentToolID; tool->GUIProcessEventsMessage += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolGUIProcessEventsMessage); // will never add a listener twice, so we don't have // to check here tool->ErrorMessage += mitk::MessageDelegate1( this, &QmitkToolSelectionBox::OnToolErrorMessage); // will never add a listener twice, so we don't have to check here tool->GeneralMessage += mitk::MessageDelegate1(this, &QmitkToolSelectionBox::OnGeneralToolMessage); ++currentButtonID; } // setting grid layout for this groupbox this->setLayout(m_ButtonLayout); this->UpdateButtonsEnabledState(); // this->update(); } void QmitkToolSelectionBox::OnToolGUIProcessEventsMessage() { qApp->processEvents(); } void QmitkToolSelectionBox::OnToolErrorMessage(std::string s) { QMessageBox::critical( this, "MITK", QString(s.c_str()), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void QmitkToolSelectionBox::OnGeneralToolMessage(std::string s) { QMessageBox::information( this, "MITK", QString(s.c_str()), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void QmitkToolSelectionBox::SetDisplayedToolGroups(const std::string &toolGroups) { if (m_DisplayedGroups != toolGroups) { QString q_DisplayedGroups = toolGroups.c_str(); // quote all unquoted single words q_DisplayedGroups = q_DisplayedGroups.replace(QRegExp("\\b(\\w+)\\b|'([^']+)'"), "'\\1\\2'"); MITK_DEBUG << "m_DisplayedGroups was \"" << toolGroups << "\""; m_DisplayedGroups = q_DisplayedGroups.toLocal8Bit().constData(); MITK_DEBUG << "m_DisplayedGroups is \"" << m_DisplayedGroups << "\""; RecreateButtons(); SetOrUnsetButtonForActiveTool(); } } void QmitkToolSelectionBox::SetLayoutColumns(int columns) { if (columns > 0 && columns != m_LayoutColumns) { m_LayoutColumns = columns; RecreateButtons(); } } void QmitkToolSelectionBox::SetShowNames(bool show) { if (show != m_ShowNames) { m_ShowNames = show; RecreateButtons(); } } void QmitkToolSelectionBox::SetGenerateAccelerators(bool accel) { if (accel != m_GenerateAccelerators) { m_GenerateAccelerators = accel; RecreateButtons(); } } void QmitkToolSelectionBox::SetToolGUIArea(QWidget *parentWidget) { m_ToolGUIWidget = parentWidget; } -void QmitkToolSelectionBox::setTitle(const QString & /*title*/) -{ -} - -void QmitkToolSelectionBox::showEvent(QShowEvent *e) -{ - QWidget::showEvent(e); - SetGUIEnabledAccordingToToolManagerState(); -} - -void QmitkToolSelectionBox::hideEvent(QHideEvent *e) -{ - QWidget::hideEvent(e); - SetGUIEnabledAccordingToToolManagerState(); -} diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h index 20d15ed015..dbdc0e8c49 100755 --- a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h +++ b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h @@ -1,150 +1,134 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkToolSelectionBox_h_Included #define QmitkToolSelectionBox_h_Included #include "QmitkToolGUIArea.h" #include #include "mitkToolManager.h" #include #include #include #include class QmitkToolGUI; /** \brief Display the tool selection state of a mitk::ToolManager \sa mitk::ToolManager \ingroup org_mitk_gui_qt_interactivesegmentation \ingroup ToolManagerEtAl This widget graphically displays the active tool of a mitk::ToolManager as a set of toggle buttons. Each button show the identification of a Tool (icon and name). When a button's toggle state is "down", the tool is activated. When a different button is clicked, the active tool is switched. When you click an already active button, the associated tool is deactivated with no replacement, which means that no tool is active then. When this widget is enabled/disabled it (normally) also enables/disables the tools. There could be cases where two QmitkToolSelectionBox widgets are associated to the same ToolManager, but if this happens, please look deeply into the code. Last contributor: $Author: maleike $ */ class MITKSEGMENTATIONUI_EXPORT QmitkToolSelectionBox : public QWidget //! { Q_OBJECT public: - enum EnabledMode - { - EnabledWithReferenceAndWorkingDataVisible, - EnabledWithReferenceData, - EnabledWithWorkingData, - AlwaysEnabled - }; - QmitkToolSelectionBox(QWidget *parent = nullptr, mitk::DataStorage *storage = nullptr); ~QmitkToolSelectionBox() override; mitk::ToolManager *GetToolManager(); void SetToolManager(mitk::ToolManager &); // no nullptr pointer allowed here, a manager is required - void setTitle(const QString &title); - /** You may specify a list of tool "groups" that should be displayed in this widget. Every Tool can report its group as a string. This method will try to find the tool's group inside the supplied string \c toolGroups . If there is a match, the tool is displayed. Effectively, you can provide a human readable list like "default, lymphnodevolumetry, oldERISstuff". @param toolGroups */ void SetDisplayedToolGroups(const std::string &toolGroups = nullptr); void OnToolManagerToolModified(); void OnToolManagerReferenceDataModified(); void OnToolManagerWorkingDataModified(); void OnToolGUIProcessEventsMessage(); void OnToolErrorMessage(std::string s); void OnGeneralToolMessage(std::string s); void RecreateButtons(); signals: /// Whenever a tool is activated. id is the index of the active tool. Counting starts at 0, -1 indicates "no tool /// selected" /// This signal is also emitted, when the whole QmitkToolSelectionBox get disabled. Then it will claim /// ToolSelected(-1) /// When it is enabled again, there will be another ToolSelected event with the tool that is currently selected void ToolSelected(int id); public slots: virtual void setEnabled(bool); - virtual void SetEnabledMode(EnabledMode mode); virtual void SetLayoutColumns(int); virtual void SetShowNames(bool); virtual void SetGenerateAccelerators(bool); virtual void SetToolGUIArea(QWidget *parentWidget); protected slots: void toolButtonClicked(int id); - void SetGUIEnabledAccordingToToolManagerState(); void UpdateButtonsEnabledState(); protected: - void showEvent(QShowEvent *) override; - void hideEvent(QHideEvent *) override; void SetOrUnsetButtonForActiveTool(); mitk::ToolManager::Pointer m_ToolManager; bool m_SelfCall; std::string m_DisplayedGroups; /// stores relationship between button IDs of the Qt widget and tool IDs of ToolManager std::map m_ButtonIDForToolID; /// stores relationship between button IDs of the Qt widget and tool IDs of ToolManager std::map m_ToolIDForButtonID; int m_LayoutColumns; bool m_ShowNames; bool m_GenerateAccelerators; QWidget *m_ToolGUIWidget; QmitkToolGUI *m_LastToolGUI; // store buttons in this group QButtonGroup *m_ToolButtonGroup; QGridLayout *m_ButtonLayout; - - EnabledMode m_EnabledMode; }; #endif diff --git a/Plugins/PluginList.cmake b/Plugins/PluginList.cmake index 793c9f1210..8b336a0d7e 100644 --- a/Plugins/PluginList.cmake +++ b/Plugins/PluginList.cmake @@ -1,89 +1,89 @@ # Plug-ins must be ordered according to their dependencies set(MITK_PLUGINS org.blueberry.core.runtime:ON org.blueberry.core.expressions:OFF org.blueberry.core.commands:OFF org.blueberry.core.jobs:OFF org.blueberry.ui.qt:OFF org.blueberry.ui.qt.help:ON org.blueberry.ui.qt.log:ON org.blueberry.ui.qt.objectinspector:OFF org.mitk.core.services:ON org.mitk.gui.common:ON org.mitk.planarfigure:ON org.mitk.core.ext:OFF org.mitk.core.jobs:OFF org.mitk.gui.qt.application:ON org.mitk.gui.qt.ext:OFF org.mitk.gui.qt.extapplication:OFF org.mitk.gui.qt.mitkworkbench.intro:OFF org.mitk.gui.qt.common:ON org.mitk.gui.qt.stdmultiwidgeteditor:ON org.mitk.gui.qt.mxnmultiwidgeteditor:OFF org.mitk.gui.qt.cmdlinemodules:OFF org.mitk.gui.qt.chartExample:OFF org.mitk.gui.qt.datamanager:ON org.mitk.gui.qt.datamanagerlight:OFF org.mitk.gui.qt.datastorageviewertest:OFF org.mitk.gui.qt.properties:ON org.mitk.gui.qt.basicimageprocessing:OFF org.mitk.gui.qt.dicombrowser:OFF org.mitk.gui.qt.dicominspector:OFF org.mitk.gui.qt.dosevisualization:OFF org.mitk.gui.qt.geometrytools:OFF org.mitk.gui.qt.igtexamples:OFF org.mitk.gui.qt.igttracking:OFF org.mitk.gui.qt.openigtlink:OFF org.mitk.gui.qt.imagecropper:OFF org.mitk.gui.qt.imagenavigator:ON org.mitk.gui.qt.viewnavigator:OFF org.mitk.gui.qt.materialeditor:OFF org.mitk.gui.qt.measurementtoolbox:OFF org.mitk.gui.qt.moviemaker:OFF org.mitk.gui.qt.pointsetinteraction:OFF org.mitk.gui.qt.pointsetinteractionmultispectrum:OFF org.mitk.gui.qt.python:OFF org.mitk.gui.qt.remeshing:OFF org.mitk.gui.qt.segmentation:OFF org.mitk.gui.qt.deformableclippingplane:OFF org.mitk.gui.qt.aicpregistration:OFF org.mitk.gui.qt.renderwindowmanager:OFF org.mitk.gui.qt.semanticrelations:OFF org.mitk.gui.qt.toftutorial:OFF org.mitk.gui.qt.tofutil:OFF org.mitk.gui.qt.tubegraph:OFF org.mitk.gui.qt.ugvisualization:OFF org.mitk.gui.qt.ultrasound:OFF org.mitk.gui.qt.volumevisualization:OFF org.mitk.gui.qt.eventrecorder:OFF org.mitk.gui.qt.xnat:OFF org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation:OFF org.mitk.gui.qt.classificationsegmentation:OFF org.mitk.gui.qt.overlaymanager:OFF org.mitk.gui.qt.igt.app.hummelprotocolmeasurements:OFF - org.mitk.gui.qt.multilabelsegmentation:OFF org.mitk.matchpoint.core.helper:OFF org.mitk.gui.qt.matchpoint.algorithm.browser:OFF org.mitk.gui.qt.matchpoint.algorithm.control:OFF org.mitk.gui.qt.matchpoint.mapper:OFF org.mitk.gui.qt.matchpoint.framereg:OFF org.mitk.gui.qt.matchpoint.visualizer:OFF org.mitk.gui.qt.matchpoint.evaluator:OFF org.mitk.gui.qt.matchpoint.manipulator:OFF org.mitk.gui.qt.preprocessing.resampling:OFF org.mitk.gui.qt.radiomics:OFF org.mitk.gui.qt.cest:OFF org.mitk.gui.qt.fit.demo:OFF org.mitk.gui.qt.fit.inspector:OFF org.mitk.gui.qt.fit.genericfitting:OFF org.mitk.gui.qt.pharmacokinetics.mri:OFF org.mitk.gui.qt.pharmacokinetics.pet:OFF org.mitk.gui.qt.pharmacokinetics.simulation:OFF org.mitk.gui.qt.pharmacokinetics.curvedescriptor:OFF org.mitk.gui.qt.pharmacokinetics.concentration.mri:OFF org.mitk.gui.qt.flowapplication:OFF org.mitk.gui.qt.flow.segmentation:OFF + org.mitk.gui.qt.pixelvalue:ON ) diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp index fed73bac3f..7ad5801806 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp @@ -1,514 +1,512 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "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) , m_BlockSignal(false) { // root node if parent is 0 if (_Parent != nullptr) { // 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 == nullptr) 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(true); } void Preferences::Flush() { { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); } 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) { QString oldValue; { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); oldValue = m_Properties[key]; m_Properties[key] = value; } if (oldValue != value) { this->SetDirty(true); if (!m_BlockSignal) { this->OnPropertyChanged(ChangeEvent(this, key, oldValue, value)); } } } 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) { this->Put(key, value ? "true" : "false"); } void Preferences::PutDouble(const QString& key, double value) { this->Put(key, QString::number(value)); } void Preferences::PutFloat(const QString& key, float value) { this->Put(key, QString::number(value)); } void Preferences::PutInt(const QString& key, int value) { this->Put(key, QString::number(value)); } void Preferences::PutLong(const QString& key, long value) { 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() { 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() { this->Flush(); } void Preferences::BlockSignals(bool block) { m_BlockSignal = block; } 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); m_Dirty = _Dirty; } if(_Dirty) { if (!m_BlockSignal) { this->OnChanged.Send(this); } } } void Preferences::SetDirty_unlocked( bool _Dirty ) { m_Dirty = _Dirty; if(_Dirty) if (!m_BlockSignal) { 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/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp b/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp index 82a03126e1..0e1381b7ee 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp @@ -1,575 +1,572 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryWindow.h" #include "berryConstants.h" #include "berrySameShellProvider.h" #include "berryMenuManager.h" #include namespace berry { const int Window::OK = 0; const int Window::CANCEL = 1; QList Window::defaultImages = QList(); Window::IExceptionHandler::Pointer Window::exceptionHandler(new DefaultExceptionHandler()); IShellProvider::Pointer Window::defaultModalParent(new DefaultModalParent()); Window::WindowShellListener::WindowShellListener(Window* wnd) : window(wnd) { } void Window::WindowShellListener::ShellClosed(const ShellEvent::Pointer& event) { event->doit = false; // don't close now if (window->CanHandleShellCloseEvent()) { window->HandleShellCloseEvent(); } } void Window::DefaultExceptionHandler::HandleException(const std::exception& t) { // Try to keep running. std::cerr << t.what(); } Shell::Pointer Window::DefaultModalParent::GetShell() const { Shell::Pointer parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetActiveShell(); // Make sure we don't pick a parent that has a modal child (this can lock the app) if (parent == 0) { // If this is a top-level window, then there must not be any open modal windows. parent = Window::GetModalChild(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShells()); } else { // If we picked a parent with a modal child, use the modal child instead Shell::Pointer modalChild = Window::GetModalChild(parent->GetShells()); if (modalChild != 0) { parent = modalChild; } } return parent; } Shell::Pointer Window::GetModalChild(const QList& toSearch) { int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL; int size = toSearch.size(); for (int i = size - 1; i < size; i--) { Shell::Pointer shell = toSearch[i]; // Check if this shell has a modal child QList children = shell->GetShells(); Shell::Pointer modalChild = GetModalChild(children); if (modalChild != 0) { return modalChild; } // If not, check if this shell is modal itself if (shell->IsVisible() && (shell->GetStyle() & modal) != 0) { return shell; } } return Shell::Pointer(nullptr); } //void Window::RunEventLoop() //{ // // //Use the display provided by the shell if possible // Display display; // if (shell == null) // { // display = Display.getCurrent(); // } // else // { // display = loopShell.getDisplay(); // } // // while (loopShell != null && !loopShell.isDisposed()) // { // try // { // if (!display.readAndDispatch()) // { // display.sleep(); // } // } catch (Throwable e) // { // exceptionHandler.handleException(e); // } // } // display.update(); //} Window::Window(Shell::Pointer parentShell) { this->parentShell = new SameShellProvider(parentShell); this->Init(); } Window::Window(IShellProvider::Pointer shellProvider) { poco_assert(shellProvider != 0); this->parentShell = shellProvider; this->Init(); } Window::~Window() { } void Window::Init() { this->shellStyle = Constants::SHELL_TRIM; this->returnCode = OK; this->block = false; } bool Window::CanHandleShellCloseEvent() { return true; } void Window::ConfigureShell(Shell::Pointer newShell) { // The single image version of this code had a comment related to bug // 46624, // and some code that did nothing if the stored image was already // disposed. // The equivalent in the multi-image version seems to be to remove the // disposed images from the array passed to the shell. if (defaultImages.size() > 0) { // ArrayList nonDisposedImages = new ArrayList(defaultImages.length); // for (int i = 0; i < defaultImages.length; ++i) // { // if (defaultImages[i] != null && !defaultImages[i].isDisposed()) // { // nonDisposedImages.add(defaultImages[i]); // } // } // // if (nonDisposedImages.size() <= 0) // { // System.err.println("Window.configureShell: images disposed"); //$NON-NLS-1$ // } // else // { // //Image[] array = new Image[nonDisposedImages.size()]; // nonDisposedImages.toArray(array); newShell->SetImages(defaultImages); // } } // Layout layout = getLayout(); // if (layout != null) // { // newShell.setLayout(layout); // } CreateTrimWidgets(newShell); } //voidWindow::ConstrainShellSize() //{ // // limit the shell size to the display size // QRect bounds = shell.getBounds(); // QRect constrained = getConstrainedShellBounds(bounds); // if (!bounds.equals(constrained)) // { // shell.setBounds(constrained); // } //} QWidget* Window::CreateContents(Shell::Pointer parent) { // by default, just create a composite //return new Composite(parent, SWT.NONE); return parent->GetControl(); } Shell::Pointer Window::CreateShell() { Shell::Pointer newParent = this->GetParentShell(); // if (newParent != 0 && newParent.isDisposed()) // { // parentShell = new SameShellProvider(null); // newParent = getParentShell();//Find a better parent // } //Create the shell Shell::Pointer newShell = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateShell(newParent, this->GetShellStyle()); // resizeListener = new Listener() { // public void handleEvent(Event e) { // resizeHasOccurred = true; // } // }; //newShell.addListener(SWT.Resize, resizeListener); newShell->SetData(Object::Pointer(this)); //Add a listener newShell->AddShellListener(this->GetShellListener()); //Set the layout this->ConfigureShell(newShell); // //Register for font changes // if (fontChangeListener == null) // { // fontChangeListener = new FontChangeListener(); // } // JFaceResources.getFontRegistry().addListener(fontChangeListener); return newShell; } QWidget* Window::GetContents() { return contents; } QPoint Window::GetInitialLocation(const QPoint& initialSize) { QWidget* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); QPoint centerPoint(0,0); QRect parentBounds(0,0,0,0); if (parent != nullptr) { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent); centerPoint.setX(parentBounds.x() + parentBounds.width()/2); centerPoint.setY(parentBounds.y() - parentBounds.height()/2); } else { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY) ->GetScreenSize(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetPrimaryScreenNumber()); centerPoint.setX(parentBounds.width()/2); centerPoint.setY(parentBounds.height()/2); } - return QPoint(centerPoint.x() - (initialSize.x() / 2), - std::max(parentBounds.y(), - std::min(centerPoint.y() - (initialSize.y() * 2 / 3), - parentBounds.y() + parentBounds.height() - initialSize.y()))); + return QPoint(centerPoint.x() - initialSize.x() / 2, centerPoint.y() - initialSize.y() / 2); } QPoint Window::GetInitialSize() { return shell->ComputeSize(Constants::DEFAULT, Constants::DEFAULT, true); } Shell::Pointer Window::GetParentShell() { Shell::Pointer parent = parentShell->GetShell(); int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL; if ((this->GetShellStyle() & modal) != 0) { // If this is a modal shell with no parent, pick a shell using defaultModalParent. if (parent == 0) { parent = defaultModalParent->GetShell(); } } return parent; } IShellListener* Window::GetShellListener() { if (windowShellListener.isNull()) windowShellListener.reset(new WindowShellListener(this)); return windowShellListener.data(); } int Window::GetShellStyle() { return shellStyle; } void Window::HandleShellCloseEvent() { this->SetReturnCode(CANCEL); this->Close(); } void Window::InitializeBounds() { // if (resizeListener != null) // { // shell.removeListener(SWT.Resize, resizeListener); // } // if (resizeHasOccurred) // { // Check if shell size has been set already. // return; // } QPoint size = this->GetInitialSize(); QPoint location = this->GetInitialLocation(size); shell->SetBounds(this->GetConstrainedShellBounds(QRect(location.x(), location.y(), size.x(), size.y()))); } QRect Window::GetConstrainedShellBounds(const QRect& preferredSize) { QRect result(preferredSize); GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); int screenNum = guiTweaklet->GetClosestScreenNumber(result); QRect bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); if (result.height() > bounds.height()) { result.setHeight(bounds.height()); } if (result.width() > bounds.width()) { result.setWidth(bounds.width()); } result.moveLeft( std::max(bounds.x(), std::min(result.x(), bounds.x() + bounds.width() - result.width()))); result.moveTop(std::max(bounds.y(), std::min(result.y(), bounds.y() + bounds.height() - result.height()))); return result; } void Window::SetParentShell(Shell::Pointer newParentShell) { poco_assert(shell == 0); // "There must not be an existing shell."; //$NON-NLS-1$ parentShell = new SameShellProvider(newParentShell); } void Window::SetReturnCode(int code) { returnCode = code; } void Window::SetShellStyle(int newShellStyle) { shellStyle = newShellStyle; } void Window::AddMenuBar() { if (GetShell().IsNull() && menuBarManager.IsNull()) { menuBarManager = CreateMenuManager(); } } SmartPointer Window::CreateMenuManager() { MenuManager::Pointer manager(new MenuManager()); return manager; } void Window::CreateTrimWidgets(SmartPointer shell) { if (menuBarManager.IsNotNull()) { QMainWindow* mw = qobject_cast(shell->GetControl()); if (mw) { mw->setMenuBar(menuBarManager->CreateMenuBar(shell->GetControl())); menuBarManager->UpdateAll(true); } } // if (showTopSeperator()) // { // seperator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); // } //CreateToolBarControl(shell); //CreateStatusLine(shell); } bool Window::Close() { // BERRY_INFO << "Window::Close()"; // // stop listening for font changes // if (fontChangeListener != null) // { // JFaceResources.getFontRegistry().removeListener(fontChangeListener); // fontChangeListener = null; // } // remove this window from a window manager if it has one if (windowManager != nullptr) { windowManager->Remove(Window::Pointer(this)); windowManager = nullptr; } if (shell == 0) { return true; } shell->RemoveShellListener(this->GetShellListener()); shell->SetData(Object::Pointer(nullptr)); // If we "close" the shell recursion will occur. // Instead, we need to "dispose" the shell to remove it from the // display. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->DisposeShell(shell); shell = nullptr; contents = nullptr; return true; } void Window::Create() { shell = this->CreateShell(); contents = this->CreateContents(shell); //initialize the bounds of the shell to that appropriate for the // contents this->InitializeBounds(); } QIcon Window::GetDefaultImage() { return (defaultImages.size() < 1) ? QIcon() : defaultImages[0]; } QList Window::GetDefaultImages() { return defaultImages; } int Window::GetReturnCode() { return returnCode; } Shell::Pointer Window::GetShell() const { return shell; } WindowManager* Window::GetWindowManager() { return windowManager; } MenuManager *Window::GetMenuBarManager() const { return menuBarManager.GetPointer(); } int Window::Open() { if (shell == 0) { // create the window this->Create(); } // limit the shell size to the display size //constrainShellSize(); // open the window shell->Open(block); // // run the event loop if specified // if (block) // { // this->RunEventLoop(); // } return returnCode; } void Window::SetBlockOnOpen(bool shouldBlock) { block = shouldBlock; } void Window::SetDefaultImage(const QIcon& image) { if (!image.isNull()) defaultImages.push_back(image); } void Window::SetDefaultImages(const QList& images) { defaultImages = images; } void Window::SetWindowManager(WindowManager* manager) { windowManager = manager; // Code to detect invalid usage if (manager != nullptr) { QList windows = manager->GetWindows(); for (int i = 0; i < windows.size(); i++) { if (windows[i] == this) { return; } } manager->Add(Window::Pointer(this)); } } void Window::SetExceptionHandler(IExceptionHandler::Pointer handler) { if (exceptionHandler == 0) { exceptionHandler = handler; } } void Window::SetDefaultModalParent(IShellProvider::Pointer provider) { defaultModalParent = provider; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp index 49d0b76b8e..1e0de9ace4 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp @@ -1,291 +1,291 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryEditorSashContainer.h" #include "berryWorkbenchPlugin.h" #include "berryMenuManager.h" #include "berryQtDnDControlWidget.h" namespace berry { WorkbenchWindowConfigurer::WindowActionBarConfigurer::WindowActionBarConfigurer(WorkbenchWindow::WeakPtr wnd) : window(wnd) { } void WorkbenchWindowConfigurer::WindowActionBarConfigurer::SetProxy(IActionBarConfigurer::Pointer proxy) { this->proxy = proxy; } IWorkbenchWindowConfigurer::Pointer WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetWindowConfigurer() { return WorkbenchWindow::Pointer(window)->GetWindowConfigurer(); } IMenuManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetMenuManager() { if (proxy.IsNotNull()) { return proxy->GetMenuManager(); } return window.Lock()->GetMenuManager(); } IToolBarManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetToolBarManager() { if (proxy.IsNotNull()) { return proxy->GetToolBarManager(); } //return window.Lock()->GetToolBarManager(); return nullptr; } WorkbenchWindowConfigurer::WorkbenchWindowConfigurer(const WorkbenchWindow::Pointer& window) : shellStyle(nullptr) , showPerspectiveBar(false) , showStatusLine(true) , showToolBar(true) , showMenuBar(true) , showProgressIndicator(false) , dropTargetListener(nullptr) - , initialSize(1024,768) + , initialSize(1632, 918) // 85% of 1920 x 1080 (FullHD, 1080p) { if (window.IsNull()) { throw Poco::InvalidArgumentException(); } this->window = window; windowTitle = "BlueBerry Application"; } IWorkbenchWindow::Pointer WorkbenchWindowConfigurer::GetWindow() { return IWorkbenchWindow::Pointer(window); } IWorkbenchConfigurer::Pointer WorkbenchWindowConfigurer::GetWorkbenchConfigurer() { return dynamic_cast(PlatformUI::GetWorkbench())->GetWorkbenchConfigurer(); } QString WorkbenchWindowConfigurer::BasicGetTitle() { return windowTitle; } QString WorkbenchWindowConfigurer::GetTitle() { Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { // update the cached title windowTitle = shell->GetText(); } return windowTitle; } void WorkbenchWindowConfigurer::SetTitle(const QString &title) { windowTitle = title; Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { shell->SetText(title); } } bool WorkbenchWindowConfigurer::GetShowMenuBar() const { return showMenuBar; } void WorkbenchWindowConfigurer::SetShowMenuBar(bool show) { showMenuBar = show; // WorkbenchWindow win = (WorkbenchWindow) getWindow(); // Shell shell = win.getShell(); // if (shell != null) // { // boolean showing = shell.getMenuBar() != null; // if (show != showing) // { // if (show) // { // shell.setMenuBar(win.getMenuBarManager().getMenu()); // } // else // { // shell.setMenuBar(null); // } // } // } } bool WorkbenchWindowConfigurer::GetShowToolBar() const { return showToolBar; } void WorkbenchWindowConfigurer::SetShowToolBar(bool show) { showToolBar = show; //window.setCoolBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowPerspectiveBar() const { return showPerspectiveBar; } void WorkbenchWindowConfigurer::SetShowPerspectiveBar(bool show) { showPerspectiveBar = show; //window.setPerspectiveBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowStatusLine() const { return showStatusLine; } void WorkbenchWindowConfigurer::SetShowStatusLine(bool show) { showStatusLine = show; // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowProgressIndicator() const { return showProgressIndicator; } void WorkbenchWindowConfigurer::SetShowProgressIndicator(bool show) { showProgressIndicator = show; // @issue need to be able to reconfigure after window's controls created } void WorkbenchWindowConfigurer::AddEditorAreaTransfer(const QStringList& transfers) { if (transfers.isEmpty()) return; int oldSize = transferTypes.size(); transferTypes.unite(QSet::fromList(transfers)); if (transferTypes.size() == oldSize) return; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->SetTransferTypes(transferTypes.toList()); } } void WorkbenchWindowConfigurer::ConfigureEditorAreaDropListener(IDropTargetListener* listener) { if (listener == nullptr) return; dropTargetListener = listener; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->AddDropListener(listener); } } QStringList WorkbenchWindowConfigurer::GetTransfers() const { return transferTypes.toList(); } IDropTargetListener* WorkbenchWindowConfigurer::GetDropTargetListener() const { return dropTargetListener; } IActionBarConfigurer::Pointer WorkbenchWindowConfigurer::GetActionBarConfigurer() { if (actionBarConfigurer.IsNull()) { // lazily initialize actionBarConfigurer = new WindowActionBarConfigurer(window); } return actionBarConfigurer; } Qt::WindowFlags WorkbenchWindowConfigurer::GetWindowFlags() const { return shellStyle; } void WorkbenchWindowConfigurer::SetWindowFlags(Qt::WindowFlags shellStyle) { this->shellStyle = shellStyle; } QPoint WorkbenchWindowConfigurer::GetInitialSize() const { return initialSize; } void WorkbenchWindowConfigurer::SetInitialSize(QPoint size) { initialSize = size; } void WorkbenchWindowConfigurer::CreateDefaultContents(Shell::Pointer shell) { WorkbenchWindow::Pointer(window)->CreateDefaultContents(shell); } QMenuBar* WorkbenchWindowConfigurer::CreateMenuBar() { return window.Lock()->GetMenuManager()->CreateMenuBar(window.Lock()->GetShell()->GetControl()); } QWidget* WorkbenchWindowConfigurer::CreateToolBar(QWidget* /*parent*/) { // IToolBarManager* toolBarManager = window->GetToolBarManager(); // if (toolBarManager) // { // return toolBarManager->CreateControl(parent); // } return nullptr; } QWidget *WorkbenchWindowConfigurer::CreatePageComposite(QWidget *parent) { return WorkbenchWindow::Pointer(window)->CreatePageComposite(parent); } bool WorkbenchWindowConfigurer::SaveState(IMemento::Pointer memento) { return WorkbenchWindow::Pointer(window)->SaveState(memento); } } diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h index eee6396cf4..99ccfe8289 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h @@ -1,198 +1,218 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIRENDERWINDOWPART_H #define MITKIRENDERWINDOWPART_H #include #include #include #include #include #include #include #include class QmitkRenderWindow; namespace mitk { struct IRenderingManager; class SliceNavigationController; /** * \ingroup org_mitk_gui_common * * \brief Interface for a MITK Workbench Part providing a render window. * * This interface allows generic access to Workbench parts which provide some * kind of render window. The interface is intended to be implemented by * subclasses of berry::IWorkbenchPart. Usually, the interface is implemented * by a Workbench editor. * * A IRenderWindowPart provides zero or more QmitkRenderWindow instances which can * be controlled via this interface. QmitkRenderWindow instances have an associated * \e id, which is implementation specific. * Additionally the defined values AXIAL, SAGITTAL, CORONAL, THREE_D from mitk::BaseRenderer * can be used to retrieve a specific QmitkRenderWindow. * * \see ILinkedRenderWindowPart * \see IRenderWindowPartListener * \see QmitkAbstractRenderEditor */ struct MITK_GUI_COMMON_PLUGIN IRenderWindowPart { static const QString DECORATION_BORDER; // = "border" static const QString DECORATION_LOGO; // = "logo" static const QString DECORATION_MENU; // = "menu" static const QString DECORATION_BACKGROUND; // = "background" static const QString DECORATION_CORNER_ANNOTATION; // = "corner annotation" virtual ~IRenderWindowPart(); /** * Get the currently active (focused) render window. * Focus handling is implementation specific. * * \return The active QmitkRenderWindow instance; nullptr * if no render window is active. */ virtual QmitkRenderWindow* GetActiveQmitkRenderWindow() const = 0; /** * Get all render windows with their ids. * * \return A hash map mapping the render window id to the QmitkRenderWindow instance. */ virtual QHash GetQmitkRenderWindows() const = 0; /** * Get a render window with a specific id. * * \param id The render window id. * \return The QmitkRenderWindow instance for id */ virtual QmitkRenderWindow* GetQmitkRenderWindow(const QString& id) const = 0; /** * Get a render window with a specific view direction. * * \param viewDirection The render window view direction. * \return The QmitkRenderWindow instance for viewDirection */ virtual QmitkRenderWindow* GetQmitkRenderWindow(const mitk::BaseRenderer::ViewDirection& viewDirection) const = 0; /** * Get the rendering manager used by this render window part. * * \return The current IRenderingManager instance or nullptr * if no rendering manager is used. */ virtual mitk::IRenderingManager* GetRenderingManager() const = 0; /** * Request an update of all render windows. * * \param requestType Specifies the type of render windows for which an update * will be requested. */ virtual void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Force an immediate update of all render windows. * * \param requestType Specifies the type of render windows for which an immediate update * will be requested. */ virtual void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; + /** + * @brief Set the reference geometry for interaction inside the render windows of the render window part. + * + * @param referenceGeometry The reference geometry which is used for updating the + * time geometry inside the render windows. + * @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom). + * If false, the current crosshair position and the camera zoom will be stored and reset + * after the reference geometry has been updated. + */ + virtual void SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) = 0; + + /** + * @brief Returns true if the render windows are coupled; false if not. + * + * Render windows are coupled if the slice navigation controller of the render windows + * are connected which means that always the same geometry is used for the render windows. + */ + virtual bool HasCoupledRenderWindows() const = 0; + /** * Get the SliceNavigationController for controlling time positions. * * \return A SliceNavigationController if the render window supports this * operation; otherwise returns nullptr. */ virtual mitk::SliceNavigationController* GetTimeNavigationController() const = 0; /** * Get the selected position in the render window with id id * or in the active render window if id is an empty string. * * \param id The render window id. * \return The currently selected position in world coordinates. */ virtual mitk::Point3D GetSelectedPosition(const QString& id = QString()) const = 0; /** * Set the selected position in the render window with id id * or in the active render window if id is nullptr. * * \param pos The position in world coordinates which should be selected. * \param id The render window id in which the selection should take place. */ virtual void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()) = 0; /** * Get the time point selected in the render window with id id * or in the active render window if id is an empty string. * * \param id The render window id. - * \return The currently selected position in world coordinates.*/ + * \return The currently selected position in world coordinates. + */ virtual TimePointType GetSelectedTimePoint(const QString& id = QString()) const = 0; /** * Enable \e decorations like colored borders, menu widgets, logos, text annotations, etc. * * Decorations are implementation specific. A set of standardized decoration names is listed * in GetDecorations(). * * \param enable If true enable the decorations specified in decorations, * otherwise disable them. * \param decorations A list of decoration names. If empty, all supported decorations are affected. * * \see GetDecorations() */ virtual void EnableDecorations(bool enable, const QStringList& decorations = QStringList()) = 0; /** * Return if a specific decoration is enabled. * * \return true if the decoration is enabled, false if it is disabled * or unknown. * * \see GetDecorations() */ virtual bool IsDecorationEnabled(const QString& decoration) const = 0; /** * Get a list of supported decorations. * * The following decoration names are standardized and should not be used for other decoration types: *
    *
  • \e DECORATION_BORDER Any border decorations like colored rectangles, etc. *
  • \e DECORATION_MENU Menus associated with render windows *
  • \e DECORATION_BACKGROUND All kinds of backgrounds (patterns, gradients, etc.) except for solid colored backgrounds *
  • \e DECORATION_LOGO Any kind of logo overlayed on the rendered scene *
* * \return A list of supported decoration names. */ virtual QStringList GetDecorations() const = 0; }; } Q_DECLARE_INTERFACE(mitk::IRenderWindowPart, "org.mitk.ui.IRenderWindowPart") #endif // MITKIRENDERWINDOWPART_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.cpp index 84a1f6a86a..55390c7ad5 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.cpp @@ -1,219 +1,241 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAbstractMultiWidgetEditor.h" // mitk qt widgets module #include #include // mitk gui qt common plugin #include "QmitkMultiWidgetDecorationManager.h" // berry #include const QString QmitkAbstractMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.abstractmultiwidget"; struct QmitkAbstractMultiWidgetEditor::Impl final { Impl(); ~Impl() = default; QmitkAbstractMultiWidget* m_MultiWidget; std::unique_ptr m_MultiWidgetDecorationManager; }; QmitkAbstractMultiWidgetEditor::Impl::Impl() : m_MultiWidget(nullptr) { // nothing here } QmitkAbstractMultiWidgetEditor::QmitkAbstractMultiWidgetEditor() : m_Impl(std::make_unique()) { // nothing here } QmitkAbstractMultiWidgetEditor::~QmitkAbstractMultiWidgetEditor() {} QmitkRenderWindow* QmitkAbstractMultiWidgetEditor::GetActiveQmitkRenderWindow() const { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { auto activeRenderWindowWidget = multiWidget->GetActiveRenderWindowWidget(); if (nullptr != activeRenderWindowWidget) { return activeRenderWindowWidget->GetRenderWindow(); } } return nullptr; } QHash QmitkAbstractMultiWidgetEditor::GetQmitkRenderWindows() const { QHash result; const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return result; } result = multiWidget->GetRenderWindows(); return result; } QmitkRenderWindow* QmitkAbstractMultiWidgetEditor::GetQmitkRenderWindow(const QString& id) const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return nullptr; } return multiWidget->GetRenderWindow(id); } QmitkRenderWindow* QmitkAbstractMultiWidgetEditor::GetQmitkRenderWindow(const mitk::BaseRenderer::ViewDirection& viewDirection) const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return nullptr; } return multiWidget->GetRenderWindow(viewDirection); } +void QmitkAbstractMultiWidgetEditor::SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) +{ + const auto& multiWidget = GetMultiWidget(); + if (nullptr == multiWidget) + { + return; + } + + multiWidget->SetReferenceGeometry(referenceGeometry, resetCamera); +} + +bool QmitkAbstractMultiWidgetEditor::HasCoupledRenderWindows() const +{ + const auto& multiWidget = GetMultiWidget(); + if (nullptr == multiWidget) + { + return false; + } + + return multiWidget->HasCoupledRenderWindows(); +} + mitk::Point3D QmitkAbstractMultiWidgetEditor::GetSelectedPosition(const QString& id/* = QString()*/) const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return mitk::Point3D(); } return multiWidget->GetSelectedPosition(id); } void QmitkAbstractMultiWidgetEditor::SetSelectedPosition(const mitk::Point3D& pos, const QString& id/* = QString()*/) { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { return multiWidget->SetSelectedPosition(pos, id); } } void QmitkAbstractMultiWidgetEditor::EnableDecorations(bool enable, const QStringList& decorations) { m_Impl->m_MultiWidgetDecorationManager->ShowDecorations(enable, decorations); } bool QmitkAbstractMultiWidgetEditor::IsDecorationEnabled(const QString& decoration) const { return m_Impl->m_MultiWidgetDecorationManager->IsDecorationVisible(decoration); } QStringList QmitkAbstractMultiWidgetEditor::GetDecorations() const { return m_Impl->m_MultiWidgetDecorationManager->GetDecorations(); } QmitkRenderWindow* QmitkAbstractMultiWidgetEditor::GetQmitkRenderWindowByIndex(int index) const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return nullptr; } QString renderWindowName = multiWidget->GetNameFromIndex(index); return multiWidget->GetRenderWindow(renderWindowName); } QmitkRenderWindow* QmitkAbstractMultiWidgetEditor::GetQmitkRenderWindowByIndex(int row, int column) const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return nullptr; } QString renderWindowName = multiWidget->GetNameFromIndex(row, column); return multiWidget->GetRenderWindow(renderWindowName); } void QmitkAbstractMultiWidgetEditor::SetMultiWidget(QmitkAbstractMultiWidget* multiWidget) { m_Impl->m_MultiWidget = multiWidget; m_Impl->m_MultiWidgetDecorationManager.reset(new QmitkMultiWidgetDecorationManager(multiWidget)); } QmitkAbstractMultiWidget* QmitkAbstractMultiWidgetEditor::GetMultiWidget() const { return m_Impl->m_MultiWidget; } int QmitkAbstractMultiWidgetEditor::GetRowCount() const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return 0; } return multiWidget->GetRowCount(); } int QmitkAbstractMultiWidgetEditor::GetColumnCount() const { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return 0; } return multiWidget->GetColumnCount(); } void QmitkAbstractMultiWidgetEditor::OnLayoutSet(int row, int column) { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { multiWidget->SetLayout(row, column); FirePropertyChange(berry::IWorkbenchPartConstants::PROP_INPUT); } } void QmitkAbstractMultiWidgetEditor::OnSynchronize(bool synchronized) { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { multiWidget->Synchronize(synchronized); } } void QmitkAbstractMultiWidgetEditor::OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme) { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { multiWidget->SetInteractionScheme(scheme); } } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.h index 5ff38c7ae0..c053a419c6 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractMultiWidgetEditor.h @@ -1,127 +1,135 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKABSTRACTMULTIWIDGETEDITOR_H #define QMITKABSTRACTMULTIWIDGETEDITOR_H #include // org mitk gui qt common plugin #include // mitk core #include // berry #include // c++ #include class QmitkAbstractMultiWidget; class QmitkLevelWindowWidget; class MITK_QT_COMMON QmitkAbstractMultiWidgetEditor : public QmitkAbstractRenderEditor, public berry::IPartListener { Q_OBJECT public: berryObjectMacro(QmitkAbstractMultiWidgetEditor, QmitkAbstractRenderEditor, IPartListener); static const QString EDITOR_ID; QmitkAbstractMultiWidgetEditor(); virtual ~QmitkAbstractMultiWidgetEditor() override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual QmitkRenderWindow* GetActiveQmitkRenderWindow() const override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual QHash GetQmitkRenderWindows() const override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual QmitkRenderWindow* GetQmitkRenderWindow(const QString& id) const override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual QmitkRenderWindow* GetQmitkRenderWindow(const mitk::BaseRenderer::ViewDirection& viewDirection) const override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ + void SetReferenceGeometry(const mitk::TimeGeometry* referenceGeometry, bool resetCamera) override; + /** + * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart + */ + bool HasCoupledRenderWindows() const override; + /** + * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart + */ virtual mitk::Point3D GetSelectedPosition(const QString& id = QString()) const override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()) override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual void EnableDecorations(bool enable, const QStringList& decorations = QStringList()) override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual bool IsDecorationEnabled(const QString& decoration) const override; /** * @brief Overridden from QmitkAbstractRenderEditor : IRenderWindowPart */ virtual QStringList GetDecorations() const override; /** * @brief Retrieve a QmitkRenderWindow by its index. */ virtual QmitkRenderWindow* GetQmitkRenderWindowByIndex(int index) const; /** * @brief Retrieve a QmitkRenderWindow by the row and column position. */ virtual QmitkRenderWindow* GetQmitkRenderWindowByIndex(int row, int column) const; /** * @brief Set the current multi widget of this editor. */ virtual void SetMultiWidget(QmitkAbstractMultiWidget* multiWidget); /** * @brief Return the current multi widget of this editor. */ virtual QmitkAbstractMultiWidget* GetMultiWidget() const; /** * @brief Return the number of rows of the underlying multi widget. */ virtual int GetRowCount() const; /** * @brief Return the number of columns of the underlying multi widget. */ virtual int GetColumnCount() const; virtual QmitkLevelWindowWidget* GetLevelWindowWidget() const = 0; public Q_SLOTS: /** * @brief A slot that can be called if the layout has been changed. * This function will call the function 'SetLayout' of the multi widget where * custom behavior can be implemented. * Finally 'FirePropertyChange' is called to inform the workbench about an input change. */ virtual void OnLayoutSet(int row, int column); virtual void OnSynchronize(bool synchronized); virtual void OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme); private: struct Impl; std::unique_ptr m_Impl; }; #endif // QMITKABSTRACTMULTIWIDGETEDITOR_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp index 7639cb1f42..9dbad4d3e8 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp @@ -1,563 +1,522 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAbstractView.h" #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkCommonActivator.h" #include "internal/QmitkDataNodeItemModel.h" // mitk Includes #include #include #include #include #include // berry Includes #include #include #include #include #include // CTK Includes #include // Qt Includes #include #include #include #include #include class QmitkAbstractViewPrivate { public: QmitkAbstractViewPrivate(QmitkAbstractView* qq) : q(qq) , m_PrefServiceTracker(QmitkCommonActivator::GetContext()) , m_DataStorageServiceTracker(QmitkCommonActivator::GetContext()) , m_Parent(nullptr) , m_DataNodeItemModel(new QmitkDataNodeItemModel) , m_DataNodeSelectionModel(new QItemSelectionModel(m_DataNodeItemModel)) , m_InDataStorageChanged(false) { m_PrefServiceTracker.open(); m_DataStorageServiceTracker.open(); } ~QmitkAbstractViewPrivate() { delete m_DataNodeSelectionModel; delete m_DataNodeItemModel; m_PrefServiceTracker.close(); m_DataStorageServiceTracker.close(); } /** * Called when a DataStorage Add Event was thrown. Sets * m_InDataStorageChanged to true and calls NodeAdded afterwards. * \see m_InDataStorageChanged */ void NodeAddedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeAdded(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage remove event was thrown. Sets * m_InDataStorageChanged to true and calls NodeRemoved afterwards. * \see m_InDataStorageChanged */ void NodeRemovedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeRemoved(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage changed event was thrown. Sets * m_InDataStorageChanged to true and calls NodeChanged afterwards. * \see m_InDataStorageChanged */ void NodeChangedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeChanged(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * reactions to selection events from views */ void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection) { if(sourcepart.IsNull() || sourcepart.GetPointer() == static_cast(q)) return; if(selection.IsNull()) { q->OnNullSelection(sourcepart); return; } mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); q->OnSelectionChanged(sourcepart, this->DataNodeSelectionToQList(_DataNodeSelection)); } /** * Converts a mitk::DataNodeSelection to a QList (possibly empty) */ QList DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const; QmitkAbstractView* const q; ctkServiceTracker m_PrefServiceTracker; ctkServiceTracker m_DataStorageServiceTracker; /** * Saves the parent of this view (this is the scrollarea created in CreatePartControl(QWidget*) * \see CreatePartControl(QWidget*) */ QWidget* m_Parent; /** * Holds the current selection (selection made by this View !!!) */ QmitkDataNodeSelectionProvider::Pointer m_SelectionProvider; /** * Holds a helper model for firing selection events. */ QmitkDataNodeItemModel* m_DataNodeItemModel; /** * The selection model for the QmitkDataNodeItemModel; */ QItemSelectionModel* m_DataNodeSelectionModel; /** * object to observe BlueBerry selections */ QScopedPointer m_BlueBerrySelectionListener; /** * Saves if this class is currently working on DataStorage changes. * This is a protector variable to avoid recursive calls on event listener functions. */ bool m_InDataStorageChanged; }; QmitkAbstractView::QmitkAbstractView() : d(new QmitkAbstractViewPrivate(this)) { } void QmitkAbstractView::CreatePartControl(QWidget* parent) { // scrollArea auto scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent d->m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(d->m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(d->m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); auto parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkAbstractView::AfterCreateQtPartControl() { this->SetSelectionProvider(); // REGISTER DATASTORAGE LISTENER this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) prefs->OnChanged.AddListener( berry::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS d->m_BlueBerrySelectionListener.reset(new berry::NullSelectionChangedAdapter( d.data(), &QmitkAbstractViewPrivate::BlueBerrySelectionChanged)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(d->m_BlueBerrySelectionListener.data()); // EMULATE INITIAL SELECTION EVENTS // send the current selection berry::IWorkbenchPart::Pointer activePart = this->GetSite()->GetPage()->GetActivePart(); if (activePart.IsNotNull()) { this->OnSelectionChanged(activePart, this->GetCurrentSelection()); } // send preferences changed event this->OnPreferencesChanged(this->GetPreferences().Cast().GetPointer()); } QmitkAbstractView::~QmitkAbstractView() { this->Register(); this->GetDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy) ); this->GetDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) { prefs->OnChanged.RemoveListener( berry::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) // prefs->Flush(); } // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(nullptr)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(d->m_BlueBerrySelectionListener.data()); } this->UnRegister(false); } void QmitkAbstractView::SetSelectionProvider() { // REGISTER A SELECTION PROVIDER d->m_SelectionProvider = QmitkDataNodeSelectionProvider::Pointer(new QmitkDataNodeSelectionProvider); d->m_SelectionProvider->SetItemSelectionModel(GetDataNodeSelectionModel()); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(d->m_SelectionProvider)); } QItemSelectionModel *QmitkAbstractView::GetDataNodeSelectionModel() const { return nullptr; } void QmitkAbstractView::OnPreferencesChanged( const berry::IBerryPreferences* ) { } void QmitkAbstractView::DataStorageModified() { } void QmitkAbstractView::DataStorageChanged(mitk::IDataStorageReference::Pointer /*dsRef*/) { } mitk::IRenderWindowPart* QmitkAbstractView::GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategies strategies) const { berry::IWorkbenchPage::Pointer page = GetSite()->GetPage(); return mitk::WorkbenchUtil::GetRenderWindowPart(page, strategies); } void QmitkAbstractView::RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType) { mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if (renderPart == nullptr) return; if (mitk::IRenderingManager* renderingManager = renderPart->GetRenderingManager()) { renderingManager->RequestUpdateAll(requestType); } else { renderPart->RequestUpdate(requestType); } } -void QmitkAbstractView::InitializeRenderWindows(const mitk::TimeGeometry *referenceGeometry, - mitk::RenderingManager::RequestType requestType, - bool resetCamera) -{ - mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); - if (nullptr == renderWindowPart) - { - return; - } - - mitk::IRenderingManager* renderingManager = renderWindowPart->GetRenderingManager(); - if (nullptr == renderingManager) - { - return; - } - - mitk::Point3D currentPosition = mitk::Point3D(); - unsigned int imageTimeStep = 0; - if (!resetCamera) - { - // store the current position to set it again later, if the camera should not be reset - currentPosition = renderWindowPart->GetSelectedPosition(); - - // store the current time step to set it again later, if the camera should not be reset - const auto currentTimePoint = renderingManager->GetTimeNavigationController()->GetSelectedTimePoint(); - if (referenceGeometry->IsValidTimePoint(currentTimePoint)) - { - imageTimeStep = referenceGeometry->TimePointToTimeStep(currentTimePoint); - } - } - - // initialize render windows - renderingManager->InitializeViews(referenceGeometry, requestType, resetCamera); - - if (!resetCamera) - { - renderWindowPart->SetSelectedPosition(currentPosition); - renderingManager->GetTimeNavigationController()->GetTime()->SetPos(imageTimeStep); - } -} - void QmitkAbstractView::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkAbstractView::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkAbstractView::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkAbstractView::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkAbstractView::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } berry::IPreferences::Pointer QmitkAbstractView::GetPreferences() const { berry::IPreferencesService* prefService = d->m_PrefServiceTracker.getService(); // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const QString id = "/" + (const_cast(this))->GetViewSite()->GetId(); return prefService ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(nullptr); } mitk::DataStorage::Pointer QmitkAbstractView::GetDataStorage() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != nullptr) { return dsService->GetDataStorage()->GetDataStorage(); } return nullptr; } mitk::IDataStorageReference::Pointer QmitkAbstractView::GetDataStorageReference() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != nullptr) { return dsService->GetDataStorage(); } return mitk::IDataStorageReference::Pointer(nullptr); } QList QmitkAbstractView::GetCurrentSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection()); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsCurrentSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); } QList QmitkAbstractView::GetDataManagerSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsDataManagerSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager"); } void QmitkAbstractView::SetDataManagerSelection(const berry::ISelection::ConstPointer &selection, QItemSelectionModel::SelectionFlags flags) const { berry::IViewPart::Pointer datamanagerView = this->GetSite()->GetWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.datamanager"); if (datamanagerView.IsNull()) return; datamanagerView->GetSite()->GetSelectionProvider().Cast()->SetSelection(selection, flags); } void QmitkAbstractView::SynchronizeDataManagerSelection() const { berry::ISelection::ConstPointer currentSelection = this->GetSite()->GetSelectionProvider()->GetSelection(); if (currentSelection.IsNull()) return; SetDataManagerSelection(currentSelection); } void QmitkAbstractView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& /*nodes*/) { } void QmitkAbstractView::OnNullSelection(berry::IWorkbenchPart::Pointer /*part*/) { } QList QmitkAbstractViewPrivate::DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const { if (currentSelection.IsNull()) return QList(); return QList::fromStdList(currentSelection->GetSelectedDataNodes()); } void QmitkAbstractView::NodeAdded( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeRemoved( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeChanged( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::FireNodeSelected( mitk::DataNode::Pointer node ) { QList nodes; nodes << node; this->FireNodesSelected(nodes); } void QmitkAbstractView::FireNodesSelected( const QList& nodes ) { // if this is the first call to FireNodesSelected and the selection provider has no QItemSelectiomMode // yet, set our helper model if (d->m_SelectionProvider->GetItemSelectionModel() == nullptr) { d->m_SelectionProvider->SetItemSelectionModel(d->m_DataNodeSelectionModel); } else if (d->m_SelectionProvider->GetItemSelectionModel() != d->m_DataNodeSelectionModel) { MITK_WARN << "A custom data node selection model has been set. Ignoring call to FireNodesSelected()."; return; } if (nodes.empty()) { d->m_DataNodeSelectionModel->clearSelection(); d->m_DataNodeItemModel->clear(); } else { // The helper data node model is just used for sending selection events. // We add the to be selected nodes and set the selection range to everything. d->m_DataNodeItemModel->clear(); foreach(mitk::DataNode::Pointer node, nodes) { d->m_DataNodeItemModel->AddDataNode(node); } d->m_DataNodeSelectionModel->select(QItemSelection(d->m_DataNodeItemModel->index(0,0), d->m_DataNodeItemModel->index(nodes.size()-1, 0)), QItemSelectionModel::ClearAndSelect); } } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h index 1566bb53f5..9217ba2cfe 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h @@ -1,375 +1,362 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKABSTRACTVIEW_H_ #define QMITKABSTRACTVIEW_H_ //# blueberry stuff #include #include #include #include //# mitk stuff #include #include "mitkDataNodeSelection.h" #include "mitkIRenderWindowPart.h" #include #include #include #include #include namespace mitk { class DataNode; } namespace berry { struct IBerryPreferences; } class QmitkAbstractViewPrivate; class QmitkAbstractViewSelectionProvider; /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK related BlueBerry Views. * * QmitkAbstractView provides several convenience methods that ease the introduction of a new view: * *
    *
  1. Access to the DataStorage (~ the shared data repository) *
  2. Access to the active IRenderWindowPart *
  3. Access to and update notification for the view's preferences *
  4. Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService *
  5. Access to and update notification for DataNode events (added/removed/modified) *
  6. Methods to send DataNode selections through the SelectionService *
  7. Some minor important convenience methods (like changing the mouse cursor/exception handling) *
* * Usually all MITK Views inherit from QmitkAbstractView to achieve a consistent Workbench behavior. * * When inheriting from QmitkAbstractView, you must implement the following methods: *
    *
  • void CreateQtPartControl(QWidget* parent) *
  • void SetFocus() *
* * You may reimplement the following private virtual methods to customize your View's behavior: *
    *
  • void SetSelectionProvider() *
  • QItemSelectionModel* GetDataNodeSelectionModel() const *
* * You may reimplement the following private virtual methods to be notified about certain changes: *
    *
  • void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) *
  • void OnNullSelection(berry::IWorkbenchPart::Pointer part) *
  • void OnPreferencesChanged(const berry::IBerryPreferences*) *
  • void NodeAdded(const mitk::DataNode* node) *
  • void NodeChanged(const mitk::DataNode* node) *
  • void NodeRemoved(const mitk::DataNode* node) *
  • void DataStorageModified() *
  • void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef) *
* * \see mitk::ILifecycleAwarePart * \see mitk::IZombieViewPart * \see mitk::IRenderWindowPartListener */ class MITK_QT_COMMON QmitkAbstractView : public berry::QtViewPart { public: /** * Creates smartpointer typedefs */ berryObjectMacro(QmitkAbstractView); /** * Nothing to do in the standard ctor. Initiliaze your GUI in CreateQtPartControl(QWidget*) * \see berry::QtViewPart::CreateQtPartControl(QWidget*) */ QmitkAbstractView(); /** * Disconnects all standard event listeners */ ~QmitkAbstractView() override; protected: /** * Informs other parts of the workbench that node is selected via the blueberry selection service. * * \note This method should not be used if you have set your own selection provider via * SetSelectionProvider() or your own QItemSelectionModel via GetDataNodeSelectionModel(). */ void FireNodeSelected(mitk::DataNode::Pointer node); /** * Informs other parts of the workbench that the nodes are selected via the blueberry selection service. * * \note This method should not be used if you have set your own selection provider via * SetSelectionProvider() or your own QItemSelectionModel via GetDataNodeSelectionModel(). */ virtual void FireNodesSelected(const QList& nodes); /** * \return The selection of the currently active part of the workbench or an empty list * if there is no selection or if it is empty. * * \see IsCurrentSelectionValid */ QList GetCurrentSelection() const; /** * Queries the state of the current selection. * * \return If the current selection is nullptr, this method returns * false and true otherwise. */ bool IsCurrentSelectionValid() const; /** * Returns the current selection made in the datamanager bundle or an empty list * if there is no selection or if it is empty. * * \see IsDataManagerSelectionValid */ QList GetDataManagerSelection() const; /** * Queries the state of the current selection of the data manager view. * * \return If the current data manager selection is nullptr, this method returns * false and true otherwise. */ bool IsDataManagerSelectionValid() const; /** * Sets the selection of the data manager view if available. * * \param selection The new selection for the data manager. * \param flags The Qt selection flags for controlling the way how the selection is updated. */ void SetDataManagerSelection(const berry::ISelection::ConstPointer& selection, QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect) const; /** * Takes the current selection and sets it on the data manager. Only matching nodes in the * data manager view will be selected. */ void SynchronizeDataManagerSelection() const; /** * Returns the Preferences object for this View. * Important: When refering to this preferences, e.g. in a PreferencePage: The ID * for this preferences object is "/", e.g. "/org.mitk.views.datamanager" */ berry::IPreferences::Pointer GetPreferences() const; /** * Returns a reference to the currently active DataStorage. */ mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Returns the currently active DataStorage. */ mitk::DataStorage::Pointer GetDataStorage() const; /** * Returns the currently active mitk::IRenderWindowPart. * * \param strategies Strategies for returning a mitk::IRenderWindowPart instance if there * is currently no active one. * \return The active mitk::IRenderWindowPart. */ mitk::IRenderWindowPart* GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategies strategies = mitk::WorkbenchUtil::NONE) const; /** * Request an update of all render windows of the currently active IRenderWindowPart. * * \param requestType Specifies the type of render windows for which an update will be requested. */ void RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); - /** - * Initialize the specified render windows to the given reference geometry. - * - * \param referenceGeometry The reference geometry which is used for updating the current world geometry - * \param requestType Specifies the type of render windows for which an update will be requested - * \param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom). - * If false, the current crosshair position will be stored and reset after the views have been - * initialized. The camera zoom will be kept after the view initialization. - */ - void InitializeRenderWindows(const mitk::TimeGeometry *referenceGeometry, - mitk::RenderingManager::RequestType requestType, - bool resetCamera); - /** * 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 parent * \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 = nullptr, bool showDialog = true ) const; /** * Calls HandleException ( std::exception&, QWidget*, bool ) internally * \see HandleException ( std::exception&, QWidget*, bool ) */ void HandleException( const char* str, QWidget* parent = nullptr, bool showDialog = true ) const; /** * Convenient method to set and reset a wait cursor ("hourglass") */ void WaitCursorOn(); /** * Convenient method to restore the standard cursor */ void WaitCursorOff(); /** * Convenient method to set and reset a busy cursor */ void BusyCursorOn(); /** * Convenient method to restore the standard cursor */ void BusyCursorOff(); /** * Convenient method to restore the standard cursor */ void RestoreOverrideCursor(); private: /** * Reimplement this method to set a custom selection provider. This method is * called once after CreateQtPartControl(). * * The default implementation registers a QmitkDataNodeSelectionProvider with * a QItemSelectionModel returned by GetDataNodeSelectionModel(). */ virtual void SetSelectionProvider(); /** * Reimplement this method to supply a custom Qt selection model. The custom * model will be used with the default selection provider QmitkDataNodeSelectionProvider * to inform the MITK Workbench about selection changes. * * If you reimplement this method, the methods FireNodeSelected() and FireNodesSelected() * will have no effect. Use your custom selection model to notify the MITK Workbench * about selection changes. * * The Qt item model used with the custom selection model must return mitk::DataNode::Pointer * objects for model indexes when the role is QmitkDataNodeRole. */ virtual QItemSelectionModel* GetDataNodeSelectionModel() const; /** * Called when the selection in the workbench changed. * May be reimplemented by deriving classes. * * \param part The source part responsible for the selection change. * \param nodes A list of selected nodes. * * \see OnNullSelection */ virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes); /** * Called when a nullptr selection occurs. * * \param part The source part responsible for the selection change. */ virtual void OnNullSelection(berry::IWorkbenchPart::Pointer part); /** * Called when the preferences object of this view changed. * May be reimplemented by deriving classes. * * \see GetPreferences() */ virtual void OnPreferencesChanged(const berry::IBerryPreferences*); /** * Called when a DataStorage Add event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeAdded(const mitk::DataNode* node); /** * Called when a DataStorage Changed event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeChanged(const mitk::DataNode* node); /** * Called when a DataStorage Remove event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeRemoved(const mitk::DataNode* node); /** * Called when a DataStorage add *or* remove *or* change event from the currently active * data storage is thrown. * * May be reimplemented by deriving classes. */ virtual void DataStorageModified(); /** * Called when the currently active DataStorage changed. * May be reimplemented by deriving classes. * * \param dsRef A reference to the new active DataStorage. */ virtual void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef); /** * Creates a scroll area for this view and calls CreateQtPartControl then */ void CreatePartControl(QWidget* parent) override; /** * Called immediately after CreateQtPartControl(). * Here standard event listeners for a QmitkAbstractView are registered */ void AfterCreateQtPartControl(); private: friend class QmitkAbstractViewPrivate; friend class QmitkViewCoordinator; Q_DISABLE_COPY(QmitkAbstractView) const QScopedPointer d; }; #endif /*QMITKABSTRACTVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.ui b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.ui index 2dc411a927..26f94b420d 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.ui +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.ui @@ -1,131 +1,116 @@ QmitkNodeSelectionDialog 0 0 800 600 Dialog true true - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - 6 6 6 6 QFrame::NoFrame Info text ... Qt::RichText true -1 24 24 6 6 6 6 error text Add the current selection to the favorites. Add to favorites QDialogButtonBox::Cancel|QDialogButtonBox::Ok diff --git a/Plugins/org.mitk.gui.qt.datamanager/documentation/UserManual/QmitkDatamanager.dox b/Plugins/org.mitk.gui.qt.datamanager/documentation/UserManual/QmitkDatamanager.dox index f9c36fce44..7c7326558c 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/documentation/UserManual/QmitkDatamanager.dox +++ b/Plugins/org.mitk.gui.qt.datamanager/documentation/UserManual/QmitkDatamanager.dox @@ -1,194 +1,192 @@ /** \page org_mitk_views_datamanager The Data Manager View \imageMacro{data-manager-dox.svg,"Icon of the Data Manager", 2.00} \tableofcontents \section DataManagerIntroduction Introduction The Datamanager is the central component to manage medical data like images, segmentation masks, registrations, surfaces, point sets, annotations, measurements, etc..
After loading data into the Datamanager the data is shown in the four-view window, the so-called Standard Display. The user can now start working on the data by interacting with the data inside the Standard Display, by using the MITK-plugins such as Segmentation or Basic Image Processing or by using the context menu inside the data manager. \section DataManagerLoadingData Loading Data There are several ways of loading data into the Datamanager as so-called data nodes:
  • drag and drop data (e.g. from a file explorer or desktop) into the Datamanager
  • drag and drop data (e.g. from a file explorer or desktop) into one of the four windows of the Standard Display
  • use the keyboard shortcut Ctrl + o
  • use the Open File Button in the left upper corner and use the Open Dialog
  • use File -> Open File... from the top menu
A lot of file-formats can be loaded into MITK, for example:
  • 2D-images / 3D-volumes with or without several time steps (*.dcm, *.ima, *.nrrd, ...)
  • Surfaces (*.stl, *.vtk, ...)
  • Point sets (*.mps)
  • and many more
The user can also load a series of 2D images (e.g. image001.png, image002.png ...) to a MITK 3D volume. To do this, just drag and drop one of those 2D data files into the Datamanager by holding the ALT key. Note: What really happens is that the data nodes are stored inside a "Data storage" and the Datamanager is just a visual representation of the data inside the "Data storage". That's why the documentation sometimes uses the term "Data storage" instead of "Datamanager". \section DataManagerSavingData Saving Data There are several ways of saving data from the Datamanager:
  • use the keyboard shortcut Ctrl + s on a single data node
  • use the keyboard shortcut Ctrl + s on multiple data nodes
  • use the context menu right-click -> Save on a single data node
  • use the context menu right-click -> Save on multiple data nodes
  • use File -> Save... from the top menu on a single data node
  • use File -> Save... from the top menu on multiple data nodes
\section DataManagerWorking Working with the Datamanager After loading data into the Datamanager the data appears as data nodes in a sorted list inside the Datamanager. The user can change the order of the data nodes manually by dragging one or multiple data nodes and dropping them at any position inside the Datamanager. Data nodes can also be sorted hierarchically as a parent-child-relation. For example after using the Segmentation-Plugin to create a segmentation on DataNode, the result is created as ChildNode, which is a child of DataNode (see \ref ParentChild "Parent-Child-Relation" screenshot).
A parent-child-relation can be changed by dragging a child of a data node and dropping it onto another data node. For this the Property Allow changing of parent nodes needs to be enabled (see \ref DataManagerPreferences "Preferences"). \anchor ParentChild \imageMacro{QmitkDatamanager_ParentChild.png, "Parent-Child-Relation", 16.00} \subsection DataManagerNodeVisibility Visibility of data nodes By default all loaded data nodes are visible in the Standard Display. The visibility is indicated by the checkbox in front of the data node name in the Datamanager. If a data node is visible, the checkbox is filled - an empty checkbox indicates a hidden data node (see \ref ParentChild "Parent-Child-Relation" screenshot). Hint: The data nodes are rendered on top of each other, such that the topmost visible data node is always displayed on top of other data nodes. By hiding the topmost visible data node the next data node becomes the topmost visible data node and the hidden data node is not rendered anymore. Note: "Visible" does not mean that the node is correctly displayed inside the render windows. The user might have to re-initialize a data node to have it correctly displayed. \subsection DataManagerNodeSelection Selection of data nodes Some MITK-plugins contain widgets to control the data nodes that are used for plugin-specific data processing. These widgets can be configured such that they listen to the current selection of the Datamanager. Having such a plugin active each selection change of data nodes inside the data manager will change the respective selection of the plugin. The data node selection widgets can have specific node predicates, which means that only specific data nodes can be controlled by the widgets. It might happen that a selected data node will not be represented in such a selection widget or that the selection widget will be emptied. \subsection DataManagerNodeRenaming Renaming data nodes There are two ways of changing the name of a data node inside the Datamanager:
  • use the F2 key on a single data node
  • double-click on a single data node
In both cases the new name can be accepted by hitting Enter or by clicking somewhere else. \section DataManagerContextMenu Context Menu The Datamanager provides a context menu for each data node that can be opened by right-clicking on a data node. An example of the context-menu can be seen in the \ref ContextMenu "Context menu" screenshot. The context menu allows to quickly perform common actions on data nodes. These actions differ according to the data type. Some of these actions are described here. For more actions see the respective modules and plugins (e.g. QmitkCreatePolygonModelAction inside the org_mitk_gui_qt_segmentation-plugin.
  • Global Reinit: Re-initializes the render windows to the common bounding box of all data nodes of the data storage that
    • have not set "includeInBoundingBox" to false
    • are "visible".
    In this case it does not matter on which node this action is performed.
  • Reinit: Re-initializes the render windows to the common bounding box of all selected data nodes of the data storage that
    • have not set "includeInBoundingBox" to false
    • are "visible".
  • Save: see \ref DataManagerSavingData "Saving Data" section
  • Remove: Removes all selected data nodes from the data storage.
  • Show only selected nodes: Enables the visibility of all selected data nodes and hides all other data nodes.
  • Toggle visibility: Shows / hides each selected data node according to each node's current visibility state.
  • Show details: Opens a pop-up window with detailed information about each node, like data type, geometry, DICOM information, file path etc.
  • Opacity: Sets the opacity via a slider for the rendering of the selected data node.
  • Color: Opens a pop-up window that allows to pick an arbitrary color for the rendering of all selected data nodes.
  • Colormap: Opens another submenu with a list of different colormaps that can be chosen for the rendering of all selected data nodes.
  • Component: Sets the currently visible data component for the rendering of this particular component of the selected data node.
  • Texture Interpolation: Smooths the data visualization for rendering of a selected data node.
  • Surface Representation: Opens another submenu with the following entries:
    • Points: Visually represents a surface (a data type) as a set of points.
    • Wireframe: Visually represents a surface (a data type) as a wireframe model.
    • Surface: Visually represents a surface (a data type) as a solid surface.
As the description of the actions showed, it is possible to open / use the context menu with a single data node or with a set of selected data nodes. If the data types of multiple selected data nodes differ, the actions might not appear / work as expected. Also some actions are not available for a set of selected data nodes. \anchor ContextMenu \imageMacro{QmitkDatamanager_ContextMenu.png, "Context menu", 16.00} \section DataManagerPreferences Preferences The MITK Workbench provides a preference page for specific plugins. The preference page provided for the Datamanager can be seen in the \ref PreferencePage "Preference page" screenshot. The user can open the preference page by
  • using the keyboard shortcut Ctrl + p
  • using Window -> Preferences... from the top menu.
It allows to set the following preferences for the Datamanager, which define the behavior of the Datamanager:
  • Place new nodes on top: If enabled, newly added data nodes will be inserted at the top of the list of data nodes inside the Datamanager. If disabled, newly added nodes will be inserted at the bottom of the list.
  • Show helper objects: If enabled, data nodes that have set "helper object" to true will be displayed in the Datamanager. If disabled, data nodes that have set "helper object" to true will not be visible in the Datamanager.
  • Show nodes containing no data: If enabled, data nodes that have no underlying base data defined will be displayed in the Datamanager. If disabled, data nodes that have no underlying base data defined will not be visible in the Datamanager. -
  • Use surface decimation: If enabled, a newly created surface will be decimated to reduce the number of triangles in the triangle mesh. - Such a surface can be created as a polygon model from a segmentation (see \ref DataManagerContextMenu "Context Menu"). If disabled, the surface will have its original number of triangles in the triangle mesh.
  • Allow changing of parent node: If enabled, the user can change the hierarchy of the data nodes manually by dragging one or multiple data nodes and dropping them at any position inside the Datamanager (see \ref DataManagerWorking "Working with the Datamanager") for changing the order of the data nodes manually).
\anchor PreferencePage \imageMacro{QmitkDatamanager_PreferencePage.png, "Preference page", 16.00} \section DataManagerHotkeys Hotkeys The MITK Workbench provides hotkeys for specific plugins. The hotkeys provided for the Datamanager can be seen in the \ref Hotkeys "Hotkeys" screenshot. They allow to expedite common operations in relation to data nodes or the Datamanager. The user can customize the hotkeys by accessing the preference page:
  • using the keyboard shortcut Ctrl + p
  • useing Window -> Preferences... from the top menu
  • Delete selected nodes Removes all selected data nodes from the data storage.
  • Global reinit Re-initializes the render windows to the common bounding box of all data nodes of the data storage that
    • have not set "includeInBoundingBox" to false
    • are "visible"
    In this case it does not matter on which node this action is performed.
  • Make all nodes invisible Hides all data nodes of the data storage.
  • Reinit selected nodes Re-initializes the render windows to the common bounding box of all selected data nodes of the data storage that
    • have not set "includeInBoundingBox" to false
    • are "visible"
  • Show node information Opens a pop-up window with detailed information about each node, like data type, geometry, DICOM information, file path etc.
  • Toggle visibility of selected nodes: Shows / hides each selected data node according to each node's current visibility state.
\anchor Hotkeys \imageMacro{QmitkDatamanager_Hotkeys.png, "Hotkeys", 16.00} */ diff --git a/Plugins/org.mitk.gui.qt.datamanager/plugin.xml b/Plugins/org.mitk.gui.qt.datamanager/plugin.xml index fac19121f7..24d7a1b211 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/plugin.xml +++ b/Plugins/org.mitk.gui.qt.datamanager/plugin.xml @@ -1,28 +1,28 @@ - + diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp index cc3a9aab2d..0e65d3117c 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp @@ -1,92 +1,88 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDataManagerPreferencePage.h" #include "QmitkDataManagerView.h" #include #include #include #include #include #include QmitkDataManagerPreferencePage::QmitkDataManagerPreferencePage() : m_MainControl(nullptr) { // nothing here } void QmitkDataManagerPreferencePage::Init(berry::IWorkbench::Pointer ) { // nothing here } void QmitkDataManagerPreferencePage::CreateQtControl(QWidget* parent) { berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_DataManagerPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataManagerView::VIEW_ID); m_MainControl = new QWidget(parent); m_EnableSingleEditing = new QCheckBox; m_PlaceNewNodesOnTop = new QCheckBox; m_ShowHelperObjects = new QCheckBox; m_ShowNodesContainingNoData = new QCheckBox; - m_UseSurfaceDecimation = new QCheckBox; m_AllowParentChange = new QCheckBox; auto formLayout = new QFormLayout; formLayout->addRow("&Single click property editing:", m_EnableSingleEditing); formLayout->addRow("&Place new nodes on top:", m_PlaceNewNodesOnTop); formLayout->addRow("&Show helper objects:", m_ShowHelperObjects); formLayout->addRow("&Show nodes containing no data", m_ShowNodesContainingNoData); - formLayout->addRow("&Use surface decimation:", m_UseSurfaceDecimation); formLayout->addRow("&Allow changing of parent node:", m_AllowParentChange); m_MainControl->setLayout(formLayout); Update(); } QWidget* QmitkDataManagerPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkDataManagerPreferencePage::PerformOk() { m_DataManagerPreferencesNode->PutBool("Single click property editing", m_EnableSingleEditing->isChecked()); m_DataManagerPreferencesNode->PutBool("Place new nodes on top", m_PlaceNewNodesOnTop->isChecked()); m_DataManagerPreferencesNode->PutBool("Show helper objects", m_ShowHelperObjects->isChecked()); m_DataManagerPreferencesNode->PutBool("Show nodes containing no data", m_ShowNodesContainingNoData->isChecked()); - m_DataManagerPreferencesNode->PutBool("Use surface decimation", m_UseSurfaceDecimation->isChecked()); m_DataManagerPreferencesNode->PutBool("Allow changing of parent node", m_AllowParentChange->isChecked()); return true; } void QmitkDataManagerPreferencePage::PerformCancel() { // nothing here } void QmitkDataManagerPreferencePage::Update() { m_EnableSingleEditing->setChecked(m_DataManagerPreferencesNode->GetBool("Single click property editing", true)); m_PlaceNewNodesOnTop->setChecked(m_DataManagerPreferencesNode->GetBool("Place new nodes on top", true)); m_ShowHelperObjects->setChecked(m_DataManagerPreferencesNode->GetBool("Show helper objects", false)); m_ShowNodesContainingNoData->setChecked(m_DataManagerPreferencesNode->GetBool("Show nodes containing no data", false)); - m_UseSurfaceDecimation->setChecked(m_DataManagerPreferencesNode->GetBool("Use surface decimation", true)); m_AllowParentChange->setChecked(m_DataManagerPreferencesNode->GetBool("Allow changing of parent node", false)); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h index 19dcb176cd..f0c478a463 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h @@ -1,64 +1,63 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERPREFERENCEPAGE_H_ #define QMITKDATAMANAGERPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include #include class QWidget; class QCheckBox; struct MITK_QT_DATAMANAGER QmitkDataManagerPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDataManagerPreferencePage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected: QWidget* m_MainControl; QCheckBox* m_EnableSingleEditing; QCheckBox* m_PlaceNewNodesOnTop; QCheckBox* m_ShowHelperObjects; QCheckBox* m_ShowNodesContainingNoData; - QCheckBox* m_UseSurfaceDecimation; QCheckBox* m_AllowParentChange; berry::IPreferences::Pointer m_DataManagerPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp index 6af9236c5b..09fad8822f 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp @@ -1,235 +1,230 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDataManagerView.h" // mitk gui qt datamanager #include "internal/QmitkDataManagerItemDelegate.h" #include "internal/QmitkNodeTableViewKeyFilter.h" // mitk core #include #include #include #include #include #include #include #include #include #include #include #include #include #include // qt widgets module #include #include #include #include #include // mitk core services plugin #include #include // mitk gui common plugin #include // mitk gui qt application plugin #include #include // mitk gui qt common plugin #include // qt #include #include #include const QString QmitkDataManagerView::VIEW_ID = "org.mitk.views.datamanager"; QmitkDataManagerView::QmitkDataManagerView() : m_ItemDelegate(nullptr) { } QmitkDataManagerView::~QmitkDataManagerView() { // nothing here } void QmitkDataManagerView::CreateQtPartControl(QWidget* parent) { m_CurrentRowCount = 0; m_Parent = parent; berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); assert(prefs); - //# GUI m_NodeTreeModel = new QmitkDataStorageTreeModel(GetDataStorage(), prefs->GetBool("Place new nodes on top", true)); m_NodeTreeModel->setParent(parent); m_NodeTreeModel->SetAllowHierarchyChange(prefs->GetBool("Allow changing of parent node", false)); - 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(nullptr); m_FilterModel = new QmitkDataStorageFilterProxyModel(); m_FilterModel->setSourceModel(m_NodeTreeModel); m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate); m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate); 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, GetDataStorage())); m_ItemDelegate = new QmitkDataManagerItemDelegate(m_NodeTreeView); m_NodeTreeView->setItemDelegate(m_ItemDelegate); connect(m_NodeTreeModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(NodeTreeViewRowsInserted(const QModelIndex&, int, int))); connect(m_NodeTreeModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(NodeTreeViewRowsRemoved(const QModelIndex&, int, int))); connect(m_NodeTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(NodeSelectionChanged(const QItemSelection &, const QItemSelection &))); connect(m_NodeTreeModel, &QmitkDataStorageTreeModel::nodeVisibilityChanged, this, &QmitkDataManagerView::OnNodeVisibilityChanged); // data node context menu and menu actions m_DataNodeContextMenu = new QmitkDataNodeContextMenu(GetSite(), m_NodeTreeView); m_DataNodeContextMenu->SetDataStorage(GetDataStorage()); - m_DataNodeContextMenu->SetSurfaceDecimation(m_SurfaceDecimation); connect(m_NodeTreeView, SIGNAL(customContextMenuRequested(const QPoint&)), m_DataNodeContextMenu, SLOT(OnContextMenuRequested(const QPoint&))); 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() { } ////////////////////////////////////////////////////////////////////////// // Node tree modification ////////////////////////////////////////////////////////////////////////// void QmitkDataManagerView::NodeTreeViewRowsInserted(const QModelIndex& parent, int /*start*/, int /*end*/) { QModelIndex viewIndex = m_FilterModel->mapFromSource(parent); m_NodeTreeView->setExpanded(viewIndex, true); // a new row was inserted if (m_CurrentRowCount == 0 && m_NodeTreeModel->rowCount() == 1) { mitk::WorkbenchUtil::OpenRenderWindowPart(GetSite()->GetPage()); m_CurrentRowCount = m_NodeTreeModel->rowCount(); } } void QmitkDataManagerView::NodeTreeViewRowsRemoved(const QModelIndex& /*parent*/, int /*start*/, int /*end*/) { m_CurrentRowCount = m_NodeTreeModel->rowCount(); } void QmitkDataManagerView::NodeSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { auto selectedNodes = GetCurrentSelection(); auto nodeSet = m_NodeTreeModel->GetNodeSet(); for (auto node : qAsConst(nodeSet)) { if (node.IsNotNull()) { node->SetSelected(selectedNodes.contains(node)); } } m_DataNodeContextMenu->SetSelectedNodes(selectedNodes); } void QmitkDataManagerView::OnNodeVisibilityChanged() { ToggleVisibilityAction::Run(GetSite(), GetDataStorage(), QList()); } 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); } 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_NodeTreeView->expandAll(); - m_SurfaceDecimation = prefs->GetBool("Use surface decimation", false); - m_DataNodeContextMenu->SetSurfaceDecimation(m_SurfaceDecimation); - m_NodeTreeModel->SetAllowHierarchyChange(prefs->GetBool("Allow changing of parent node", false)); GlobalReinitAction::Run(GetSite(), GetDataStorage()); } QItemSelectionModel* QmitkDataManagerView::GetDataNodeSelectionModel() const { return m_NodeTreeView->selectionModel(); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h index d788e63c56..4258ce4e39 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h @@ -1,127 +1,123 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERVIEW_H #define QMITKDATAMANAGERVIEW_H #include // mitk core #include // berry plugin #include // mitk gui qt common plugin #include // mitk gui qt application #include // qt #include // forward declarations class QModelIndex; class QTreeView; class QmitkDnDFrameWidget; class QmitkDataStorageTreeModel; class QmitkDataManagerItemDelegate; class QmitkDataStorageFilterProxyModel; /** * @brief A view that shows all data nodes of the data storage in a qt tree view. * */ class MITK_QT_DATAMANAGER QmitkDataManagerView : public QmitkAbstractView { Q_OBJECT public: static const QString VIEW_ID; // = "org.mitk.views.datamanager" QmitkDataManagerView(); ~QmitkDataManagerView() override; public Q_SLOTS: // invoked when the berry preferences were changed void OnPreferencesChanged(const berry::IBerryPreferences* prefs) override; ////////////////////////////////////////////////////////////////////////// // Slots for Qt node tree signals ////////////////////////////////////////////////////////////////////////// /// When rows are inserted auto expand them void NodeTreeViewRowsInserted(const QModelIndex& parent, int start, int end); /// will setup m_CurrentRowCount void NodeTreeViewRowsRemoved(const QModelIndex& parent, int start, int end); /// Whenever the selection changes set the "selected" property respectively void NodeSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); void OnNodeVisibilityChanged(); protected: void CreateQtPartControl(QWidget* parent) override; void SetFocus() override; /// /// React to node changes. Overridden from QmitkAbstractView. /// void NodeChanged(const mitk::DataNode* node) override; protected: QWidget* m_Parent; QmitkDnDFrameWidget* m_DnDFrameWidget; /// /// \brief A plain widget as the base pane. /// QmitkDataStorageTreeModel* m_NodeTreeModel; QmitkDataStorageFilterProxyModel* m_FilterModel; mitk::NodePredicateBase::Pointer m_HelperObjectFilterPredicate; mitk::NodePredicateBase::Pointer m_NodeWithNoDataFilterPredicate; /// /// Holds the preferences for the data manager. /// berry::IBerryPreferences::Pointer m_DataManagerPreferencesNode; /// /// \brief The Table view to show the selected nodes. /// QTreeView* m_NodeTreeView; /// /// \brief The context menu that shows up when right clicking on a node. /// QmitkDataNodeContextMenu* m_DataNodeContextMenu; - /// - /// \brief flag indicating whether a surface created from a selected decimation is decimated with vtkQuadricDecimation or not - /// - bool m_SurfaceDecimation; /// saves the current amount of rows shown in the data manager size_t m_CurrentRowCount; QmitkDataManagerItemDelegate* m_ItemDelegate; private: QItemSelectionModel* GetDataNodeSelectionModel() const override; }; #endif // QMITKDATAMANAGERVIEW_H diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp index 99584a9962..926a63b541 100644 --- a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp +++ b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp @@ -1,156 +1,152 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Blueberry #include #include // Qmitk #include "InteractionEventRecorder.h" // Qt #include #include // us #include "usGetModuleContext.h" #include "usModuleContext.h" #include "usModuleResource.h" #include #include #include #include "QmitkRenderWindow.h" US_INITIALIZE_MODULE const std::string InteractionEventRecorder::VIEW_ID = "org.mitk.views.interactioneventrecorder"; void InteractionEventRecorder::SetFocus() { m_Controls.textFileName->setFocus(); } void InteractionEventRecorder::StartRecording() { MITK_INFO << "Start Recording"; MITK_INFO << "Performing Reinit"; mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage()); m_CurrentObserver->SetOutputFile(m_Controls.textFileName->text().toStdString()); m_CurrentObserver->StartRecording(); } void InteractionEventRecorder::StopRecording() { MITK_INFO << "Stop Recording"; m_CurrentObserver->StopRecording(); } void InteractionEventRecorder::Play() { std::ifstream xmlStream(m_Controls.textFileName->text().toStdString().c_str()); mitk::XML2EventParser parser(xmlStream); mitk::XML2EventParser::EventContainerType events = parser.GetInteractions(); MITK_INFO << "parsed events"; for (std::size_t i=0; i < events.size(); ++i) events.at(i)->GetSender()->GetDispatcher()->ProcessEvent(events.at(i)); MITK_INFO << "DONE"; } void InteractionEventRecorder::OpenFile() { QString fn = QFileDialog::getOpenFileName(nullptr, "Open File...", QString(), "All Files (*)"); if (!fn.isEmpty()) this->m_Controls.textFileName->setText(fn); } void InteractionEventRecorder::RotatePlanes() { mitk::Point3D center; center.Fill(0); mitk::Vector3D firstVec; mitk::Vector3D secondVec; firstVec[0] = 1.0; firstVec[1] = .5; firstVec[2] = .25; secondVec[0] = 1; secondVec[1] = .25; secondVec[2] = 1; // Rotate Planes to a predefined state which can later be used again in tests auto* axialRenderWindow = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow("axial"); axialRenderWindow->GetSliceNavigationController()->ReorientSlices( center, firstVec,secondVec ); axialRenderWindow->GetRenderer()->RequestUpdate(); } void InteractionEventRecorder::RotateView() { // Rotate the view in 3D to a predefined state which can later be used again in tests // this simulates a prior VTK Interaction - - vtkRenderWindow* renderWindow = mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"); - - if (renderWindow == nullptr) - return; - - mitk::Stepper* stepper = mitk::BaseRenderer::GetInstance(renderWindow)->GetCameraRotationController()->GetSlice(); - - if (stepper == nullptr) - return; - - unsigned int newPos = 17; - - - stepper->SetPos(newPos); - - auto* axialRenderWindow = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow("axial"); - axialRenderWindow->GetRenderer()->RequestUpdate(); + auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows(); + for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit) + { + vtkRenderWindow* renderWindow = mapit->first; + if (renderWindow == nullptr) + continue; + + mitk::Stepper* stepper = mapit->second->GetCameraRotationController()->GetSlice(); + if (stepper == nullptr) + return; + + unsigned int newPos = 17; + stepper->SetPos(newPos); + } } void InteractionEventRecorder::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); connect( m_Controls.btnStopRecording, SIGNAL(clicked()), this, SLOT(StopRecording()) ); connect( m_Controls.btnStartRecording, SIGNAL(clicked()), this, SLOT(StartRecording()) ); connect( m_Controls.btnPlay, SIGNAL(clicked()), this, SLOT(Play()) ); connect( m_Controls.btnOpenFile, SIGNAL(clicked()), this, SLOT(OpenFile()) ); connect( m_Controls.rotatePlanes, SIGNAL(clicked()), this, SLOT(RotatePlanes()) ); connect( m_Controls.rotate3D, SIGNAL(clicked()), this, SLOT(RotateView()) ); m_CurrentObserver = new mitk::EventRecorder(); // Register as listener via micro services us::ServiceProperties props; props["name"] = std::string("EventRecorder"); m_ServiceRegistration = us::GetModuleContext()->RegisterService(m_CurrentObserver,props); /* delete m_CurrentObserverDEBUG; m_ServiceRegistrationDEBUG.Unregister(); */ } diff --git a/Plugins/org.mitk.gui.qt.ext/resources/Editor.png b/Plugins/org.mitk.gui.qt.ext/resources/Editor.png deleted file mode 100644 index 8043b0e626..0000000000 Binary files a/Plugins/org.mitk.gui.qt.ext/resources/Editor.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.ext/resources/Editor.svg b/Plugins/org.mitk.gui.qt.ext/resources/Editor.svg new file mode 100644 index 0000000000..d83bb006c3 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.ext/resources/Editor.svg @@ -0,0 +1,80 @@ + + + + + + + image/svg+xml + + + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.ext/resources/org_mitk_gui_qt_ext.qrc b/Plugins/org.mitk.gui.qt.ext/resources/org_mitk_gui_qt_ext.qrc index 25c011d9dd..93d9148ccb 100644 --- a/Plugins/org.mitk.gui.qt.ext/resources/org_mitk_gui_qt_ext.qrc +++ b/Plugins/org.mitk.gui.qt.ext/resources/org_mitk_gui_qt_ext.qrc @@ -1,10 +1,10 @@ dicom.svg - Editor.png + Editor.svg image_navigator.svg index.html xnat-icon.png view-manager.svg diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index 1ff5df4acd..0a488bd357 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1437 +1,1437 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "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 #include #include #include #include #include // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include #include #include QmitkExtWorkbenchWindowAdvisorHack* QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; static bool USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS = false; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const override { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) override { windowAdvisor->UpdateTitle(false); } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor) { windowAdvisor->UpdateTitle(true); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForViewNavigator: public berry::IPartListener { public: PartListenerForViewNavigator(QAction* act) : viewNavigatorAction(act) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(false); } } private: QAction* viewNavigatorAction; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { 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 override { if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED; } else { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED | Events::CLOSED | Events::OPENED; } } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { 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.dicombrowser")) { windowAdvisor->openDicomEditorAction->setEnabled(true); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { windowAdvisor->openStdMultiWidgetEditorAction->setEnabled(true); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { windowAdvisor->openMxNMultiWidgetEditorAction->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*/) override { 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.dicombrowser")) { windowAdvisor->openDicomEditorAction->setEnabled(false); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { windowAdvisor->openStdMultiWidgetEditorAction->setEnabled(false); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { windowAdvisor->openMxNMultiWidgetEditorAction->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 override { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) override { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) override { 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(nullptr) , 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.viewnavigator"); } QmitkExtWorkbenchWindowAdvisor::~QmitkExtWorkbenchWindowAdvisor() { } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer) { if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) { berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkExtActionBarAdvisor(configurer)); return actionBarAdvisor; } else { return berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor(configurer); } } QWidget* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent) { QWidget* parentWidget = static_cast(parent); auto 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()); if (!windowIcon.isEmpty()) { mainWindow->setWindowIcon(QIcon(windowIcon)); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); // Load icon theme QIcon::setThemeSearchPaths(QStringList() << QStringLiteral(":/org_mitk_icons/icons/")); QIcon::setThemeName(QStringLiteral("awesome")); // ==== Application menu ============================ QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ menuBar->setNativeMenuBar(true); #else menuBar->setNativeMenuBar(false); #endif auto basePath = QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/"); auto fileOpenAction = new QmitkFileOpenAction(berry::QtStyleManager::ThemeIcon(basePath + "document-open.svg"), window); fileOpenAction->setShortcut(QKeySequence::Open); auto fileSaveAction = new QmitkFileSaveAction(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg"), window); fileSaveAction->setShortcut(QKeySequence::Save); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg")); closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "edit-delete.svg")); auto perspGroup = new QActionGroup(menuBar); std::map VDMap; // sort elements (converting vector to map...) QList::const_iterator iter; berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const QList viewDescriptors = viewRegistry->GetViews(); bool 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.viewnavigator") continue; std::pair p((*iter)->GetLabel(), (*iter)); VDMap.insert(p); } 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 (!USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) { QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); fileMenu->addAction(fileOpenAction); fileMenu->addAction(fileSaveAction); fileMenu->addAction(fileSaveProjectAction); fileMenu->addAction(closeProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "system-log-out.svg")); fileExitAction->setShortcut(QKeySequence::Quit); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "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(berry::QtStyleManager::ThemeIcon(basePath + "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)"); // ==== 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 = nullptr; 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(); QList perspectives( perspRegistry->GetPerspectives()); 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()); if (showViewMenuItem) { for (auto viewAction : qAsConst(viewActions)) { viewMenu->addAction(viewAction); } } // ===== 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())); // ===================================================== } else { undoAction = new QmitkUndoAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"), nullptr); undoAction->setShortcut(QKeySequence::Undo); redoAction = new QmitkRedoAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"), nullptr); redoAction->setShortcut(QKeySequence::Redo); } // toolbar for showing file open, undo, redo and other main actions auto mainActionsToolBar = new QToolBar; mainActionsToolBar->setObjectName("mainActionsToolBar"); mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif basePath = QStringLiteral(":/org.mitk.gui.qt.ext/"); imageNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(basePath + "image_navigator.svg"), "&Image Navigator", nullptr); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser")) { openDicomEditorAction = new QmitkOpenDicomEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "dicom.svg"), window); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { - openStdMultiWidgetEditorAction = new QmitkOpenStdMultiWidgetEditorAction(QIcon(":/org.mitk.gui.qt.ext/Editor.png"), window); + openStdMultiWidgetEditorAction = new QmitkOpenStdMultiWidgetEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "Editor.svg"), window); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { - openMxNMultiWidgetEditorAction = new QmitkOpenMxNMultiWidgetEditorAction(QIcon(":/org.mitk.gui.qt.ext/Editor.png"), window); + openMxNMultiWidgetEditorAction = new QmitkOpenMxNMultiWidgetEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "Editor.svg"), window); } 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(berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org.mitk.gui.qt.ext/view-manager.svg")),"&View Navigator", nullptr); viewNavigatorFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.viewnavigator"); 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.viewnavigator"); viewNavigatorAction->setChecked(false); if (viewnavigatorview) { bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview); if (isViewNavigatorVisible) viewNavigatorAction->setChecked(true); } viewNavigatorAction->setToolTip("Toggle View Navigator"); } 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.dicombrowser")) { mainActionsToolBar->addAction(openDicomEditorAction); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { mainActionsToolBar->addAction(openStdMultiWidgetEditorAction); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { mainActionsToolBar->addAction(openMxNMultiWidgetEditorAction); } if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } if (viewNavigatorFound) { mainActionsToolBar->addAction(viewNavigatorAction); } mainWindow->addToolBar(mainActionsToolBar); // ==== Perspective Toolbar ================================== auto qPerspectiveToolbar = new QToolBar; qPerspectiveToolbar->setObjectName("perspectiveToolBar"); if (showPerspectiveToolbar) { qPerspectiveToolbar->addActions(perspGroup->actions()); mainWindow->addToolBar(qPerspectiveToolbar); } else delete qPerspectiveToolbar; if (showViewToolbar) { auto prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); berry::IPreferences::Pointer stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); bool showCategoryNames = stylePrefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true); // Order view descriptors by category QMultiMap categoryViewDescriptorMap; for (const auto &labelViewDescriptorPair : VDMap) { auto viewDescriptor = labelViewDescriptorPair.second; auto category = !viewDescriptor->GetCategoryPath().isEmpty() ? viewDescriptor->GetCategoryPath().back() : QString(); categoryViewDescriptorMap.insert(category, viewDescriptor); } // Create a separate toolbar for each category for (const auto &category : categoryViewDescriptorMap.uniqueKeys()) { auto viewDescriptorsInCurrentCategory = categoryViewDescriptorMap.values(category); if (!viewDescriptorsInCurrentCategory.isEmpty()) { auto toolbar = new QToolBar; toolbar->setObjectName(category + " View Toolbar"); mainWindow->addToolBar(toolbar); if (showCategoryNames && !category.isEmpty()) { auto categoryButton = new QToolButton; categoryButton->setToolButtonStyle(Qt::ToolButtonTextOnly); categoryButton->setText(category); categoryButton->setStyleSheet("background: transparent; margin: 0; padding: 0;"); toolbar->addWidget(categoryButton); connect(categoryButton, &QToolButton::clicked, [toolbar]() { for (QWidget* widget : toolbar->findChildren()) { if (QStringLiteral("qt_toolbar_ext_button") == widget->objectName() && widget->isVisible()) { QMouseEvent pressEvent(QEvent::MouseButtonPress, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QMouseEvent releaseEvent(QEvent::MouseButtonRelease, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(widget, &pressEvent); QApplication::sendEvent(widget, &releaseEvent); } } }); } for (const auto &viewDescriptor : qAsConst(viewDescriptorsInCurrentCategory)) { auto viewAction = new berry::QtShowViewAction(window, viewDescriptor); toolbar->addAction(viewAction); } } } } QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); auto qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar auto statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); auto progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); // progBar->AddStepsToDo(2); // progBar->Progress(1); mainWindow->setStatusBar(qStatusBar); if (showMemoryIndicator) { auto 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); } } auto introPart = configurer->GetWindow()->GetWorkbench()->GetIntroManager()->GetIntro(); if (introPart.IsNotNull()) { configurer->GetWindow()->GetWorkbench()->GetIntroManager()->ShowIntro(GetWindowConfigurer()->GetWindow(), false); } } 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"; } } // safe calls to the complete chain // berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); // to cover for all possible cases of closed pages etc. static void SafeHandleNavigatorView(QString view_query_name) { berry::IWorkbench* wbench = berry::PlatformUI::GetWorkbench(); if( wbench == nullptr ) return; berry::IWorkbenchWindow::Pointer wbench_window = wbench->GetActiveWorkbenchWindow(); if( wbench_window.IsNull() ) return; berry::IWorkbenchPage::Pointer wbench_page = wbench_window->GetActivePage(); if( wbench_page.IsNull() ) return; auto wbench_view = wbench_page->FindView( view_query_name ); if( wbench_view.IsNotNull() ) { bool isViewVisible = wbench_page->IsPartVisible( wbench_view ); if( isViewVisible ) { wbench_page->HideView( wbench_view ); return; } } wbench_page->ShowView( view_query_name ); } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // show/hide ImageNavigatorView SafeHandleNavigatorView("org.mitk.views.imagenavigator"); } void QmitkExtWorkbenchWindowAdvisorHack::onViewNavigator() { // show/hide viewnavigatorView SafeHandleNavigatorView("org.mitk.views.viewnavigator"); } 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(nullptr); } 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(nullptr, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == nullptr) { 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 = nullptr; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == nullptr) { 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() { auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),nullptr); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener.reset(new PartListenerForTitle(this)); titlePerspectiveListener.reset(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.data()); 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; berry::IProduct::Pointer product = berry::Platform::GetProduct(); if (product.IsNotNull()) { title = product->GetName(); } if (title.isEmpty()) { // instead of the product name, we use a custom variable for now title = productName; } if(showMitkVersionInfo) { QString mitkVersionInfo = MITK_REVISION_DESC; if(mitkVersionInfo.isEmpty()) mitkVersionInfo = MITK_VERSION_STRING; title += " " + mitkVersionInfo; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 | VTK %4.%5.%6 | Qt %7)") .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); 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 = nullptr; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = nullptr; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } auto lockedLastActiveEditor = lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull()) { lockedLastActiveEditor->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) { auto lockedLastActiveEditor = lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull()) { QString newTitle = lockedLastActiveEditor->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.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp index 0cca148ebd..6e8222469f 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp @@ -1,38 +1,41 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkExtDefaultPerspective.h" #include "berryIViewLayout.h" QmitkExtDefaultPerspective::QmitkExtDefaultPerspective() { } void QmitkExtDefaultPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { QString editorArea = layout->GetEditorArea(); - layout->AddView("org.mitk.views.datamanager", berry::IPageLayout::LEFT, 0.3f, editorArea); + layout->AddView("org.mitk.views.datamanager", berry::IPageLayout::LEFT, 0.21f, editorArea); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.datamanager"); lo->SetCloseable(false); - layout->AddView("org.mitk.views.imagenavigator", - berry::IPageLayout::BOTTOM, 0.5f, "org.mitk.views.datamanager"); + auto folder = layout->CreateFolder("bottomleft", berry::IPageLayout::BOTTOM, 0.72f, "org.mitk.views.datamanager"); + folder->AddView("org.mitk.views.imagenavigator"); + folder->AddView("org.mitk.views.pixelvalue"); + + layout->AddView("org.mitk.views.viewnavigator", berry::IPageLayout::RIGHT, 0.7f, editorArea); berry::IPlaceholderFolderLayout::Pointer bottomFolder = layout->CreatePlaceholderFolder("bottom", berry::IPageLayout::BOTTOM, 0.7f, editorArea); bottomFolder->AddPlaceholder("org.blueberry.views.logview"); bottomFolder->AddPlaceholder("org.mitk.views.modules"); layout->AddPerspectiveShortcut("org.mitk.mitkworkbench.perspectives.editor"); layout->AddPerspectiveShortcut("org.mitk.mitkworkbench.perspectives.visualization"); } diff --git a/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp b/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp index d9896a2c1c..a27da1b754 100644 --- a/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp +++ b/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp @@ -1,820 +1,859 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationTaskListWidget.h" #include "org_mitk_gui_qt_flow_segmentation_Activator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { berry::IPreferences::Pointer GetSegmentationPreferences() { return berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); } mitk::DataStorage* GetDataStorage() { auto* pluginContext = org_mitk_gui_qt_flow_segmentation_Activator::GetContext(); auto dataStorageServiceReference = pluginContext->getServiceReference(); if (dataStorageServiceReference) { auto* dataStorageService = pluginContext->getService(dataStorageServiceReference); if (dataStorageService != nullptr) { auto dataStorageReference = dataStorageService->GetDataStorage(); pluginContext->ungetService(dataStorageServiceReference); return dataStorageReference->GetDataStorage(); } } return nullptr; } std::filesystem::path GetInputLocation(const mitk::BaseData* data) { std::string result; if (data != nullptr) data->GetPropertyList()->GetStringProperty("MITK.IO.reader.inputlocation", result); return result; } QString ColorString(const QString& string, const QColor& color, const QColor& backgroundColor = QColor::Invalid) { if (!color.isValid() && !backgroundColor.isValid()) return string; auto result = QStringLiteral("%1").arg(string); return result; } } /* This constructor has three objectives: * 1. Do widget initialization that cannot be done in the .ui file * 2. Connect signals and slots * 3. Explicitly trigger a reset to a valid initial widget state */ QmitkSegmentationTaskListWidget::QmitkSegmentationTaskListWidget(QWidget* parent) : QWidget(parent), m_Ui(new Ui::QmitkSegmentationTaskListWidget), m_FileSystemWatcher(new QFileSystemWatcher(this)), m_UnsavedChanges(false) { m_Ui->setupUi(this); m_Ui->selectionWidget->SetDataStorage(GetDataStorage()); m_Ui->selectionWidget->SetSelectionIsOptional(true); m_Ui->selectionWidget->SetEmptyInfo(QStringLiteral("Select a segmentation task list")); m_Ui->selectionWidget->SetAutoSelectNewNodes(true); m_Ui->selectionWidget->SetNodePredicate(mitk::TNodePredicateDataType::New()); m_Ui->progressBar->setStyleSheet(QString("QProgressBar::chunk { background-color: %1; }").arg(QmitkStyleManager::GetIconAccentColor())); using Self = QmitkSegmentationTaskListWidget; connect(m_Ui->selectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &Self::OnSelectionChanged); connect(m_Ui->previousButton, &QToolButton::clicked, this, &Self::OnPreviousButtonClicked); connect(m_Ui->nextButton, &QToolButton::clicked, this, &Self::OnNextButtonClicked); connect(m_Ui->loadButton, &QPushButton::clicked, this, &Self::OnLoadButtonClicked); connect(m_FileSystemWatcher, &QFileSystemWatcher::directoryChanged, this, &Self::OnResultDirectoryChanged); auto* prevShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key::Key_P), this); connect(prevShortcut, &QShortcut::activated, this, &Self::OnPreviousTaskShortcutActivated); + auto* prevUndoneShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key::Key_P), this); + connect(prevUndoneShortcut, &QShortcut::activated, this, &Self::OnPreviousTaskShortcutActivated); + auto* nextShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key::Key_N), this); connect(nextShortcut, &QShortcut::activated, this, &Self::OnNextTaskShortcutActivated); + auto* nextUndoneShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key::Key_N), this); + connect(nextUndoneShortcut, &QShortcut::activated, this, &Self::OnNextTaskShortcutActivated); + auto* loadShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key::Key_L), this); connect(loadShortcut, &QShortcut::activated, this, &Self::OnLoadTaskShortcutActivated); this->OnSelectionChanged(m_Ui->selectionWidget->GetSelectedNodes()); } QmitkSegmentationTaskListWidget::~QmitkSegmentationTaskListWidget() { } void QmitkSegmentationTaskListWidget::OnUnsavedChangesSaved() { if (m_UnsavedChanges) { m_UnsavedChanges = false; if (this->ActiveTaskIsShown()) this->UpdateDetailsLabel(); } } /* Make sure that the widget transitions into a valid state whenever the * selection changes. */ void QmitkSegmentationTaskListWidget::OnSelectionChanged(const QmitkSingleNodeSelectionWidget::NodeList& nodes) { this->UnloadTasks(); this->ResetControls(); if (!nodes.empty()) { m_TaskListNode = nodes.front(); auto taskList = dynamic_cast(m_TaskListNode->GetData()); if (taskList != nullptr) { this->OnTaskListChanged(taskList); return; } } this->SetTaskList(nullptr); m_TaskListNode = nullptr; } /* Reset all controls to a default state as a common basis for further * adjustments. */ void QmitkSegmentationTaskListWidget::ResetControls() { m_Ui->progressBar->setEnabled(false); m_Ui->progressBar->setFormat(""); m_Ui->progressBar->setValue(0); m_Ui->progressBar->setMaximum(1); m_Ui->previousButton->setEnabled(false); m_Ui->nextButton->setEnabled(false); this->UpdateLoadButton(); this->UpdateDetailsLabel(); } /* If the segmentation task changed, reset all member variables to expected * default values and reset the file system watcher. */ void QmitkSegmentationTaskListWidget::SetTaskList(mitk::SegmentationTaskList* taskList) { if (m_TaskList != taskList) { m_TaskList = taskList; if (taskList != nullptr) { this->SetCurrentTaskIndex(0); } else { this->SetCurrentTaskIndex(std::nullopt); } this->ResetFileSystemWatcher(); } } void QmitkSegmentationTaskListWidget::ResetFileSystemWatcher() { auto paths = m_FileSystemWatcher->directories(); if (!paths.empty()) m_FileSystemWatcher->removePaths(paths); if (m_TaskList.IsNotNull()) { for (const auto& task : *m_TaskList) { auto resultPath = m_TaskList->GetAbsolutePath(task.GetResult()).remove_filename(); if (!std::filesystem::exists(resultPath)) { try { std::filesystem::create_directories(resultPath); } catch (const std::filesystem::filesystem_error& e) { MITK_ERROR << e.what(); } } if (std::filesystem::exists(resultPath)) m_FileSystemWatcher->addPath(QString::fromStdString(resultPath.string())); } } } void QmitkSegmentationTaskListWidget::OnResultDirectoryChanged(const QString&) { // TODO: If a segmentation was modified ("Unsaved changes"), saved ("Done"), and then the file is deleted, the status should be "Unsaved changes" instead of "Not done". this->UpdateProgressBar(); this->UpdateDetailsLabel(); } void QmitkSegmentationTaskListWidget::UpdateProgressBar() { int progress = 0; for (size_t i = 0; i < m_TaskList->GetNumberOfTasks(); ++i) { if (m_TaskList->IsDone(i)) ++progress; } m_Ui->progressBar->setValue(progress); } /* Provided that a valid segmentation task list is currently selected and the * widget is in its default state, update all controls accordingly. */ void QmitkSegmentationTaskListWidget::OnTaskListChanged(mitk::SegmentationTaskList* taskList) { this->SetTaskList(taskList); const auto numTasks = taskList->GetNumberOfTasks(); m_Ui->progressBar->setMaximum(numTasks); m_Ui->progressBar->setFormat(QStringLiteral("%v/%m Task(s) done")); m_Ui->progressBar->setEnabled(true); this->UpdateProgressBar(); m_Ui->loadButton->setEnabled(true); if (numTasks > 1) m_Ui->nextButton->setEnabled(true); } /* If possible, change the currently displayed task to the previous task. * Enable/disable navigation buttons according to the task's position. */ void QmitkSegmentationTaskListWidget::OnPreviousButtonClicked() { auto current = m_CurrentTaskIndex.value(); - if (current != 0) - this->SetCurrentTaskIndex(current - 1); + // If the shift modifier key is pressed, look for the previous undone task. + if (QApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier)) + { + if (current > 0) + { + for (decltype(current) i = current; i > 0; --i) + { + if (!m_TaskList->IsDone(i - 1)) + { + this->SetCurrentTaskIndex(i - 1); + break; + } + } + } + } + else + { + if (current != 0) + this->SetCurrentTaskIndex(current - 1); + } this->UpdateNavigationButtons(); } /* If possible, change the currently displayed task to the next task. * Enable/disable navigation buttons according to the task's position. */ void QmitkSegmentationTaskListWidget::OnNextButtonClicked() { - const auto maxIndex = m_TaskList->GetNumberOfTasks() - 1; + const auto numTasks = m_TaskList->GetNumberOfTasks(); auto current = m_CurrentTaskIndex.value(); - if (current < maxIndex) - this->SetCurrentTaskIndex(current + 1); + // If the shift modifier key is pressed, look for the next undone task. + if (QApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier)) + { + for (std::remove_const_t i = current + 1; i < numTasks; ++i) + { + if (!m_TaskList->IsDone(i)) + { + this->SetCurrentTaskIndex(i); + break; + } + } + } + else + { + if (current < numTasks - 1) + this->SetCurrentTaskIndex(current + 1); + } this->UpdateNavigationButtons(); } void QmitkSegmentationTaskListWidget::UpdateNavigationButtons() { if (m_TaskList.IsNull() || m_TaskList->GetNumberOfTasks() == 0) { m_Ui->previousButton->setEnabled(false); m_Ui->nextButton->setEnabled(false); return; } const auto maxIndex = m_TaskList->GetNumberOfTasks() - 1; const auto current = m_CurrentTaskIndex.value(); m_Ui->previousButton->setEnabled(current != 0); m_Ui->nextButton->setEnabled(current != maxIndex); } /* Update affected controls when the currently displayed task changed. */ void QmitkSegmentationTaskListWidget::OnCurrentTaskChanged() { this->UpdateLoadButton(); this->UpdateNavigationButtons(); this->UpdateDetailsLabel(); } /* Update the load button according to the currently displayed task. */ void QmitkSegmentationTaskListWidget::UpdateLoadButton() { auto text = !this->ActiveTaskIsShown() ? QStringLiteral("Load task") : QStringLiteral("Task"); if (m_CurrentTaskIndex.has_value()) { const auto current = m_CurrentTaskIndex.value(); if (m_TaskList.IsNotNull()) { text += QString(" %1/%2").arg(current + 1).arg(m_TaskList->GetNumberOfTasks()); if (m_TaskList->HasName(current)) text += QStringLiteral(":\n") + QString::fromStdString(m_TaskList->GetName(current)); } m_Ui->loadButton->setDisabled(this->ActiveTaskIsShown()); } else { m_Ui->loadButton->setEnabled(false); } m_Ui->loadButton->setText(text); } /* Update the details label according to the currently display task. * The text is composed of the status of the task and a variable number * of text blocks according to the optional values provided by the task. */ void QmitkSegmentationTaskListWidget::UpdateDetailsLabel() { if (!m_CurrentTaskIndex.has_value()) { m_Ui->detailsLabel->clear(); return; } const auto current = m_CurrentTaskIndex.value(); bool isDone = m_TaskList->IsDone(current); auto details = QString("

Status: %1 / ").arg(this->ActiveTaskIsShown() ? ColorString("Active", Qt::white, QColor(Qt::green).darker()) : ColorString("Inactive", Qt::white, QColor(Qt::red).darker())); if (m_UnsavedChanges && this->ActiveTaskIsShown()) { details += QString("%1

").arg(ColorString("Unsaved changes", Qt::white, QColor(Qt::red).darker())); } else { details += QString("%1

").arg(isDone ? ColorString("Done", Qt::white, QColor(Qt::green).darker()) : ColorString("Not done", Qt::white, QColor(Qt::red).darker())); } if (m_TaskList->HasDescription(current)) details += QString("

Description: %1

").arg(QString::fromStdString(m_TaskList->GetDescription(current))); QStringList stringList; if (m_TaskList->HasImage(current)) stringList << QString::fromStdString("Image: " + m_TaskList->GetImage(current).string()); if (m_TaskList->HasSegmentation(current)) stringList << QString::fromStdString("Segmentation: " + m_TaskList->GetSegmentation(current).string()); if (m_TaskList->HasLabelName(current)) stringList << QString::fromStdString("Label name: " + m_TaskList->GetLabelName(current)); if (m_TaskList->HasLabelNameSuggestions(current)) stringList << QString::fromStdString("Label name suggestions: " + m_TaskList->GetLabelNameSuggestions(current).string()); if (m_TaskList->HasPreset(current)) stringList << QString::fromStdString("Label set preset: " + m_TaskList->GetPreset(current).string()); if (m_TaskList->HasDynamic(current)) stringList << QString("Segmentation type: %1").arg(m_TaskList->GetDynamic(current) ? "Dynamic" : "Static"); if (!stringList.empty()) details += QString("

%1

").arg(stringList.join(QStringLiteral("
"))); m_Ui->detailsLabel->setText(details); } /* Load/activate the currently displayed task. Unload all data nodes from * previously active tasks first, but spare and reuse the image if possible. */ void QmitkSegmentationTaskListWidget::OnLoadButtonClicked() { if (!this->HandleUnsavedChanges() || m_UnsavedChanges) return; m_Ui->loadButton->setEnabled(false); QApplication::setOverrideCursor(Qt::BusyCursor); this->LoadTask(this->GetImageDataNode(m_CurrentTaskIndex.value())); QApplication::restoreOverrideCursor(); } /* If present, return the image data node for the task with the specified * index. Otherwise, return nullptr. */ mitk::DataNode* QmitkSegmentationTaskListWidget::GetImageDataNode(size_t index) const { const auto imagePath = m_TaskList->GetAbsolutePath(m_TaskList->GetImage(index)); auto imageNodes = GetDataStorage()->GetDerivations(m_TaskListNode, mitk::NodePredicateFunction::New([imagePath](const mitk::DataNode* node) { return imagePath == GetInputLocation(node->GetData()); })); return !imageNodes->empty() ? imageNodes->front() : nullptr; } /* If present, return the segmentation data node for the task with the * specified index. Otherwise, return nullptr. */ mitk::DataNode* QmitkSegmentationTaskListWidget::GetSegmentationDataNode(size_t index) const { const auto* imageNode = this->GetImageDataNode(index); if (imageNode != nullptr) { auto segmentations = GetDataStorage()->GetDerivations(imageNode, mitk::TNodePredicateDataType::New()); if (!segmentations->empty()) return segmentations->front(); } return nullptr; } /* Unload all task data nodes but spare the passed image data node. */ void QmitkSegmentationTaskListWidget::UnloadTasks(const mitk::DataNode* skip) { this->UnsubscribeFromActiveSegmentation(); if (m_TaskListNode.IsNotNull()) { mitk::DataStorage::Pointer dataStorage = GetDataStorage(); auto imageNodes = dataStorage->GetDerivations(m_TaskListNode, mitk::TNodePredicateDataType::New()); for (auto imageNode : *imageNodes) { dataStorage->Remove(dataStorage->GetDerivations(imageNode, nullptr, false)); if (imageNode != skip) dataStorage->Remove(imageNode); } } this->SetActiveTaskIndex(std::nullopt); } void QmitkSegmentationTaskListWidget::LoadNextUnfinishedTask() { const auto current = m_CurrentTaskIndex.value(); const auto numTasks = m_TaskList->GetNumberOfTasks(); for (size_t unboundNext = current; unboundNext < current + numTasks; ++unboundNext) { auto next = unboundNext % numTasks; if (!m_TaskList->IsDone(next)) { this->SetCurrentTaskIndex(next); this->OnLoadButtonClicked(); break; } } } /* Load/activate the currently displayed task. The task must specify * an image. The segmentation is either created from scratch with an optional * name for the first label, possibly based on a label set preset specified by * the task, or loaded as specified by the task. If a result file does * exist, it is chosen as segmentation instead. */ void QmitkSegmentationTaskListWidget::LoadTask(mitk::DataNode::Pointer imageNode) { this->UnloadTasks(imageNode); const auto current = m_CurrentTaskIndex.value(); mitk::Image::Pointer image; mitk::LabelSetImage::Pointer segmentation; try { if (imageNode.IsNull()) { const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetImage(current)); image = mitk::IOUtil::Load(path.string()); } const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetResult(current)); const auto interimPath = m_TaskList->GetInterimPath(path); if (std::filesystem::exists(path)) { segmentation = mitk::IOUtil::Load(path.string()); } else if (std::filesystem::exists(interimPath)) { segmentation = mitk::IOUtil::Load(interimPath.string()); } else if (m_TaskList->HasSegmentation(current)) { const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetSegmentation(current)); segmentation = mitk::IOUtil::Load(path.string()); } } catch (const mitk::Exception&) { return; } auto dataStorage = GetDataStorage(); if (imageNode.IsNull()) { imageNode = mitk::DataNode::New(); imageNode->SetData(image); dataStorage->Add(imageNode, m_TaskListNode); mitk::RenderingManager::GetInstance()->InitializeViews(image->GetTimeGeometry()); } else { image = static_cast(imageNode->GetData()); } auto name = "Task " + std::to_string(current + 1); imageNode->SetName(name); if (segmentation.IsNull()) { mitk::Image::ConstPointer templateImage = image; if (templateImage->GetDimension() > 3) { if (m_TaskList->HasDynamic(current)) { if (!m_TaskList->GetDynamic(current)) templateImage = mitk::SegmentationHelper::GetStaticSegmentationTemplate(image); } else { QmitkStaticDynamicSegmentationDialog dialog(this); dialog.SetReferenceImage(templateImage); dialog.exec(); templateImage = dialog.GetSegmentationTemplate(); } } auto segmentationNode = mitk::LabelSetImageHelper::CreateNewSegmentationNode(imageNode, templateImage, name); segmentation = static_cast(segmentationNode->GetData()); if (m_TaskList->HasPreset(current)) { const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetPreset(current)); mitk::LabelSetIOHelper::LoadLabelSetImagePreset(path.string(), segmentation); } else { auto label = mitk::LabelSetImageHelper::CreateNewLabel(segmentation); if (m_TaskList->HasLabelName(current)) label->SetName(m_TaskList->GetLabelName(current)); segmentation->GetActiveLabelSet()->AddLabel(label); } dataStorage->Add(segmentationNode, imageNode); } else { auto segmentationNode = mitk::DataNode::New(); segmentationNode->SetName(name); segmentationNode->SetData(segmentation); dataStorage->Add(segmentationNode, imageNode); } auto prefs = GetSegmentationPreferences(); if (prefs.IsNotNull()) { if (m_TaskList->HasLabelNameSuggestions(current)) { auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetLabelNameSuggestions(current)); prefs->PutBool("default label naming", false); prefs->Put("label suggestions", QString::fromStdString(path.string())); prefs->PutBool("replace standard suggestions", true); prefs->PutBool("suggest once", true); } else { prefs->PutBool("default label naming", true); prefs->Put("label suggestions", ""); } } m_UnsavedChanges = false; this->SetActiveTaskIndex(current); this->SubscribeToActiveSegmentation(); this->OnCurrentTaskChanged(); } void QmitkSegmentationTaskListWidget::SubscribeToActiveSegmentation() { if (m_ActiveTaskIndex.has_value()) { auto segmentationNode = this->GetSegmentationDataNode(m_ActiveTaskIndex.value()); if (segmentationNode != nullptr) { auto segmentation = static_cast(segmentationNode->GetData()); auto command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationTaskListWidget::OnSegmentationModified); m_SegmentationModifiedObserverTag = segmentation->AddObserver(itk::ModifiedEvent(), command); } } } void QmitkSegmentationTaskListWidget::UnsubscribeFromActiveSegmentation() { if (m_ActiveTaskIndex.has_value() && m_SegmentationModifiedObserverTag.has_value()) { auto segmentationNode = this->GetSegmentationDataNode(m_ActiveTaskIndex.value()); if (segmentationNode != nullptr) { auto segmentation = static_cast(segmentationNode->GetData()); segmentation->RemoveObserver(m_SegmentationModifiedObserverTag.value()); } m_SegmentationModifiedObserverTag.reset(); } } void QmitkSegmentationTaskListWidget::OnSegmentationModified() { if (!m_UnsavedChanges) { m_UnsavedChanges = true; if (m_ActiveTaskIndex.value() == m_CurrentTaskIndex) this->UpdateDetailsLabel(); } } void QmitkSegmentationTaskListWidget::SetActiveTaskIndex(const std::optional& index) { if (m_ActiveTaskIndex != index) { m_ActiveTaskIndex = index; emit ActiveTaskChanged(m_ActiveTaskIndex); } } void QmitkSegmentationTaskListWidget::SetCurrentTaskIndex(const std::optional& index) { if (m_CurrentTaskIndex != index) { m_CurrentTaskIndex = index; this->OnCurrentTaskChanged(); emit CurrentTaskChanged(m_CurrentTaskIndex); } } bool QmitkSegmentationTaskListWidget::ActiveTaskIsShown() const { return m_ActiveTaskIndex.has_value() && m_CurrentTaskIndex.has_value() && m_ActiveTaskIndex == m_CurrentTaskIndex; } bool QmitkSegmentationTaskListWidget::HandleUnsavedChanges(const QString& alternativeTitle) { if (m_UnsavedChanges) { const auto active = m_ActiveTaskIndex.value(); const auto current = m_CurrentTaskIndex.value(); QString title; if (alternativeTitle.isEmpty()) { title = QString("Load task %1").arg(current + 1); if (m_TaskList->HasName(current)) title += ": " + QString::fromStdString(m_TaskList->GetName(current)); } else { title = alternativeTitle; } auto text = QString("The currently active task %1 ").arg(active + 1); if (m_TaskList->HasName(active)) text += "(" + QString::fromStdString(m_TaskList->GetName(active)) + ") "; text += "has unsaved changes."; auto reply = QMessageBox::question(this, title, text, QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel); switch (reply) { case QMessageBox::Save: this->SaveActiveTask(!std::filesystem::exists(m_TaskList->GetResult(active))); break; case QMessageBox::Discard: m_UnsavedChanges = false; break; default: return false; } } return true; } void QmitkSegmentationTaskListWidget::SaveActiveTask(bool saveAsIntermediateResult) { if (!m_ActiveTaskIndex.has_value()) return; QApplication::setOverrideCursor(Qt::BusyCursor); try { const auto active = m_ActiveTaskIndex.value(); m_TaskList->SaveTask(active, this->GetSegmentationDataNode(active)->GetData(), saveAsIntermediateResult); this->OnUnsavedChangesSaved(); } catch (const mitk::Exception& e) { MITK_ERROR << e; } QApplication::restoreOverrideCursor(); } bool QmitkSegmentationTaskListWidget::OnPreShutdown() { return this->HandleUnsavedChanges(QStringLiteral("Application shutdown")); } void QmitkSegmentationTaskListWidget::OnPreviousTaskShortcutActivated() { m_Ui->previousButton->click(); } void QmitkSegmentationTaskListWidget::OnNextTaskShortcutActivated() { m_Ui->nextButton->click(); } void QmitkSegmentationTaskListWidget::OnLoadTaskShortcutActivated() { m_Ui->loadButton->click(); } diff --git a/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/perspectives/QmitkFlowSegmentationPerspective.cpp b/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/perspectives/QmitkFlowSegmentationPerspective.cpp index cb09bd4f9f..d5650449a4 100644 --- a/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/perspectives/QmitkFlowSegmentationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/perspectives/QmitkFlowSegmentationPerspective.cpp @@ -1,43 +1,43 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkFlowSegmentationPerspective.h" #include "berryIViewLayout.h" QmitkFlowSegmentationPerspective::QmitkFlowSegmentationPerspective() { } void QmitkFlowSegmentationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { QString editorArea = layout->GetEditorArea(); - layout->AddView("org.mitk.views.segmentation", berry::IPageLayout::LEFT, 0.3f, editorArea); + layout->AddView("org.mitk.views.segmentation", berry::IPageLayout::LEFT, 0.24f, editorArea); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.segmentation"); lo->SetCloseable(false); - layout->AddStandaloneView("org.mitk.views.flow.control",false, berry::IPageLayout::RIGHT, 0.6f, editorArea); + layout->AddStandaloneView("org.mitk.views.flow.control",false, berry::IPageLayout::RIGHT, 0.72f, editorArea); lo = layout->GetViewLayout("org.mitk.views.flow.control"); lo->SetCloseable(false); layout->AddView("org.mitk.views.imagenavigator", berry::IPageLayout::TOP, 0.1f, "org.mitk.views.flow.control"); berry::IPlaceholderFolderLayout::Pointer bottomFolder = layout->CreatePlaceholderFolder("bottom", berry::IPageLayout::BOTTOM, 0.7f, editorArea); bottomFolder->AddPlaceholder("org.blueberry.views.logview"); berry::IPlaceholderFolderLayout::Pointer rightFolder = layout->CreatePlaceholderFolder("right", berry::IPageLayout::RIGHT, 0.3f, editorArea); rightFolder->AddPlaceholder("org.mitk.views.datamanager"); layout->AddPerspectiveShortcut("org.mitk.qt.flowapplication.defaultperspective"); } diff --git a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepCombinedModality.cpp b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepCombinedModality.cpp index 47f2470863..623ec2bfb6 100644 --- a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepCombinedModality.cpp +++ b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepCombinedModality.cpp @@ -1,426 +1,424 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkUSNavigationStepCombinedModality.h" #include "ui_QmitkUSNavigationStepCombinedModality.h" #include "mitkAbstractUltrasoundTrackerDevice.h" #include "mitkUSCombinedModality.h" #include "../Widgets/QmitkUSCombinedModalityEditWidget.h" #include #include #include #include "mitkBaseRenderer.h" QmitkUSNavigationStepCombinedModality::QmitkUSNavigationStepCombinedModality(QWidget *parent) : QmitkUSAbstractNavigationStep(parent), m_LastCalibrationFilename(""), m_CalibrationLoadedNecessary(true), m_ListenerDeviceChanged(this, &QmitkUSNavigationStepCombinedModality::OnDevicePropertyChanged), ui(new Ui::QmitkUSNavigationStepCombinedModality) { ui->setupUi(this); // combined modality create widget should only be visible after button press ui->combinedModalityCreateWidget->setVisible(false); ui->combinedModalityEditWidget->setVisible(false); connect(ui->combinedModalityListWidget, SIGNAL(ServiceSelectionChanged(us::ServiceReferenceU)), this, SLOT(OnDeviceSelectionChanged())); connect(ui->combinedModalityListWidget, SIGNAL(ServiceModified(us::ServiceReferenceU)), this, SLOT(OnDeviceSelectionChanged())); connect(ui->combinedModalityCreateWidget, SIGNAL(SignalAborted()), this, SLOT(OnCombinedModalityCreationExit())); connect(ui->combinedModalityCreateWidget, SIGNAL(SignalCreated()), this, SLOT(OnCombinedModalityCreationExit())); connect(ui->combinedModalityEditWidget, SIGNAL(SignalAborted()), this, SLOT(OnCombinedModalityEditExit())); connect(ui->combinedModalityEditWidget, SIGNAL(SignalSaved()), this, SLOT(OnCombinedModalityEditExit())); std::string filterOnlyCombinedModalities = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.AbstractUltrasoundTrackerDevice)(" + mitk::AbstractUltrasoundTrackerDevice::US_PROPKEY_CLASS + "=" + mitk::AbstractUltrasoundTrackerDevice::DeviceClassIdentifier + "))"; //std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice))"; ui->combinedModalityListWidget->Initialize(filterOnlyCombinedModalities); ui->combinedModalityListWidget->SetAutomaticallySelectFirstEntry(true); //try to load UI settings QSettings settings; settings.beginGroup(QString::fromStdString("QmitkUSNavigationStepCombinedModality")); m_LastCalibrationFilename = settings.value("LastCalibrationFilename", QVariant("")).toString().toStdString(); MITK_DEBUG << "PERSISTENCE load: " << m_LastCalibrationFilename; settings.endGroup(); } QmitkUSNavigationStepCombinedModality::~QmitkUSNavigationStepCombinedModality() { ui->combinedModalityListWidget->blockSignals(true); //save UI settings QSettings settings; settings.beginGroup(QString::fromStdString("QmitkUSNavigationStepCombinedModality")); settings.setValue("LastCalibrationFilename", QVariant(m_LastCalibrationFilename.c_str())); settings.endGroup(); MITK_DEBUG << "PERSISTENCE save: " << m_LastCalibrationFilename; //delete UI delete ui; } void QmitkUSNavigationStepCombinedModality::OnDeviceSelectionChanged() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetSelectedCombinedModality(); bool combinedModalitySelected = combinedModality.IsNotNull(); ui->calibrationGroupBox->setEnabled(combinedModalitySelected); ui->combinedModalityDeleteButton->setEnabled(combinedModalitySelected); ui->combinedModalitEditButton->setEnabled(combinedModalitySelected); if (!combinedModalitySelected || m_CombinedModality != combinedModality) { emit SignalNoLongerReadyForNextStep(); if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetUltrasoundDevice().IsNotNull()) { m_CombinedModality->GetUltrasoundDevice()->RemovePropertyChangedListener(m_ListenerDeviceChanged); } if (combinedModalitySelected && combinedModality->GetUltrasoundDevice().IsNotNull()) { combinedModality->GetUltrasoundDevice()->RemovePropertyChangedListener(m_ListenerDeviceChanged); } } m_CombinedModality = combinedModality; if (combinedModalitySelected) { bool calibrated = this->UpdateCalibrationState(); if (!m_CalibrationLoadedNecessary) { emit SignalReadyForNextStep(); } else { if (calibrated) { emit SignalReadyForNextStep(); } else { emit SignalNoLongerReadyForNextStep(); } } // enable disconnect button only if combined modality is connected or active ui->combinedModalityDistconnectButton->setEnabled(combinedModality->GetUltrasoundDevice()->GetDeviceState() >= mitk::USDevice::State_Connected); ui->combinedModalityActivateButton->setEnabled(combinedModality->GetUltrasoundDevice()->GetDeviceState() < mitk::USDevice::State_Activated); this->UpdateTrackingToolNames(); } else { ui->combinedModalityDistconnectButton->setEnabled(false); ui->combinedModalityActivateButton->setEnabled(false); } } void QmitkUSNavigationStepCombinedModality::OnLoadCalibration() { QString filename = QFileDialog::getOpenFileName(QApplication::activeWindow(), "Load Calibration", m_LastCalibrationFilename.c_str(), "Calibration files *.cal"); m_LastCalibrationFilename = filename.toStdString(); mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetSelectedCombinedModality(); if (combinedModality.IsNull()) { ui->calibrationLoadStateLabel->setText("Selected device is no USCombinedModality."); emit SignalNoLongerReadyForNextStep(); return; } if (filename.isEmpty()) { bool calibrated = this->UpdateCalibrationState(); if (!calibrated) { emit SignalNoLongerReadyForNextStep(); } return; } QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { MITK_WARN << "Cannot open file '" << filename.toStdString() << "' for reading."; ui->calibrationLoadStateLabel->setText("Cannot open file '" + filename + "' for reading."); emit SignalNoLongerReadyForNextStep(); return; } QTextStream inStream(&file); m_LoadedCalibration = inStream.readAll().toStdString(); if (m_LoadedCalibration.empty()) { MITK_WARN << "Failed to load file. Unsupported format?"; ui->calibrationLoadStateLabel->setText("Failed to load file. Unsupported format?"); emit SignalNoLongerReadyForNextStep(); return; } try { combinedModality->DeserializeCalibration(m_LoadedCalibration); } catch (const mitk::Exception& /*exception*/) { MITK_WARN << "Failed to deserialize calibration. Unsuppoerted format?"; ui->calibrationLoadStateLabel->setText("Failed to deserialize calibration. Unsuppoerted format?"); emit SignalNoLongerReadyForNextStep(); return; } ui->calibrationLoadStateLabel->setText("Loaded calibration : " + filename); m_CombinedModality = combinedModality; emit SignalReadyForNextStep(); } void QmitkUSNavigationStepCombinedModality::OnCombinedModalityCreateNewButtonClicked() { this->SetCombinedModalityCreateWidgetEnabled(true); } void QmitkUSNavigationStepCombinedModality::OnCombinedModalityCreationExit() { this->SetCombinedModalityCreateWidgetEnabled(false); - mitk::DataNode::Pointer usNode = mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))->GetDataStorage()//GetDataStorage - ->GetNamedNode("US Viewing Stream - Image 0"); + mitk::DataNode::Pointer usNode = mitk::RenderingManager::GetInstance()->GetDataStorage()->GetNamedNode("US Viewing Stream - Image 0"); if (usNode.IsNotNull()) { - mitk::RenderingManager::GetInstance()->InitializeViews(//Reinit - usNode->GetData()->GetTimeGeometry());//GetNode + mitk::RenderingManager::GetInstance()->InitializeViews(usNode->GetData()->GetTimeGeometry()); } else { MITK_WARN << "No reinit possible"; } } void QmitkUSNavigationStepCombinedModality::OnCombinedModalityEditExit() { this->SetCombinedModalityEditWidgetEnabled(false); ui->combinedModalityEditWidget->SetCombinedModality(nullptr); } void QmitkUSNavigationStepCombinedModality::OnDeleteButtonClicked() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetSelectedCombinedModality(); if (combinedModality.IsNotNull()) { combinedModality->RemoveAllObservers(); combinedModality->UnregisterOnService(); } } void QmitkUSNavigationStepCombinedModality::OnCombinedModalityEditButtonClicked() { ui->combinedModalityEditWidget->SetCombinedModality(m_CombinedModality); this->SetCombinedModalityEditWidgetEnabled(true); } void QmitkUSNavigationStepCombinedModality::OnActivateButtonClicked() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetSelectedCombinedModality(); if (combinedModality.IsNotNull()) { if (!combinedModality->GetUltrasoundDevice()->GetIsConnected()) { combinedModality->GetUltrasoundDevice()->Connect(); } if (!combinedModality->GetUltrasoundDevice()->GetIsActive()) { combinedModality->GetUltrasoundDevice()->Activate(); } } } void QmitkUSNavigationStepCombinedModality::OnDisconnectButtonClicked() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetSelectedCombinedModality(); if (combinedModality.IsNotNull()) { if (combinedModality->GetUltrasoundDevice()->GetIsActive()) { combinedModality->GetUltrasoundDevice()->Deactivate(); } if (combinedModality->GetUltrasoundDevice()->GetIsConnected()) { combinedModality->GetUltrasoundDevice()->Disconnect(); } } } bool QmitkUSNavigationStepCombinedModality::OnStartStep() { return true; } bool QmitkUSNavigationStepCombinedModality::OnRestartStep() { return true; } bool QmitkUSNavigationStepCombinedModality::OnFinishStep() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetSelectedCombinedModality(); if (combinedModality.IsNotNull()) { QApplication::setOverrideCursor(Qt::WaitCursor); // make sure that the combined modality is in connected state before using it if (combinedModality->GetUltrasoundDevice()->GetDeviceState() < mitk::USDevice::State_Connected) { combinedModality->GetUltrasoundDevice()->Connect(); } if (combinedModality->GetUltrasoundDevice()->GetDeviceState() < mitk::USDevice::State_Activated) { combinedModality->GetUltrasoundDevice()->Activate(); } QApplication::restoreOverrideCursor(); } emit SignalCombinedModalityChanged(combinedModality); this->CreateCombinedModalityResultAndSignalIt(); return true; } bool QmitkUSNavigationStepCombinedModality::OnActivateStep() { // make sure that device selection status is up-to-date this->OnDeviceSelectionChanged(); return true; } void QmitkUSNavigationStepCombinedModality::OnUpdate() { } QString QmitkUSNavigationStepCombinedModality::GetTitle() { return "Selection of Combined Modality"; } bool QmitkUSNavigationStepCombinedModality::GetIsRestartable() { return false; } void QmitkUSNavigationStepCombinedModality::SetCombinedModalityCreateWidgetEnabled(bool enabled) { ui->combinedModalityLabel->setVisible(!enabled); ui->combinedModalityListWidget->setVisible(!enabled); ui->combinedModalityCreateButton->setVisible(!enabled); ui->combinedModalityDeleteButton->setVisible(!enabled); ui->combinedModalitEditButton->setVisible(!enabled); ui->combinedModalityActivateButton->setVisible(!enabled); ui->combinedModalityDistconnectButton->setVisible(!enabled); ui->helpLabel->setVisible(!enabled); ui->calibrationGroupBox->setVisible(!enabled); ui->combinedModalityCreateWidget->setVisible(enabled); } void QmitkUSNavigationStepCombinedModality::SetCombinedModalityEditWidgetEnabled(bool enabled) { ui->combinedModalityLabel->setVisible(!enabled); ui->combinedModalityListWidget->setVisible(!enabled); ui->combinedModalityCreateButton->setVisible(!enabled); ui->combinedModalityDeleteButton->setVisible(!enabled); ui->combinedModalitEditButton->setVisible(!enabled); ui->combinedModalityActivateButton->setVisible(!enabled); ui->combinedModalityDistconnectButton->setVisible(!enabled); ui->helpLabel->setVisible(!enabled); ui->calibrationGroupBox->setVisible(!enabled); ui->combinedModalityEditWidget->setVisible(enabled); } void QmitkUSNavigationStepCombinedModality::CreateCombinedModalityResultAndSignalIt() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetCombinedModality(); mitk::USDevice::Pointer usDevice = combinedModality->GetUltrasoundDevice(); // save identifiers and calibration to a result object mitk::DataNode::Pointer combinedModalityResult = mitk::DataNode::New(); combinedModalityResult->SetName("CombinedModalityResult"); combinedModalityResult->SetStringProperty("USNavigation::CombinedModality", std::string(combinedModality->GetUltrasoundDevice()->GetManufacturer() + ": " + combinedModality->GetUltrasoundDevice()->GetName() + " (" + combinedModality->GetUltrasoundDevice()->GetComment() + ")").c_str()); combinedModalityResult->SetStringProperty("USNavigation::UltrasoundDevice", std::string(usDevice->GetManufacturer() + ": " + usDevice->GetName() + " (" + usDevice->GetComment() + ")").c_str()); combinedModalityResult->SetStringProperty("USNavigation::TrackingDevice", combinedModality->GetNavigationDataSource()->GetName().c_str()); combinedModalityResult->SetStringProperty("USNavigation::Calibration", combinedModality->SerializeCalibration().c_str()); emit SignalIntermediateResult(combinedModalityResult); } bool QmitkUSNavigationStepCombinedModality::UpdateCalibrationState() { if (m_CombinedModality.IsNull()) { return false; } bool calibrated = m_CombinedModality->GetContainsAtLeastOneCalibration(); if (calibrated) { ui->calibrationLoadStateLabel->setText("Selected device contains at least one calibration."); } else { ui->calibrationLoadStateLabel->setText("Selected device is not calibrated."); } return calibrated; } mitk::AbstractUltrasoundTrackerDevice::Pointer QmitkUSNavigationStepCombinedModality::GetSelectedCombinedModality() { // nothing more to do if no device is selected at the moment if (!ui->combinedModalityListWidget->GetIsServiceSelected()) { return nullptr; } mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = ui->combinedModalityListWidget->GetSelectedService(); if (combinedModality.IsNull()) { MITK_WARN << "Selected device is no USCombinedModality."; } return combinedModality; } void QmitkUSNavigationStepCombinedModality::SetCalibrationLoadedNecessary(bool necessary) { m_CalibrationLoadedNecessary = necessary; } void QmitkUSNavigationStepCombinedModality::OnDevicePropertyChanged(const std::string& key, const std::string&) { // property changes only matter if the navigation step is currently active // (being sensitive to them in other states may even be dangerous) if (this->GetNavigationStepState() < QmitkUSAbstractNavigationStep::State_Active) { return; } // calibration state could have changed if the depth was changed if (key == mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DEPTH) { bool calibrated = this->UpdateCalibrationState(); if (calibrated) { emit SignalReadyForNextStep(); } else { emit SignalNoLongerReadyForNextStep(); } } } void QmitkUSNavigationStepCombinedModality::UpdateTrackingToolNames() { //check if everything is initialized if (m_CombinedModality.IsNull()) { return; } mitk::NavigationDataSource::Pointer navigationDataSource = m_CombinedModality->GetNavigationDataSource(); if (navigationDataSource.IsNull()) { return; } if (GetDataStorage(false).IsNull()) { return; } // get the settings node mitk::DataNode::Pointer settingsNode = this->GetNamedDerivedNode(DATANAME_SETTINGS, DATANAME_BASENODE); std::string needleNames; itk::ProcessObject::DataObjectPointerArray outputs = navigationDataSource->GetOutputs(); for (itk::ProcessObject::DataObjectPointerArray::iterator it = outputs.begin(); it != outputs.end(); ++it) { needleNames += std::string((static_cast(it->GetPointer()))->GetName()) + ";"; } // change the settings node only if the settings changed std::string oldProperty; if (!settingsNode->GetStringProperty("settings.needle-names", oldProperty) || oldProperty != needleNames || !settingsNode->GetStringProperty("settings.reference-names", oldProperty) || oldProperty != needleNames) { settingsNode->SetStringProperty("settings.needle-names", needleNames.c_str()); settingsNode->SetStringProperty("settings.reference-names", needleNames.c_str()); emit SignalSettingsNodeChanged(settingsNode); } } diff --git a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp index d25ad9abc3..493f9ad55c 100644 --- a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp +++ b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp @@ -1,1013 +1,1017 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkUSNavigationStepMarkerIntervention.h" #include "ui_QmitkUSNavigationStepMarkerIntervention.h" #include "mitkBaseRenderer.h" #include "mitkContourModel.h" #include "mitkNeedleProjectionFilter.h" #include "mitkNodeDisplacementFilter.h" #include "mitkSurface.h" #include "mitkTextAnnotation2D.h" #include #include #include "../Filter/mitkUSNavigationTargetIntersectionFilter.h" #include "../Filter/mitkUSNavigationTargetOcclusionFilter.h" #include "../Filter/mitkUSNavigationTargetUpdateFilter.h" #include "../QmitkUSNavigationMarkerPlacement.h" #include "../Widgets/QmitkZoneProgressBar.h" #include "../mitkUSTargetPlacementQualityCalculator.h" #include "../Interactors/mitkUSPointMarkInteractor.h" #include "usModuleRegistry.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkSurface.h" // VTK #include "vtkCellLocator.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkIdList.h" #include "vtkLinearTransform.h" #include "vtkLookupTable.h" #include "vtkMath.h" #include "vtkOBBTree.h" #include "vtkPointData.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkSelectEnclosedPoints.h" #include "vtkSmartPointer.h" #include #include "vtkTransformPolyDataFilter.h" #include "vtkWarpScalar.h" QmitkUSNavigationStepMarkerIntervention::QmitkUSNavigationStepMarkerIntervention(QWidget *parent) : QmitkUSAbstractNavigationStep(parent), m_NumberOfTargets(0), m_PlannedTargetsNodes(), m_ReachedTargetsNodes(), m_TargetProgressBar(new QmitkZoneProgressBar(QString::fromStdString("Target: %1 mm"), 200, 0, this)), m_PlannedTargetProgressBar(nullptr), m_CurrentTargetIndex(0), m_CurrentTargetReached(false), m_ShowPlanningColors(false), m_PointMarkInteractor(mitk::USPointMarkInteractor::New()), m_TargetNode(nullptr), m_TargetColorLookupTableProperty(nullptr), m_TargetSurface(nullptr), m_NeedleProjectionFilter(mitk::NeedleProjectionFilter::New()), m_NodeDisplacementFilter(mitk::NodeDisplacementFilter::New()), m_TargetUpdateFilter(mitk::USNavigationTargetUpdateFilter::New()), m_TargetOcclusionFilter(mitk::USNavigationTargetOcclusionFilter::New()), m_TargetIntersectionFilter(mitk::USNavigationTargetIntersectionFilter::New()), m_PlacementQualityCalculator(mitk::USTargetPlacementQualityCalculator::New()), m_TargetStructureWarnOverlay(mitk::TextAnnotation2D::New()), m_ReferenceSensorName(), m_NeedleSensorName(), m_ReferenceSensorIndex(1), m_NeedleSensorIndex(0), m_ListenerTargetCoordinatesChanged(this, &QmitkUSNavigationStepMarkerIntervention::UpdateTargetCoordinates), ui(new Ui::QmitkUSNavigationStepMarkerIntervention) { m_ActiveTargetColor[0] = 1; m_ActiveTargetColor[1] = 1; m_ActiveTargetColor[2] = 0; m_InactiveTargetColor[0] = 1; m_InactiveTargetColor[1] = 1; m_InactiveTargetColor[2] = 0.5; m_ReachedTargetColor[0] = 0.6; m_ReachedTargetColor[1] = 1; m_ReachedTargetColor[2] = 0.6; ui->setupUi(this); connect(ui->freezeImageButton, SIGNAL(SignalFreezed(bool)), this, SLOT(OnFreeze(bool))); connect(ui->backToLastTargetButton, SIGNAL(clicked()), this, SLOT(OnBackToLastTargetClicked())); connect(ui->targetReachedButton, SIGNAL(clicked()), this, SLOT(OnTargetLeft())); connect(this, SIGNAL(TargetReached(int)), this, SLOT(OnTargetReached())); connect(this, SIGNAL(TargetLeft(int)), this, SLOT(OnTargetLeft())); connect(ui->riskStructuresRangeWidget, SIGNAL(SignalZoneViolated(const mitk::DataNode *, mitk::Point3D)), this, SLOT(OnRiskZoneViolated(const mitk::DataNode *, mitk::Point3D))); m_PointMarkInteractor->CoordinatesChangedEvent.AddListener(m_ListenerTargetCoordinatesChanged); this->GenerateTargetColorLookupTable(); m_TargetProgressBar->SetTextFormatInvalid("Target is not on Needle Path"); ui->targetStructuresRangeLayout->addWidget(m_TargetProgressBar); m_TargetUpdateFilter->SetScalarArrayIdentifier("USNavigation::ReachedTargetScores"); } QmitkUSNavigationStepMarkerIntervention::~QmitkUSNavigationStepMarkerIntervention() { mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(false); if (dataStorage.IsNotNull()) { // remove the node for the needle path mitk::DataNode::Pointer node = this->GetNamedDerivedNode("Needle Path", QmitkUSAbstractNavigationStep::DATANAME_BASENODE); if (node.IsNotNull()) { dataStorage->Remove(node); } } delete ui; m_PointMarkInteractor->CoordinatesChangedEvent.RemoveListener(m_ListenerTargetCoordinatesChanged); } bool QmitkUSNavigationStepMarkerIntervention::OnStartStep() { m_NeedleProjectionFilter->SelectInput(m_NeedleSensorIndex); // create node for Needle Projection mitk::DataNode::Pointer node = this->GetNamedDerivedNodeAndCreate("Needle Path", QmitkUSAbstractNavigationStep::DATANAME_BASENODE); node->SetData(m_NeedleProjectionFilter->GetProjection()); node->SetBoolProperty("show contour", true); // initialize warning overlay (and do not display it, yet) m_TargetStructureWarnOverlay->SetText("Warning: Needle is Inside the Target Structure."); m_TargetStructureWarnOverlay->SetVisibility(false); // set position and font size for the text overlay mitk::Point2D overlayPosition; overlayPosition.SetElement(0, 10.0f); overlayPosition.SetElement(1, 10.0f); m_TargetStructureWarnOverlay->SetPosition2D(overlayPosition); m_TargetStructureWarnOverlay->SetFontSize(18); // overlay should be red mitk::Color color; color[0] = 1; color[1] = 0; color[2] = 0; m_TargetStructureWarnOverlay->SetColor(color); - mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_TargetStructureWarnOverlay.GetPointer(), "stdmulti.widget3"); + auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows(); + for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit) + { + mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_TargetStructureWarnOverlay.GetPointer(), mapit->second); + } return true; } bool QmitkUSNavigationStepMarkerIntervention::OnStopStep() { mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(); // remove all reached nodes from the data storage for (QVector>::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { dataStorage->Remove(*it); } m_ReachedTargetsNodes.clear(); m_CurrentTargetIndex = 0; // reset button states ui->freezeImageButton->setEnabled(false); ui->backToLastTargetButton->setEnabled(false); ui->targetReachedButton->setEnabled(true); // make sure that it is unfreezed after stopping the step ui->freezeImageButton->Unfreeze(); // remove base node for reached targets from the data storage mitk::DataNode::Pointer reachedTargetsNode = this->GetNamedDerivedNode( QmitkUSAbstractNavigationStep::DATANAME_BASENODE, QmitkUSNavigationMarkerPlacement::DATANAME_REACHED_TARGETS); if (reachedTargetsNode.IsNotNull()) { dataStorage->Remove(reachedTargetsNode); } return true; } bool QmitkUSNavigationStepMarkerIntervention::OnFinishStep() { return true; } bool QmitkUSNavigationStepMarkerIntervention::OnActivateStep() { this->ClearZones(); // clear risk zones before adding new ones // get target node from data storage and make sure that it contains data m_TargetNode = this->GetNamedDerivedNode(QmitkUSNavigationMarkerPlacement::DATANAME_TARGETSURFACE, QmitkUSNavigationMarkerPlacement::DATANAME_TUMOUR); if (m_TargetNode.IsNull() || m_TargetNode->GetData() == nullptr) { mitkThrow() << "Target node (" << QmitkUSNavigationMarkerPlacement::DATANAME_TARGETSURFACE << ") must not be null."; } // get target data and make sure that it is a surface m_TargetSurface = dynamic_cast(m_TargetNode->GetData()); if (m_TargetSurface.IsNull()) { mitkThrow() << "Target node (" << QmitkUSNavigationMarkerPlacement::DATANAME_TARGETSURFACE << ") data must be of type mitk::Surface"; } // delete progress bars for reinitializing them again afterwards if (m_PlannedTargetProgressBar) { ui->targetStructuresRangeLayout->removeWidget(m_PlannedTargetProgressBar); delete m_PlannedTargetProgressBar; m_PlannedTargetProgressBar = nullptr; } m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex); this->UpdateTargetProgressDisplay(); mitk::DataNode::Pointer tumourNode = this->GetNamedDerivedNode(QmitkUSNavigationMarkerPlacement::DATANAME_TUMOUR, QmitkUSAbstractNavigationStep::DATANAME_BASENODE); if (tumourNode.IsNotNull()) { // do not show tumour node during intervention (target surface is shown) tumourNode->SetBoolProperty("visible", false); // add tumour as a risk structure ui->riskStructuresRangeWidget->AddZone(tumourNode); } // set target structure for target update filter m_TargetUpdateFilter->SetTargetStructure(m_TargetNode); m_TargetOcclusionFilter->SetTargetStructure(m_TargetNode); // set lookup table of tumour node m_TargetNode->SetProperty("LookupTable", m_TargetColorLookupTableProperty); // mitk::DataNode::Pointer targetsBaseNode = this->GetNamedDerivedNode(QmitkUSNavigationMarkerPlacement::DATANAME_TARGETS, QmitkUSAbstractNavigationStep::DATANAME_BASENODE); mitk::DataStorage::SetOfObjects::ConstPointer plannedTargetNodes; if (targetsBaseNode.IsNotNull()) { plannedTargetNodes = this->GetDataStorage()->GetDerivations(targetsBaseNode); } if (plannedTargetNodes.IsNotNull() && plannedTargetNodes->Size() > 0) { for (mitk::DataStorage::SetOfObjects::ConstIterator it = plannedTargetNodes->Begin(); it != plannedTargetNodes->End(); ++it) { m_PlannedTargetsNodes.push_back(it->Value()); } m_PlannedTargetProgressBar = new QmitkZoneProgressBar(QString::fromStdString("Planned Target"), 200, 0); ui->targetStructuresRangeLayout->addWidget(m_PlannedTargetProgressBar); } // add progress bars for risk zone nodes mitk::DataNode::Pointer zonesBaseNode = this->GetNamedDerivedNode(QmitkUSNavigationMarkerPlacement::DATANAME_ZONES, QmitkUSAbstractNavigationStep::DATANAME_BASENODE); // only add progress bars if the base node for zones was created if (zonesBaseNode.IsNotNull()) { mitk::DataStorage::SetOfObjects::ConstPointer zoneNodes = this->GetDataStorage()->GetDerivations(zonesBaseNode); for (mitk::DataStorage::SetOfObjects::ConstIterator it = zoneNodes->Begin(); it != zoneNodes->End(); ++it) { ui->riskStructuresRangeWidget->AddZone(it->Value()); } m_TargetOcclusionFilter->SelectStartPositionInput(m_NeedleSensorIndex); m_TargetOcclusionFilter->SetObstacleStructures(zoneNodes); } return true; } bool QmitkUSNavigationStepMarkerIntervention::OnDeactivateStep() { ui->freezeImageButton->Unfreeze(); return true; } void QmitkUSNavigationStepMarkerIntervention::OnUpdate() { // get navigation data source and make sure that it is not null mitk::NavigationDataSource::Pointer navigationDataSource = this->GetCombinedModality()->GetNavigationDataSource(); if (navigationDataSource.IsNull()) { MITK_ERROR("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Navigation Data Source of Combined Modality must not be null."; mitkThrow() << "Navigation Data Source of Combined Modality must not be null."; } ui->riskStructuresRangeWidget->UpdateDistancesToNeedlePosition(navigationDataSource->GetOutput(m_NeedleSensorIndex)); this->UpdateBodyMarkerStatus(navigationDataSource->GetOutput(m_ReferenceSensorIndex)); this->UpdateTargetColors(); this->UpdateTargetScore(); this->UpdateTargetViolationStatus(); } void QmitkUSNavigationStepMarkerIntervention::OnSettingsChanged(const itk::SmartPointer settingsNode) { if (settingsNode.IsNull()) { return; } int numberOfTargets; if (settingsNode->GetIntProperty("settings.number-of-targets", numberOfTargets)) { m_NumberOfTargets = numberOfTargets; m_TargetUpdateFilter->SetNumberOfTargets(numberOfTargets); m_PlacementQualityCalculator->SetOptimalAngle(m_TargetUpdateFilter->GetOptimalAngle()); } std::string referenceSensorName; if (settingsNode->GetStringProperty("settings.reference-name-selected", referenceSensorName)) { m_ReferenceSensorName = referenceSensorName; } std::string needleSensorName; if (settingsNode->GetStringProperty("settings.needle-name-selected", needleSensorName)) { m_NeedleSensorName = needleSensorName; } this->UpdateSensorsNames(); } QString QmitkUSNavigationStepMarkerIntervention::GetTitle() { return "Computer-assisted Intervention"; } bool QmitkUSNavigationStepMarkerIntervention::GetIsRestartable() { return true; } QmitkUSAbstractNavigationStep::FilterVector QmitkUSNavigationStepMarkerIntervention::GetFilter() { FilterVector filter; filter.push_back(m_NeedleProjectionFilter.GetPointer()); filter.push_back(m_NodeDisplacementFilter.GetPointer()); filter.push_back(m_TargetOcclusionFilter.GetPointer()); return filter; } void QmitkUSNavigationStepMarkerIntervention::OnSetCombinedModality() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetCombinedModality(false); if (combinedModality.IsNotNull()) { mitk::AffineTransform3D::Pointer calibration = combinedModality->GetCalibration(); if (calibration.IsNotNull()) { m_NeedleProjectionFilter->SetTargetPlane(calibration); } } ui->freezeImageButton->SetCombinedModality(combinedModality, m_ReferenceSensorIndex); this->UpdateSensorsNames(); } void QmitkUSNavigationStepMarkerIntervention::OnTargetReached() { m_CurrentTargetReached = true; } void QmitkUSNavigationStepMarkerIntervention::OnTargetLeft() { m_CurrentTargetReached = false; m_CurrentTargetIndex++; if (m_CurrentTargetIndex >= 0 && static_cast(m_CurrentTargetIndex) >= m_NumberOfTargets) { ui->targetReachedButton->setDisabled(true); } ui->backToLastTargetButton->setEnabled(true); ui->freezeImageButton->setEnabled(true); this->UpdateTargetProgressDisplay(); if (m_ReachedTargetsNodes.size() < m_CurrentTargetIndex) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetName( (QString("Target ") + QString("%1").arg(m_CurrentTargetIndex, 2, 10, QLatin1Char('0'))).toStdString()); this->GetDataStorage()->Add( node, this->GetNamedDerivedNodeAndCreate(QmitkUSNavigationMarkerPlacement::DATANAME_REACHED_TARGETS, QmitkUSAbstractNavigationStep::DATANAME_BASENODE)); m_ReachedTargetsNodes.push_back(node); } mitk::DataNode::Pointer node = m_ReachedTargetsNodes.at(m_CurrentTargetIndex - 1); mitk::Surface::Pointer zone = mitk::Surface::New(); // create a vtk sphere with given radius vtkSmartPointer vtkSphere = vtkSmartPointer::New(); vtkSphere->SetRadius(5); vtkSphere->SetCenter(0, 0, 0); vtkSphere->Update(); zone->SetVtkPolyData(vtkSphere->GetOutput()); // set vtk sphere and origin to data node node->SetData(zone); node->GetData()->GetGeometry()->SetOrigin( this->GetCombinedModality()->GetNavigationDataSource()->GetOutput(m_NeedleSensorIndex)->GetPosition()); node->SetColor(0.2, 0.9, 0.2); this->UpdateTargetCoordinates(node); } void QmitkUSNavigationStepMarkerIntervention::OnBackToLastTargetClicked() { if (m_CurrentTargetIndex < 1) { MITK_WARN << "Cannot go back to last target as there is no last target."; return; } m_CurrentTargetIndex--; if (m_ReachedTargetsNodes.size() > m_CurrentTargetIndex) { this->GetDataStorage()->Remove(m_ReachedTargetsNodes.last()); MITK_INFO("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Removed Target " << m_ReachedTargetsNodes.size(); m_ReachedTargetsNodes.pop_back(); } if (m_CurrentTargetIndex == 0) { ui->backToLastTargetButton->setDisabled(true); } if (m_CurrentTargetIndex >= 0 && static_cast(m_CurrentTargetIndex) < m_NumberOfTargets) { ui->targetReachedButton->setEnabled(true); } ui->freezeImageButton->setEnabled(false); ui->freezeImageButton->Unfreeze(); this->UpdateTargetProgressDisplay(); m_TargetUpdateFilter->RemovePositionOfTarget(m_CurrentTargetIndex); } void QmitkUSNavigationStepMarkerIntervention::OnFreeze(bool freezed) { if (freezed) { this->GetCombinedModality()->SetIsFreezed(true); // load state machine and event config for data interactor m_PointMarkInteractor->LoadStateMachine("USPointMarkInteractions.xml", us::ModuleRegistry::GetModule("MitkUS")); m_PointMarkInteractor->SetEventConfig("globalConfig.xml"); if (m_CurrentTargetIndex < 1) { mitkThrow() << "Current target index has to be greater zero when freeze button is clicked."; } if (m_ReachedTargetsNodes.size() < m_CurrentTargetIndex) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetName( (QString("Target ") + QString("%1").arg(m_CurrentTargetIndex, 2, 10, QLatin1Char('0'))).toStdString()); this->GetDataStorage()->Add( node, this->GetNamedDerivedNodeAndCreate(QmitkUSNavigationMarkerPlacement::DATANAME_REACHED_TARGETS, QmitkUSAbstractNavigationStep::DATANAME_BASENODE)); m_ReachedTargetsNodes.push_back(node); } m_PointMarkInteractor->SetDataNode(m_ReachedTargetsNodes.last()); } else { m_PointMarkInteractor->SetDataNode(nullptr); this->GetCombinedModality()->SetIsFreezed(false); } } void QmitkUSNavigationStepMarkerIntervention::OnShowPlanningView(bool show) { m_ShowPlanningColors = show; } void QmitkUSNavigationStepMarkerIntervention::OnRiskZoneViolated(const mitk::DataNode *node, mitk::Point3D position) { MITK_INFO << "Risk zone (" << node->GetName() << ") violated at position " << position << "."; } void QmitkUSNavigationStepMarkerIntervention::ClearZones() { ui->riskStructuresRangeWidget->ClearZones(); // remove all reached target nodes from the data storage and clear the list mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(); for (QVector::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { if (it->IsNotNull()) { dataStorage->Remove(*it); } } m_ReachedTargetsNodes.clear(); } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetCoordinates(mitk::DataNode *dataNode) { m_NodeDisplacementFilter->ResetNodes(); for (QVector>::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { if (it->IsNotNull() && (*it)->GetData() != nullptr) { m_NodeDisplacementFilter->AddNode(*it); } } mitk::BaseData *baseData = dataNode->GetData(); if (!baseData) { mitkThrow() << "Data of the data node must not be null."; } mitk::BaseGeometry::Pointer geometry = baseData->GetGeometry(); if (geometry.IsNull()) { mitkThrow() << "Geometry of the data node must not be null."; } m_TargetUpdateFilter->SetControlNode(m_CurrentTargetIndex - 1, dataNode); if (m_PlannedTargetsNodes.size() > m_CurrentTargetIndex - 1) { m_PlannedTargetsNodes.at(m_CurrentTargetIndex - 1)->SetVisibility(false); } MITK_INFO("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Target " << m_CurrentTargetIndex << " reached at position " << geometry->GetOrigin(); this->CalculateTargetPlacementQuality(); } void QmitkUSNavigationStepMarkerIntervention::UpdateBodyMarkerStatus(mitk::NavigationData::Pointer bodyMarker) { if (bodyMarker.IsNull()) { MITK_ERROR("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Current Navigation Data for body marker of Combined Modality must not be null."; mitkThrow() << "Current Navigation Data for body marker of Combined Modality must not be null."; } bool valid = bodyMarker->IsDataValid(); // update body marker status label if (valid) { ui->bodyMarkerTrackingStatusLabel->setStyleSheet( "background-color: #8bff8b; margin-right: 1em; margin-left: 1em; border: 1px solid grey"); ui->bodyMarkerTrackingStatusLabel->setText("Body marker is inside the tracking volume."); } else { ui->bodyMarkerTrackingStatusLabel->setStyleSheet( "background-color: #ff7878; margin-right: 1em; margin-left: 1em; border: 1px solid grey"); ui->bodyMarkerTrackingStatusLabel->setText("Body marker is not inside the tracking volume."); } ui->targetStructuresRangeGroupBox->setEnabled(valid); ui->riskStructuresRangeGroupBox->setEnabled(valid); } void QmitkUSNavigationStepMarkerIntervention::GenerateTargetColorLookupTable() { vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetHueRange(0.0, 0.33); lookupTable->SetSaturationRange(1.0, 1.0); lookupTable->SetValueRange(1.0, 1.0); lookupTable->SetTableRange(0.0, 1.0); lookupTable->Build(); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); lut->SetVtkLookupTable(lookupTable); m_TargetColorLookupTableProperty = mitk::LookupTableProperty::New(lut); } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetColors() { if (m_TargetNode.IsNull()) { return; } m_TargetNode->SetColor(1, 1, 1); mitk::BaseData *targetNodeData = m_TargetNode->GetData(); if (targetNodeData == nullptr) { return; } mitk::Surface::Pointer targetNodeSurface = dynamic_cast(targetNodeData); vtkSmartPointer targetNodeSurfaceVtk = targetNodeSurface->GetVtkPolyData(); vtkPointData *targetPointData = targetNodeSurface->GetVtkPolyData()->GetPointData(); vtkFloatArray *scalars = dynamic_cast(targetPointData->GetScalars("USNavigation::Occlusion")); vtkFloatArray *targetScoreScalars; if (m_ShowPlanningColors) { targetScoreScalars = dynamic_cast(targetPointData->GetScalars("USNavigation::PlanningScalars")); } else { targetScoreScalars = dynamic_cast(targetPointData->GetScalars("USNavigation::ReachedTargetScores")); } if (!scalars || !targetScoreScalars) { return; } unsigned int numberOfTupels = scalars->GetNumberOfTuples(); vtkSmartPointer colors = vtkSmartPointer::New(); colors->SetNumberOfComponents(1); colors->SetNumberOfTuples(numberOfTupels); colors->SetName("Colors"); double color, intersection, markerScore; for (unsigned int n = 0; n < numberOfTupels; n++) { scalars->GetTuple(n, &intersection); targetScoreScalars->GetTuple(n, &markerScore); if (intersection > 0) { color = 0; } else { color = markerScore; } colors->SetTuple(n, &color); } if (numberOfTupels > 0) { targetNodeSurfaceVtk->GetPointData()->SetScalars(colors); targetNodeSurfaceVtk->GetPointData()->Update(); } } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetScore() { if (m_NeedleProjectionFilter->GetProjection()->GetSize() != 2) { return; } vtkSmartPointer targetSurfaceVtk = m_TargetSurface->GetVtkPolyData(); m_TargetIntersectionFilter->SetTargetSurface(m_TargetSurface); m_TargetIntersectionFilter->SetLine(m_NeedleProjectionFilter->GetProjection()); m_TargetIntersectionFilter->CalculateIntersection(); if (m_TargetIntersectionFilter->GetIsIntersecting()) { vtkFloatArray *scalars = dynamic_cast(targetSurfaceVtk->GetPointData()->GetScalars("USNavigation::ReachedTargetScores")); double score; scalars->GetTuple(m_TargetIntersectionFilter->GetIntersectionNearestSurfacePointId(), &score); double color[3]; m_TargetColorLookupTableProperty->GetLookupTable()->GetVtkLookupTable()->GetColor(score, color); float colorF[3]; colorF[0] = color[0]; colorF[1] = color[1]; colorF[2] = color[2]; m_TargetProgressBar->SetColor(colorF); m_TargetProgressBar->SetBorderColor(colorF); m_TargetProgressBar->setValue(m_TargetIntersectionFilter->GetDistanceToIntersection()); if (m_PlannedTargetProgressBar) { vtkFloatArray *scalars = dynamic_cast(targetSurfaceVtk->GetPointData()->GetScalars("USNavigation::PlanningScalars")); if (scalars) { double score; scalars->GetTuple(m_TargetIntersectionFilter->GetIntersectionNearestSurfacePointId(), &score); double color[3]; m_TargetColorLookupTableProperty->GetLookupTable()->GetVtkLookupTable()->GetColor(score, color); float colorF[3]; colorF[0] = color[0]; colorF[1] = color[1]; colorF[2] = color[2]; m_PlannedTargetProgressBar->SetColor(colorF); m_PlannedTargetProgressBar->SetBorderColor(colorF); m_PlannedTargetProgressBar->SetTextFormatValid("Planned Target: %1 mm"); mitk::Point3D intersectionPoint = m_TargetIntersectionFilter->GetIntersectionPoint(); mitk::ScalarType minDistance = -1; for (QVector>::iterator it = m_PlannedTargetsNodes.begin(); it != m_PlannedTargetsNodes.end(); ++it) { mitk::ScalarType distance = intersectionPoint.EuclideanDistanceTo((*it)->GetData()->GetGeometry()->GetOrigin()); if (minDistance < 0 || distance < minDistance) { minDistance = distance; } } m_PlannedTargetProgressBar->setValue(minDistance); } } } else { m_TargetProgressBar->setValueInvalid(); } } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetProgressDisplay() { QString description; if (m_CurrentTargetIndex >= static_cast(m_NumberOfTargets)) { description = "All Targets Reached"; if (m_TargetProgressBar) { m_TargetProgressBar->hide(); } } else { description = QString("Distance to Target ") + QString::number(m_CurrentTargetIndex + 1) + QString(" of ") + QString::number(m_NumberOfTargets); if (m_TargetProgressBar) { m_TargetProgressBar->show(); } } ui->targetStructuresRangeGroupBox->setTitle(description); } void QmitkUSNavigationStepMarkerIntervention::UpdatePlannedTargetProgressDisplay() { // make sure that the needle projection consists of two points if (m_NeedleProjectionFilter->GetProjection()->GetSize() != 2) { return; } vtkSmartPointer targetSurfaceVtk = m_TargetSurface->GetVtkPolyData(); m_TargetIntersectionFilter->SetTargetSurface(m_TargetSurface); m_TargetIntersectionFilter->SetLine(m_NeedleProjectionFilter->GetProjection()); m_TargetIntersectionFilter->CalculateIntersection(); // update target progress bar according to the color of the intersection // point on the target surface and the distance to the intersection if (m_TargetIntersectionFilter->GetIsIntersecting()) { vtkFloatArray *scalars = dynamic_cast(targetSurfaceVtk->GetPointData()->GetScalars("Colors")); double score; scalars->GetTuple(m_TargetIntersectionFilter->GetIntersectionNearestSurfacePointId(), &score); double color[3]; m_TargetColorLookupTableProperty->GetLookupTable()->GetVtkLookupTable()->GetColor(score, color); float colorF[3]; colorF[0] = color[0]; colorF[1] = color[1]; colorF[2] = color[2]; m_TargetProgressBar->SetColor(colorF); m_TargetProgressBar->SetBorderColor(colorF); m_TargetProgressBar->setValue(m_TargetIntersectionFilter->GetDistanceToIntersection()); } else { float red[3] = {0.6f, 0.0f, 0.0f}; m_TargetProgressBar->SetBorderColor(red); m_TargetProgressBar->setValueInvalid(); } } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetViolationStatus() { // transform vtk polydata according to mitk geometry vtkSmartPointer transformFilter = vtkSmartPointer::New(); transformFilter->SetInputData(0, m_TargetSurface->GetVtkPolyData()); transformFilter->SetTransform(m_TargetSurface->GetGeometry()->GetVtkTransform()); transformFilter->Update(); vtkSmartPointer enclosedPoints = vtkSmartPointer::New(); enclosedPoints->Initialize(transformFilter->GetOutput()); mitk::Point3D needleTip = m_NeedleProjectionFilter->GetProjection()->GetPoint(0); // show warning if the needle tip is inside the target surface if (enclosedPoints->IsInsideSurface(needleTip[0], needleTip[1], needleTip[2])) { if (!m_TargetStructureWarnOverlay->IsVisible(nullptr)) { m_TargetStructureWarnOverlay->SetVisibility(true); mitk::DataNode::Pointer targetViolationResult = mitk::DataNode::New(); targetViolationResult->SetName("TargetViolation"); targetViolationResult->SetProperty("USNavigation::TargetViolationPoint", mitk::Point3dProperty::New(needleTip)); emit SignalIntermediateResult(targetViolationResult); } MITK_INFO("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Target surface violated at " << needleTip << "."; } else { m_TargetStructureWarnOverlay->SetVisibility(false); } } void QmitkUSNavigationStepMarkerIntervention::CalculateTargetPlacementQuality() { // clear quality display if there aren't all targets reached if (m_ReachedTargetsNodes.size() != static_cast(m_NumberOfTargets)) { ui->placementQualityGroupBox->setEnabled(false); ui->angleDifferenceValue->setText(""); ui->centersOfMassValue->setText(""); return; } ui->placementQualityGroupBox->setEnabled(true); mitk::Surface::Pointer targetSurface = dynamic_cast(m_TargetNode->GetData()); if (targetSurface.IsNull()) { mitkThrow() << "Target surface must not be null."; } m_PlacementQualityCalculator->SetTargetSurface(targetSurface); mitk::PointSet::Pointer targetPointSet = mitk::PointSet::New(); // copy the origins of all reached target nodes into a point set // for the quality calculator mitk::PointSet::PointIdentifier n = 0; for (QVector>::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { targetPointSet->InsertPoint(n++, (*it)->GetData()->GetGeometry()->GetOrigin()); } m_PlacementQualityCalculator->SetTargetPoints(targetPointSet); m_PlacementQualityCalculator->Update(); double centersOfMassDistance = m_PlacementQualityCalculator->GetCentersOfMassDistance(); ui->centersOfMassValue->setText(QString::number(centersOfMassDistance, 103, 2) + " mm"); double meanAnglesDifference = m_PlacementQualityCalculator->GetMeanAngleDifference(); ui->angleDifferenceValue->setText(QString::number(meanAnglesDifference, 103, 2) + QString::fromLatin1(" °")); // create an intermediate result of the placement quality mitk::DataNode::Pointer placementQualityResult = mitk::DataNode::New(); placementQualityResult->SetName("PlacementQuality"); placementQualityResult->SetFloatProperty("USNavigation::CentersOfMassDistance", centersOfMassDistance); placementQualityResult->SetFloatProperty("USNavigation::MeanAngleDifference", meanAnglesDifference); placementQualityResult->SetProperty( "USNavigation::AngleDifferences", mitk::GenericProperty::New(m_PlacementQualityCalculator->GetAngleDifferences())); if (m_PlannedTargetsNodes.size() == static_cast(m_NumberOfTargets)) { mitk::VnlVector reachedPlannedDifferences; double reachedPlannedDifferencesSum = 0; double reachedPlannedDifferencesMax = 0; reachedPlannedDifferences.set_size(m_NumberOfTargets); // get sum and maximum of the planning / reality differences for (unsigned int n = 0; n < m_NumberOfTargets; ++n) { mitk::ScalarType distance = m_PlannedTargetsNodes.at(n)->GetData()->GetGeometry()->GetOrigin().EuclideanDistanceTo( m_ReachedTargetsNodes.at(n)->GetData()->GetGeometry()->GetOrigin()); reachedPlannedDifferences.put(n, distance); reachedPlannedDifferencesSum += distance; if (distance > reachedPlannedDifferencesMax) { reachedPlannedDifferencesMax = distance; } } // add distances between planning and reality to the quality intermediate result placementQualityResult->SetProperty("USNavigation::PlanningRealityDistances", mitk::GenericProperty::New(reachedPlannedDifferences)); placementQualityResult->SetProperty( "USNavigation::MeanPlanningRealityDistance", mitk::DoubleProperty::New(reachedPlannedDifferencesSum / static_cast(m_NumberOfTargets))); placementQualityResult->SetProperty("USNavigation::MaximumPlanningRealityDistance", mitk::DoubleProperty::New(reachedPlannedDifferencesMax)); } emit SignalIntermediateResult(placementQualityResult); } void QmitkUSNavigationStepMarkerIntervention::UpdateSensorsNames() { mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality = this->GetCombinedModality(false); if (combinedModality.IsNull()) { return; } mitk::NavigationDataSource::Pointer navigationDataSource = combinedModality->GetNavigationDataSource(); if (navigationDataSource.IsNull()) { return; } if (!m_NeedleSensorName.empty()) { try { m_NeedleSensorIndex = navigationDataSource->GetOutputIndex(m_NeedleSensorName); } catch (const std::exception &e) { MITK_WARN("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepPlacementPlanning") << "Cannot get index for needle sensor name: " << e.what(); } } if (this->GetNavigationStepState() >= QmitkUSAbstractNavigationStep::State_Active) { m_NeedleProjectionFilter->SelectInput(m_NeedleSensorIndex); } if (!m_ReferenceSensorName.empty()) { try { m_ReferenceSensorIndex = navigationDataSource->GetOutputIndex(m_ReferenceSensorName); } catch (const std::exception &e) { MITK_WARN("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepPlacementPlanning") << "Cannot get index for reference sensor name: " << e.what(); } } if (this->GetNavigationStepState() >= QmitkUSAbstractNavigationStep::State_Active) { m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex); } ui->freezeImageButton->SetCombinedModality(combinedModality, m_ReferenceSensorIndex); } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/files.cmake b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/files.cmake index fe593005bc..ce3944d94d 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/files.cmake +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/files.cmake @@ -1,39 +1,42 @@ set(SRC_CPP_FILES ) set(INTERNAL_CPP_FILES QmitkMitkWorkbenchIntroPlugin.cpp QmitkMitkWorkbenchIntroPart.cpp + QmitkMitkWorkbenchIntroPreferencePage.cpp ) set(MOC_H_FILES src/internal/QmitkMitkWorkbenchIntroPlugin.h src/internal/QmitkMitkWorkbenchIntroPart.h + src/internal/QmitkMitkWorkbenchIntroPreferencePage.h ) set(UI_FILES src/internal/QmitkWelcomeScreenViewControls.ui + src/internal/QmitkMitkWorkbenchIntroPreferencePage.ui ) set(CACHED_RESOURCE_FILES # list of resource files which can be used by the plug-in # system without loading the plug-ins shared library, # for example the icon used in the menu and tabs for the # plug-in views in the workbench plugin.xml ) set(QRC_FILES resources/QmitkWelcomeScreenView.qrc ) 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/Plugins/org.mitk.gui.qt.mitkworkbench.intro/plugin.xml b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/plugin.xml index dda81a0406..002333fb74 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/plugin.xml +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/plugin.xml @@ -1,12 +1,17 @@ + + + + + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/QmitkWelcomeScreenView.qrc b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/QmitkWelcomeScreenView.qrc index d8a478614a..319c197c41 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/QmitkWelcomeScreenView.qrc +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/QmitkWelcomeScreenView.qrc @@ -1,59 +1,13 @@ + img/levelwindow/standarddisplay.svg + img/mousenavigation/click.svg + img/mousenavigation/crosshair.svg + img/mousenavigation/pan.svg + img/mousenavigation/scroll.svg + img/mousenavigation/zoom.svg + index.html + script.js style.css - function.js - pics/background.jpg - pics/popup_bttn_close.png - pics/experimental.png - pics/button_mitka.png - pics/button_mitk.png - pics/WelcomeMITK.png - mitkworkbenchwelcomeview.html - - - WelcomePresentation.html - js/reveal.js - css/print/paper.css - css/print/pdf.css - css/reveal.css - css/reveal.scss - css/theme/MITK.css - css/theme/README.md - css/theme/source/MITK.scss - images/welcome/Alt.png - images/welcome/ArrowDown.png - images/welcome/ArrowKeys.png - images/welcome/ControlArrows.png - images/welcome/DataManagerData.png - images/welcome/DisplayAreaScan.png - images/welcome/DisplayAreaSmall.png - images/welcome/DisplayWindowAxial.png - images/welcome/DisplayWindowButtons.png - images/welcome/Esc.png - images/welcome/HelpWelcome.png - images/welcome/IconDataManager.png - images/welcome/IconHelp.svg - images/welcome/IconImageNavigator.png - images/welcome/ImageNavigator.png - images/welcome/LayoutList.png - images/welcome/Levelwindow.png - images/welcome/MITK.png - images/welcome/MITKArrow.png - images/welcome/MITKArrow2.png - images/welcome/MITKPoint.png - images/welcome/MousePointerClick.png - images/welcome/MouseTangoStyle.svg - images/welcome/ScreenScanData.png - images/welcome/ScreenScanPlugins.png - images/welcome/ScreenWithScan.png - images/welcome/Spacebar.png - images/welcome/Toolbar.png - images/welcome/ToolbarLeft.png - images/welcome/ToolbarRight.png - images/welcome/WelcomePage.png - lib/css/zenburn.css - lib/js/classList.js - lib/js/head.min.js - lib/js/html5shiv.js diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/WelcomePresentation.html b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/WelcomePresentation.html deleted file mode 100644 index 0f4c56df50..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/WelcomePresentation.html +++ /dev/null @@ -1,286 +0,0 @@ - - - - - - - - May I introduce you to MITK? - - - - - - - - - - - -
- -
- - -
-
-
-
-
-
-

May I introduce you to MITK?

-
-
-
-
-

For a short explanation of the navigation through the tutorial, press DOWN.

- -
-
-

Navigation through the tutorial slides

-

In the lower right corner you see four arrows for navigation through the slides.

- -
-
-
-

If an arrow turns bold, you can follow it in this direction either using your mouse or keyboard.

- - -
-

Besides the arrow keys you can also use the space bar,
to navigate you through all slides.

- -

When you press "Esc", you will see an overview about all the available slides.

- - -
-
- - - - -
-

Welcome Page

-
-

The first window you will see, is the
Welcome Page!

- -
-

You can always reopen it by clicking on
"Help" and then "Welcome".
To return there from this presentation
click the MITK logo in the lower left corner.

- -
-
-
-

Here you can find links to further on-line tutorials and related documentation.

- -
-
- - - - -
-

Window overview

- -
-

On the upper border you find the Toolbar
with shortcuts to all important functions.

- -
-

Your images and results appear
in the Display area in 2D and 3D views.

- -
-
-
-
-

Tools are called Plugins in MITK. After opening they appear to the sides of the display area by default.

- - -
- - - - -
-

Toolbar

-

You can access the main functions with the buttons on the left side of the toolbar.

- -
- -
    -
  • Open File
  • -
  • Save/Close Project
  • -
  • Undo/Redo
  • -
  • Image Navigator
  • -
  • ...
  • -
-

On the right side you find the available Plugins for working on your data.

-
- -
    -

    Plugins:

    -
  • Clipping Plane
  • -
  • Segmentation Utilities
  • -
  • Movie Maker
  • -
  • Image Cropper
  • -
  • ...
  • -
-

The help button can also be found here.

- -
-
-
-
-
-
-
-
- - - - -
-

Data Manager

- -

In the Data Manager you get an overview of all your data.

- -
-
-
-
-
-

Besides the image itself, additional objects
such as segmentations, 3D models, ...
are shown

- -
-
-
-

The Image Navigator helps to scroll faster through your scans or to navigate to a certain slice.

- - -
- - - - -
-

Display Area

-

Three windows of the display area show you slices from the three different anatomical planes.

- -

axial

-

coronal

-

sagittal

-
-
-
-
-

On the right side is the level-window
for adjusting the displayed
grey level range of the image.

-
-
-
-

The fourth window shows you the 3D view.

-

3D

- -
- - - - -
-

Display Windows

-

A crosshair is shown in each display window to facilitate the navigation and slice selection.

-

On the upper right corner you have more options to customize the view,
for example if you want to rotate the sectional planes.

-

Here you can also select other layouts of the display windows.

-
-
-
-
-
- - - - - -
-
-
- - - - -
-

Mouse Navigation

-

Inside the Display area you can easily navigate through the images with your mouse.

- -

Press left and move the cursor:
Moves the crosshair in all 3 planes.

- -

Scrolling:
Scrolls through the slides.

- -

Press the scroll wheel and move:
Shifts the section you are looking at.

-
- -
-

Right-Click and moving:
Zooms in and out.

-
- -
-
-
-
- - - - -
-

Thank you for downloading MITK!

-
-

Press F1, to get fast access
to the documentation of the Plugin you're currently using!
Try it now inside of the Data Manager Plugin.

-
-

Maybe one of the following links could also interest you: -

-

The end!

-
-
- - - - - -
- - - - - - - diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/print/paper.css b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/print/paper.css deleted file mode 100644 index d112815366..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/print/paper.css +++ /dev/null @@ -1,202 +0,0 @@ -/* Default Print Stylesheet Template - by Rob Glazebrook of CSSnewbie.com - Last Updated: June 4, 2008 - - Feel free (nay, compelled) to edit, append, and - manipulate this file as you see fit. */ - - -@media print { - - /* SECTION 1: Set default width, margin, float, and - background. This prevents elements from extending - beyond the edge of the printed page, and prevents - unnecessary background images from printing */ - html { - background: #fff; - width: auto; - height: auto; - overflow: visible; - } - body { - background: #fff; - font-size: 20pt; - width: auto; - height: auto; - border: 0; - margin: 0 5%; - padding: 0; - overflow: visible; - float: none !important; - } - - /* SECTION 2: Remove any elements not needed in print. - This would include navigation, ads, sidebars, etc. */ - .nestedarrow, - .controls, - .fork-reveal, - .share-reveal, - .state-background, - .reveal .progress, - .reveal .backgrounds { - display: none !important; - } - - /* SECTION 3: Set body font face, size, and color. - Consider using a serif font for readability. */ - body, p, td, li, div { - font-size: 20pt!important; - font-family: Georgia, "Times New Roman", Times, serif !important; - color: #000; - } - - /* SECTION 4: Set heading font face, sizes, and color. - Differentiate your headings from your body text. - Perhaps use a large sans-serif for distinction. */ - h1,h2,h3,h4,h5,h6 { - color: #000!important; - height: auto; - line-height: normal; - font-family: Georgia, "Times New Roman", Times, serif !important; - text-shadow: 0 0 0 #000 !important; - text-align: left; - letter-spacing: normal; - } - /* Need to reduce the size of the fonts for printing */ - h1 { font-size: 28pt !important; } - h2 { font-size: 24pt !important; } - h3 { font-size: 22pt !important; } - h4 { font-size: 22pt !important; font-variant: small-caps; } - h5 { font-size: 21pt !important; } - h6 { font-size: 20pt !important; font-style: italic; } - - /* SECTION 5: Make hyperlinks more usable. - Ensure links are underlined, and consider appending - the URL to the end of the link for usability. */ - a:link, - a:visited { - color: #000 !important; - font-weight: bold; - text-decoration: underline; - } - /* - .reveal a:link:after, - .reveal a:visited:after { - content: " (" attr(href) ") "; - color: #222 !important; - font-size: 90%; - } - */ - - - /* SECTION 6: more reveal.js specific additions by @skypanther */ - ul, ol, div, p { - visibility: visible; - position: static; - width: auto; - height: auto; - display: block; - overflow: visible; - margin: 0; - text-align: left !important; - } - .reveal pre, - .reveal table { - margin-left: 0; - margin-right: 0; - } - .reveal pre code { - padding: 20px; - border: 1px solid #ddd; - } - .reveal blockquote { - margin: 20px 0; - } - .reveal .slides { - position: static !important; - width: auto !important; - height: auto !important; - - left: 0 !important; - top: 0 !important; - margin-left: 0 !important; - margin-top: 0 !important; - padding: 0 !important; - zoom: 1 !important; - - overflow: visible !important; - display: block !important; - - text-align: left !important; - -webkit-perspective: none; - -moz-perspective: none; - -ms-perspective: none; - perspective: none; - - -webkit-perspective-origin: 50% 50%; - -moz-perspective-origin: 50% 50%; - -ms-perspective-origin: 50% 50%; - perspective-origin: 50% 50%; - } - .reveal .slides section { - visibility: visible !important; - position: static !important; - width: 100% !important; - height: auto !important; - display: block !important; - overflow: visible !important; - - left: 0 !important; - top: 0 !important; - margin-left: 0 !important; - margin-top: 0 !important; - padding: 60px 20px !important; - z-index: auto !important; - - opacity: 1 !important; - - page-break-after: always !important; - - -webkit-transform-style: flat !important; - -moz-transform-style: flat !important; - -ms-transform-style: flat !important; - transform-style: flat !important; - - -webkit-transform: none !important; - -moz-transform: none !important; - -ms-transform: none !important; - transform: none !important; - - -webkit-transition: none !important; - -moz-transition: none !important; - -ms-transition: none !important; - transition: none !important; - } - .reveal .slides section.stack { - padding: 0 !important; - } - .reveal section:last-of-type { - page-break-after: avoid !important; - } - .reveal section .fragment { - opacity: 1 !important; - visibility: visible !important; - - -webkit-transform: none !important; - -moz-transform: none !important; - -ms-transform: none !important; - transform: none !important; - } - .reveal section img { - display: block; - margin: 15px 0px; - background: rgba(255,255,255,1); - border: 1px solid #666; - box-shadow: none; - } - - .reveal section small { - font-size: 0.8em; - } - -} \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/print/pdf.css b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/print/pdf.css deleted file mode 100644 index 9813bc5b74..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/print/pdf.css +++ /dev/null @@ -1,156 +0,0 @@ -/* Default Print Stylesheet Template - by Rob Glazebrook of CSSnewbie.com - Last Updated: June 4, 2008 - - Feel free (nay, compelled) to edit, append, and - manipulate this file as you see fit. */ - - -/* SECTION 1: Set default width, margin, float, and - background. This prevents elements from extending - beyond the edge of the printed page, and prevents - unnecessary background images from printing */ - -* { - -webkit-print-color-adjust: exact; -} - -body { - margin: 0 auto !important; - border: 0; - padding: 0; - float: none !important; - overflow: visible; -} - -html { - width: 100%; - height: 100%; - overflow: visible; -} - -/* SECTION 2: Remove any elements not needed in print. - This would include navigation, ads, sidebars, etc. */ -.nestedarrow, -.reveal .controls, -.reveal .progress, -.reveal .slide-number, -.reveal .playback, -.reveal.overview, -.fork-reveal, -.share-reveal, -.state-background { - display: none !important; -} - -/* SECTION 3: Set body font face, size, and color. - Consider using a serif font for readability. */ -body, p, td, li, div { - -} - -/* SECTION 4: Set heading font face, sizes, and color. - Differentiate your headings from your body text. - Perhaps use a large sans-serif for distinction. */ -h1,h2,h3,h4,h5,h6 { - text-shadow: 0 0 0 #000 !important; -} - -.reveal pre code { - overflow: hidden !important; - font-family: Courier, 'Courier New', monospace !important; -} - - -/* SECTION 5: more reveal.js specific additions by @skypanther */ -ul, ol, div, p { - visibility: visible; - position: static; - width: auto; - height: auto; - display: block; - overflow: visible; - margin: auto; -} -.reveal { - width: auto !important; - height: auto !important; - overflow: hidden !important; -} -.reveal .slides { - position: static; - width: 100%; - height: auto; - - left: auto; - top: auto; - margin: 0 !important; - padding: 0 !important; - - overflow: visible; - display: block; - - -webkit-perspective: none; - -moz-perspective: none; - -ms-perspective: none; - perspective: none; - - -webkit-perspective-origin: 50% 50%; /* there isn't a none/auto value but 50-50 is the default */ - -moz-perspective-origin: 50% 50%; - -ms-perspective-origin: 50% 50%; - perspective-origin: 50% 50%; -} -.reveal .slides section { - page-break-after: always !important; - - visibility: visible !important; - position: relative !important; - display: block !important; - position: relative !important; - - margin: 0 !important; - padding: 0 !important; - box-sizing: border-box !important; - min-height: 1px; - - opacity: 1 !important; - - -webkit-transform-style: flat !important; - -moz-transform-style: flat !important; - -ms-transform-style: flat !important; - transform-style: flat !important; - - -webkit-transform: none !important; - -moz-transform: none !important; - -ms-transform: none !important; - transform: none !important; -} -.reveal section.stack { - margin: 0 !important; - padding: 0 !important; - page-break-after: avoid !important; - height: auto !important; - min-height: auto !important; -} -.reveal img { - box-shadow: none; -} -.reveal .roll { - overflow: visible; - line-height: 1em; -} - -/* Slide backgrounds are placed inside of their slide when exporting to PDF */ -.reveal section .slide-background { - display: block !important; - position: absolute; - top: 0; - left: 0; - width: 100%; - z-index: -1; -} -/* All elements should be above the slide-background */ -.reveal section>* { - position: relative; - z-index: 1; -} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/reveal.css b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/reveal.css deleted file mode 100644 index 6efa4c383a..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/reveal.css +++ /dev/null @@ -1,1254 +0,0 @@ -/*! - * reveal.js - * http://lab.hakim.se/reveal-js - * MIT licensed - * - * Copyright (C) 2015 Hakim El Hattab, http://hakim.se - */ -/********************************************* - * RESET STYLES - *********************************************/ -html, body, .reveal div, .reveal span, .reveal applet, .reveal object, .reveal iframe, .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6, .reveal p, .reveal blockquote, .reveal pre, .reveal a, .reveal abbr, .reveal acronym, .reveal address, .reveal big, .reveal cite, .reveal code, .reveal del, .reveal dfn, .reveal em, .reveal img, .reveal ins, .reveal kbd, .reveal q, .reveal s, .reveal samp, .reveal small, .reveal strike, .reveal strong, .reveal sub, .reveal sup, .reveal tt, .reveal var, .reveal b, .reveal u, .reveal center, .reveal dl, .reveal dt, .reveal dd, .reveal ol, .reveal ul, .reveal li, .reveal fieldset, .reveal form, .reveal label, .reveal legend, .reveal table, .reveal caption, .reveal tbody, .reveal tfoot, .reveal thead, .reveal tr, .reveal th, .reveal td, .reveal article, .reveal aside, .reveal canvas, .reveal details, .reveal embed, .reveal figure, .reveal figcaption, .reveal footer, .reveal header, .reveal hgroup, .reveal menu, .reveal nav, .reveal output, .reveal ruby, .reveal section, .reveal summary, .reveal time, .reveal mark, .reveal audio, video { - margin: 0; - padding: 0; - border: 0; - font-size: 100%; - font: inherit; - vertical-align: baseline; } - -.reveal article, .reveal aside, .reveal details, .reveal figcaption, .reveal figure, .reveal footer, .reveal header, .reveal hgroup, .reveal menu, .reveal nav, .reveal section { - display: block; } - -/********************************************* - * GLOBAL STYLES - *********************************************/ -html, body { - width: 100%; - height: 100%; - overflow: hidden; } - -body { - position: relative; - line-height: 1; - background-color: #fff; - color: #000; } - -/********************************************* - * VIEW FRAGMENTS - *********************************************/ -.reveal .slides section .fragment { - opacity: 0; - visibility: hidden; - -webkit-transition: all 0.2s ease; - transition: all 0.2s ease; } - .reveal .slides section .fragment.visible { - opacity: 1; - visibility: visible; } - -.reveal .slides section .fragment.grow { - opacity: 1; - visibility: visible; } - .reveal .slides section .fragment.grow.visible { - -webkit-transform: scale(1.3); - -ms-transform: scale(1.3); - transform: scale(1.3); } - -.reveal .slides section .fragment.shrink { - opacity: 1; - visibility: visible; } - .reveal .slides section .fragment.shrink.visible { - -webkit-transform: scale(0.7); - -ms-transform: scale(0.7); - transform: scale(0.7); } - -.reveal .slides section .fragment.zoom-in { - -webkit-transform: scale(0.1); - -ms-transform: scale(0.1); - transform: scale(0.1); } - .reveal .slides section .fragment.zoom-in.visible { - -webkit-transform: none; - -ms-transform: none; - transform: none; } - -.reveal .slides section .fragment.fade-out { - opacity: 1; - visibility: visible; } - .reveal .slides section .fragment.fade-out.visible { - opacity: 0; - visibility: hidden; } - -.reveal .slides section .fragment.semi-fade-out { - opacity: 1; - visibility: visible; } - .reveal .slides section .fragment.semi-fade-out.visible { - opacity: 0.5; - visibility: visible; } - -.reveal .slides section .fragment.strike { - opacity: 1; } - .reveal .slides section .fragment.strike.visible { - text-decoration: line-through; } - -.reveal .slides section .fragment.current-visible { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.current-visible.current-fragment { - opacity: 1; - visibility: visible; } - -.reveal .slides section .fragment.step-visible-1s { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.step-visible-1s.current-fragment { - opacity: 1; - visibility: visible; - transition: all 0.5s ease-in 1s;} - -.reveal .slides section .fragment.step-visible-15s { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.step-visible-15s.current-fragment { - opacity: 1; - visibility: visible; - transition: all 0.5s ease-in 1.5s;} - -.reveal .slides section .fragment.step-visible-2s { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.step-visible-2s.current-fragment { - opacity: 1; - visibility: visible; - transition: all 0.5s ease-in 2s;} - -.reveal .slides section .fragment.step-visible-3s { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.step-visible-3s.current-fragment { - opacity: 1; - visibility: visible; - transition: all 0.5s ease-in 3s;} - -.reveal .slides section .fragment.step-visible-4s { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.step-visible-4s.current-fragment { - opacity: 1; - visibility: visible; - transition: all 0.5s ease-in 4s;} - -.reveal .slides section .fragment.step-visible-5s { - opacity: 0; - visibility: hidden; } - .reveal .slides section .fragment.step-visible-5s.current-fragment { - opacity: 1; - visibility: visible; - transition: all 0.5s ease-in 5s;} - -.reveal .slides section .fragment.highlight-red, .reveal .slides section .fragment.highlight-current-red, .reveal .slides section .fragment.highlight-green, .reveal .slides section .fragment.highlight-current-green, .reveal .slides section .fragment.highlight-blue, .reveal .slides section .fragment.highlight-current-blue { - opacity: 1; - visibility: visible; } - -.reveal .slides section .fragment.highlight-red.visible { - color: #ff2c2d; } - -.reveal .slides section .fragment.highlight-green.visible { - color: #17ff2e; } - -.reveal .slides section .fragment.highlight-blue.visible { - color: #1b91ff; } - -.reveal .slides section .fragment.highlight-current-red.current-fragment { - color: #ff2c2d; } - -.reveal .slides section .fragment.highlight-current-green.current-fragment { - color: #17ff2e; } - -.reveal .slides section .fragment.highlight-current-blue.current-fragment { - color: #1b91ff; } - -/********************************************* - * DEFAULT ELEMENT STYLES - *********************************************/ -/* Fixes issue in Chrome where italic fonts did not appear when printing to PDF */ -.reveal:after { - content: ''; - font-style: italic; } - -.reveal iframe { - z-index: 1; } - -/** Prevents layering issues in certain browser/transition combinations */ -.reveal a { - position: relative; } - -.reveal .stretch { - max-width: none; - max-height: none; } - -.reveal pre.stretch code { - height: 100%; - max-height: 100%; - -moz-box-sizing: border-box; - box-sizing: border-box; } - -/********************************************* - * CONTROLS - *********************************************/ -.reveal .controls { - display: none; - position: fixed; - width: 110px; - height: 110px; - z-index: 30; - right: 10px; - bottom: 10px; - -webkit-user-select: none; } - -.reveal .controls div { - position: absolute; - opacity: 0.05; - width: 0; - height: 0; - border: 12px solid transparent; - -webkit-transform: scale(0.9999); - -ms-transform: scale(0.9999); - transform: scale(0.9999); - -webkit-transition: all 0.2s ease; - transition: all 0.2s ease; - -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } - -.reveal .controls div.enabled { - opacity: 0.7; - cursor: pointer; } - -.reveal .controls div.enabled:active { - margin-top: 1px; } - -.reveal .controls div.navigate-left { - top: 42px; - border-right-width: 22px; - border-right-color: #000; } - -.reveal .controls div.navigate-left.fragmented { - opacity: 0.3; } - -.reveal .controls div.navigate-right { - left: 74px; - top: 42px; - border-left-width: 22px; - border-left-color: #000; } - -.reveal .controls div.navigate-right.fragmented { - opacity: 0.3; } - -.reveal .controls div.navigate-up { - left: 42px; - border-bottom-width: 22px; - border-bottom-color: #000; } - -.reveal .controls div.navigate-up.fragmented { - opacity: 0.3; } - -.reveal .controls div.navigate-down { - left: 42px; - top: 74px; - border-top-width: 22px; - border-top-color: #000; } - -.reveal .controls div.navigate-down.fragmented { - opacity: 0.3; } - -/********************************************* - * PROGRESS BAR - *********************************************/ -.reveal .progress { - position: fixed; - display: none; - height: 3px; - width: 100%; - bottom: 0; - left: 0; - z-index: 10; - background-color: rgba(0, 0, 0, 0.2); } - -.reveal .progress:after { - content: ''; - display: block; - position: absolute; - height: 20px; - width: 100%; - top: -20px; } - -.reveal .progress span { - display: block; - height: 100%; - width: 0px; - background-color: #000; - -webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); - transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); } - -/********************************************* - * SLIDE NUMBER - *********************************************/ -.reveal .slide-number { - position: fixed; - display: block; - right: 15px; - bottom: 15px; - opacity: 0.5; - z-index: 31; - font-size: 12px; } - -/********************************************* - * SLIDES - *********************************************/ -.reveal { - position: relative; - width: 100%; - height: 100%; - overflow: hidden; - -ms-touch-action: none; - touch-action: none; } - -.reveal .slides { - position: absolute; - width: 100%; - height: 100%; - top: 0; - right: 0; - bottom: 0; - left: 0; - margin: auto; - overflow: visible; - z-index: 1; - text-align: center; - -webkit-perspective: 600px; - perspective: 600px; - -webkit-perspective-origin: 50% 40%; - perspective-origin: 50% 40%; } - -.reveal .slides > section { - -ms-perspective: 600px; } - -.reveal .slides > section, .reveal .slides > section > section { - display: none; - position: absolute; - width: 100%; - padding: 20px 0px; - z-index: 10; - -webkit-transform-style: preserve-3d; - transform-style: preserve-3d; - -webkit-transition: -webkit-transform-origin 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), -webkit-transform 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), visibility 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), opacity 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); - transition: -ms-transform-origin 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), transform 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), visibility 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), opacity 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); - transition: transform-origin 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), transform 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), visibility 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985), opacity 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); } - -/* Global transition speed settings */ -.reveal[data-transition-speed="fast"] .slides section { - -webkit-transition-duration: 400ms; - transition-duration: 400ms; } - -.reveal[data-transition-speed="slow"] .slides section { - -webkit-transition-duration: 1200ms; - transition-duration: 1200ms; } - -/* Slide-specific transition speed overrides */ -.reveal .slides section[data-transition-speed="fast"] { - -webkit-transition-duration: 400ms; - transition-duration: 400ms; } - -.reveal .slides section[data-transition-speed="slow"] { - -webkit-transition-duration: 1200ms; - transition-duration: 1200ms; } - -.reveal .slides > section.stack { - padding-top: 0; - padding-bottom: 0; } - -.reveal .slides > section.present, .reveal .slides > section > section.present { - display: block; - z-index: 11; - opacity: 1; } - -.reveal.center, .reveal.center .slides, .reveal.center .slides section { - min-height: 0 !important; } - -/* Don't allow interaction with invisible slides */ -.reveal .slides > section.future, .reveal .slides > section > section.future, .reveal .slides > section.past, .reveal .slides > section > section.past { - pointer-events: none; } - -.reveal.overview .slides > section, .reveal.overview .slides > section > section { - pointer-events: auto; } - -.reveal .slides > section.past, .reveal .slides > section.future, .reveal .slides > section > section.past, .reveal .slides > section > section.future { - opacity: 0; } - -/********************************************* - * Slide Footer - *********************************************/ - -.reveal .footer{ - position: absolute; - bottom: 1%; - width: 100%; - text-align: center; - font-size: 0.75rem; - color: rgb(144, 144, 144); -} - -a.mitk-logo { - z-index: 99; - width: 10%; - position: absolute; - bottom: 1%; - left: 1%; -} - -a.mitk-logo img { - width: 100%; -} -a.mitk-logo:hover img { - box-shadow: none !important; - transform: scale(1.1); -} - -/********************************************* - * Mixins for readability of transitions - *********************************************/ -/********************************************* - * SLIDE TRANSITION - * Aliased 'linear' for backwards compatibility - *********************************************/ -.reveal.slide section { - -webkit-backface-visibility: hidden; - backface-visibility: hidden; } - -.reveal .slides > section[data-transition=slide].past, .reveal .slides > section[data-transition~=slide-out].past, .reveal.slide .slides > section:not([data-transition]).past { - -webkit-transform: translate(-150%, 0); - -ms-transform: translate(-150%, 0); - transform: translate(-150%, 0); } - -.reveal .slides > section[data-transition=slide].future, .reveal .slides > section[data-transition~=slide-in].future, .reveal.slide .slides > section:not([data-transition]).future { - -webkit-transform: translate(150%, 0); - -ms-transform: translate(150%, 0); - transform: translate(150%, 0); } - -.reveal .slides > section > section[data-transition=slide].past, .reveal .slides > section > section[data-transition~=slide-out].past, .reveal.slide .slides > section > section:not([data-transition]).past { - -webkit-transform: translate(0, -150%); - -ms-transform: translate(0, -150%); - transform: translate(0, -150%); } - -.reveal .slides > section > section[data-transition=slide].future, .reveal .slides > section > section[data-transition~=slide-in].future, .reveal.slide .slides > section > section:not([data-transition]).future { - -webkit-transform: translate(0, 150%); - -ms-transform: translate(0, 150%); - transform: translate(0, 150%); } - -.reveal.linear section { - -webkit-backface-visibility: hidden; - backface-visibility: hidden; } - -.reveal .slides > section[data-transition=linear].past, .reveal .slides > section[data-transition~=linear-out].past, .reveal.linear .slides > section:not([data-transition]).past { - -webkit-transform: translate(-150%, 0); - -ms-transform: translate(-150%, 0); - transform: translate(-150%, 0); } - -.reveal .slides > section[data-transition=linear].future, .reveal .slides > section[data-transition~=linear-in].future, .reveal.linear .slides > section:not([data-transition]).future { - -webkit-transform: translate(150%, 0); - -ms-transform: translate(150%, 0); - transform: translate(150%, 0); } - -.reveal .slides > section > section[data-transition=linear].past, .reveal .slides > section > section[data-transition~=linear-out].past, .reveal.linear .slides > section > section:not([data-transition]).past { - -webkit-transform: translate(0, -150%); - -ms-transform: translate(0, -150%); - transform: translate(0, -150%); } - -.reveal .slides > section > section[data-transition=linear].future, .reveal .slides > section > section[data-transition~=linear-in].future, .reveal.linear .slides > section > section:not([data-transition]).future { - -webkit-transform: translate(0, 150%); - -ms-transform: translate(0, 150%); - transform: translate(0, 150%); } - -/********************************************* - * CONVEX TRANSITION - * Aliased 'default' for backwards compatibility - *********************************************/ -.reveal .slides > section[data-transition=default].past, .reveal .slides > section[data-transition~=default-out].past, .reveal.default .slides > section:not([data-transition]).past { - -webkit-transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); - transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); } - -.reveal .slides > section[data-transition=default].future, .reveal .slides > section[data-transition~=default-in].future, .reveal.default .slides > section:not([data-transition]).future { - -webkit-transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); - transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); } - -.reveal .slides > section > section[data-transition=default].past, .reveal .slides > section > section[data-transition~=default-out].past, .reveal.default .slides > section > section:not([data-transition]).past { - -webkit-transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0); - transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0); } - -.reveal .slides > section > section[data-transition=default].future, .reveal .slides > section > section[data-transition~=default-in].future, .reveal.default .slides > section > section:not([data-transition]).future { - -webkit-transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0); - transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0); } - -.reveal .slides > section[data-transition=convex].past, .reveal .slides > section[data-transition~=convex-out].past, .reveal.convex .slides > section:not([data-transition]).past { - -webkit-transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); - transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); } - -.reveal .slides > section[data-transition=convex].future, .reveal .slides > section[data-transition~=convex-in].future, .reveal.convex .slides > section:not([data-transition]).future { - -webkit-transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); - transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); } - -.reveal .slides > section > section[data-transition=convex].past, .reveal .slides > section > section[data-transition~=convex-out].past, .reveal.convex .slides > section > section:not([data-transition]).past { - -webkit-transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0); - transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0); } - -.reveal .slides > section > section[data-transition=convex].future, .reveal .slides > section > section[data-transition~=convex-in].future, .reveal.convex .slides > section > section:not([data-transition]).future { - -webkit-transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0); - transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0); } - -/********************************************* - * CONCAVE TRANSITION - *********************************************/ -.reveal .slides > section[data-transition=concave].past, .reveal .slides > section[data-transition~=concave-out].past, .reveal.concave .slides > section:not([data-transition]).past { - -webkit-transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0); - transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0); } - -.reveal .slides > section[data-transition=concave].future, .reveal .slides > section[data-transition~=concave-in].future, .reveal.concave .slides > section:not([data-transition]).future { - -webkit-transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0); - transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0); } - -.reveal .slides > section > section[data-transition=concave].past, .reveal .slides > section > section[data-transition~=concave-out].past, .reveal.concave .slides > section > section:not([data-transition]).past { - -webkit-transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0); - transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0); } - -.reveal .slides > section > section[data-transition=concave].future, .reveal .slides > section > section[data-transition~=concave-in].future, .reveal.concave .slides > section > section:not([data-transition]).future { - -webkit-transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0); - transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0); } - -/********************************************* - * ZOOM TRANSITION - *********************************************/ -.reveal .slides > section[data-transition=zoom], .reveal.zoom .slides > section:not([data-transition]) { - -webkit-transition-timing-function: ease; - transition-timing-function: ease; } - -.reveal .slides > section[data-transition=zoom].past, .reveal .slides > section[data-transition~=zoom-out].past, .reveal.zoom .slides > section:not([data-transition]).past { - visibility: hidden; - -webkit-transform: scale(16); - -ms-transform: scale(16); - transform: scale(16); } - -.reveal .slides > section[data-transition=zoom].future, .reveal .slides > section[data-transition~=zoom-in].future, .reveal.zoom .slides > section:not([data-transition]).future { - visibility: hidden; - -webkit-transform: scale(0.2); - -ms-transform: scale(0.2); - transform: scale(0.2); } - -.reveal .slides > section > section[data-transition=zoom].past, .reveal .slides > section > section[data-transition~=zoom-out].past, .reveal.zoom .slides > section > section:not([data-transition]).past { - -webkit-transform: translate(0, -150%); - -ms-transform: translate(0, -150%); - transform: translate(0, -150%); } - -.reveal .slides > section > section[data-transition=zoom].future, .reveal .slides > section > section[data-transition~=zoom-in].future, .reveal.zoom .slides > section > section:not([data-transition]).future { - -webkit-transform: translate(0, 150%); - -ms-transform: translate(0, 150%); - transform: translate(0, 150%); } - -/********************************************* - * CUBE TRANSITION - *********************************************/ -.reveal.cube .slides { - -webkit-perspective: 1300px; - perspective: 1300px; } - -.reveal.cube .slides section { - padding: 30px; - min-height: 700px; - -webkit-backface-visibility: hidden; - backface-visibility: hidden; - -moz-box-sizing: border-box; - box-sizing: border-box; } - -.reveal.center.cube .slides section { - min-height: 0; } - -.reveal.cube .slides section:not(.stack):before { - content: ''; - position: absolute; - display: block; - width: 100%; - height: 100%; - left: 0; - top: 0; - background: rgba(0, 0, 0, 0.1); - border-radius: 4px; - -webkit-transform: translateZ(-20px); - transform: translateZ(-20px); } - -.reveal.cube .slides section:not(.stack):after { - content: ''; - position: absolute; - display: block; - width: 90%; - height: 30px; - left: 5%; - bottom: 0; - background: none; - z-index: 1; - border-radius: 4px; - box-shadow: 0px 95px 25px rgba(0, 0, 0, 0.2); - -webkit-transform: translateZ(-90px) rotateX(65deg); - transform: translateZ(-90px) rotateX(65deg); } - -.reveal.cube .slides > section.stack { - padding: 0; - background: none; } - -.reveal.cube .slides > section.past { - -webkit-transform-origin: 100% 0%; - -ms-transform-origin: 100% 0%; - transform-origin: 100% 0%; - -webkit-transform: translate3d(-100%, 0, 0) rotateY(-90deg); - transform: translate3d(-100%, 0, 0) rotateY(-90deg); } - -.reveal.cube .slides > section.future { - -webkit-transform-origin: 0% 0%; - -ms-transform-origin: 0% 0%; - transform-origin: 0% 0%; - -webkit-transform: translate3d(100%, 0, 0) rotateY(90deg); - transform: translate3d(100%, 0, 0) rotateY(90deg); } - -.reveal.cube .slides > section > section.past { - -webkit-transform-origin: 0% 100%; - -ms-transform-origin: 0% 100%; - transform-origin: 0% 100%; - -webkit-transform: translate3d(0, -100%, 0) rotateX(90deg); - transform: translate3d(0, -100%, 0) rotateX(90deg); } - -.reveal.cube .slides > section > section.future { - -webkit-transform-origin: 0% 0%; - -ms-transform-origin: 0% 0%; - transform-origin: 0% 0%; - -webkit-transform: translate3d(0, 100%, 0) rotateX(-90deg); - transform: translate3d(0, 100%, 0) rotateX(-90deg); } - -/********************************************* - * PAGE TRANSITION - *********************************************/ -.reveal.page .slides { - -webkit-perspective-origin: 0% 50%; - perspective-origin: 0% 50%; - -webkit-perspective: 3000px; - perspective: 3000px; } - -.reveal.page .slides section { - padding: 30px; - min-height: 700px; - -moz-box-sizing: border-box; - box-sizing: border-box; } - -.reveal.page .slides section.past { - z-index: 12; } - -.reveal.page .slides section:not(.stack):before { - content: ''; - position: absolute; - display: block; - width: 100%; - height: 100%; - left: 0; - top: 0; - background: rgba(0, 0, 0, 0.1); - -webkit-transform: translateZ(-20px); - transform: translateZ(-20px); } - -.reveal.page .slides section:not(.stack):after { - content: ''; - position: absolute; - display: block; - width: 90%; - height: 30px; - left: 5%; - bottom: 0; - background: none; - z-index: 1; - border-radius: 4px; - box-shadow: 0px 95px 25px rgba(0, 0, 0, 0.2); - -webkit-transform: translateZ(-90px) rotateX(65deg); } - -.reveal.page .slides > section.stack { - padding: 0; - background: none; } - -.reveal.page .slides > section.past { - -webkit-transform-origin: 0% 0%; - -ms-transform-origin: 0% 0%; - transform-origin: 0% 0%; - -webkit-transform: translate3d(-40%, 0, 0) rotateY(-80deg); - transform: translate3d(-40%, 0, 0) rotateY(-80deg); } - -.reveal.page .slides > section.future { - -webkit-transform-origin: 100% 0%; - -ms-transform-origin: 100% 0%; - transform-origin: 100% 0%; - -webkit-transform: translate3d(0, 0, 0); - transform: translate3d(0, 0, 0); } - -.reveal.page .slides > section > section.past { - -webkit-transform-origin: 0% 0%; - -ms-transform-origin: 0% 0%; - transform-origin: 0% 0%; - -webkit-transform: translate3d(0, -40%, 0) rotateX(80deg); - transform: translate3d(0, -40%, 0) rotateX(80deg); } - -.reveal.page .slides > section > section.future { - -webkit-transform-origin: 0% 100%; - -ms-transform-origin: 0% 100%; - transform-origin: 0% 100%; - -webkit-transform: translate3d(0, 0, 0); - transform: translate3d(0, 0, 0); } - -/********************************************* - * FADE TRANSITION - *********************************************/ -.reveal .slides section[data-transition=fade], .reveal.fade .slides section:not([data-transition]), .reveal.fade .slides > section > section:not([data-transition]) { - -webkit-transform: none; - -ms-transform: none; - transform: none; - -webkit-transition: opacity 0.5s; - transition: opacity 0.5s; } - -.reveal.fade.overview .slides section, .reveal.fade.overview .slides > section > section { - -webkit-transition: none; - transition: none; } - -/********************************************* - * NO TRANSITION - *********************************************/ -.reveal .slides > section[data-transition=none], .reveal.none .slides > section:not([data-transition]) { - -webkit-transform: none; - -ms-transform: none; - transform: none; - -webkit-transition: none; - transition: none; } - -/********************************************* - * PAUSED MODE - *********************************************/ -.reveal .pause-overlay { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: black; - visibility: hidden; - opacity: 0; - z-index: 100; - -webkit-transition: all 1s ease; - transition: all 1s ease; } - -.reveal.paused .pause-overlay { - visibility: visible; - opacity: 1; } - -/********************************************* - * FALLBACK - *********************************************/ -.no-transforms { - overflow-y: auto; } - -.no-transforms .reveal .slides { - position: relative; - width: 80%; - height: auto !important; - top: 0; - left: 50%; - margin: 0; - text-align: center; } - -.no-transforms .reveal .controls, .no-transforms .reveal .progress { - display: none !important; - z-index: -1; -} - -.no-transforms .reveal .slides section { - display: block !important; - opacity: 1 !important; - position: relative !important; - height: auto; - min-height: 0; - top: 0; - left: -50%; - margin: 70px 0; - -webkit-transform: none; - -ms-transform: none; - transform: none; } - -.no-transforms .reveal .slides section section { - left: 0; } - -.reveal .no-transition, .reveal .no-transition * { - -webkit-transition: none !important; - transition: none !important; } - -/********************************************* - * PER-SLIDE BACKGROUNDS - *********************************************/ -.reveal .backgrounds { - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; - -webkit-perspective: 600px; - perspective: 600px; } - -.reveal .slide-background { - display: none; - position: absolute; - width: 100%; - height: 100%; - opacity: 0; - visibility: hidden; - background-color: rgba(0, 0, 0, 0); - background-position: 50% 50%; - background-repeat: no-repeat; - background-size: cover; - -webkit-transition: all 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); - transition: all 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); } - -.reveal .slide-background.stack { - display: block; } - -.reveal .slide-background.present { - opacity: 1; - visibility: visible; } - -.print-pdf .reveal .slide-background { - opacity: 1 !important; - visibility: visible !important; } - -/* Video backgrounds */ -.reveal .slide-background video { - position: absolute; - width: 100%; - height: 100%; - max-width: none; - max-height: none; - top: 0; - left: 0; } - -/* Immediate transition style */ -.reveal[data-background-transition=none] > .backgrounds .slide-background, .reveal > .backgrounds .slide-background[data-background-transition=none] { - -webkit-transition: none; - transition: none; } - -/* Slide */ -.reveal[data-background-transition=slide] > .backgrounds .slide-background, .reveal > .backgrounds .slide-background[data-background-transition=slide] { - opacity: 1; - -webkit-backface-visibility: hidden; - backface-visibility: hidden; } - -.reveal[data-background-transition=slide] > .backgrounds .slide-background.past, .reveal > .backgrounds .slide-background.past[data-background-transition=slide] { - -webkit-transform: translate(-100%, 0); - -ms-transform: translate(-100%, 0); - transform: translate(-100%, 0); } - -.reveal[data-background-transition=slide] > .backgrounds .slide-background.future, .reveal > .backgrounds .slide-background.future[data-background-transition=slide] { - -webkit-transform: translate(100%, 0); - -ms-transform: translate(100%, 0); - transform: translate(100%, 0); } - -.reveal[data-background-transition=slide] > .backgrounds .slide-background > .slide-background.past, .reveal > .backgrounds .slide-background > .slide-background.past[data-background-transition=slide] { - -webkit-transform: translate(0, -100%); - -ms-transform: translate(0, -100%); - transform: translate(0, -100%); } - -.reveal[data-background-transition=slide] > .backgrounds .slide-background > .slide-background.future, .reveal > .backgrounds .slide-background > .slide-background.future[data-background-transition=slide] { - -webkit-transform: translate(0, 100%); - -ms-transform: translate(0, 100%); - transform: translate(0, 100%); } - -/* Convex */ -.reveal[data-background-transition=convex] > .backgrounds .slide-background.past, .reveal > .backgrounds .slide-background.past[data-background-transition=convex] { - opacity: 0; - -webkit-transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); - transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); } - -.reveal[data-background-transition=convex] > .backgrounds .slide-background.future, .reveal > .backgrounds .slide-background.future[data-background-transition=convex] { - opacity: 0; - -webkit-transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); - transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); } - -.reveal[data-background-transition=convex] > .backgrounds .slide-background > .slide-background.past, .reveal > .backgrounds .slide-background > .slide-background.past[data-background-transition=convex] { - opacity: 0; - -webkit-transform: translate3d(0, -100%, 0) rotateX(90deg) translate3d(0, -100%, 0); - transform: translate3d(0, -100%, 0) rotateX(90deg) translate3d(0, -100%, 0); } - -.reveal[data-background-transition=convex] > .backgrounds .slide-background > .slide-background.future, .reveal > .backgrounds .slide-background > .slide-background.future[data-background-transition=convex] { - opacity: 0; - -webkit-transform: translate3d(0, 100%, 0) rotateX(-90deg) translate3d(0, 100%, 0); - transform: translate3d(0, 100%, 0) rotateX(-90deg) translate3d(0, 100%, 0); } - -/* Concave */ -.reveal[data-background-transition=concave] > .backgrounds .slide-background.past, .reveal > .backgrounds .slide-background.past[data-background-transition=concave] { - opacity: 0; - -webkit-transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0); - transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0); } - -.reveal[data-background-transition=concave] > .backgrounds .slide-background.future, .reveal > .backgrounds .slide-background.future[data-background-transition=concave] { - opacity: 0; - -webkit-transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0); - transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0); } - -.reveal[data-background-transition=concave] > .backgrounds .slide-background > .slide-background.past, .reveal > .backgrounds .slide-background > .slide-background.past[data-background-transition=concave] { - opacity: 0; - -webkit-transform: translate3d(0, -100%, 0) rotateX(-90deg) translate3d(0, -100%, 0); - transform: translate3d(0, -100%, 0) rotateX(-90deg) translate3d(0, -100%, 0); } - -.reveal[data-background-transition=concave] > .backgrounds .slide-background > .slide-background.future, .reveal > .backgrounds .slide-background > .slide-background.future[data-background-transition=concave] { - opacity: 0; - -webkit-transform: translate3d(0, 100%, 0) rotateX(90deg) translate3d(0, 100%, 0); - transform: translate3d(0, 100%, 0) rotateX(90deg) translate3d(0, 100%, 0); } - -/* Zoom */ -.reveal[data-background-transition=zoom] > .backgrounds .slide-background, .reveal > .backgrounds .slide-background[data-background-transition=zoom] { - -webkit-transition-timing-function: ease; - transition-timing-function: ease; } - -.reveal[data-background-transition=zoom] > .backgrounds .slide-background.past, .reveal > .backgrounds .slide-background.past[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - -webkit-transform: scale(16); - -ms-transform: scale(16); - transform: scale(16); } - -.reveal[data-background-transition=zoom] > .backgrounds .slide-background.future, .reveal > .backgrounds .slide-background.future[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - -webkit-transform: scale(0.2); - -ms-transform: scale(0.2); - transform: scale(0.2); } - -.reveal[data-background-transition=zoom] > .backgrounds .slide-background > .slide-background.past, .reveal > .backgrounds .slide-background > .slide-background.past[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - -webkit-transform: scale(16); - -ms-transform: scale(16); - transform: scale(16); } - -.reveal[data-background-transition=zoom] > .backgrounds .slide-background > .slide-background.future, .reveal > .backgrounds .slide-background > .slide-background.future[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - -webkit-transform: scale(0.2); - -ms-transform: scale(0.2); - transform: scale(0.2); } - -/* Global transition speed settings */ -.reveal[data-transition-speed="fast"] > .backgrounds .slide-background { - -webkit-transition-duration: 400ms; - transition-duration: 400ms; } - -.reveal[data-transition-speed="slow"] > .backgrounds .slide-background { - -webkit-transition-duration: 1200ms; - transition-duration: 1200ms; } - -/********************************************* - * OVERVIEW - *********************************************/ -.reveal.overview { - -webkit-perspective-origin: 50% 50%; - perspective-origin: 50% 50%; - -webkit-perspective: 700px; - perspective: 700px; } - .reveal.overview .slides section { - height: 700px; - opacity: 1 !important; - overflow: hidden; - visibility: visible !important; - cursor: pointer; - -moz-box-sizing: border-box; - box-sizing: border-box; } - .reveal.overview .slides section:hover, .reveal.overview .slides section.present { - outline: 10px solid rgba(150, 150, 150, 0.4); - outline-offset: 10px; } - .reveal.overview .slides section .fragment { - opacity: 1; - -webkit-transition: none; - transition: none; } - .reveal.overview .slides section:after, .reveal.overview .slides section:before { - display: none !important; } - .reveal.overview .slides > section.stack { - padding: 0; - top: 0 !important; - background: none; - outline: none; - overflow: visible; } - .reveal.overview .backgrounds { - -webkit-perspective: inherit; - perspective: inherit; } - .reveal.overview .backgrounds .slide-background { - opacity: 1; - visibility: visible; - outline: 10px solid rgba(150, 150, 150, 0.1); - outline-offset: 10px; } - -.reveal.overview .slides section, .reveal.overview-deactivating .slides section { - -webkit-transition: none; - transition: none; } - -.reveal.overview .backgrounds .slide-background, .reveal.overview-deactivating .backgrounds .slide-background { - -webkit-transition: none; - transition: none; } - -.reveal.overview-animated .slides { - -webkit-transition: -webkit-transform 0.4s ease; - transition: transform 0.4s ease; } - -/********************************************* - * RTL SUPPORT - *********************************************/ -.reveal.rtl .slides, .reveal.rtl .slides h1, .reveal.rtl .slides h2, .reveal.rtl .slides h3, .reveal.rtl .slides h4, .reveal.rtl .slides h5, .reveal.rtl .slides h6 { - direction: rtl; - font-family: sans-serif; } - -.reveal.rtl pre, .reveal.rtl code { - direction: ltr; } - -.reveal.rtl ol, .reveal.rtl ul { - text-align: right; } - -.reveal.rtl .progress span { - float: right; } - -/********************************************* - * PARALLAX BACKGROUND - *********************************************/ -.reveal.has-parallax-background .backgrounds { - -webkit-transition: all 0.8s ease; - transition: all 0.8s ease; } - -/* Global transition speed settings */ -.reveal.has-parallax-background[data-transition-speed="fast"] .backgrounds { - -webkit-transition-duration: 400ms; - transition-duration: 400ms; } - -.reveal.has-parallax-background[data-transition-speed="slow"] .backgrounds { - -webkit-transition-duration: 1200ms; - transition-duration: 1200ms; } - -/********************************************* - * LINK PREVIEW OVERLAY - *********************************************/ -.reveal .overlay { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - z-index: 1000; - background: rgba(0, 0, 0, 0.9); - opacity: 0; - visibility: hidden; - -webkit-transition: all 0.3s ease; - transition: all 0.3s ease; } - -.reveal .overlay.visible { - opacity: 1; - visibility: visible; } - -.reveal .overlay .spinner { - position: absolute; - display: block; - top: 50%; - left: 50%; - width: 32px; - height: 32px; - margin: -16px 0 0 -16px; - z-index: 10; - background-image: url(data:image/gif;base64,R0lGODlhIAAgAPMAAJmZmf%2F%2F%2F6%2Bvr8nJybW1tcDAwOjo6Nvb26ioqKOjo7Ozs%2FLy8vz8%2FAAAAAAAAAAAACH%2FC05FVFNDQVBFMi4wAwEAAAAh%2FhpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh%2BQQJCgAAACwAAAAAIAAgAAAE5xDISWlhperN52JLhSSdRgwVo1ICQZRUsiwHpTJT4iowNS8vyW2icCF6k8HMMBkCEDskxTBDAZwuAkkqIfxIQyhBQBFvAQSDITM5VDW6XNE4KagNh6Bgwe60smQUB3d4Rz1ZBApnFASDd0hihh12BkE9kjAJVlycXIg7CQIFA6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YJvpJivxNaGmLHT0VnOgSYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ%2FV%2FnmOM82XiHRLYKhKP1oZmADdEAAAh%2BQQJCgAAACwAAAAAIAAgAAAE6hDISWlZpOrNp1lGNRSdRpDUolIGw5RUYhhHukqFu8DsrEyqnWThGvAmhVlteBvojpTDDBUEIFwMFBRAmBkSgOrBFZogCASwBDEY%2FCZSg7GSE0gSCjQBMVG023xWBhklAnoEdhQEfyNqMIcKjhRsjEdnezB%2BA4k8gTwJhFuiW4dokXiloUepBAp5qaKpp6%2BHo7aWW54wl7obvEe0kRuoplCGepwSx2jJvqHEmGt6whJpGpfJCHmOoNHKaHx61WiSR92E4lbFoq%2BB6QDtuetcaBPnW6%2BO7wDHpIiK9SaVK5GgV543tzjgGcghAgAh%2BQQJCgAAACwAAAAAIAAgAAAE7hDISSkxpOrN5zFHNWRdhSiVoVLHspRUMoyUakyEe8PTPCATW9A14E0UvuAKMNAZKYUZCiBMuBakSQKG8G2FzUWox2AUtAQFcBKlVQoLgQReZhQlCIJesQXI5B0CBnUMOxMCenoCfTCEWBsJColTMANldx15BGs8B5wlCZ9Po6OJkwmRpnqkqnuSrayqfKmqpLajoiW5HJq7FL1Gr2mMMcKUMIiJgIemy7xZtJsTmsM4xHiKv5KMCXqfyUCJEonXPN2rAOIAmsfB3uPoAK%2B%2BG%2Bw48edZPK%2BM6hLJpQg484enXIdQFSS1u6UhksENEQAAIfkECQoAAAAsAAAAACAAIAAABOcQyEmpGKLqzWcZRVUQnZYg1aBSh2GUVEIQ2aQOE%2BG%2BcD4ntpWkZQj1JIiZIogDFFyHI0UxQwFugMSOFIPJftfVAEoZLBbcLEFhlQiqGp1Vd140AUklUN3eCA51C1EWMzMCezCBBmkxVIVHBWd3HHl9JQOIJSdSnJ0TDKChCwUJjoWMPaGqDKannasMo6WnM562R5YluZRwur0wpgqZE7NKUm%2BFNRPIhjBJxKZteWuIBMN4zRMIVIhffcgojwCF117i4nlLnY5ztRLsnOk%2BaV%2BoJY7V7m76PdkS4trKcdg0Zc0tTcKkRAAAIfkECQoAAAAsAAAAACAAIAAABO4QyEkpKqjqzScpRaVkXZWQEximw1BSCUEIlDohrft6cpKCk5xid5MNJTaAIkekKGQkWyKHkvhKsR7ARmitkAYDYRIbUQRQjWBwJRzChi9CRlBcY1UN4g0%2FVNB0AlcvcAYHRyZPdEQFYV8ccwR5HWxEJ02YmRMLnJ1xCYp0Y5idpQuhopmmC2KgojKasUQDk5BNAwwMOh2RtRq5uQuPZKGIJQIGwAwGf6I0JXMpC8C7kXWDBINFMxS4DKMAWVWAGYsAdNqW5uaRxkSKJOZKaU3tPOBZ4DuK2LATgJhkPJMgTwKCdFjyPHEnKxFCDhEAACH5BAkKAAAALAAAAAAgACAAAATzEMhJaVKp6s2nIkolIJ2WkBShpkVRWqqQrhLSEu9MZJKK9y1ZrqYK9WiClmvoUaF8gIQSNeF1Er4MNFn4SRSDARWroAIETg1iVwuHjYB1kYc1mwruwXKC9gmsJXliGxc%2BXiUCby9ydh1sOSdMkpMTBpaXBzsfhoc5l58Gm5yToAaZhaOUqjkDgCWNHAULCwOLaTmzswadEqggQwgHuQsHIoZCHQMMQgQGubVEcxOPFAcMDAYUA85eWARmfSRQCdcMe0zeP1AAygwLlJtPNAAL19DARdPzBOWSm1brJBi45soRAWQAAkrQIykShQ9wVhHCwCQCACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiRMDjI0Fd30%2FiI2UA5GSS5UDj2l6NoqgOgN4gksEBgYFf0FDqKgHnyZ9OX8HrgYHdHpcHQULXAS2qKpENRg7eAMLC7kTBaixUYFkKAzWAAnLC7FLVxLWDBLKCwaKTULgEwbLA4hJtOkSBNqITT3xEgfLpBtzE%2FjiuL04RGEBgwWhShRgQExHBAAh%2BQQJCgAAACwAAAAAIAAgAAAE7xDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfZiCqGk5dTESJeaOAlClzsJsqwiJwiqnFrb2nS9kmIcgEsjQydLiIlHehhpejaIjzh9eomSjZR%2BipslWIRLAgMDOR2DOqKogTB9pCUJBagDBXR6XB0EBkIIsaRsGGMMAxoDBgYHTKJiUYEGDAzHC9EACcUGkIgFzgwZ0QsSBcXHiQvOwgDdEwfFs0sDzt4S6BK4xYjkDOzn0unFeBzOBijIm1Dgmg5YFQwsCMjp1oJ8LyIAACH5BAkKAAAALAAAAAAgACAAAATwEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GGl6NoiPOH16iZKNlH6KmyWFOggHhEEvAwwMA0N9GBsEC6amhnVcEwavDAazGwIDaH1ipaYLBUTCGgQDA8NdHz0FpqgTBwsLqAbWAAnIA4FWKdMLGdYGEgraigbT0OITBcg5QwPT4xLrROZL6AuQAPUS7bxLpoWidY0JtxLHKhwwMJBTHgPKdEQAACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GAULDJCRiXo1CpGXDJOUjY%2BYip9DhToJA4RBLwMLCwVDfRgbBAaqqoZ1XBMHswsHtxtFaH1iqaoGNgAIxRpbFAgfPQSqpbgGBqUD1wBXeCYp1AYZ19JJOYgH1KwA4UBvQwXUBxPqVD9L3sbp2BNk2xvvFPJd%2BMFCN6HAAIKgNggY0KtEBAAh%2BQQJCgAAACwAAAAAIAAgAAAE6BDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfYIDMaAFdTESJeaEDAIMxYFqrOUaNW4E4ObYcCXaiBVEgULe0NJaxxtYksjh2NLkZISgDgJhHthkpU4mW6blRiYmZOlh4JWkDqILwUGBnE6TYEbCgevr0N1gH4At7gHiRpFaLNrrq8HNgAJA70AWxQIH1%2BvsYMDAzZQPC9VCNkDWUhGkuE5PxJNwiUK4UfLzOlD4WvzAHaoG9nxPi5d%2BjYUqfAhhykOFwJWiAAAIfkECQoAAAAsAAAAACAAIAAABPAQyElpUqnqzaciSoVkXVUMFaFSwlpOCcMYlErAavhOMnNLNo8KsZsMZItJEIDIFSkLGQoQTNhIsFehRww2CQLKF0tYGKYSg%2BygsZIuNqJksKgbfgIGepNo2cIUB3V1B3IvNiBYNQaDSTtfhhx0CwVPI0UJe0%2Bbm4g5VgcGoqOcnjmjqDSdnhgEoamcsZuXO1aWQy8KAwOAuTYYGwi7w5h%2BKr0SJ8MFihpNbx%2B4Erq7BYBuzsdiH1jCAzoSfl0rVirNbRXlBBlLX%2BBP0XJLAPGzTkAuAOqb0WT5AH7OcdCm5B8TgRwSRKIHQtaLCwg1RAAAOwAAAAAAAAAAAA%3D%3D); - visibility: visible; - opacity: 0.6; - -webkit-transition: all 0.3s ease; - transition: all 0.3s ease; } - -.reveal .overlay header { - position: absolute; - left: 0; - top: 0; - width: 100%; - height: 40px; - z-index: 2; - border-bottom: 1px solid #222; } - -.reveal .overlay header a { - display: inline-block; - width: 40px; - height: 40px; - padding: 0 10px; - float: right; - opacity: 0.6; - -moz-box-sizing: border-box; - box-sizing: border-box; } - -.reveal .overlay header a:hover { - opacity: 1; } - -.reveal .overlay header a .icon { - display: inline-block; - width: 20px; - height: 20px; - background-position: 50% 50%; - background-size: 100%; - background-repeat: no-repeat; } - -.reveal .overlay header a.close .icon { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABkklEQVRYR8WX4VHDMAxG6wnoJrABZQPYBCaBTWAD2g1gE5gg6OOsXuxIlr40d81dfrSJ9V4c2VLK7spHuTJ/5wpM07QXuXc5X0opX2tEJcadjHuV80li/FgxTIEK/5QBCICBD6xEhSMGHgQPgBgLiYVAB1dpSqKDawxTohFw4JSEA3clzgIBPCURwE2JucBR7rhPJJv5OpJwDX+SfDjgx1wACQeJG1aChP9K/IMmdZ8DtESV1WyP3Bt4MwM6sj4NMxMYiqUWHQu4KYA/SYkIjOsm3BXYWMKFDwU2khjCQ4ELJUJ4SmClRArOCmSXGuKma0fYD5CbzHxFpCSGAhfAVSSUGDUk2BWZaff2g6GE15BsBQ9nwmpIGDiyHQddwNTMKkbZaf9fajXQca1EX44puJZUsnY0ObGmITE3GVLCbEhQUjGVt146j6oasWN+49Vph2w1pZ5EansNZqKBm1txbU57iRRcZ86RWMDdWtBJUHBHwoQPi1GV+JCbntmvok7iTX4/Up9mgyTc/FJYDTcndgH/AA5A/CHsyEkVAAAAAElFTkSuQmCC); } - -.reveal .overlay header a.external .icon { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAcElEQVRYR+2WSQoAIQwEzf8f7XiOMkUQxUPlGkM3hVmiQfQR9GYnH1SsAQlI4DiBqkCMoNb9y2e90IAEJPAcgdznU9+engMaeJ7Azh5Y1U67gAho4DqBqmB1buAf0MB1AlVBek83ZPkmJMGc1wAR+AAqod/B97TRpQAAAABJRU5ErkJggg==); } - -.reveal .overlay .viewport { - position: absolute; - top: 40px; - right: 0; - bottom: 0; - left: 0; } - -.reveal .overlay.overlay-preview .viewport iframe { - width: 100%; - height: 100%; - max-width: 100%; - max-height: 100%; - border: 0; - opacity: 0; - visibility: hidden; - -webkit-transition: all 0.3s ease; - transition: all 0.3s ease; } - -.reveal .overlay.overlay-preview.loaded .viewport iframe { - opacity: 1; - visibility: visible; } - -.reveal .overlay.overlay-preview.loaded .spinner { - opacity: 0; - visibility: hidden; - -webkit-transform: scale(0.2); - -ms-transform: scale(0.2); - transform: scale(0.2); } - -.reveal .overlay.overlay-help .viewport { - overflow: auto; - color: #fff; } - -.reveal .overlay.overlay-help .viewport .viewport-inner { - width: 600px; - margin: 0 auto; - padding: 60px; - text-align: center; - letter-spacing: normal; } - -.reveal .overlay.overlay-help .viewport .viewport-inner .title { - font-size: 20px; } - -.reveal .overlay.overlay-help .viewport .viewport-inner table { - border: 1px solid #fff; - border-collapse: collapse; - font-size: 14px; } - -.reveal .overlay.overlay-help .viewport .viewport-inner table th, .reveal .overlay.overlay-help .viewport .viewport-inner table td { - width: 200px; - padding: 10px; - border: 1px solid #fff; - vertical-align: middle; } - -.reveal .overlay.overlay-help .viewport .viewport-inner table th { - padding-top: 20px; - padding-bottom: 20px; } - -/********************************************* - * PLAYBACK COMPONENT - *********************************************/ -.reveal .playback { - position: fixed; - left: 15px; - bottom: 15px; - z-index: 30; - cursor: pointer; - -webkit-transition: all 400ms ease; - transition: all 400ms ease; } - -.reveal.overview .playback { - opacity: 0; - visibility: hidden; } - -/********************************************* - * ROLLING LINKS - *********************************************/ -.reveal .roll { - display: inline-block; - line-height: 1.2; - overflow: hidden; - vertical-align: top; - -webkit-perspective: 400px; - perspective: 400px; - -webkit-perspective-origin: 50% 50%; - perspective-origin: 50% 50%; } - -.reveal .roll:hover { - background: none; - text-shadow: none; } - -.reveal .roll span { - display: block; - position: relative; - padding: 0 2px; - pointer-events: none; - -webkit-transition: all 400ms ease; - transition: all 400ms ease; - -webkit-transform-origin: 50% 0%; - -ms-transform-origin: 50% 0%; - transform-origin: 50% 0%; - -webkit-transform-style: preserve-3d; - transform-style: preserve-3d; - -webkit-backface-visibility: hidden; - backface-visibility: hidden; } - -.reveal .roll:hover span { - background: rgba(0, 0, 0, 0.5); - -webkit-transform: translate3d(0px, 0px, -45px) rotateX(90deg); - transform: translate3d(0px, 0px, -45px) rotateX(90deg); } - -.reveal .roll span:after { - content: attr(data-title); - display: block; - position: absolute; - left: 0; - top: 0; - padding: 0 2px; - -webkit-backface-visibility: hidden; - backface-visibility: hidden; - -webkit-transform-origin: 50% 0%; - -ms-transform-origin: 50% 0%; - transform-origin: 50% 0%; - -webkit-transform: translate3d(0px, 110%, 0px) rotateX(-90deg); - transform: translate3d(0px, 110%, 0px) rotateX(-90deg); } - -/********************************************* - * SPEAKER NOTES - *********************************************/ -.reveal aside.notes { - display: none; } - -/********************************************* - * ZOOM PLUGIN - *********************************************/ -.zoomed .reveal *, .zoomed .reveal *:before, .zoomed .reveal *:after { - -webkit-backface-visibility: visible !important; - backface-visibility: visible !important; } - -.zoomed .reveal .progress, .zoomed .reveal .controls { - opacity: 0; } - -.zoomed .reveal .roll span { - background: none; } - -.zoomed .reveal .roll span:after { - visibility: hidden; } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/reveal.scss b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/reveal.scss deleted file mode 100644 index 2bbc51e2fe..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/reveal.scss +++ /dev/null @@ -1,1317 +0,0 @@ -/*! - * reveal.js - * http://lab.hakim.se/reveal-js - * MIT licensed - * - * Copyright (C) 2015 Hakim El Hattab, http://hakim.se - */ - - -/********************************************* - * RESET STYLES - *********************************************/ - -html, body, .reveal div, .reveal span, .reveal applet, .reveal object, .reveal iframe, -.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6, .reveal p, .reveal blockquote, .reveal pre, -.reveal a, .reveal abbr, .reveal acronym, .reveal address, .reveal big, .reveal cite, .reveal code, -.reveal del, .reveal dfn, .reveal em, .reveal img, .reveal ins, .reveal kbd, .reveal q, .reveal s, .reveal samp, -.reveal small, .reveal strike, .reveal strong, .reveal sub, .reveal sup, .reveal tt, .reveal var, -.reveal b, .reveal u, .reveal center, -.reveal dl, .reveal dt, .reveal dd, .reveal ol, .reveal ul, .reveal li, -.reveal fieldset, .reveal form, .reveal label, .reveal legend, -.reveal table, .reveal caption, .reveal tbody, .reveal tfoot, .reveal thead, .reveal tr, .reveal th, .reveal td, -.reveal article, .reveal aside, .reveal canvas, .reveal details, .reveal embed, -.reveal figure, .reveal figcaption, .reveal footer, .reveal header, .reveal hgroup, -.reveal menu, .reveal nav, .reveal output, .reveal ruby, .reveal section, .reveal summary, -.reveal time, .reveal mark, .reveal audio, video { - margin: 0; - padding: 0; - border: 0; - font-size: 100%; - font: inherit; - vertical-align: baseline; -} - -.reveal article, .reveal aside, .reveal details, .reveal figcaption, .reveal figure, -.reveal footer, .reveal header, .reveal hgroup, .reveal menu, .reveal nav, .reveal section { - display: block; -} - - -/********************************************* - * GLOBAL STYLES - *********************************************/ - -html, -body { - width: 100%; - height: 100%; - overflow: hidden; -} - -body { - position: relative; - line-height: 1; - - background-color: #fff; - color: #000; -} - - -/********************************************* - * VIEW FRAGMENTS - *********************************************/ - -.reveal .slides section .fragment { - opacity: 0; - visibility: hidden; - transition: all .2s ease; - - &.visible { - opacity: 1; - visibility: visible; - } -} - -.reveal .slides section .fragment.grow { - opacity: 1; - visibility: visible; - - &.visible { - transform: scale( 1.3 ); - } -} - -.reveal .slides section .fragment.shrink { - opacity: 1; - visibility: visible; - - &.visible { - transform: scale( 0.7 ); - } -} - -.reveal .slides section .fragment.zoom-in { - transform: scale( 0.1 ); - - &.visible { - transform: none; - } -} - -.reveal .slides section .fragment.fade-out { - opacity: 1; - visibility: visible; - - &.visible { - opacity: 0; - visibility: hidden; - } -} - -.reveal .slides section .fragment.semi-fade-out { - opacity: 1; - visibility: visible; - - &.visible { - opacity: 0.5; - visibility: visible; - } -} - -.reveal .slides section .fragment.strike { - opacity: 1; - - &.visible { - text-decoration: line-through; - } -} - -.reveal .slides section .fragment.current-visible { - opacity: 0; - visibility: hidden; - - &.current-fragment { - opacity: 1; - visibility: visible; - } -} - -.reveal .slides section .fragment.highlight-red, -.reveal .slides section .fragment.highlight-current-red, -.reveal .slides section .fragment.highlight-green, -.reveal .slides section .fragment.highlight-current-green, -.reveal .slides section .fragment.highlight-blue, -.reveal .slides section .fragment.highlight-current-blue { - opacity: 1; - visibility: visible; -} - .reveal .slides section .fragment.highlight-red.visible { - color: #ff2c2d - } - .reveal .slides section .fragment.highlight-green.visible { - color: #17ff2e; - } - .reveal .slides section .fragment.highlight-blue.visible { - color: #1b91ff; - } - -.reveal .slides section .fragment.highlight-current-red.current-fragment { - color: #ff2c2d -} -.reveal .slides section .fragment.highlight-current-green.current-fragment { - color: #17ff2e; -} -.reveal .slides section .fragment.highlight-current-blue.current-fragment { - color: #1b91ff; -} - - -/********************************************* - * DEFAULT ELEMENT STYLES - *********************************************/ - -/* Fixes issue in Chrome where italic fonts did not appear when printing to PDF */ -.reveal:after { - content: ''; - font-style: italic; -} - -.reveal iframe { - z-index: 1; -} - -/** Prevents layering issues in certain browser/transition combinations */ -.reveal a { - position: relative; -} - -.reveal .stretch { - max-width: none; - max-height: none; -} - -.reveal pre.stretch code { - height: 100%; - max-height: 100%; - box-sizing: border-box; -} - - -/********************************************* - * CONTROLS - *********************************************/ - -.reveal .controls { - display: none; - position: fixed; - width: 110px; - height: 110px; - z-index: 30; - right: 10px; - bottom: 10px; - - -webkit-user-select: none; -} - -.reveal .controls div { - position: absolute; - opacity: 0.05; - width: 0; - height: 0; - border: 12px solid transparent; - transform: scale(.9999); - transition: all 0.2s ease; - - -webkit-tap-highlight-color: rgba( 0, 0, 0, 0 ); -} - -.reveal .controls div.enabled { - opacity: 0.7; - cursor: pointer; -} - -.reveal .controls div.enabled:active { - margin-top: 1px; -} - - .reveal .controls div.navigate-left { - top: 42px; - - border-right-width: 22px; - border-right-color: #000; - } - .reveal .controls div.navigate-left.fragmented { - opacity: 0.3; - } - - .reveal .controls div.navigate-right { - left: 74px; - top: 42px; - - border-left-width: 22px; - border-left-color: #000; - } - .reveal .controls div.navigate-right.fragmented { - opacity: 0.3; - } - - .reveal .controls div.navigate-up { - left: 42px; - - border-bottom-width: 22px; - border-bottom-color: #000; - } - .reveal .controls div.navigate-up.fragmented { - opacity: 0.3; - } - - .reveal .controls div.navigate-down { - left: 42px; - top: 74px; - - border-top-width: 22px; - border-top-color: #000; - } - .reveal .controls div.navigate-down.fragmented { - opacity: 0.3; - } - - -/********************************************* - * PROGRESS BAR - *********************************************/ - -.reveal .progress { - position: fixed; - display: none; - height: 3px; - width: 100%; - bottom: 0; - left: 0; - z-index: 10; - - background-color: rgba( 0, 0, 0, 0.2 ); -} - .reveal .progress:after { - content: ''; - display: block; - position: absolute; - height: 20px; - width: 100%; - top: -20px; - } - .reveal .progress span { - display: block; - height: 100%; - width: 0px; - - background-color: #000; - transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); - } - -/********************************************* - * SLIDE NUMBER - *********************************************/ - -.reveal .slide-number { - position: fixed; - display: block; - right: 15px; - bottom: 15px; - opacity: 0.5; - z-index: 31; - font-size: 12px; -} - -/********************************************* - * SLIDES - *********************************************/ - -.reveal { - position: relative; - width: 100%; - height: 100%; - overflow: hidden; - touch-action: none; -} - -.reveal .slides { - position: absolute; - width: 100%; - height: 100%; - top: 0; - right: 0; - bottom: 0; - left: 0; - margin: auto; - - overflow: visible; - z-index: 1; - text-align: center; - perspective: 600px; - perspective-origin: 50% 40%; -} - -.reveal .slides>section { - -ms-perspective: 600px; -} - -.reveal .slides>section, -.reveal .slides>section>section { - display: none; - position: absolute; - width: 100%; - padding: 20px 0px; - - z-index: 10; - transform-style: preserve-3d; - transition: transform-origin 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985), - transform 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985), - visibility 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985), - opacity 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); -} - -/* Global transition speed settings */ -.reveal[data-transition-speed="fast"] .slides section { - transition-duration: 400ms; -} -.reveal[data-transition-speed="slow"] .slides section { - transition-duration: 1200ms; -} - -/* Slide-specific transition speed overrides */ -.reveal .slides section[data-transition-speed="fast"] { - transition-duration: 400ms; -} -.reveal .slides section[data-transition-speed="slow"] { - transition-duration: 1200ms; -} - -.reveal .slides>section.stack { - padding-top: 0; - padding-bottom: 0; -} - -.reveal .slides>section.present, -.reveal .slides>section>section.present { - display: block; - z-index: 11; - opacity: 1; -} - -.reveal.center, -.reveal.center .slides, -.reveal.center .slides section { - min-height: 0 !important; -} - -/* Don't allow interaction with invisible slides */ -.reveal .slides>section.future, -.reveal .slides>section>section.future, -.reveal .slides>section.past, -.reveal .slides>section>section.past { - pointer-events: none; -} - -.reveal.overview .slides>section, -.reveal.overview .slides>section>section { - pointer-events: auto; -} - -.reveal .slides>section.past, -.reveal .slides>section.future, -.reveal .slides>section>section.past, -.reveal .slides>section>section.future { - opacity: 0; -} - - -/********************************************* - * Mixins for readability of transitions - *********************************************/ - -@mixin transition-global($style) { - .reveal .slides>section[data-transition=#{$style}], - .reveal.#{$style} .slides>section:not([data-transition]) { - @content; - } -} -@mixin transition-horizontal-past($style) { - .reveal .slides>section[data-transition=#{$style}].past, - .reveal .slides>section[data-transition~=#{$style}-out].past, - .reveal.#{$style} .slides>section:not([data-transition]).past { - @content; - } -} -@mixin transition-horizontal-future($style) { - .reveal .slides>section[data-transition=#{$style}].future, - .reveal .slides>section[data-transition~=#{$style}-in].future, - .reveal.#{$style} .slides>section:not([data-transition]).future { - @content; - } -} - -@mixin transition-vertical-past($style) { - .reveal .slides>section>section[data-transition=#{$style}].past, - .reveal .slides>section>section[data-transition~=#{$style}-out].past, - .reveal.#{$style} .slides>section>section:not([data-transition]).past { - @content; - } -} -@mixin transition-vertical-future($style) { - .reveal .slides>section>section[data-transition=#{$style}].future, - .reveal .slides>section>section[data-transition~=#{$style}-in].future, - .reveal.#{$style} .slides>section>section:not([data-transition]).future { - @content; - } -} - -/********************************************* - * SLIDE TRANSITION - * Aliased 'linear' for backwards compatibility - *********************************************/ - -@each $stylename in slide, linear { - .reveal.#{$stylename} section { - backface-visibility: hidden; - } - @include transition-horizontal-past(#{$stylename}) { - transform: translate(-150%, 0); - } - @include transition-horizontal-future(#{$stylename}) { - transform: translate(150%, 0); - } - @include transition-vertical-past(#{$stylename}) { - transform: translate(0, -150%); - } - @include transition-vertical-future(#{$stylename}) { - transform: translate(0, 150%); - } -} - -/********************************************* - * CONVEX TRANSITION - * Aliased 'default' for backwards compatibility - *********************************************/ - -@each $stylename in default, convex { - @include transition-horizontal-past(#{$stylename}) { - transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); - } - @include transition-horizontal-future(#{$stylename}) { - transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); - } - @include transition-vertical-past(#{$stylename}) { - transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0); - } - @include transition-vertical-future(#{$stylename}) { - transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0); - } -} - -/********************************************* - * CONCAVE TRANSITION - *********************************************/ - -@include transition-horizontal-past(concave) { - transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0); -} -@include transition-horizontal-future(concave) { - transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0); -} -@include transition-vertical-past(concave) { - transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0); -} -@include transition-vertical-future(concave) { - transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0); -} - - -/********************************************* - * ZOOM TRANSITION - *********************************************/ - -@include transition-global(zoom) { - transition-timing-function: ease; -} -@include transition-horizontal-past(zoom) { - visibility: hidden; - transform: scale(16); -} -@include transition-horizontal-future(zoom) { - visibility: hidden; - transform: scale(0.2); -} -@include transition-vertical-past(zoom) { - transform: translate(0, -150%); -} -@include transition-vertical-future(zoom) { - transform: translate(0, 150%); -} - - -/********************************************* - * CUBE TRANSITION - *********************************************/ - -.reveal.cube .slides { - perspective: 1300px; -} - -.reveal.cube .slides section { - padding: 30px; - min-height: 700px; - backface-visibility: hidden; - box-sizing: border-box; -} - .reveal.center.cube .slides section { - min-height: 0; - } - .reveal.cube .slides section:not(.stack):before { - content: ''; - position: absolute; - display: block; - width: 100%; - height: 100%; - left: 0; - top: 0; - background: rgba(0,0,0,0.1); - border-radius: 4px; - transform: translateZ( -20px ); - } - .reveal.cube .slides section:not(.stack):after { - content: ''; - position: absolute; - display: block; - width: 90%; - height: 30px; - left: 5%; - bottom: 0; - background: none; - z-index: 1; - - border-radius: 4px; - box-shadow: 0px 95px 25px rgba(0,0,0,0.2); - transform: translateZ(-90px) rotateX( 65deg ); - } - -.reveal.cube .slides>section.stack { - padding: 0; - background: none; -} - -.reveal.cube .slides>section.past { - transform-origin: 100% 0%; - transform: translate3d(-100%, 0, 0) rotateY(-90deg); -} - -.reveal.cube .slides>section.future { - transform-origin: 0% 0%; - transform: translate3d(100%, 0, 0) rotateY(90deg); -} - -.reveal.cube .slides>section>section.past { - transform-origin: 0% 100%; - transform: translate3d(0, -100%, 0) rotateX(90deg); -} - -.reveal.cube .slides>section>section.future { - transform-origin: 0% 0%; - transform: translate3d(0, 100%, 0) rotateX(-90deg); -} - - -/********************************************* - * PAGE TRANSITION - *********************************************/ - -.reveal.page .slides { - perspective-origin: 0% 50%; - perspective: 3000px; -} - -.reveal.page .slides section { - padding: 30px; - min-height: 700px; - box-sizing: border-box; -} - .reveal.page .slides section.past { - z-index: 12; - } - .reveal.page .slides section:not(.stack):before { - content: ''; - position: absolute; - display: block; - width: 100%; - height: 100%; - left: 0; - top: 0; - background: rgba(0,0,0,0.1); - transform: translateZ( -20px ); - } - .reveal.page .slides section:not(.stack):after { - content: ''; - position: absolute; - display: block; - width: 90%; - height: 30px; - left: 5%; - bottom: 0; - background: none; - z-index: 1; - - border-radius: 4px; - box-shadow: 0px 95px 25px rgba(0,0,0,0.2); - - -webkit-transform: translateZ(-90px) rotateX( 65deg ); - } - -.reveal.page .slides>section.stack { - padding: 0; - background: none; -} - -.reveal.page .slides>section.past { - transform-origin: 0% 0%; - transform: translate3d(-40%, 0, 0) rotateY(-80deg); -} - -.reveal.page .slides>section.future { - transform-origin: 100% 0%; - transform: translate3d(0, 0, 0); -} - -.reveal.page .slides>section>section.past { - transform-origin: 0% 0%; - transform: translate3d(0, -40%, 0) rotateX(80deg); -} - -.reveal.page .slides>section>section.future { - transform-origin: 0% 100%; - transform: translate3d(0, 0, 0); -} - - -/********************************************* - * FADE TRANSITION - *********************************************/ - -.reveal .slides section[data-transition=fade], -.reveal.fade .slides section:not([data-transition]), -.reveal.fade .slides>section>section:not([data-transition]) { - transform: none; - transition: opacity 0.5s; -} - - -.reveal.fade.overview .slides section, -.reveal.fade.overview .slides>section>section { - transition: none; -} - - -/********************************************* - * NO TRANSITION - *********************************************/ - -@include transition-global(none) { - transform: none; - transition: none; -} - - -/********************************************* - * PAUSED MODE - *********************************************/ - -.reveal .pause-overlay { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: black; - visibility: hidden; - opacity: 0; - z-index: 100; - transition: all 1s ease; -} -.reveal.paused .pause-overlay { - visibility: visible; - opacity: 1; -} - - -/********************************************* - * FALLBACK - *********************************************/ - -.no-transforms { - overflow-y: auto; -} - -.no-transforms .reveal .slides { - position: relative; - width: 80%; - height: auto !important; - top: 0; - left: 50%; - margin: 0; - text-align: center; -} - -.no-transforms .reveal .controls, -.no-transforms .reveal .progress { - display: none !important; -} - -.no-transforms .reveal .slides section { - display: block !important; - opacity: 1 !important; - position: relative !important; - height: auto; - min-height: 0; - top: 0; - left: -50%; - margin: 70px 0; - transform: none; -} - -.no-transforms .reveal .slides section section { - left: 0; -} - -.reveal .no-transition, -.reveal .no-transition * { - transition: none !important; -} - - -/********************************************* - * PER-SLIDE BACKGROUNDS - *********************************************/ - -.reveal .backgrounds { - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; - perspective: 600px; -} - .reveal .slide-background { - display: none; - position: absolute; - width: 100%; - height: 100%; - opacity: 0; - visibility: hidden; - - background-color: rgba( 0, 0, 0, 0 ); - background-position: 50% 50%; - background-repeat: no-repeat; - background-size: cover; - - transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); - } - - .reveal .slide-background.stack { - display: block; - } - - .reveal .slide-background.present { - opacity: 1; - visibility: visible; - } - - .print-pdf .reveal .slide-background { - opacity: 1 !important; - visibility: visible !important; - } - -/* Video backgrounds */ -.reveal .slide-background video { - position: absolute; - width: 100%; - height: 100%; - max-width: none; - max-height: none; - top: 0; - left: 0; -} - -/* Immediate transition style */ -.reveal[data-background-transition=none]>.backgrounds .slide-background, -.reveal>.backgrounds .slide-background[data-background-transition=none] { - transition: none; -} - -/* Slide */ -.reveal[data-background-transition=slide]>.backgrounds .slide-background, -.reveal>.backgrounds .slide-background[data-background-transition=slide] { - opacity: 1; - backface-visibility: hidden; -} - .reveal[data-background-transition=slide]>.backgrounds .slide-background.past, - .reveal>.backgrounds .slide-background.past[data-background-transition=slide] { - transform: translate(-100%, 0); - } - .reveal[data-background-transition=slide]>.backgrounds .slide-background.future, - .reveal>.backgrounds .slide-background.future[data-background-transition=slide] { - transform: translate(100%, 0); - } - - .reveal[data-background-transition=slide]>.backgrounds .slide-background>.slide-background.past, - .reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=slide] { - transform: translate(0, -100%); - } - .reveal[data-background-transition=slide]>.backgrounds .slide-background>.slide-background.future, - .reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=slide] { - transform: translate(0, 100%); - } - - -/* Convex */ -.reveal[data-background-transition=convex]>.backgrounds .slide-background.past, -.reveal>.backgrounds .slide-background.past[data-background-transition=convex] { - opacity: 0; - transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0); -} -.reveal[data-background-transition=convex]>.backgrounds .slide-background.future, -.reveal>.backgrounds .slide-background.future[data-background-transition=convex] { - opacity: 0; - transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0); -} - -.reveal[data-background-transition=convex]>.backgrounds .slide-background>.slide-background.past, -.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=convex] { - opacity: 0; - transform: translate3d(0, -100%, 0) rotateX(90deg) translate3d(0, -100%, 0); -} -.reveal[data-background-transition=convex]>.backgrounds .slide-background>.slide-background.future, -.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=convex] { - opacity: 0; - transform: translate3d(0, 100%, 0) rotateX(-90deg) translate3d(0, 100%, 0); -} - - -/* Concave */ -.reveal[data-background-transition=concave]>.backgrounds .slide-background.past, -.reveal>.backgrounds .slide-background.past[data-background-transition=concave] { - opacity: 0; - transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0); -} -.reveal[data-background-transition=concave]>.backgrounds .slide-background.future, -.reveal>.backgrounds .slide-background.future[data-background-transition=concave] { - opacity: 0; - transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0); -} - -.reveal[data-background-transition=concave]>.backgrounds .slide-background>.slide-background.past, -.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=concave] { - opacity: 0; - transform: translate3d(0, -100%, 0) rotateX(-90deg) translate3d(0, -100%, 0); -} -.reveal[data-background-transition=concave]>.backgrounds .slide-background>.slide-background.future, -.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=concave] { - opacity: 0; - transform: translate3d(0, 100%, 0) rotateX(90deg) translate3d(0, 100%, 0); -} - -/* Zoom */ -.reveal[data-background-transition=zoom]>.backgrounds .slide-background, -.reveal>.backgrounds .slide-background[data-background-transition=zoom] { - transition-timing-function: ease; -} - -.reveal[data-background-transition=zoom]>.backgrounds .slide-background.past, -.reveal>.backgrounds .slide-background.past[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - transform: scale(16); -} -.reveal[data-background-transition=zoom]>.backgrounds .slide-background.future, -.reveal>.backgrounds .slide-background.future[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - transform: scale(0.2); -} - -.reveal[data-background-transition=zoom]>.backgrounds .slide-background>.slide-background.past, -.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - transform: scale(16); -} -.reveal[data-background-transition=zoom]>.backgrounds .slide-background>.slide-background.future, -.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=zoom] { - opacity: 0; - visibility: hidden; - transform: scale(0.2); -} - - -/* Global transition speed settings */ -.reveal[data-transition-speed="fast"]>.backgrounds .slide-background { - transition-duration: 400ms; -} -.reveal[data-transition-speed="slow"]>.backgrounds .slide-background { - transition-duration: 1200ms; -} - - -/********************************************* - * OVERVIEW - *********************************************/ - -.reveal.overview { - perspective-origin: 50% 50%; - perspective: 700px; - - .slides section { - height: 700px; - opacity: 1 !important; - overflow: hidden; - visibility: visible !important; - cursor: pointer; - box-sizing: border-box; - } - .slides section:hover, - .slides section.present { - outline: 10px solid rgba(150,150,150,0.4); - outline-offset: 10px; - } - .slides section .fragment { - opacity: 1; - transition: none; - } - .slides section:after, - .slides section:before { - display: none !important; - } - .slides>section.stack { - padding: 0; - top: 0 !important; - background: none; - outline: none; - overflow: visible; - } - - .backgrounds { - perspective: inherit; - } - - .backgrounds .slide-background { - opacity: 1; - visibility: visible; - - // This can't be applied to the slide itself in Safari - outline: 10px solid rgba(150,150,150,0.1); - outline-offset: 10px; - } -} - -// Disable transitions transitions while we're activating -// or deactivating the overview mode. -.reveal.overview .slides section, -.reveal.overview-deactivating .slides section { - transition: none; -} - -.reveal.overview .backgrounds .slide-background, -.reveal.overview-deactivating .backgrounds .slide-background { - transition: none; -} - -.reveal.overview-animated .slides { - transition: transform 0.4s ease; -} - - -/********************************************* - * RTL SUPPORT - *********************************************/ - -.reveal.rtl .slides, -.reveal.rtl .slides h1, -.reveal.rtl .slides h2, -.reveal.rtl .slides h3, -.reveal.rtl .slides h4, -.reveal.rtl .slides h5, -.reveal.rtl .slides h6 { - direction: rtl; - font-family: sans-serif; -} - -.reveal.rtl pre, -.reveal.rtl code { - direction: ltr; -} - -.reveal.rtl ol, -.reveal.rtl ul { - text-align: right; -} - -.reveal.rtl .progress span { - float: right -} - -/********************************************* - * PARALLAX BACKGROUND - *********************************************/ - -.reveal.has-parallax-background .backgrounds { - transition: all 0.8s ease; -} - -/* Global transition speed settings */ -.reveal.has-parallax-background[data-transition-speed="fast"] .backgrounds { - transition-duration: 400ms; -} -.reveal.has-parallax-background[data-transition-speed="slow"] .backgrounds { - transition-duration: 1200ms; -} - - -/********************************************* - * LINK PREVIEW OVERLAY - *********************************************/ - -.reveal .overlay { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - z-index: 1000; - background: rgba( 0, 0, 0, 0.9 ); - opacity: 0; - visibility: hidden; - transition: all 0.3s ease; -} - .reveal .overlay.visible { - opacity: 1; - visibility: visible; - } - - .reveal .overlay .spinner { - position: absolute; - display: block; - top: 50%; - left: 50%; - width: 32px; - height: 32px; - margin: -16px 0 0 -16px; - z-index: 10; - background-image: url(data:image/gif;base64,R0lGODlhIAAgAPMAAJmZmf%2F%2F%2F6%2Bvr8nJybW1tcDAwOjo6Nvb26ioqKOjo7Ozs%2FLy8vz8%2FAAAAAAAAAAAACH%2FC05FVFNDQVBFMi4wAwEAAAAh%2FhpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh%2BQQJCgAAACwAAAAAIAAgAAAE5xDISWlhperN52JLhSSdRgwVo1ICQZRUsiwHpTJT4iowNS8vyW2icCF6k8HMMBkCEDskxTBDAZwuAkkqIfxIQyhBQBFvAQSDITM5VDW6XNE4KagNh6Bgwe60smQUB3d4Rz1ZBApnFASDd0hihh12BkE9kjAJVlycXIg7CQIFA6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YJvpJivxNaGmLHT0VnOgSYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ%2FV%2FnmOM82XiHRLYKhKP1oZmADdEAAAh%2BQQJCgAAACwAAAAAIAAgAAAE6hDISWlZpOrNp1lGNRSdRpDUolIGw5RUYhhHukqFu8DsrEyqnWThGvAmhVlteBvojpTDDBUEIFwMFBRAmBkSgOrBFZogCASwBDEY%2FCZSg7GSE0gSCjQBMVG023xWBhklAnoEdhQEfyNqMIcKjhRsjEdnezB%2BA4k8gTwJhFuiW4dokXiloUepBAp5qaKpp6%2BHo7aWW54wl7obvEe0kRuoplCGepwSx2jJvqHEmGt6whJpGpfJCHmOoNHKaHx61WiSR92E4lbFoq%2BB6QDtuetcaBPnW6%2BO7wDHpIiK9SaVK5GgV543tzjgGcghAgAh%2BQQJCgAAACwAAAAAIAAgAAAE7hDISSkxpOrN5zFHNWRdhSiVoVLHspRUMoyUakyEe8PTPCATW9A14E0UvuAKMNAZKYUZCiBMuBakSQKG8G2FzUWox2AUtAQFcBKlVQoLgQReZhQlCIJesQXI5B0CBnUMOxMCenoCfTCEWBsJColTMANldx15BGs8B5wlCZ9Po6OJkwmRpnqkqnuSrayqfKmqpLajoiW5HJq7FL1Gr2mMMcKUMIiJgIemy7xZtJsTmsM4xHiKv5KMCXqfyUCJEonXPN2rAOIAmsfB3uPoAK%2B%2BG%2Bw48edZPK%2BM6hLJpQg484enXIdQFSS1u6UhksENEQAAIfkECQoAAAAsAAAAACAAIAAABOcQyEmpGKLqzWcZRVUQnZYg1aBSh2GUVEIQ2aQOE%2BG%2BcD4ntpWkZQj1JIiZIogDFFyHI0UxQwFugMSOFIPJftfVAEoZLBbcLEFhlQiqGp1Vd140AUklUN3eCA51C1EWMzMCezCBBmkxVIVHBWd3HHl9JQOIJSdSnJ0TDKChCwUJjoWMPaGqDKannasMo6WnM562R5YluZRwur0wpgqZE7NKUm%2BFNRPIhjBJxKZteWuIBMN4zRMIVIhffcgojwCF117i4nlLnY5ztRLsnOk%2BaV%2BoJY7V7m76PdkS4trKcdg0Zc0tTcKkRAAAIfkECQoAAAAsAAAAACAAIAAABO4QyEkpKqjqzScpRaVkXZWQEximw1BSCUEIlDohrft6cpKCk5xid5MNJTaAIkekKGQkWyKHkvhKsR7ARmitkAYDYRIbUQRQjWBwJRzChi9CRlBcY1UN4g0%2FVNB0AlcvcAYHRyZPdEQFYV8ccwR5HWxEJ02YmRMLnJ1xCYp0Y5idpQuhopmmC2KgojKasUQDk5BNAwwMOh2RtRq5uQuPZKGIJQIGwAwGf6I0JXMpC8C7kXWDBINFMxS4DKMAWVWAGYsAdNqW5uaRxkSKJOZKaU3tPOBZ4DuK2LATgJhkPJMgTwKCdFjyPHEnKxFCDhEAACH5BAkKAAAALAAAAAAgACAAAATzEMhJaVKp6s2nIkolIJ2WkBShpkVRWqqQrhLSEu9MZJKK9y1ZrqYK9WiClmvoUaF8gIQSNeF1Er4MNFn4SRSDARWroAIETg1iVwuHjYB1kYc1mwruwXKC9gmsJXliGxc%2BXiUCby9ydh1sOSdMkpMTBpaXBzsfhoc5l58Gm5yToAaZhaOUqjkDgCWNHAULCwOLaTmzswadEqggQwgHuQsHIoZCHQMMQgQGubVEcxOPFAcMDAYUA85eWARmfSRQCdcMe0zeP1AAygwLlJtPNAAL19DARdPzBOWSm1brJBi45soRAWQAAkrQIykShQ9wVhHCwCQCACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiRMDjI0Fd30%2FiI2UA5GSS5UDj2l6NoqgOgN4gksEBgYFf0FDqKgHnyZ9OX8HrgYHdHpcHQULXAS2qKpENRg7eAMLC7kTBaixUYFkKAzWAAnLC7FLVxLWDBLKCwaKTULgEwbLA4hJtOkSBNqITT3xEgfLpBtzE%2FjiuL04RGEBgwWhShRgQExHBAAh%2BQQJCgAAACwAAAAAIAAgAAAE7xDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfZiCqGk5dTESJeaOAlClzsJsqwiJwiqnFrb2nS9kmIcgEsjQydLiIlHehhpejaIjzh9eomSjZR%2BipslWIRLAgMDOR2DOqKogTB9pCUJBagDBXR6XB0EBkIIsaRsGGMMAxoDBgYHTKJiUYEGDAzHC9EACcUGkIgFzgwZ0QsSBcXHiQvOwgDdEwfFs0sDzt4S6BK4xYjkDOzn0unFeBzOBijIm1Dgmg5YFQwsCMjp1oJ8LyIAACH5BAkKAAAALAAAAAAgACAAAATwEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GGl6NoiPOH16iZKNlH6KmyWFOggHhEEvAwwMA0N9GBsEC6amhnVcEwavDAazGwIDaH1ipaYLBUTCGgQDA8NdHz0FpqgTBwsLqAbWAAnIA4FWKdMLGdYGEgraigbT0OITBcg5QwPT4xLrROZL6AuQAPUS7bxLpoWidY0JtxLHKhwwMJBTHgPKdEQAACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GAULDJCRiXo1CpGXDJOUjY%2BYip9DhToJA4RBLwMLCwVDfRgbBAaqqoZ1XBMHswsHtxtFaH1iqaoGNgAIxRpbFAgfPQSqpbgGBqUD1wBXeCYp1AYZ19JJOYgH1KwA4UBvQwXUBxPqVD9L3sbp2BNk2xvvFPJd%2BMFCN6HAAIKgNggY0KtEBAAh%2BQQJCgAAACwAAAAAIAAgAAAE6BDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfYIDMaAFdTESJeaEDAIMxYFqrOUaNW4E4ObYcCXaiBVEgULe0NJaxxtYksjh2NLkZISgDgJhHthkpU4mW6blRiYmZOlh4JWkDqILwUGBnE6TYEbCgevr0N1gH4At7gHiRpFaLNrrq8HNgAJA70AWxQIH1%2BvsYMDAzZQPC9VCNkDWUhGkuE5PxJNwiUK4UfLzOlD4WvzAHaoG9nxPi5d%2BjYUqfAhhykOFwJWiAAAIfkECQoAAAAsAAAAACAAIAAABPAQyElpUqnqzaciSoVkXVUMFaFSwlpOCcMYlErAavhOMnNLNo8KsZsMZItJEIDIFSkLGQoQTNhIsFehRww2CQLKF0tYGKYSg%2BygsZIuNqJksKgbfgIGepNo2cIUB3V1B3IvNiBYNQaDSTtfhhx0CwVPI0UJe0%2Bbm4g5VgcGoqOcnjmjqDSdnhgEoamcsZuXO1aWQy8KAwOAuTYYGwi7w5h%2BKr0SJ8MFihpNbx%2B4Erq7BYBuzsdiH1jCAzoSfl0rVirNbRXlBBlLX%2BBP0XJLAPGzTkAuAOqb0WT5AH7OcdCm5B8TgRwSRKIHQtaLCwg1RAAAOwAAAAAAAAAAAA%3D%3D); - - visibility: visible; - opacity: 0.6; - transition: all 0.3s ease; - } - - .reveal .overlay header { - position: absolute; - left: 0; - top: 0; - width: 100%; - height: 40px; - z-index: 2; - border-bottom: 1px solid #222; - } - .reveal .overlay header a { - display: inline-block; - width: 40px; - height: 40px; - padding: 0 10px; - float: right; - opacity: 0.6; - - box-sizing: border-box; - } - .reveal .overlay header a:hover { - opacity: 1; - } - .reveal .overlay header a .icon { - display: inline-block; - width: 20px; - height: 20px; - - background-position: 50% 50%; - background-size: 100%; - background-repeat: no-repeat; - } - .reveal .overlay header a.close .icon { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABkklEQVRYR8WX4VHDMAxG6wnoJrABZQPYBCaBTWAD2g1gE5gg6OOsXuxIlr40d81dfrSJ9V4c2VLK7spHuTJ/5wpM07QXuXc5X0opX2tEJcadjHuV80li/FgxTIEK/5QBCICBD6xEhSMGHgQPgBgLiYVAB1dpSqKDawxTohFw4JSEA3clzgIBPCURwE2JucBR7rhPJJv5OpJwDX+SfDjgx1wACQeJG1aChP9K/IMmdZ8DtESV1WyP3Bt4MwM6sj4NMxMYiqUWHQu4KYA/SYkIjOsm3BXYWMKFDwU2khjCQ4ELJUJ4SmClRArOCmSXGuKma0fYD5CbzHxFpCSGAhfAVSSUGDUk2BWZaff2g6GE15BsBQ9nwmpIGDiyHQddwNTMKkbZaf9fajXQca1EX44puJZUsnY0ObGmITE3GVLCbEhQUjGVt146j6oasWN+49Vph2w1pZ5EansNZqKBm1txbU57iRRcZ86RWMDdWtBJUHBHwoQPi1GV+JCbntmvok7iTX4/Up9mgyTc/FJYDTcndgH/AA5A/CHsyEkVAAAAAElFTkSuQmCC); - } - .reveal .overlay header a.external .icon { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAcElEQVRYR+2WSQoAIQwEzf8f7XiOMkUQxUPlGkM3hVmiQfQR9GYnH1SsAQlI4DiBqkCMoNb9y2e90IAEJPAcgdznU9+engMaeJ7Azh5Y1U67gAho4DqBqmB1buAf0MB1AlVBek83ZPkmJMGc1wAR+AAqod/B97TRpQAAAABJRU5ErkJggg==); - } - - .reveal .overlay .viewport { - position: absolute; - top: 40px; - right: 0; - bottom: 0; - left: 0; - } - - .reveal .overlay.overlay-preview .viewport iframe { - width: 100%; - height: 100%; - max-width: 100%; - max-height: 100%; - border: 0; - - opacity: 0; - visibility: hidden; - transition: all 0.3s ease; - } - - .reveal .overlay.overlay-preview.loaded .viewport iframe { - opacity: 1; - visibility: visible; - } - - .reveal .overlay.overlay-preview.loaded .spinner { - opacity: 0; - visibility: hidden; - transform: scale(0.2); - } - - .reveal .overlay.overlay-help .viewport { - overflow: auto; - color: #fff; - } - - .reveal .overlay.overlay-help .viewport .viewport-inner { - width: 600px; - margin: 0 auto; - padding: 60px; - text-align: center; - letter-spacing: normal; - } - - .reveal .overlay.overlay-help .viewport .viewport-inner .title { - font-size: 20px; - } - - .reveal .overlay.overlay-help .viewport .viewport-inner table { - border: 1px solid #fff; - border-collapse: collapse; - font-size: 14px; - } - - .reveal .overlay.overlay-help .viewport .viewport-inner table th, - .reveal .overlay.overlay-help .viewport .viewport-inner table td { - width: 200px; - padding: 10px; - border: 1px solid #fff; - vertical-align: middle; - } - - .reveal .overlay.overlay-help .viewport .viewport-inner table th { - padding-top: 20px; - padding-bottom: 20px; - } - - - -/********************************************* - * PLAYBACK COMPONENT - *********************************************/ - -.reveal .playback { - position: fixed; - left: 15px; - bottom: 15px; - z-index: 30; - cursor: pointer; - transition: all 400ms ease; -} - -.reveal.overview .playback { - opacity: 0; - visibility: hidden; -} - - -/********************************************* - * ROLLING LINKS - *********************************************/ - -.reveal .roll { - display: inline-block; - line-height: 1.2; - overflow: hidden; - - vertical-align: top; - perspective: 400px; - perspective-origin: 50% 50%; -} - .reveal .roll:hover { - background: none; - text-shadow: none; - } -.reveal .roll span { - display: block; - position: relative; - padding: 0 2px; - - pointer-events: none; - transition: all 400ms ease; - transform-origin: 50% 0%; - transform-style: preserve-3d; - backface-visibility: hidden; -} - .reveal .roll:hover span { - background: rgba(0,0,0,0.5); - transform: translate3d( 0px, 0px, -45px ) rotateX( 90deg ); - } -.reveal .roll span:after { - content: attr(data-title); - - display: block; - position: absolute; - left: 0; - top: 0; - padding: 0 2px; - backface-visibility: hidden; - transform-origin: 50% 0%; - transform: translate3d( 0px, 110%, 0px ) rotateX( -90deg ); -} - - -/********************************************* - * SPEAKER NOTES - *********************************************/ - -.reveal aside.notes { - display: none; -} - - -/********************************************* - * ZOOM PLUGIN - *********************************************/ - -.zoomed .reveal *, -.zoomed .reveal *:before, -.zoomed .reveal *:after { - backface-visibility: visible !important; -} - -.zoomed .reveal .progress, -.zoomed .reveal .controls { - opacity: 0; -} - -.zoomed .reveal .roll span { - background: none; -} - -.zoomed .reveal .roll span:after { - visibility: hidden; -} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/MITK.css b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/MITK.css deleted file mode 100644 index 92d6bec796..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/MITK.css +++ /dev/null @@ -1,369 +0,0 @@ -/** - * A simple theme for reveal.js presentations, similar - * to the default theme. The accent color is darkblue. - * - * This theme is Copyright (C) 2012 Owen Versteeg, https://github.com/StereotypicalApps. It is MIT licensed. - * reveal.js is Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se - */ -/********************************************* - * GLOBAL STYLES - *********************************************/ -body { - background: #fff; - background-color: #fff; -} - -.reveal { - font-family: "Open Sans", sans-serif; - font-size: 36px; - font-weight: normal; - color: #000; } - -::selection { - color: #fff; - background: rgba(0, 0, 0, 0.99); - text-shadow: none; } - -.reveal .slides > section, -.reveal .slides > section > section { - line-height: 1.3; - font-weight: inherit; } - -/********************************************* - * HEADERS - *********************************************/ -.reveal h1, -.reveal h2, -.reveal h3, -.reveal h4, -.reveal h5, -.reveal h6 { - margin: 0 0 20px 0; - color: #2d5c88; - font-family: "Open Sans", sans-serif; - font-weight: bold; - line-height: 1.2; - letter-spacing: normal; - text-transform: none; - text-shadow: none; - word-wrap: break-word; } - -.reveal h1 { - font-size: 3.77em; } - -.reveal h2 { - font-size: 2.11em; } - -.reveal h3 { - font-size: 1.55em; } - -.reveal h4 { - font-size: 1em; } - -.reveal h1 { - text-shadow: none; } - -/********************************************* - * OTHER - *********************************************/ -.reveal p { - margin: 20px 0; - line-height: 1.3; } - -/* Ensure certain elements are never larger than the slide itself */ -.reveal img, -.reveal video, -.reveal iframe { - max-width: 95%; - max-height: 95%; } - -.reveal strong, -.reveal b { - font-weight: bold; } - -.reveal em { - font-style: italic; } - -.reveal ol, -.reveal dl, -.reveal ul { - display: inline-block; - text-align: left; - margin: 0 0 0 1em; } - -.reveal ol { - list-style-type: decimal; } - -.reveal ul { - list-style-type: disc; } - -.reveal ul ul { - list-style-type: square; } - -.reveal ul ul ul { - list-style-type: circle; } - -.reveal ul ul, -.reveal ul ol, -.reveal ol ol, -.reveal ol ul { - display: block; - margin-left: 40px; } - -.reveal dt { - font-weight: bold; } - -.reveal dd { - margin-left: 40px; } - -.reveal q, -.reveal blockquote { - quotes: none; } - -.reveal blockquote { - display: block; - position: relative; - width: 60%; - margin: 20px auto; - border: 2px solid; - border-color: rgb(45, 92, 136); - padding: 5px; - font-style: italic; - background: rgba(45, 92, 136, 0.05); - box-shadow: 2px 4px 3px rgba(0, 0, 0, 0.1); } - -.reveal blockquote p:first-child, -.reveal blockquote p:last-child { - display: inline-block; } - -.reveal q { - font-style: italic; } - -.reveal pre { - display: block; - position: relative; - width: 90%; - margin: 20px auto; - text-align: left; - font-size: 0.55em; - font-family: monospace; - line-height: 1.2em; - word-wrap: break-word; - box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.3); } - -.reveal code { - font-family: monospace; } - -.reveal pre code { - display: block; - padding: 5px; - overflow: auto; - max-height: 400px; - word-wrap: normal; - background: #3F3F3F; - color: #DCDCDC; } - -.reveal table { - margin: auto; - border-collapse: collapse; - border-spacing: 0; } - -.reveal table th { - font-weight: bold; } - -.reveal table th, -.reveal table td { - text-align: left; - padding: 0.2em 0.5em 0.2em 0.5em; - border-bottom: 1px solid; } - -.reveal table th[align="center"], -.reveal table td[align="center"] { - text-align: center; } - -.reveal table th[align="right"], -.reveal table td[align="right"] { - text-align: right; } - -.reveal table tr:last-child td { - border-bottom: none; } - -.reveal sup { - vertical-align: super; } - -.reveal sub { - vertical-align: sub; } - -.reveal small { - display: inline-block; - font-size: 0.6em; - line-height: 1.2em; - vertical-align: top; } - -.reveal small * { - vertical-align: top; } - -/********************************************* - * LINKS - *********************************************/ -.reveal a { - color: rgb(0,0,0); - text-decoration: none; - -webkit-transition: color .15s ease; - -moz-transition: color .15s ease; - transition: color .15s ease; } - -.reveal a:hover { - color: #2d5a88; - text-shadow: none; - border: none; } - -.reveal .roll span:after { - color: #fff; - background: #00003f; } - -/********************************************* - * IMAGES - *********************************************/ -.reveal section img { - margin: 15px 0px; - background: rgba(255, 255, 255, 0.12); - border: none; - box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); } - -.reveal a img { - -webkit-transition: all .15s linear; - -moz-transition: all .15s linear; - transition: all .15s linear; } - -.reveal a:hover img { - background: rgba(255, 255, 255, 0.2); - border-color: #00008B; - box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); } - -/********************************************* - * NAVIGATION CONTROLS - *********************************************/ -.reveal .controls div.navigate-left, -.reveal .controls div.navigate-left.enabled { - border-right-color: rgb( 45, 92, 136); } - -.reveal .controls div.navigate-right, -.reveal .controls div.navigate-right.enabled { - border-left-color: rgb( 45, 92, 136); } - -.reveal .controls div.navigate-up, -.reveal .controls div.navigate-up.enabled { - border-bottom-color: rgb( 45, 92, 136); } - -.reveal .controls div.navigate-down, -.reveal .controls div.navigate-down.enabled { - border-top-color: rgb( 45, 92, 136); } - -.reveal .controls div.navigate-left.enabled:hover { - border-right-color: rgba( 45, 92, 136, 0.5); } - -.reveal .controls div.navigate-right.enabled:hover { - border-left-color: rgba( 45, 92, 136, 0.5); } - -.reveal .controls div.navigate-up.enabled:hover { - border-bottom-color: rgba( 45, 92, 136, 0.5); } - -.reveal .controls div.navigate-down.enabled:hover { - border-top-color: rgba( 45, 92, 136, 0.5); } - - -/********************************************* - * PROGRESS BAR - *********************************************/ -.reveal .progress { - background: rgba(0, 0, 0, 0.2); } - -.reveal .progress span { - background: rgb( 45, 92, 136); - -webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); - -moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); - transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); } - -/********************************************* - * SLIDE NUMBER - *********************************************/ -.reveal .slide-number { - color: #00008B; } - - -/********************************************* - * Video Container - *********************************************/ -.videoContainer { - position: absolute; - top: 0%; - height: 100%; - width: 100%; - overflow: hidden; -} - -.videoContainer { - min-width: 100%; - min-height: 100%; -} - - -/********************************************* - * Delayed Animation Versuche - *********************************************/ - -@keyframes delayed { - 0% { opacity: 0; } - 100% { opacity: 1; } -} - -.delayed: { - animation: delayed 2s ease; - animation-delay: 2s; - animation-fill-mode: both; - opacity: 0; - transition: ease; - transition-delay: 2s; -} - -.test{ - opacity: 0.5; - transition: all 2s linear 2s; -} - -.test:target{ - opacity: 1; -} - -.test.is-hidden{ - opacity: 0; -} - -.delayed[time="5s"] { - animation-delay: 5s; - transition-delay: 5s; -} - - -.delayed[time="10s"] { - animation-delay: 10s; - transition-delay: 10s; -} - -.5s-delay { - transition-delay: 5s !important; -} - -/********************************************* - * Hover = Animation, beim Drüberfahren - *********************************************/ - -.test { - border: 1px solid red; -} - -.test:hover { - border: 10px solid red; - transition: border 5s linear; -} \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/README.md b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/README.md deleted file mode 100644 index 753e0c0d25..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Dependencies - -Themes are written using Sass to keep things modular and reduce the need for repeated selectors across files. Make sure that you have the reveal.js development environment including the Grunt dependencies installed before proceding: https://github.com/hakimel/reveal.js#full-setup - -## Creating a Theme - -To create your own theme, start by duplicating any ```.scss``` file in [/css/theme/source](https://github.com/hakimel/reveal.js/blob/master/css/theme/source) and adding it to the compilation list in the [Gruntfile](https://github.com/hakimel/reveal.js/blob/master/Gruntfile.js). - -Each theme file does four things in the following order: - -1. **Include [/css/theme/template/mixins.scss](https://github.com/hakimel/reveal.js/blob/master/css/theme/template/mixins.scss)** -Shared utility functions. - -2. **Include [/css/theme/template/settings.scss](https://github.com/hakimel/reveal.js/blob/master/css/theme/template/settings.scss)** -Declares a set of custom variables that the template file (step 4) expects. Can be overridden in step 3. - -3. **Override** -This is where you override the default theme. Either by specifying variables (see [settings.scss](https://github.com/hakimel/reveal.js/blob/master/css/theme/template/settings.scss) for reference) or by adding any selectors and styles you please. - -4. **Include [/css/theme/template/theme.scss](https://github.com/hakimel/reveal.js/blob/master/css/theme/template/theme.scss)** -The template theme file which will generate final CSS output based on the currently defined variables. - -When you are done, run `grunt css-themes` to compile the Sass file to CSS and you are ready to use your new theme. diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/source/MITK.scss b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/source/MITK.scss deleted file mode 100644 index ef86218492..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/css/theme/source/MITK.scss +++ /dev/null @@ -1,38 +0,0 @@ -/** - * A simple theme for reveal.js presentations, similar - * to the default theme. The accent color is darkblue. - * - * This theme is Copyright (C) 2012 Owen Versteeg, https://github.com/StereotypicalApps. It is MIT licensed. - * reveal.js is Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se - */ - - -// Default mixins and settings ----------------- -@import "../template/mixins"; -@import "../template/settings"; -// --------------------------------------------- - - - -// Include theme-specific fonts -@import url(https://fonts.googleapis.com/css?family=News+Cycle:400,700); -@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic); - - -// Override theme settings (see ../template/settings.scss) -$mainFont: 'Open Sans', sans-serif; -$mainColor: #000; -$headingFont: 'Open Sans', Impact, sans-serif; -$headingColor: rgb(45, 92, 136); -$headingTextShadow: none; -$headingTextTransform: none; -$backgroundColor: #fff; -$linkColor: #00008B; -$linkColorHover: lighten( $linkColor, 20% ); -$selectionBackgroundColor: rgba(0, 0, 0, 0.99); - - - -// Theme template ------------------------------ -@import "../template/theme"; -// --------------------------------------------- \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/function.js b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/function.js deleted file mode 100644 index 7238d27761..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/function.js +++ /dev/null @@ -1,232 +0,0 @@ -// If you want to create a new button you have to add some data (strings) to the following five arrays. -// Make sure that you add your data at the same position in each array. -// The buttons will be generated in order to the array's index. e.g. data at array's index '0' will generate the first button. - -// enter the name of your module here -var moduleNames = new Array("MITK Website", - "Tutorials Website"); - -// add the MITK-link to your module -var moduleLinks = new Array("https://www.mitk.org", - "https://www.mitk.org/Tutorials"); - -// add the filename of your icon for the module. Place the picture in subdirectory "pics". -// The picture's width should be 136 pixel; the height 123 pixel. -var picFilenames = new Array("button_mitk.png", - "button_mitk.png"); - -// if your module is not stable, you can mark it as experimental. -// just set true for experimental or false for stable. -var experimental = new Array(false, - false); - -// add the description for your module. The description is displayed in a PopUp-window. -var moduleDescriptions = new Array("Open the MITK website in an external browser.", - "Open the MITK tutorials overview in an external browser."); - -var bttns = new Array(); - -var d = document, da = d.all; - -// holds id of current mouseover-HTML-element -var currentTarget; - -// get the id of current mouseover-HTML-element -d.onmouseover = function(o){ - var e = da ? event.srcElement : o.target; - currentTarget = e.id; -} - - -// build-function called by onload-event in HTML-document -function createButtons(){ - - for (i=0; i < moduleNames.length; i++){ - bttns[i] = new Button(moduleNames[i],moduleLinks[i], picFilenames[i], moduleDescriptions[i]); - bttns[i].createButton(); - } - - for (i=0; i < moduleNames.length; i++){ - - if(experimental[i]){ - setExperimental(i); - } - } - - createClearFloat(); -} - -// Class Button -function Button(moduleName, moduleLink, picFilename, moduleDescr){ - - // Properties - this.bttnID = "bttn" + moduleName.replace(/\s/g,''); - this.modName = moduleName; - this.modLink = moduleLink; - this.picPath = "qrc:/org.mitk.gui.qt.welcomescreen/pics/" + picFilename; - this.modDescr = moduleDescr; - - // Methods - this.createButton = function(){ - - // get DIV-wrapper for Button and append it to HTML-document - bttnWrapper = this.createWrapper(); - document.getElementById("generatedButtonField").appendChild(bttnWrapper); - - // Create a button and append it to document - this.createCSSClass(); - bttnPicLink = this.createPicLink(); - bttnPicLink.href = this.modLink; - bttnWrapper.appendChild(bttnPicLink); - - // create text-link and add it to DIV-wrapper - bttnTxtLink = document.createElement("a"); - bttnTxtLink.onclick = function(){openPage();}; - bttnTxtLink.href = this.modLink; - bttnTxtLink.className = "textLink"; - bttnTxtLink.appendChild(document.createTextNode(this.modName)); - bttnWrapper.appendChild(bttnTxtLink); - - // create pop-up link for module description - if (this.modDescr.length != 0) { - bttnPopUpLink = document.createElement("a"); - modName = this.modName; - modDescr = this.modDescr; - bttnPopUpLink.onclick = function(){showPopUpWindow();}; - bttnPopUpLink.className = "popUpLink"; - bttnPopUpLink.id = "popup" + this.modName; - bttnPopUpLink.appendChild(document.createTextNode("more info >>")); - bttnWrapper.appendChild(document.createElement("br")); - bttnWrapper.appendChild(bttnPopUpLink); - } - - return bttnPicLink; - } - - this.createWrapper = function(){ - bttnWrapper = document.createElement("div"); - bttnWrapper.id = "wrapper" + this.modName; - bttnWrapper.className = "bttnWrap"; - - return bttnWrapper; - } - - this.createPicLink = function(){ - picLink = document.createElement("a"); - picLink.id = "link" + this.modName; - picLink.href = this.modLink; - picLink.className = "genericButton " + this.bttnID; - - return picLink; - } - - this.createCSSClass = function(){ - var style = document.createElement('style'); - style.type = 'text/css'; - style.innerHTML = '.' + this.bttnID +' { background-image: url(' + this.picPath +'); }'; - document.getElementsByTagName('head')[0].appendChild(style); - } - -} - - -function showPopUpWindow(){ - - // modules position in array? - modulePos = getPos(currentTarget,"popup"); - - // get reference to anchor-element in HTML-document - popUpAnchor = document.getElementById("popupAnchor"); - - // check if a popUp is open - if(popUpAnchor.hasChildNodes()){ - // if a popUp is open, remove it! - popUpAnchor.removeChild(document.getElementById("popup")); - } - - // create new container for popUp - container = document.createElement("div"); - container.id = "popup"; - container.align = "right"; - - // append popUp-container to HTML-document - popUpAnchor.appendChild(container); - - // create close-button and append it to popUp-container - bttnClose = document.createElement("img"); - bttnClose.src = "pics/popup_bttn_close.png"; - bttnClose.id = "bttnClose"; - bttnClose.onclick = function(){closeInfoWindow();}; - container.appendChild(bttnClose); - - // create container for content-elements - contHeadline = document.createElement("div"); - contHeadline.id = "contHeadline"; - contDescription = document.createElement("div"); - contDescription.id = "contDescription"; - contModLink = document.createElement("div"); - contModLink.id = "contModLink"; - - // append content-container to popUp-container - container.appendChild(contHeadline); - container.appendChild(contDescription); - container.appendChild(contModLink); - - // create text-elements with content - headline = document.createTextNode(moduleNames[modulePos] + " "); - description = document.createTextNode(moduleDescriptions[modulePos]); - moduleLink = document.createElement("a"); - moduleLink.href = moduleLinks[modulePos] ; - moduleLink.className = 'moduleLink'; - moduleLinkTxt = document.createTextNode("Click here to open '" + moduleNames[modulePos].toLowerCase() + "'"); - moduleLink.appendChild(moduleLinkTxt); - - // append text-elements to their container - contHeadline.appendChild(headline); - contDescription.appendChild(description); - contModLink.appendChild(moduleLink); -} - -function getPos(id,prefix){ - - if(prefix == "popup"){ - targetID = id.slice(5); - }else{ - if(prefix == "bttn"){ - targetID = id.slice(4); - } - } - - for(i=0; i < moduleNames.length; i++ ){ - if(moduleNames[i] == targetID){ - return i; - } - } -} - -function setExperimental(modPos){ - linkID = "link" + moduleNames[modPos]; - - expPic = document.createElement("img"); - expPic.src = "pics/experimental.png"; - expPic.className = "expPic"; - - document.getElementById(linkID).appendChild(expPic); -} - - -function openPage(){ - window.open("https://www.mitk.org","_blank"); -} - -// function to close PopUp-window -function closeInfoWindow(){ - popUpAnchor = document.getElementById("popupAnchor"); - popUpAnchor.removeChild(document.getElementById("popup")); -} - -function createClearFloat(){ - cf = document.createElement("div"); - cf.className = "clearfloat"; - document.getElementById("generatedButtonField").appendChild(cf); -} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Alt.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Alt.png deleted file mode 100644 index bee1ed05a1..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Alt.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ArrowDown.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ArrowDown.png deleted file mode 100644 index d4e617dda6..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ArrowDown.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ArrowKeys.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ArrowKeys.png deleted file mode 100644 index 031152a6b9..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ArrowKeys.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ControlArrows.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ControlArrows.png deleted file mode 100644 index b628ace5e3..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ControlArrows.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DataManagerData.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DataManagerData.png deleted file mode 100644 index 5d876bc703..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DataManagerData.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayAreaScan.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayAreaScan.png deleted file mode 100644 index 4ccbe27e7b..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayAreaScan.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayAreaSmall.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayAreaSmall.png deleted file mode 100644 index e51550df97..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayAreaSmall.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayWindowAxial.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayWindowAxial.png deleted file mode 100644 index a0b0bba042..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayWindowAxial.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayWindowButtons.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayWindowButtons.png deleted file mode 100644 index 383ccf0321..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/DisplayWindowButtons.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Esc.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Esc.png deleted file mode 100644 index 1446c07cd1..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Esc.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/HelpWelcome.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/HelpWelcome.png deleted file mode 100644 index 3a7b9591a9..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/HelpWelcome.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconDataManager.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconDataManager.png deleted file mode 100644 index 6b35281c8c..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconDataManager.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconHelp.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconHelp.svg deleted file mode 100644 index 851327f776..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconHelp.svg +++ /dev/null @@ -1,224 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - Help Browser - 2005-11-06 - - - Tuomas Kuosmanen - - - - - help - browser - documentation - docs - man - info - - - - - - Jakub Steiner, Andreas Nilsson - - - http://tigert.com - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconImageNavigator.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconImageNavigator.png deleted file mode 100644 index 6ba4333787..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/IconImageNavigator.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ImageNavigator.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ImageNavigator.png deleted file mode 100644 index a99e847939..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ImageNavigator.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/LayoutList.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/LayoutList.png deleted file mode 100644 index 66955ac80b..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/LayoutList.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Levelwindow.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Levelwindow.png deleted file mode 100644 index 6bfd8148b5..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Levelwindow.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITK.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITK.png deleted file mode 100644 index 2ae88b9d62..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITK.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKArrow.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKArrow.png deleted file mode 100644 index e508182729..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKArrow.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKArrow2.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKArrow2.png deleted file mode 100644 index 06b5a3fe41..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKArrow2.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKPoint.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKPoint.png deleted file mode 100644 index 711f5e0059..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MITKPoint.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MousePointerClick.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MousePointerClick.png deleted file mode 100644 index 58c178ef8f..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MousePointerClick.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MouseTangoStyle.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MouseTangoStyle.svg deleted file mode 100644 index 2fda0182a9..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/MouseTangoStyle.svg +++ /dev/null @@ -1,343 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - Input - Mouse - - - Jakub Steiner - - - http://jimmac.musichall.cz - - - mouse - input - device - HID - pointer - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenScanData.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenScanData.png deleted file mode 100644 index 29cea3938e..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenScanData.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenScanPlugins.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenScanPlugins.png deleted file mode 100644 index 0bdfe48703..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenScanPlugins.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenWithScan.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenWithScan.png deleted file mode 100644 index 92e82a94d4..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ScreenWithScan.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Spacebar.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Spacebar.png deleted file mode 100644 index 37ea6b668e..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Spacebar.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Toolbar.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Toolbar.png deleted file mode 100644 index 7f72f8852f..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/Toolbar.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ToolbarLeft.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ToolbarLeft.png deleted file mode 100644 index 9caa2156da..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ToolbarLeft.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ToolbarRight.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ToolbarRight.png deleted file mode 100644 index 6f70b16bb4..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/ToolbarRight.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/WelcomePage.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/WelcomePage.png deleted file mode 100644 index cc5e0e3767..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/images/welcome/WelcomePage.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/levelwindow/standarddisplay.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/levelwindow/standarddisplay.svg new file mode 100644 index 0000000000..572cb50788 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/levelwindow/standarddisplay.svg @@ -0,0 +1,478 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/click.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/click.svg new file mode 100644 index 0000000000..80bcae90d7 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/click.svg @@ -0,0 +1 @@ + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/crosshair.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/crosshair.svg new file mode 100644 index 0000000000..7af4ef445a --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/crosshair.svg @@ -0,0 +1,278 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/pan.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/pan.svg new file mode 100644 index 0000000000..eaae753c1e --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/pan.svg @@ -0,0 +1 @@ + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/scroll.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/scroll.svg new file mode 100644 index 0000000000..bb8f0207fe --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/scroll.svg @@ -0,0 +1 @@ + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/zoom.svg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/zoom.svg new file mode 100644 index 0000000000..c2d833820a --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/img/mousenavigation/zoom.svg @@ -0,0 +1 @@ + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/index.html b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/index.html new file mode 100644 index 0000000000..4f2113bf1f --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/index.html @@ -0,0 +1,84 @@ + + + + + Welcome to the MITK Workbench! + + + + +
+

Welcome to the MITK Workbench!

+

+ Load and view medical images from all kinds of imaging modalities like X-ray, US, CT, MRI, and many more. + Use our tools to efficiently create segmentations, measure anatomical structures, inspect image statistics, or register multiple images to each other. +

+

+ + The MITK Workbench is developed at the ↪ German Cancer Research Center (DKFZ).
+ It is based on the free open source ↪ Medical Imaging Interaction Toolkit (MITK). +
+

+
+ +
+

Mouse navigation

+
+ Crosshair +

+ Your images are typically shown from three different view directions at once: axial, sagittal, and coronal. + Together, the view planes resemble the shape of a three-dimensional crosshair slicing through your image data. + Use the mouse to navigate in these views. +

+
+
+
+

Focus

+ Left mouse button +

Use the left mouse button to focus all views on the clicked position.

+
+
+

Zoom

+ Right mouse button +

Press and hold the right mouse button and move the mouse up and down to zoom in and out.

+
+
+

Pan

+ Middle mouse button +

Press and hold the middle mouse button and move the mouse to pan around.

+
+
+

Scroll

+ Scroll wheel +

Use the scroll wheel to scroll through slices along the view's direction.

+
+
+
+
+
+
+

Image contrast

+
+ Standard display with level window +

+ For images, a vertical scale is shown right next to the views. + It is called the level window. +

+

+ The values shown in the level window represent the pixel intensities of an image. + The blue bar defines the range of pixel intensities that is mapped onto the whole range of displayable pixel brightness. + Hence, a shorter range of pixel intensities results in higher displayed image contrast. +

+

+ Grab the blue bar to move it up and down.
+ Grab the tips of the blue bar to change its size. +

+

+ Right-click on the level window for many more options. +

+
+
+
+
+ + diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/js/reveal.js b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/js/reveal.js deleted file mode 100644 index d42be35b0d..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/js/reveal.js +++ /dev/null @@ -1,4508 +0,0 @@ -/*! - * reveal.js - * http://lab.hakim.se/reveal-js - * MIT licensed - * - * Copyright (C) 2015 Hakim El Hattab, http://hakim.se - */ -(function( root, factory ) { - if( typeof define === 'function' && define.amd ) { - // AMD. Register as an anonymous module. - define( function() { - root.Reveal = factory(); - return root.Reveal; - } ); - } else if( typeof exports === 'object' ) { - // Node. Does not work with strict CommonJS. - module.exports = factory(); - } else { - // Browser globals. - root.Reveal = factory(); - } -}( this, function() { - - 'use strict'; - - var Reveal; - - var SLIDES_SELECTOR = '.slides section', - HORIZONTAL_SLIDES_SELECTOR = '.slides>section', - VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section', - HOME_SLIDE_SELECTOR = '.slides>section:first-of-type', - - // Configuration defaults, can be overridden at initialization time - config = { - - // The "normal" size of the presentation, aspect ratio will be preserved - // when the presentation is scaled to fit different resolutions - width: 960, - height: 700, - - // Factor of the display size that should remain empty around the content - margin: 0.1, - - // Bounds for smallest/largest possible scale to apply to content - minScale: 0.2, - maxScale: 1.5, - - // Display controls in the bottom right corner - controls: true, - - // Display a presentation progress bar - progress: true, - - // Display the page number of the current slide - slideNumber: false, - - // Push each slide change to the browser history - history: false, - - // Enable keyboard shortcuts for navigation - keyboard: true, - - // Optional function that blocks keyboard events when retuning false - keyboardCondition: null, - - // Enable the slide overview mode - overview: true, - - // Vertical centering of slides - center: true, - - // Enables touch navigation on devices with touch input - touch: true, - - // Loop the presentation - loop: false, - - // Change the presentation direction to be RTL - rtl: false, - - // Turns fragments on and off globally - fragments: true, - - // Flags if the presentation is running in an embedded mode, - // i.e. contained within a limited portion of the screen - embedded: false, - - // Flags if we should show a help overlay when the questionmark - // key is pressed - help: true, - - // Flags if it should be possible to pause the presentation (blackout) - pause: true, - - // Number of milliseconds between automatically proceeding to the - // next slide, disabled when set to 0, this value can be overwritten - // by using a data-autoslide attribute on your slides - autoSlide: 0, - - // Stop auto-sliding after user input - autoSlideStoppable: true, - - // Enable slide navigation via mouse wheel - mouseWheel: false, - - // Apply a 3D roll to links on hover - rollingLinks: false, - - // Hides the address bar on mobile devices - hideAddressBar: true, - - // Opens links in an iframe preview overlay - previewLinks: false, - - // Exposes the reveal.js API through window.postMessage - postMessage: true, - - // Dispatches all reveal.js events to the parent window through postMessage - postMessageEvents: false, - - // Focuses body when page changes visiblity to ensure keyboard shortcuts work - focusBodyOnPageVisibilityChange: true, - - // Transition style - transition: 'slide', // none/fade/slide/convex/concave/zoom - - // Transition speed - transitionSpeed: 'default', // default/fast/slow - - // Transition style for full page slide backgrounds - backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom - - // Parallax background image - parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px" - - // Amount of pixels to move the parallax background per slide step - parallaxBackgroundHorizontal: null, - parallaxBackgroundVertical: null, - - // Number of slides away from the current that are visible - viewDistance: 3, - - // Script dependencies to load - dependencies: [] - - }, - - // Flags if reveal.js is loaded (has dispatched the 'ready' event) - loaded = false, - - // Flags if the overview mode is currently active - overview = false, - - // The horizontal and vertical index of the currently active slide - indexh, - indexv, - - // The previous and current slide HTML elements - previousSlide, - currentSlide, - - previousBackground, - - // Slides may hold a data-state attribute which we pick up and apply - // as a class to the body. This list contains the combined state of - // all current slides. - state = [], - - // The current scale of the presentation (see width/height config) - scale = 1, - - // CSS transform that is currently applied to the slides container, - // split into two groups - slidesTransform = { layout: '', overview: '' }, - - // Cached references to DOM elements - dom = {}, - - // Features supported by the browser, see #checkCapabilities() - features = {}, - - // Client is a mobile device, see #checkCapabilities() - isMobileDevice, - - // Throttles mouse wheel navigation - lastMouseWheelStep = 0, - - // Delays updates to the URL due to a Chrome thumbnailer bug - writeURLTimeout = 0, - - // Flags if the interaction event listeners are bound - eventsAreBound = false, - - // The current auto-slide duration - autoSlide = 0, - - // Auto slide properties - autoSlidePlayer, - autoSlideTimeout = 0, - autoSlideStartTime = -1, - autoSlidePaused = false, - - // Holds information about the currently ongoing touch input - touch = { - startX: 0, - startY: 0, - startSpan: 0, - startCount: 0, - captured: false, - threshold: 40 - }, - - // Holds information about the keyboard shortcuts - keyboardShortcuts = { - 'N , SPACE': 'Next slide', - 'P': 'Previous slide', - '← , H': 'Navigate left', - '→ , L': 'Navigate right', - '↑ , K': 'Navigate up', - '↓ , J': 'Navigate down', - 'Home': 'First slide', - 'End': 'Last slide', - 'B , .': 'Pause', - 'F': 'Fullscreen', - 'ESC, O': 'Slide overview' - }; - - /** - * Starts up the presentation if the client is capable. - */ - function initialize( options ) { - - checkCapabilities(); - - if( !features.transforms2d && !features.transforms3d ) { - document.body.setAttribute( 'class', 'no-transforms' ); - - // Since JS won't be running any further, we load all lazy - // loading elements upfront - var images = toArray( document.getElementsByTagName( 'img' ) ), - iframes = toArray( document.getElementsByTagName( 'iframe' ) ); - - var lazyLoadable = images.concat( iframes ); - - for( var i = 0, len = lazyLoadable.length; i < len; i++ ) { - var element = lazyLoadable[i]; - if( element.getAttribute( 'data-src' ) ) { - element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); - element.removeAttribute( 'data-src' ); - } - } - - // If the browser doesn't support core features we won't be - // using JavaScript to control the presentation - return; - } - - // Cache references to key DOM elements - dom.wrapper = document.querySelector( '.reveal' ); - dom.slides = document.querySelector( '.reveal .slides' ); - - // Force a layout when the whole page, incl fonts, has loaded - window.addEventListener( 'load', layout, false ); - - var query = Reveal.getQueryHash(); - - // Do not accept new dependencies via query config to avoid - // the potential of malicious script injection - if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies']; - - // Copy options over to our config object - extend( config, options ); - extend( config, query ); - - // Hide the address bar in mobile browsers - hideAddressBar(); - - // Loads the dependencies and continues to #start() once done - load(); - - } - - /** - * Inspect the client to see what it's capable of, this - * should only happens once per runtime. - */ - function checkCapabilities() { - - features.transforms3d = 'WebkitPerspective' in document.body.style || - 'MozPerspective' in document.body.style || - 'msPerspective' in document.body.style || - 'OPerspective' in document.body.style || - 'perspective' in document.body.style; - - features.transforms2d = 'WebkitTransform' in document.body.style || - 'MozTransform' in document.body.style || - 'msTransform' in document.body.style || - 'OTransform' in document.body.style || - 'transform' in document.body.style; - - features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; - features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function'; - - features.canvas = !!document.createElement( 'canvas' ).getContext; - - features.touch = !!( 'ontouchstart' in window ); - - // Transitions in the overview are disabled in desktop and - // mobile Safari due to lag - features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( navigator.userAgent ); - - isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( navigator.userAgent ); - - } - - /** - * Loads the dependencies of reveal.js. Dependencies are - * defined via the configuration option 'dependencies' - * and will be loaded prior to starting/binding reveal.js. - * Some dependencies may have an 'async' flag, if so they - * will load after reveal.js has been started up. - */ - function load() { - - var scripts = [], - scriptsAsync = [], - scriptsToPreload = 0; - - // Called once synchronous scripts finish loading - function proceed() { - if( scriptsAsync.length ) { - // Load asynchronous scripts - head.js.apply( null, scriptsAsync ); - } - - start(); - } - - function loadScript( s ) { - head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() { - // Extension may contain callback functions - if( typeof s.callback === 'function' ) { - s.callback.apply( this ); - } - - if( --scriptsToPreload === 0 ) { - proceed(); - } - }); - } - - for( var i = 0, len = config.dependencies.length; i < len; i++ ) { - var s = config.dependencies[i]; - - // Load if there's no condition or the condition is truthy - if( !s.condition || s.condition() ) { - if( s.async ) { - scriptsAsync.push( s.src ); - } - else { - scripts.push( s.src ); - } - - loadScript( s ); - } - } - - if( scripts.length ) { - scriptsToPreload = scripts.length; - - // Load synchronous scripts - head.js.apply( null, scripts ); - } - else { - proceed(); - } - - } - - /** - * Starts up reveal.js by binding input events and navigating - * to the current URL deeplink if there is one. - */ - function start() { - - // Make sure we've got all the DOM elements we need - setupDOM(); - - // Listen to messages posted to this window - setupPostMessage(); - - // Prevent iframes from scrolling the slides out of view - setupIframeScrollPrevention(); - - // Resets all vertical slides so that only the first is visible - resetVerticalSlides(); - - // Updates the presentation to match the current configuration values - configure(); - - // Read the initial hash - readURL(); - - // Update all backgrounds - updateBackground( true ); - - // Notify listeners that the presentation is ready but use a 1ms - // timeout to ensure it's not fired synchronously after #initialize() - setTimeout( function() { - // Enable transitions now that we're loaded - dom.slides.classList.remove( 'no-transition' ); - - loaded = true; - - dispatchEvent( 'ready', { - 'indexh': indexh, - 'indexv': indexv, - 'currentSlide': currentSlide - } ); - }, 1 ); - - // Special setup and config is required when printing to PDF - if( isPrintingPDF() ) { - removeEventListeners(); - - // The document needs to have loaded for the PDF layout - // measurements to be accurate - if( document.readyState === 'complete' ) { - setupPDF(); - } - else { - window.addEventListener( 'load', setupPDF ); - } - } - - } - - /** - * Finds and stores references to DOM elements which are - * required by the presentation. If a required element is - * not found, it is created. - */ - function setupDOM() { - - // Prevent transitions while we're loading - dom.slides.classList.add( 'no-transition' ); - - // Background element - dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null ); - - // Progress bar - dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '' ); - dom.progressbar = dom.progress.querySelector( 'span' ); - - // Arrow controls - createSingletonNode( dom.wrapper, 'aside', 'controls', - '' + - '' + - '' + - '' ); - - // Slide number - dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' ); - - // Overlay graphic which is displayed during the paused mode - createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null ); - - // Cache references to elements - dom.controls = document.querySelector( '.reveal .controls' ); - dom.theme = document.querySelector( '#theme' ); - - dom.wrapper.setAttribute( 'role', 'application' ); - - // There can be multiple instances of controls throughout the page - dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) ); - dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) ); - dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) ); - dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) ); - dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) ); - dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) ); - - dom.statusDiv = createStatusDiv(); - } - - /** - * Creates a hidden div with role aria-live to announce the - * current slide content. Hide the div off-screen to make it - * available only to Assistive Technologies. - */ - function createStatusDiv() { - - var statusDiv = document.getElementById( 'aria-status-div' ); - if( !statusDiv ) { - statusDiv = document.createElement( 'div' ); - statusDiv.style.position = 'absolute'; - statusDiv.style.height = '1px'; - statusDiv.style.width = '1px'; - statusDiv.style.overflow ='hidden'; - statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )'; - statusDiv.setAttribute( 'id', 'aria-status-div' ); - statusDiv.setAttribute( 'aria-live', 'polite' ); - statusDiv.setAttribute( 'aria-atomic','true' ); - dom.wrapper.appendChild( statusDiv ); - } - return statusDiv; - - } - - /** - * Configures the presentation for printing to a static - * PDF. - */ - function setupPDF() { - - var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight ); - - // Dimensions of the PDF pages - var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ), - pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) ); - - // Dimensions of slides within the pages - var slideWidth = slideSize.width, - slideHeight = slideSize.height; - - // Let the browser know what page size we want to print - injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' ); - - // Limit the size of certain elements to the dimensions of the slide - injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' ); - - document.body.classList.add( 'print-pdf' ); - document.body.style.width = pageWidth + 'px'; - document.body.style.height = pageHeight + 'px'; - - // Slide and slide background layout - toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { - - // Vertical stacks are not centred since their section - // children will be - if( slide.classList.contains( 'stack' ) === false ) { - // Center the slide inside of the page, giving the slide some margin - var left = ( pageWidth - slideWidth ) / 2, - top = ( pageHeight - slideHeight ) / 2; - - var contentHeight = getAbsoluteHeight( slide ); - var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 ); - - // Center slides vertically - if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) { - top = Math.max( ( pageHeight - contentHeight ) / 2, 0 ); - } - - // Position the slide inside of the page - slide.style.left = left + 'px'; - slide.style.top = top + 'px'; - slide.style.width = slideWidth + 'px'; - - // TODO Backgrounds need to be multiplied when the slide - // stretches over multiple pages - var background = slide.querySelector( '.slide-background' ); - if( background ) { - background.style.width = pageWidth + 'px'; - background.style.height = ( pageHeight * numberOfPages ) + 'px'; - background.style.top = -top + 'px'; - background.style.left = -left + 'px'; - } - } - - } ); - - // Show all fragments - toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) { - fragment.classList.add( 'visible' ); - } ); - - } - - /** - * This is an unfortunate necessity. Iframes can trigger the - * parent window to scroll, for example by focusing an input. - * This scrolling can not be prevented by hiding overflow in - * CSS so we have to resort to repeatedly checking if the - * browser has decided to offset our slides :( - */ - function setupIframeScrollPrevention() { - - if( dom.slides.querySelector( 'iframe' ) ) { - setInterval( function() { - if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) { - dom.wrapper.scrollTop = 0; - dom.wrapper.scrollLeft = 0; - } - }, 500 ); - } - - } - - /** - * Creates an HTML element and returns a reference to it. - * If the element already exists the existing instance will - * be returned. - */ - function createSingletonNode( container, tagname, classname, innerHTML ) { - - // Find all nodes matching the description - var nodes = container.querySelectorAll( '.' + classname ); - - // Check all matches to find one which is a direct child of - // the specified container - for( var i = 0; i < nodes.length; i++ ) { - var testNode = nodes[i]; - if( testNode.parentNode === container ) { - return testNode; - } - } - - // If no node was found, create it now - var node = document.createElement( tagname ); - node.classList.add( classname ); - if( typeof innerHTML === 'string' ) { - node.innerHTML = innerHTML; - } - container.appendChild( node ); - - return node; - - } - - /** - * Creates the slide background elements and appends them - * to the background container. One element is created per - * slide no matter if the given slide has visible background. - */ - function createBackgrounds() { - - var printMode = isPrintingPDF(); - - // Clear prior backgrounds - dom.background.innerHTML = ''; - dom.background.classList.add( 'no-transition' ); - - // Iterate over all horizontal slides - toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) { - - var backgroundStack; - - if( printMode ) { - backgroundStack = createBackground( slideh, slideh ); - } - else { - backgroundStack = createBackground( slideh, dom.background ); - } - - // Iterate over all vertical slides - toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) { - - if( printMode ) { - createBackground( slidev, slidev ); - } - else { - createBackground( slidev, backgroundStack ); - } - - backgroundStack.classList.add( 'stack' ); - - } ); - - } ); - - // Add parallax background if specified - if( config.parallaxBackgroundImage ) { - - dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")'; - dom.background.style.backgroundSize = config.parallaxBackgroundSize; - - // Make sure the below properties are set on the element - these properties are - // needed for proper transitions to be set on the element via CSS. To remove - // annoying background slide-in effect when the presentation starts, apply - // these properties after short time delay - setTimeout( function() { - dom.wrapper.classList.add( 'has-parallax-background' ); - }, 1 ); - - } - else { - - dom.background.style.backgroundImage = ''; - dom.wrapper.classList.remove( 'has-parallax-background' ); - - } - - } - - /** - * Creates a background for the given slide. - * - * @param {HTMLElement} slide - * @param {HTMLElement} container The element that the background - * should be appended to - */ - function createBackground( slide, container ) { - - var data = { - background: slide.getAttribute( 'data-background' ), - backgroundSize: slide.getAttribute( 'data-background-size' ), - backgroundImage: slide.getAttribute( 'data-background-image' ), - backgroundVideo: slide.getAttribute( 'data-background-video' ), - backgroundIframe: slide.getAttribute( 'data-background-iframe' ), - backgroundColor: slide.getAttribute( 'data-background-color' ), - backgroundRepeat: slide.getAttribute( 'data-background-repeat' ), - backgroundPosition: slide.getAttribute( 'data-background-position' ), - backgroundTransition: slide.getAttribute( 'data-background-transition' ) - }; - - var element = document.createElement( 'div' ); - - // Carry over custom classes from the slide to the background - element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' ); - - if( data.background ) { - // Auto-wrap image urls in url(...) - if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) { - slide.setAttribute( 'data-background-image', data.background ); - } - else { - element.style.background = data.background; - } - } - - // Create a hash for this combination of background settings. - // This is used to determine when two slide backgrounds are - // the same. - if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) { - element.setAttribute( 'data-background-hash', data.background + - data.backgroundSize + - data.backgroundImage + - data.backgroundVideo + - data.backgroundIframe + - data.backgroundColor + - data.backgroundRepeat + - data.backgroundPosition + - data.backgroundTransition ); - } - - // Additional and optional background properties - if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize; - if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor; - if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat; - if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition; - if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition ); - - container.appendChild( element ); - - // If backgrounds are being recreated, clear old classes - slide.classList.remove( 'has-dark-background' ); - slide.classList.remove( 'has-light-background' ); - - // If this slide has a background color, add a class that - // signals if it is light or dark. If the slide has no background - // color, no class will be set - var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor; - if( computedBackgroundColor ) { - var rgb = colorToRgb( computedBackgroundColor ); - - // Ignore fully transparent backgrounds. Some browsers return - // rgba(0,0,0,0) when reading the computed background color of - // an element with no background - if( rgb && rgb.a !== 0 ) { - if( colorBrightness( computedBackgroundColor ) < 128 ) { - slide.classList.add( 'has-dark-background' ); - } - else { - slide.classList.add( 'has-light-background' ); - } - } - } - - return element; - - } - - /** - * Registers a listener to postMessage events, this makes it - * possible to call all reveal.js API methods from another - * window. For example: - * - * revealWindow.postMessage( JSON.stringify({ - * method: 'slide', - * args: [ 2 ] - * }), '*' ); - */ - function setupPostMessage() { - - if( config.postMessage ) { - window.addEventListener( 'message', function ( event ) { - var data = event.data; - - // Make sure we're dealing with JSON - if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) { - data = JSON.parse( data ); - - // Check if the requested method can be found - if( data.method && typeof Reveal[data.method] === 'function' ) { - Reveal[data.method].apply( Reveal, data.args ); - } - } - }, false ); - } - - } - - /** - * Applies the configuration settings from the config - * object. May be called multiple times. - */ - function configure( options ) { - - var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length; - - dom.wrapper.classList.remove( config.transition ); - - // New config options may be passed when this method - // is invoked through the API after initialization - if( typeof options === 'object' ) extend( config, options ); - - // Force linear transition based on browser capabilities - if( features.transforms3d === false ) config.transition = 'linear'; - - dom.wrapper.classList.add( config.transition ); - - dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed ); - dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition ); - - dom.controls.style.display = config.controls ? 'block' : 'none'; - dom.progress.style.display = config.progress ? 'block' : 'none'; - - if( config.rtl ) { - dom.wrapper.classList.add( 'rtl' ); - } - else { - dom.wrapper.classList.remove( 'rtl' ); - } - - if( config.center ) { - dom.wrapper.classList.add( 'center' ); - } - else { - dom.wrapper.classList.remove( 'center' ); - } - - // Exit the paused mode if it was configured off - if( config.pause === false ) { - resume(); - } - - if( config.mouseWheel ) { - document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF - document.addEventListener( 'mousewheel', onDocumentMouseScroll, false ); - } - else { - document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF - document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false ); - } - - // Rolling 3D links - if( config.rollingLinks ) { - enableRollingLinks(); - } - else { - disableRollingLinks(); - } - - // Iframe link previews - if( config.previewLinks ) { - enablePreviewLinks(); - } - else { - disablePreviewLinks(); - enablePreviewLinks( '[data-preview-link]' ); - } - - // Remove existing auto-slide controls - if( autoSlidePlayer ) { - autoSlidePlayer.destroy(); - autoSlidePlayer = null; - } - - // Generate auto-slide controls if needed - if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) { - autoSlidePlayer = new Playback( dom.wrapper, function() { - return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 ); - } ); - - autoSlidePlayer.on( 'click', onAutoSlidePlayerClick ); - autoSlidePaused = false; - } - - // When fragments are turned off they should be visible - if( config.fragments === false ) { - toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) { - element.classList.add( 'visible' ); - element.classList.remove( 'current-fragment' ); - } ); - } - - sync(); - - } - - /** - * Binds all event listeners. - */ - function addEventListeners() { - - eventsAreBound = true; - - window.addEventListener( 'hashchange', onWindowHashChange, false ); - window.addEventListener( 'resize', onWindowResize, false ); - - if( config.touch ) { - dom.wrapper.addEventListener( 'touchstart', onTouchStart, false ); - dom.wrapper.addEventListener( 'touchmove', onTouchMove, false ); - dom.wrapper.addEventListener( 'touchend', onTouchEnd, false ); - - // Support pointer-style touch interaction as well - if( window.navigator.pointerEnabled ) { - // IE 11 uses un-prefixed version of pointer events - dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false ); - dom.wrapper.addEventListener( 'pointermove', onPointerMove, false ); - dom.wrapper.addEventListener( 'pointerup', onPointerUp, false ); - } - else if( window.navigator.msPointerEnabled ) { - // IE 10 uses prefixed version of pointer events - dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false ); - dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false ); - dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false ); - } - } - - if( config.keyboard ) { - document.addEventListener( 'keydown', onDocumentKeyDown, false ); - document.addEventListener( 'keypress', onDocumentKeyPress, false ); - } - - if( config.progress && dom.progress ) { - dom.progress.addEventListener( 'click', onProgressClicked, false ); - } - - if( config.focusBodyOnPageVisibilityChange ) { - var visibilityChange; - - if( 'hidden' in document ) { - visibilityChange = 'visibilitychange'; - } - else if( 'msHidden' in document ) { - visibilityChange = 'msvisibilitychange'; - } - else if( 'webkitHidden' in document ) { - visibilityChange = 'webkitvisibilitychange'; - } - - if( visibilityChange ) { - document.addEventListener( visibilityChange, onPageVisibilityChange, false ); - } - } - - // Listen to both touch and click events, in case the device - // supports both - var pointerEvents = [ 'touchstart', 'click' ]; - - // Only support touch for Android, fixes double navigations in - // stock browser - if( navigator.userAgent.match( /android/gi ) ) { - pointerEvents = [ 'touchstart' ]; - } - - pointerEvents.forEach( function( eventName ) { - dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } ); - dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } ); - dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } ); - dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } ); - dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } ); - dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } ); - } ); - - } - - /** - * Unbinds all event listeners. - */ - function removeEventListeners() { - - eventsAreBound = false; - - document.removeEventListener( 'keydown', onDocumentKeyDown, false ); - document.removeEventListener( 'keypress', onDocumentKeyPress, false ); - window.removeEventListener( 'hashchange', onWindowHashChange, false ); - window.removeEventListener( 'resize', onWindowResize, false ); - - dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false ); - dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false ); - dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false ); - - // IE11 - if( window.navigator.pointerEnabled ) { - dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false ); - dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false ); - dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false ); - } - // IE10 - else if( window.navigator.msPointerEnabled ) { - dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false ); - dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false ); - dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false ); - } - - if ( config.progress && dom.progress ) { - dom.progress.removeEventListener( 'click', onProgressClicked, false ); - } - - [ 'touchstart', 'click' ].forEach( function( eventName ) { - dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } ); - dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } ); - dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } ); - dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } ); - dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } ); - dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } ); - } ); - - } - - /** - * Extend object a with the properties of object b. - * If there's a conflict, object b takes precedence. - */ - function extend( a, b ) { - - for( var i in b ) { - a[ i ] = b[ i ]; - } - - } - - /** - * Converts the target object to an array. - */ - function toArray( o ) { - - return Array.prototype.slice.call( o ); - - } - - /** - * Utility for deserializing a value. - */ - function deserialize( value ) { - - if( typeof value === 'string' ) { - if( value === 'null' ) return null; - else if( value === 'true' ) return true; - else if( value === 'false' ) return false; - else if( value.match( /^\d+$/ ) ) return parseFloat( value ); - } - - return value; - - } - - /** - * Measures the distance in pixels between point a - * and point b. - * - * @param {Object} a point with x/y properties - * @param {Object} b point with x/y properties - */ - function distanceBetween( a, b ) { - - var dx = a.x - b.x, - dy = a.y - b.y; - - return Math.sqrt( dx*dx + dy*dy ); - - } - - /** - * Applies a CSS transform to the target element. - */ - function transformElement( element, transform ) { - - element.style.WebkitTransform = transform; - element.style.MozTransform = transform; - element.style.msTransform = transform; - element.style.transform = transform; - - } - - /** - * Applies CSS transforms to the slides container. The container - * is transformed from two separate sources: layout and the overview - * mode. - */ - function transformSlides( transforms ) { - - // Pick up new transforms from arguments - if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout; - if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview; - - // Apply the transforms to the slides container - if( slidesTransform.layout ) { - transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview ); - } - else { - transformElement( dom.slides, slidesTransform.overview ); - } - - } - - /** - * Injects the given CSS styles into the DOM. - */ - function injectStyleSheet( value ) { - - var tag = document.createElement( 'style' ); - tag.type = 'text/css'; - if( tag.styleSheet ) { - tag.styleSheet.cssText = value; - } - else { - tag.appendChild( document.createTextNode( value ) ); - } - document.getElementsByTagName( 'head' )[0].appendChild( tag ); - - } - - /** - * Converts various color input formats to an {r:0,g:0,b:0} object. - * - * @param {String} color The string representation of a color, - * the following formats are supported: - * - #000 - * - #000000 - * - rgb(0,0,0) - */ - function colorToRgb( color ) { - - var hex3 = color.match( /^#([0-9a-f]{3})$/i ); - if( hex3 && hex3[1] ) { - hex3 = hex3[1]; - return { - r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11, - g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11, - b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11 - }; - } - - var hex6 = color.match( /^#([0-9a-f]{6})$/i ); - if( hex6 && hex6[1] ) { - hex6 = hex6[1]; - return { - r: parseInt( hex6.substr( 0, 2 ), 16 ), - g: parseInt( hex6.substr( 2, 2 ), 16 ), - b: parseInt( hex6.substr( 4, 2 ), 16 ) - }; - } - - var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i ); - if( rgb ) { - return { - r: parseInt( rgb[1], 10 ), - g: parseInt( rgb[2], 10 ), - b: parseInt( rgb[3], 10 ) - }; - } - - var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i ); - if( rgba ) { - return { - r: parseInt( rgba[1], 10 ), - g: parseInt( rgba[2], 10 ), - b: parseInt( rgba[3], 10 ), - a: parseFloat( rgba[4] ) - }; - } - - return null; - - } - - /** - * Calculates brightness on a scale of 0-255. - * - * @param color See colorStringToRgb for supported formats. - */ - function colorBrightness( color ) { - - if( typeof color === 'string' ) color = colorToRgb( color ); - - if( color ) { - return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000; - } - - return null; - - } - - /** - * Retrieves the height of the given element by looking - * at the position and height of its immediate children. - */ - function getAbsoluteHeight( element ) { - - var height = 0; - - if( element ) { - var absoluteChildren = 0; - - toArray( element.childNodes ).forEach( function( child ) { - - if( typeof child.offsetTop === 'number' && child.style ) { - // Count # of abs children - if( window.getComputedStyle( child ).position === 'absolute' ) { - absoluteChildren += 1; - } - - height = Math.max( height, child.offsetTop + child.offsetHeight ); - } - - } ); - - // If there are no absolute children, use offsetHeight - if( absoluteChildren === 0 ) { - height = element.offsetHeight; - } - - } - - return height; - - } - - /** - * Returns the remaining height within the parent of the - * target element. - * - * remaining height = [ configured parent height ] - [ current parent height ] - */ - function getRemainingHeight( element, height ) { - - height = height || 0; - - if( element ) { - var newHeight, oldHeight = element.style.height; - - // Change the .stretch element height to 0 in order find the height of all - // the other elements - element.style.height = '0px'; - newHeight = height - element.parentNode.offsetHeight; - - // Restore the old height, just in case - element.style.height = oldHeight + 'px'; - - return newHeight; - } - - return height; - - } - - /** - * Checks if this instance is being used to print a PDF. - */ - function isPrintingPDF() { - - return ( /print-pdf/gi ).test( window.location.search ); - - } - - /** - * Hides the address bar if we're on a mobile device. - */ - function hideAddressBar() { - - if( config.hideAddressBar && isMobileDevice ) { - // Events that should trigger the address bar to hide - window.addEventListener( 'load', removeAddressBar, false ); - window.addEventListener( 'orientationchange', removeAddressBar, false ); - } - - } - - /** - * Causes the address bar to hide on mobile devices, - * more vertical space ftw. - */ - function removeAddressBar() { - - setTimeout( function() { - window.scrollTo( 0, 1 ); - }, 10 ); - - } - - /** - * Dispatches an event of the specified type from the - * reveal DOM element. - */ - function dispatchEvent( type, args ) { - - var event = document.createEvent( 'HTMLEvents', 1, 2 ); - event.initEvent( type, true, true ); - extend( event, args ); - dom.wrapper.dispatchEvent( event ); - - // If we're in an iframe, post each reveal.js event to the - // parent window. Used by the notes plugin - if( config.postMessageEvents && window.parent !== window.self ) { - window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' ); - } - - } - - /** - * Wrap all links in 3D goodness. - */ - function enableRollingLinks() { - - if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) { - var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' ); - - for( var i = 0, len = anchors.length; i < len; i++ ) { - var anchor = anchors[i]; - - if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) { - var span = document.createElement('span'); - span.setAttribute('data-title', anchor.text); - span.innerHTML = anchor.innerHTML; - - anchor.classList.add( 'roll' ); - anchor.innerHTML = ''; - anchor.appendChild(span); - } - } - } - - } - - /** - * Unwrap all 3D links. - */ - function disableRollingLinks() { - - var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' ); - - for( var i = 0, len = anchors.length; i < len; i++ ) { - var anchor = anchors[i]; - var span = anchor.querySelector( 'span' ); - - if( span ) { - anchor.classList.remove( 'roll' ); - anchor.innerHTML = span.innerHTML; - } - } - - } - - /** - * Bind preview frame links. - */ - function enablePreviewLinks( selector ) { - - var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) ); - - anchors.forEach( function( element ) { - if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { - element.addEventListener( 'click', onPreviewLinkClicked, false ); - } - } ); - - } - - /** - * Unbind preview frame links. - */ - function disablePreviewLinks() { - - var anchors = toArray( document.querySelectorAll( 'a' ) ); - - anchors.forEach( function( element ) { - if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { - element.removeEventListener( 'click', onPreviewLinkClicked, false ); - } - } ); - - } - - /** - * Opens a preview window for the target URL. - */ - function showPreview( url ) { - - closeOverlay(); - - dom.overlay = document.createElement( 'div' ); - dom.overlay.classList.add( 'overlay' ); - dom.overlay.classList.add( 'overlay-preview' ); - dom.wrapper.appendChild( dom.overlay ); - - dom.overlay.innerHTML = [ - '
', - '', - '', - '
', - '
', - '
', - '', - '
' - ].join(''); - - dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) { - dom.overlay.classList.add( 'loaded' ); - }, false ); - - dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { - closeOverlay(); - event.preventDefault(); - }, false ); - - dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) { - closeOverlay(); - }, false ); - - setTimeout( function() { - dom.overlay.classList.add( 'visible' ); - }, 1 ); - - } - - /** - * Opens a overlay window with help material. - */ - function showHelp() { - - if( config.help ) { - - closeOverlay(); - - dom.overlay = document.createElement( 'div' ); - dom.overlay.classList.add( 'overlay' ); - dom.overlay.classList.add( 'overlay-help' ); - dom.wrapper.appendChild( dom.overlay ); - - var html = '

Keyboard Shortcuts


'; - - html += ''; - for( var key in keyboardShortcuts ) { - html += ''; - } - - html += '
KEYACTION
' + key + '' + keyboardShortcuts[ key ] + '
'; - - dom.overlay.innerHTML = [ - '
', - '', - '
', - '
', - '
'+ html +'
', - '
' - ].join(''); - - dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { - closeOverlay(); - event.preventDefault(); - }, false ); - - setTimeout( function() { - dom.overlay.classList.add( 'visible' ); - }, 1 ); - - } - - } - - /** - * Closes any currently open overlay. - */ - function closeOverlay() { - - if( dom.overlay ) { - dom.overlay.parentNode.removeChild( dom.overlay ); - dom.overlay = null; - } - - } - - /** - * Applies JavaScript-controlled layout rules to the - * presentation. - */ - function layout() { - - if( dom.wrapper && !isPrintingPDF() ) { - - var size = getComputedSlideSize(); - - var slidePadding = 20; // TODO Dig this out of DOM - - // Layout the contents of the slides - layoutSlideContents( config.width, config.height, slidePadding ); - - dom.slides.style.width = size.width + 'px'; - dom.slides.style.height = size.height + 'px'; - - // Determine scale of content to fit within available space - scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); - - // Respect max/min scale settings - scale = Math.max( scale, config.minScale ); - scale = Math.min( scale, config.maxScale ); - - // Don't apply any scaling styles if scale is 1 - if( scale === 1 ) { - dom.slides.style.zoom = ''; - dom.slides.style.left = ''; - dom.slides.style.top = ''; - dom.slides.style.bottom = ''; - dom.slides.style.right = ''; - transformSlides( { layout: '' } ); - } - else { - // Prefer zooming in desktop Chrome so that content remains crisp - if( !isMobileDevice && /chrome/i.test( navigator.userAgent ) && typeof dom.slides.style.zoom !== 'undefined' ) { - dom.slides.style.zoom = scale; - transformSlides( { layout: '' } ); - } - // Apply scale transform as a fallback - else { - dom.slides.style.left = '50%'; - dom.slides.style.top = '50%'; - dom.slides.style.bottom = 'auto'; - dom.slides.style.right = 'auto'; - transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } ); - } - } - - // Select all slides, vertical and horizontal - var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ); - - for( var i = 0, len = slides.length; i < len; i++ ) { - var slide = slides[ i ]; - - // Don't bother updating invisible slides - if( slide.style.display === 'none' ) { - continue; - } - - if( config.center || slide.classList.contains( 'center' ) ) { - // Vertical stacks are not centred since their section - // children will be - if( slide.classList.contains( 'stack' ) ) { - slide.style.top = 0; - } - else { - slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px'; - } - } - else { - slide.style.top = ''; - } - - } - - updateProgress(); - updateParallax(); - - } - - } - - /** - * Applies layout logic to the contents of all slides in - * the presentation. - */ - function layoutSlideContents( width, height, padding ) { - - // Handle sizing of elements with the 'stretch' class - toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) { - - // Determine how much vertical space we can use - var remainingHeight = getRemainingHeight( element, height ); - - // Consider the aspect ratio of media elements - if( /(img|video)/gi.test( element.nodeName ) ) { - var nw = element.naturalWidth || element.videoWidth, - nh = element.naturalHeight || element.videoHeight; - - var es = Math.min( width / nw, remainingHeight / nh ); - - element.style.width = ( nw * es ) + 'px'; - element.style.height = ( nh * es ) + 'px'; - - } - else { - element.style.width = width + 'px'; - element.style.height = remainingHeight + 'px'; - } - - } ); - - } - - /** - * Calculates the computed pixel size of our slides. These - * values are based on the width and height configuration - * options. - */ - function getComputedSlideSize( presentationWidth, presentationHeight ) { - - var size = { - // Slide size - width: config.width, - height: config.height, - - // Presentation size - presentationWidth: presentationWidth || dom.wrapper.offsetWidth, - presentationHeight: presentationHeight || dom.wrapper.offsetHeight - }; - - // Reduce available space by margin - size.presentationWidth -= ( size.presentationWidth * config.margin ); - size.presentationHeight -= ( size.presentationHeight * config.margin ); - - // Slide width may be a percentage of available width - if( typeof size.width === 'string' && /%$/.test( size.width ) ) { - size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth; - } - - // Slide height may be a percentage of available height - if( typeof size.height === 'string' && /%$/.test( size.height ) ) { - size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight; - } - - return size; - - } - - /** - * Stores the vertical index of a stack so that the same - * vertical slide can be selected when navigating to and - * from the stack. - * - * @param {HTMLElement} stack The vertical stack element - * @param {int} v Index to memorize - */ - function setPreviousVerticalIndex( stack, v ) { - - if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) { - stack.setAttribute( 'data-previous-indexv', v || 0 ); - } - - } - - /** - * Retrieves the vertical index which was stored using - * #setPreviousVerticalIndex() or 0 if no previous index - * exists. - * - * @param {HTMLElement} stack The vertical stack element - */ - function getPreviousVerticalIndex( stack ) { - - if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) { - // Prefer manually defined start-indexv - var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv'; - - return parseInt( stack.getAttribute( attributeName ) || 0, 10 ); - } - - return 0; - - } - - /** - * Displays the overview of slides (quick nav) by scaling - * down and arranging all slide elements. - */ - function activateOverview() { - - // Only proceed if enabled in config - if( config.overview && !isOverview() ) { - - overview = true; - - dom.wrapper.classList.add( 'overview' ); - dom.wrapper.classList.remove( 'overview-deactivating' ); - - if( features.overviewTransitions ) { - setTimeout( function() { - dom.wrapper.classList.add( 'overview-animated' ); - }, 1 ); - } - - // Don't auto-slide while in overview mode - cancelAutoSlide(); - - // Move the backgrounds element into the slide container to - // that the same scaling is applied - dom.slides.appendChild( dom.background ); - - // Clicking on an overview slide navigates to it - toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { - if( !slide.classList.contains( 'stack' ) ) { - slide.addEventListener( 'click', onOverviewSlideClicked, true ); - } - } ); - - updateSlidesVisibility(); - layoutOverview(); - updateOverview(); - - layout(); - - // Notify observers of the overview showing - dispatchEvent( 'overviewshown', { - 'indexh': indexh, - 'indexv': indexv, - 'currentSlide': currentSlide - } ); - - } - - } - - /** - * Uses CSS transforms to position all slides in a grid for - * display inside of the overview mode. - */ - function layoutOverview() { - - var margin = 70; - var slideWidth = config.width + margin, - slideHeight = config.height + margin; - - // Reverse in RTL mode - if( config.rtl ) { - slideWidth = -slideWidth; - } - - // Layout slides - toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { - hslide.setAttribute( 'data-index-h', h ); - transformElement( hslide, 'translate3d(' + ( h * slideWidth ) + 'px, 0, 0)' ); - - if( hslide.classList.contains( 'stack' ) ) { - - toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { - vslide.setAttribute( 'data-index-h', h ); - vslide.setAttribute( 'data-index-v', v ); - - transformElement( vslide, 'translate3d(0, ' + ( v * slideHeight ) + 'px, 0)' ); - } ); - - } - } ); - - // Layout slide backgrounds - toArray( dom.background.childNodes ).forEach( function( hbackground, h ) { - transformElement( hbackground, 'translate3d(' + ( h * slideWidth ) + 'px, 0, 0)' ); - - toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) { - transformElement( vbackground, 'translate3d(0, ' + ( v * slideHeight ) + 'px, 0)' ); - } ); - } ); - - } - - /** - * Moves the overview viewport to the current slides. - * Called each time the current slide changes. - */ - function updateOverview() { - - var margin = 70; - var slideWidth = config.width + margin, - slideHeight = config.height + margin; - - // Reverse in RTL mode - if( config.rtl ) { - slideWidth = -slideWidth; - } - - transformSlides( { - overview: [ - 'translateX('+ ( -indexh * slideWidth ) +'px)', - 'translateY('+ ( -indexv * slideHeight ) +'px)', - 'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)' - ].join( ' ' ) - } ); - - } - - /** - * Exits the slide overview and enters the currently - * active slide. - */ - function deactivateOverview() { - - // Only proceed if enabled in config - if( config.overview ) { - - overview = false; - - dom.wrapper.classList.remove( 'overview' ); - dom.wrapper.classList.remove( 'overview-animated' ); - - // Temporarily add a class so that transitions can do different things - // depending on whether they are exiting/entering overview, or just - // moving from slide to slide - dom.wrapper.classList.add( 'overview-deactivating' ); - - setTimeout( function () { - dom.wrapper.classList.remove( 'overview-deactivating' ); - }, 1 ); - - // Move the background element back out - dom.wrapper.appendChild( dom.background ); - - // Clean up changes made to slides - toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { - transformElement( slide, '' ); - - slide.removeEventListener( 'click', onOverviewSlideClicked, true ); - } ); - - // Clean up changes made to backgrounds - toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) { - transformElement( background, '' ); - } ); - - transformSlides( { overview: '' } ); - - slide( indexh, indexv ); - - layout(); - - cueAutoSlide(); - - // Notify observers of the overview hiding - dispatchEvent( 'overviewhidden', { - 'indexh': indexh, - 'indexv': indexv, - 'currentSlide': currentSlide - } ); - - } - } - - /** - * Toggles the slide overview mode on and off. - * - * @param {Boolean} override Optional flag which overrides the - * toggle logic and forcibly sets the desired state. True means - * overview is open, false means it's closed. - */ - function toggleOverview( override ) { - - if( typeof override === 'boolean' ) { - override ? activateOverview() : deactivateOverview(); - } - else { - isOverview() ? deactivateOverview() : activateOverview(); - } - - } - - /** - * Checks if the overview is currently active. - * - * @return {Boolean} true if the overview is active, - * false otherwise - */ - function isOverview() { - - return overview; - - } - - /** - * Checks if the current or specified slide is vertical - * (nested within another slide). - * - * @param {HTMLElement} slide [optional] The slide to check - * orientation of - */ - function isVerticalSlide( slide ) { - - // Prefer slide argument, otherwise use current slide - slide = slide ? slide : currentSlide; - - return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i ); - - } - - /** - * Handling the fullscreen functionality via the fullscreen API - * - * @see http://fullscreen.spec.whatwg.org/ - * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode - */ - function enterFullscreen() { - - var element = document.body; - - // Check which implementation is available - var requestMethod = element.requestFullScreen || - element.webkitRequestFullscreen || - element.webkitRequestFullScreen || - element.mozRequestFullScreen || - element.msRequestFullscreen; - - if( requestMethod ) { - requestMethod.apply( element ); - } - - } - - /** - * Enters the paused mode which fades everything on screen to - * black. - */ - function pause() { - - if( config.pause ) { - var wasPaused = dom.wrapper.classList.contains( 'paused' ); - - cancelAutoSlide(); - dom.wrapper.classList.add( 'paused' ); - - if( wasPaused === false ) { - dispatchEvent( 'paused' ); - } - } - - } - - /** - * Exits from the paused mode. - */ - function resume() { - - var wasPaused = dom.wrapper.classList.contains( 'paused' ); - dom.wrapper.classList.remove( 'paused' ); - - cueAutoSlide(); - - if( wasPaused ) { - dispatchEvent( 'resumed' ); - } - - } - - /** - * Toggles the paused mode on and off. - */ - function togglePause( override ) { - - if( typeof override === 'boolean' ) { - override ? pause() : resume(); - } - else { - isPaused() ? resume() : pause(); - } - - } - - /** - * Checks if we are currently in the paused mode. - */ - function isPaused() { - - return dom.wrapper.classList.contains( 'paused' ); - - } - - /** - * Toggles the auto slide mode on and off. - * - * @param {Boolean} override Optional flag which sets the desired state. - * True means autoplay starts, false means it stops. - */ - - function toggleAutoSlide( override ) { - - if( typeof override === 'boolean' ) { - override ? resumeAutoSlide() : pauseAutoSlide(); - } - - else { - autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide(); - } - - } - - /** - * Checks if the auto slide mode is currently on. - */ - function isAutoSliding() { - - return !!( autoSlide && !autoSlidePaused ); - - } - - /** - * Steps from the current point in the presentation to the - * slide which matches the specified horizontal and vertical - * indices. - * - * @param {int} h Horizontal index of the target slide - * @param {int} v Vertical index of the target slide - * @param {int} f Optional index of a fragment within the - * target slide to activate - * @param {int} o Optional origin for use in multimaster environments - */ - function slide( h, v, f, o ) { - - // Remember where we were at before - previousSlide = currentSlide; - - // Query all horizontal slides in the deck - var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); - - // If no vertical index is specified and the upcoming slide is a - // stack, resume at its previous vertical index - if( v === undefined && !isOverview() ) { - v = getPreviousVerticalIndex( horizontalSlides[ h ] ); - } - - // If we were on a vertical stack, remember what vertical index - // it was on so we can resume at the same position when returning - if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) { - setPreviousVerticalIndex( previousSlide.parentNode, indexv ); - } - - // Remember the state before this slide - var stateBefore = state.concat(); - - // Reset the state array - state.length = 0; - - var indexhBefore = indexh || 0, - indexvBefore = indexv || 0; - - // Activate and transition to the new slide - indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h ); - indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v ); - - // Update the visibility of slides now that the indices have changed - updateSlidesVisibility(); - - layout(); - - // Apply the new state - stateLoop: for( var i = 0, len = state.length; i < len; i++ ) { - // Check if this state existed on the previous slide. If it - // did, we will avoid adding it repeatedly - for( var j = 0; j < stateBefore.length; j++ ) { - if( stateBefore[j] === state[i] ) { - stateBefore.splice( j, 1 ); - continue stateLoop; - } - } - - document.documentElement.classList.add( state[i] ); - - // Dispatch custom event matching the state's name - dispatchEvent( state[i] ); - } - - // Clean up the remains of the previous state - while( stateBefore.length ) { - document.documentElement.classList.remove( stateBefore.pop() ); - } - - // Update the overview if it's currently active - if( isOverview() ) { - updateOverview(); - } - - // Find the current horizontal slide and any possible vertical slides - // within it - var currentHorizontalSlide = horizontalSlides[ indexh ], - currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' ); - - // Store references to the previous and current slides - currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide; - - // Show fragment, if specified - if( typeof f !== 'undefined' ) { - navigateFragment( f ); - } - - // Dispatch an event if the slide changed - var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore ); - if( slideChanged ) { - dispatchEvent( 'slidechanged', { - 'indexh': indexh, - 'indexv': indexv, - 'previousSlide': previousSlide, - 'currentSlide': currentSlide, - 'origin': o - } ); - } - else { - // Ensure that the previous slide is never the same as the current - previousSlide = null; - } - - // Solves an edge case where the previous slide maintains the - // 'present' class when navigating between adjacent vertical - // stacks - if( previousSlide ) { - previousSlide.classList.remove( 'present' ); - previousSlide.setAttribute( 'aria-hidden', 'true' ); - - // Reset all slides upon navigate to home - // Issue: #285 - if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) { - // Launch async task - setTimeout( function () { - var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i; - for( i in slides ) { - if( slides[i] ) { - // Reset stack - setPreviousVerticalIndex( slides[i], 0 ); - } - } - }, 0 ); - } - } - - // Handle embedded content - if( slideChanged || !previousSlide ) { - stopEmbeddedContent( previousSlide ); - startEmbeddedContent( currentSlide ); - } - - // Announce the current slide contents, for screen readers - dom.statusDiv.textContent = currentSlide.textContent; - - updateControls(); - updateProgress(); - updateBackground(); - updateParallax(); - updateSlideNumber(); - - // Update the URL hash - writeURL(); - - cueAutoSlide(); - - } - - /** - * Syncs the presentation with the current DOM. Useful - * when new slides or control elements are added or when - * the configuration has changed. - */ - function sync() { - - // Subscribe to input - removeEventListeners(); - addEventListeners(); - - // Force a layout to make sure the current config is accounted for - layout(); - - // Reflect the current autoSlide value - autoSlide = config.autoSlide; - - // Start auto-sliding if it's enabled - cueAutoSlide(); - - // Re-create the slide backgrounds - createBackgrounds(); - - // Write the current hash to the URL - writeURL(); - - sortAllFragments(); - - updateControls(); - updateProgress(); - updateBackground( true ); - updateSlideNumber(); - updateSlidesVisibility(); - - formatEmbeddedContent(); - startEmbeddedContent( currentSlide ); - - if( isOverview() ) { - layoutOverview(); - } - - } - - /** - * Resets all vertical slides so that only the first - * is visible. - */ - function resetVerticalSlides() { - - var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); - horizontalSlides.forEach( function( horizontalSlide ) { - - var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); - verticalSlides.forEach( function( verticalSlide, y ) { - - if( y > 0 ) { - verticalSlide.classList.remove( 'present' ); - verticalSlide.classList.remove( 'past' ); - verticalSlide.classList.add( 'future' ); - verticalSlide.setAttribute( 'aria-hidden', 'true' ); - } - - } ); - - } ); - - } - - /** - * Sorts and formats all of fragments in the - * presentation. - */ - function sortAllFragments() { - - var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); - horizontalSlides.forEach( function( horizontalSlide ) { - - var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); - verticalSlides.forEach( function( verticalSlide, y ) { - - sortFragments( verticalSlide.querySelectorAll( '.fragment' ) ); - - } ); - - if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) ); - - } ); - - } - - /** - * Updates one dimension of slides by showing the slide - * with the specified index. - * - * @param {String} selector A CSS selector that will fetch - * the group of slides we are working with - * @param {Number} index The index of the slide that should be - * shown - * - * @return {Number} The index of the slide that is now shown, - * might differ from the passed in index if it was out of - * bounds. - */ - function updateSlides( selector, index ) { - - // Select all slides and convert the NodeList result to - // an array - var slides = toArray( dom.wrapper.querySelectorAll( selector ) ), - slidesLength = slides.length; - - var printMode = isPrintingPDF(); - - if( slidesLength ) { - - // Should the index loop? - if( config.loop ) { - index %= slidesLength; - - if( index < 0 ) { - index = slidesLength + index; - } - } - - // Enforce max and minimum index bounds - index = Math.max( Math.min( index, slidesLength - 1 ), 0 ); - - for( var i = 0; i < slidesLength; i++ ) { - var element = slides[i]; - - var reverse = config.rtl && !isVerticalSlide( element ); - - element.classList.remove( 'past' ); - element.classList.remove( 'present' ); - element.classList.remove( 'future' ); - - // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute - element.setAttribute( 'hidden', '' ); - element.setAttribute( 'aria-hidden', 'true' ); - - // If this element contains vertical slides - if( element.querySelector( 'section' ) ) { - element.classList.add( 'stack' ); - } - - // If we're printing static slides, all slides are "present" - if( printMode ) { - element.classList.add( 'present' ); - continue; - } - - if( i < index ) { - // Any element previous to index is given the 'past' class - element.classList.add( reverse ? 'future' : 'past' ); - - if( config.fragments ) { - var pastFragments = toArray( element.querySelectorAll( '.fragment' ) ); - - // Show all fragments on prior slides - while( pastFragments.length ) { - var pastFragment = pastFragments.pop(); - pastFragment.classList.add( 'visible' ); - pastFragment.classList.remove( 'current-fragment' ); - } - } - } - else if( i > index ) { - // Any element subsequent to index is given the 'future' class - element.classList.add( reverse ? 'past' : 'future' ); - - if( config.fragments ) { - var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) ); - - // No fragments in future slides should be visible ahead of time - while( futureFragments.length ) { - var futureFragment = futureFragments.pop(); - futureFragment.classList.remove( 'visible' ); - futureFragment.classList.remove( 'current-fragment' ); - } - } - } - } - - // Mark the current slide as present - slides[index].classList.add( 'present' ); - slides[index].removeAttribute( 'hidden' ); - slides[index].removeAttribute( 'aria-hidden' ); - - // If this slide has a state associated with it, add it - // onto the current state of the deck - var slideState = slides[index].getAttribute( 'data-state' ); - if( slideState ) { - state = state.concat( slideState.split( ' ' ) ); - } - - } - else { - // Since there are no slides we can't be anywhere beyond the - // zeroth index - index = 0; - } - - return index; - - } - - /** - * Optimization method; hide all slides that are far away - * from the present slide. - */ - function updateSlidesVisibility() { - - // Select all slides and convert the NodeList result to - // an array - var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ), - horizontalSlidesLength = horizontalSlides.length, - distanceX, - distanceY; - - if( horizontalSlidesLength && typeof indexh !== 'undefined' ) { - - // The number of steps away from the present slide that will - // be visible - var viewDistance = isOverview() ? 10 : config.viewDistance; - - // Limit view distance on weaker devices - if( isMobileDevice ) { - viewDistance = isOverview() ? 6 : 2; - } - - // All slides need to be visible when exporting to PDF - if( isPrintingPDF() ) { - viewDistance = Number.MAX_VALUE; - } - - for( var x = 0; x < horizontalSlidesLength; x++ ) { - var horizontalSlide = horizontalSlides[x]; - - var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ), - verticalSlidesLength = verticalSlides.length; - - // Determine how far away this slide is from the present - distanceX = Math.abs( ( indexh || 0 ) - x ) || 0; - - // If the presentation is looped, distance should measure - // 1 between the first and last slides - if( config.loop ) { - distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0; - } - - // Show the horizontal slide if it's within the view distance - if( distanceX < viewDistance ) { - showSlide( horizontalSlide ); - } - else { - hideSlide( horizontalSlide ); - } - - if( verticalSlidesLength ) { - - var oy = getPreviousVerticalIndex( horizontalSlide ); - - for( var y = 0; y < verticalSlidesLength; y++ ) { - var verticalSlide = verticalSlides[y]; - - distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy ); - - if( distanceX + distanceY < viewDistance ) { - showSlide( verticalSlide ); - } - else { - hideSlide( verticalSlide ); - } - } - - } - } - - } - - } - - /** - * Updates the progress bar to reflect the current slide. - */ - function updateProgress() { - - // Update progress if enabled - if( config.progress && dom.progressbar ) { - - dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px'; - - } - - } - - /** - * Updates the slide number div to reflect the current slide. - * - * Slide number format can be defined as a string using the - * following variables: - * h: current slide's horizontal index - * v: current slide's vertical index - * c: current slide index (flattened) - * t: total number of slides (flattened) - */ - function updateSlideNumber() { - - // Update slide number if enabled - if( config.slideNumber && dom.slideNumber) { - - // Default to only showing the current slide number - var format = 'c'; - - // Check if a custom slide number format is available - if( typeof config.slideNumber === 'string' ) { - format = config.slideNumber; - } - - dom.slideNumber.innerHTML = format.replace( /h/g, indexh ) - .replace( /v/g, indexv ) - .replace( /c/g, getSlidePastCount() + 1 ) - .replace( /t/g, getTotalSlides() ); - } - - } - - /** - * Updates the state of all control/navigation arrows. - */ - function updateControls() { - - var routes = availableRoutes(); - var fragments = availableFragments(); - - // Remove the 'enabled' class from all directions - dom.controlsLeft.concat( dom.controlsRight ) - .concat( dom.controlsUp ) - .concat( dom.controlsDown ) - .concat( dom.controlsPrev ) - .concat( dom.controlsNext ).forEach( function( node ) { - node.classList.remove( 'enabled' ); - node.classList.remove( 'fragmented' ); - } ); - - // Add the 'enabled' class to the available routes - if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } ); - if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } ); - if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } ); - if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } ); - - // Prev/next buttons - if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } ); - if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } ); - - // Highlight fragment directions - if( currentSlide ) { - - // Always apply fragment decorator to prev/next buttons - if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); - if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); - - // Apply fragment decorators to directional buttons based on - // what slide axis they are in - if( isVerticalSlide( currentSlide ) ) { - if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); - if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); - } - else { - if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); - if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); - } - - } - - } - - /** - * Updates the background elements to reflect the current - * slide. - * - * @param {Boolean} includeAll If true, the backgrounds of - * all vertical slides (not just the present) will be updated. - */ - function updateBackground( includeAll ) { - - var currentBackground = null; - - // Reverse past/future classes when in RTL mode - var horizontalPast = config.rtl ? 'future' : 'past', - horizontalFuture = config.rtl ? 'past' : 'future'; - - // Update the classes of all backgrounds to match the - // states of their slides (past/present/future) - toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) { - - backgroundh.classList.remove( 'past' ); - backgroundh.classList.remove( 'present' ); - backgroundh.classList.remove( 'future' ); - - if( h < indexh ) { - backgroundh.classList.add( horizontalPast ); - } - else if ( h > indexh ) { - backgroundh.classList.add( horizontalFuture ); - } - else { - backgroundh.classList.add( 'present' ); - - // Store a reference to the current background element - currentBackground = backgroundh; - } - - if( includeAll || h === indexh ) { - toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) { - - backgroundv.classList.remove( 'past' ); - backgroundv.classList.remove( 'present' ); - backgroundv.classList.remove( 'future' ); - - if( v < indexv ) { - backgroundv.classList.add( 'past' ); - } - else if ( v > indexv ) { - backgroundv.classList.add( 'future' ); - } - else { - backgroundv.classList.add( 'present' ); - - // Only if this is the present horizontal and vertical slide - if( h === indexh ) currentBackground = backgroundv; - } - - } ); - } - - } ); - - // Stop any currently playing video background - if( previousBackground ) { - - var previousVideo = previousBackground.querySelector( 'video' ); - if( previousVideo ) previousVideo.pause(); - - } - - if( currentBackground ) { - - // Start video playback - var currentVideo = currentBackground.querySelector( 'video' ); - if( currentVideo ) { - currentVideo.currentTime = 0; - currentVideo.play(); - } - - var backgroundImageURL = currentBackground.style.backgroundImage || ''; - - // Restart GIFs (doesn't work in Firefox) - if( /\.gif/i.test( backgroundImageURL ) ) { - currentBackground.style.backgroundImage = ''; - window.getComputedStyle( currentBackground ).opacity; - currentBackground.style.backgroundImage = backgroundImageURL; - } - - // Don't transition between identical backgrounds. This - // prevents unwanted flicker. - var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null; - var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); - if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) { - dom.background.classList.add( 'no-transition' ); - } - - previousBackground = currentBackground; - - } - - // If there's a background brightness flag for this slide, - // bubble it to the .reveal container - if( currentSlide ) { - [ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) { - if( currentSlide.classList.contains( classToBubble ) ) { - dom.wrapper.classList.add( classToBubble ); - } - else { - dom.wrapper.classList.remove( classToBubble ); - } - } ); - } - - // Allow the first background to apply without transition - setTimeout( function() { - dom.background.classList.remove( 'no-transition' ); - }, 1 ); - - } - - /** - * Updates the position of the parallax background based - * on the current slide index. - */ - function updateParallax() { - - if( config.parallaxBackgroundImage ) { - - var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), - verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); - - var backgroundSize = dom.background.style.backgroundSize.split( ' ' ), - backgroundWidth, backgroundHeight; - - if( backgroundSize.length === 1 ) { - backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 ); - } - else { - backgroundWidth = parseInt( backgroundSize[0], 10 ); - backgroundHeight = parseInt( backgroundSize[1], 10 ); - } - - var slideWidth = dom.background.offsetWidth, - horizontalSlideCount = horizontalSlides.length, - horizontalOffsetMultiplier, - horizontalOffset; - - if( typeof config.parallaxBackgroundHorizontal === 'number' ) { - horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal; - } - else { - horizontalOffsetMultiplier = ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ); - } - - horizontalOffset = horizontalOffsetMultiplier * indexh * -1; - - var slideHeight = dom.background.offsetHeight, - verticalSlideCount = verticalSlides.length, - verticalOffsetMultiplier, - verticalOffset; - - if( typeof config.parallaxBackgroundVertical === 'number' ) { - verticalOffsetMultiplier = config.parallaxBackgroundVertical; - } - else { - verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ); - } - - verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0; - - dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px'; - - } - - } - - /** - * Called when the given slide is within the configured view - * distance. Shows the slide element and loads any content - * that is set to load lazily (data-src). - */ - function showSlide( slide ) { - - // Show the slide element - slide.style.display = 'block'; - - // Media elements with data-src attributes - toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) { - element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); - element.removeAttribute( 'data-src' ); - } ); - - // Media elements with children - toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) { - var sources = 0; - - toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) { - source.setAttribute( 'src', source.getAttribute( 'data-src' ) ); - source.removeAttribute( 'data-src' ); - sources += 1; - } ); - - // If we rewrote sources for this video/audio element, we need - // to manually tell it to load from its new origin - if( sources > 0 ) { - media.load(); - } - } ); - - - // Show the corresponding background element - var indices = getIndices( slide ); - var background = getSlideBackground( indices.h, indices.v ); - if( background ) { - background.style.display = 'block'; - - // If the background contains media, load it - if( background.hasAttribute( 'data-loaded' ) === false ) { - background.setAttribute( 'data-loaded', 'true' ); - - var backgroundImage = slide.getAttribute( 'data-background-image' ), - backgroundVideo = slide.getAttribute( 'data-background-video' ), - backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ), - backgroundIframe = slide.getAttribute( 'data-background-iframe' ); - - // Images - if( backgroundImage ) { - background.style.backgroundImage = 'url('+ backgroundImage +')'; - } - // Videos - else if ( backgroundVideo && !isSpeakerNotes() ) { - var video = document.createElement( 'video' ); - - if( backgroundVideoLoop ) { - video.setAttribute( 'loop', '' ); - } - - // Support comma separated lists of video sources - backgroundVideo.split( ',' ).forEach( function( source ) { - video.innerHTML += ''; - } ); - - background.appendChild( video ); - } - // Iframes - else if( backgroundIframe ) { - var iframe = document.createElement( 'iframe' ); - iframe.setAttribute( 'src', backgroundIframe ); - iframe.style.width = '100%'; - iframe.style.height = '100%'; - iframe.style.maxHeight = '100%'; - iframe.style.maxWidth = '100%'; - - background.appendChild( iframe ); - } - } - } - - } - - /** - * Called when the given slide is moved outside of the - * configured view distance. - */ - function hideSlide( slide ) { - - // Hide the slide element - slide.style.display = 'none'; - - // Hide the corresponding background element - var indices = getIndices( slide ); - var background = getSlideBackground( indices.h, indices.v ); - if( background ) { - background.style.display = 'none'; - } - - } - - /** - * Determine what available routes there are for navigation. - * - * @return {Object} containing four booleans: left/right/up/down - */ - function availableRoutes() { - - var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), - verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); - - var routes = { - left: indexh > 0 || config.loop, - right: indexh < horizontalSlides.length - 1 || config.loop, - up: indexv > 0, - down: indexv < verticalSlides.length - 1 - }; - - // reverse horizontal controls for rtl - if( config.rtl ) { - var left = routes.left; - routes.left = routes.right; - routes.right = left; - } - - return routes; - - } - - /** - * Returns an object describing the available fragment - * directions. - * - * @return {Object} two boolean properties: prev/next - */ - function availableFragments() { - - if( currentSlide && config.fragments ) { - var fragments = currentSlide.querySelectorAll( '.fragment' ); - var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' ); - - return { - prev: fragments.length - hiddenFragments.length > 0, - next: !!hiddenFragments.length - }; - } - else { - return { prev: false, next: false }; - } - - } - - /** - * Enforces origin-specific format rules for embedded media. - */ - function formatEmbeddedContent() { - - var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) { - toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) { - var src = el.getAttribute( sourceAttribute ); - if( src && src.indexOf( param ) === -1 ) { - el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param ); - } - }); - }; - - // YouTube frames must include "?enablejsapi=1" - _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' ); - _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); - - // Vimeo frames must include "?api=1" - _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' ); - _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' ); - - } - - /** - * Start playback of any embedded content inside of - * the targeted slide. - */ - function startEmbeddedContent( slide ) { - - if( slide && !isSpeakerNotes() ) { - // Restart GIFs - toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) { - // Setting the same unchanged source like this was confirmed - // to work in Chrome, FF & Safari - el.setAttribute( 'src', el.getAttribute( 'src' ) ); - } ); - - // HTML5 media elements - toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { - if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) { - el.play(); - } - } ); - - // Normal iframes - toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) { - startEmbeddedIframe( { target: el } ); - } ); - - // Lazy loading iframes - toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { - if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) { - el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes - el.addEventListener( 'load', startEmbeddedIframe ); - el.setAttribute( 'src', el.getAttribute( 'data-src' ) ); - } - } ); - } - - } - - /** - * "Starts" the content of an embedded iframe using the - * postmessage API. - */ - function startEmbeddedIframe( event ) { - - var iframe = event.target; - - // YouTube postMessage API - if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { - iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); - } - // Vimeo postMessage API - else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { - iframe.contentWindow.postMessage( '{"method":"play"}', '*' ); - } - // Generic postMessage API - else { - iframe.contentWindow.postMessage( 'slide:start', '*' ); - } - - } - - /** - * Stop playback of any embedded content inside of - * the targeted slide. - */ - function stopEmbeddedContent( slide ) { - - if( slide && slide.parentNode ) { - // HTML5 media elements - toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { - if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) { - el.pause(); - } - } ); - - // Generic postMessage API for non-lazy loaded iframes - toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) { - el.contentWindow.postMessage( 'slide:stop', '*' ); - el.removeEventListener( 'load', startEmbeddedIframe ); - }); - - // YouTube postMessage API - toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) { - if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { - el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); - } - }); - - // Vimeo postMessage API - toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) { - if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { - el.contentWindow.postMessage( '{"method":"pause"}', '*' ); - } - }); - - // Lazy loading iframes - toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { - // Only removing the src doesn't actually unload the frame - // in all browsers (Firefox) so we set it to blank first - el.setAttribute( 'src', 'about:blank' ); - el.removeAttribute( 'src' ); - } ); - } - - } - - /** - * Returns the number of past slides. This can be used as a global - * flattened index for slides. - */ - function getSlidePastCount() { - - var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); - - // The number of past slides - var pastCount = 0; - - // Step through all slides and count the past ones - mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) { - - var horizontalSlide = horizontalSlides[i]; - var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); - - for( var j = 0; j < verticalSlides.length; j++ ) { - - // Stop as soon as we arrive at the present - if( verticalSlides[j].classList.contains( 'present' ) ) { - break mainLoop; - } - - pastCount++; - - } - - // Stop as soon as we arrive at the present - if( horizontalSlide.classList.contains( 'present' ) ) { - break; - } - - // Don't count the wrapping section for vertical slides - if( horizontalSlide.classList.contains( 'stack' ) === false ) { - pastCount++; - } - - } - - return pastCount; - - } - - /** - * Returns a value ranging from 0-1 that represents - * how far into the presentation we have navigated. - */ - function getProgress() { - - // The number of past and total slides - var totalCount = getTotalSlides(); - var pastCount = getSlidePastCount(); - - if( currentSlide ) { - - var allFragments = currentSlide.querySelectorAll( '.fragment' ); - - // If there are fragments in the current slide those should be - // accounted for in the progress. - if( allFragments.length > 0 ) { - var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); - - // This value represents how big a portion of the slide progress - // that is made up by its fragments (0-1) - var fragmentWeight = 0.9; - - // Add fragment progress to the past slide count - pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight; - } - - } - - return pastCount / ( totalCount - 1 ); - - } - - /** - * Checks if this presentation is running inside of the - * speaker notes window. - */ - function isSpeakerNotes() { - - return !!window.location.search.match( /receiver/gi ); - - } - - /** - * Reads the current URL (hash) and navigates accordingly. - */ - function readURL() { - - var hash = window.location.hash; - - // Attempt to parse the hash as either an index or name - var bits = hash.slice( 2 ).split( '/' ), - name = hash.replace( /#|\//gi, '' ); - - // If the first bit is invalid and there is a name we can - // assume that this is a named link - if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) { - var element; - - // Ensure the named link is a valid HTML ID attribute - if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) { - // Find the slide with the specified ID - element = document.getElementById( name ); - } - - if( element ) { - // Find the position of the named slide and navigate to it - var indices = Reveal.getIndices( element ); - slide( indices.h, indices.v ); - } - // If the slide doesn't exist, navigate to the current slide - else { - slide( indexh || 0, indexv || 0 ); - } - } - else { - // Read the index components of the hash - var h = parseInt( bits[0], 10 ) || 0, - v = parseInt( bits[1], 10 ) || 0; - - if( h !== indexh || v !== indexv ) { - slide( h, v ); - } - } - - } - - /** - * Updates the page URL (hash) to reflect the current - * state. - * - * @param {Number} delay The time in ms to wait before - * writing the hash - */ - function writeURL( delay ) { - - if( config.history ) { - - // Make sure there's never more than one timeout running - clearTimeout( writeURLTimeout ); - - // If a delay is specified, timeout this call - if( typeof delay === 'number' ) { - writeURLTimeout = setTimeout( writeURL, delay ); - } - else if( currentSlide ) { - var url = '/'; - - // Attempt to create a named link based on the slide's ID - var id = currentSlide.getAttribute( 'id' ); - if( id ) { - id = id.toLowerCase(); - id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' ); - } - - // If the current slide has an ID, use that as a named link - if( typeof id === 'string' && id.length ) { - url = '/' + id; - } - // Otherwise use the /h/v index - else { - if( indexh > 0 || indexv > 0 ) url += indexh; - if( indexv > 0 ) url += '/' + indexv; - } - - window.location.hash = url; - } - } - - } - - /** - * Retrieves the h/v location of the current, or specified, - * slide. - * - * @param {HTMLElement} slide If specified, the returned - * index will be for this slide rather than the currently - * active one - * - * @return {Object} { h: , v: , f: } - */ - function getIndices( slide ) { - - // By default, return the current indices - var h = indexh, - v = indexv, - f; - - // If a slide is specified, return the indices of that slide - if( slide ) { - var isVertical = isVerticalSlide( slide ); - var slideh = isVertical ? slide.parentNode : slide; - - // Select all horizontal slides - var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); - - // Now that we know which the horizontal slide is, get its index - h = Math.max( horizontalSlides.indexOf( slideh ), 0 ); - - // Assume we're not vertical - v = undefined; - - // If this is a vertical slide, grab the vertical index - if( isVertical ) { - v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 ); - } - } - - if( !slide && currentSlide ) { - var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0; - if( hasFragments ) { - var currentFragment = currentSlide.querySelector( '.current-fragment' ); - if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) { - f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 ); - } - else { - f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1; - } - } - } - - return { h: h, v: v, f: f }; - - } - - /** - * Retrieves the total number of slides in this presentation. - */ - function getTotalSlides() { - - return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length; - - } - - /** - * Returns the slide element matching the specified index. - */ - function getSlide( x, y ) { - - var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ]; - var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' ); - - if( verticalSlides && verticalSlides.length && typeof y === 'number' ) { - return verticalSlides ? verticalSlides[ y ] : undefined; - } - - return horizontalSlide; - - } - - /** - * Returns the background element for the given slide. - * All slides, even the ones with no background properties - * defined, have a background element so as long as the - * index is valid an element will be returned. - */ - function getSlideBackground( x, y ) { - - // When printing to PDF the slide backgrounds are nested - // inside of the slides - if( isPrintingPDF() ) { - var slide = getSlide( x, y ); - if( slide ) { - var background = slide.querySelector( '.slide-background' ); - if( background && background.parentNode === slide ) { - return background; - } - } - - return undefined; - } - - var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ]; - var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' ); - - if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) { - return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined; - } - - return horizontalBackground; - - } - - /** - * Retrieves the current state of the presentation as - * an object. This state can then be restored at any - * time. - */ - function getState() { - - var indices = getIndices(); - - return { - indexh: indices.h, - indexv: indices.v, - indexf: indices.f, - paused: isPaused(), - overview: isOverview() - }; - - } - - /** - * Restores the presentation to the given state. - * - * @param {Object} state As generated by getState() - */ - function setState( state ) { - - if( typeof state === 'object' ) { - slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) ); - - var pausedFlag = deserialize( state.paused ), - overviewFlag = deserialize( state.overview ); - - if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) { - togglePause( pausedFlag ); - } - - if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) { - toggleOverview( overviewFlag ); - } - } - - } - - /** - * Return a sorted fragments list, ordered by an increasing - * "data-fragment-index" attribute. - * - * Fragments will be revealed in the order that they are returned by - * this function, so you can use the index attributes to control the - * order of fragment appearance. - * - * To maintain a sensible default fragment order, fragments are presumed - * to be passed in document order. This function adds a "fragment-index" - * attribute to each node if such an attribute is not already present, - * and sets that attribute to an integer value which is the position of - * the fragment within the fragments list. - */ - function sortFragments( fragments ) { - - fragments = toArray( fragments ); - - var ordered = [], - unordered = [], - sorted = []; - - // Group ordered and unordered elements - fragments.forEach( function( fragment, i ) { - if( fragment.hasAttribute( 'data-fragment-index' ) ) { - var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 ); - - if( !ordered[index] ) { - ordered[index] = []; - } - - ordered[index].push( fragment ); - } - else { - unordered.push( [ fragment ] ); - } - } ); - - // Append fragments without explicit indices in their - // DOM order - ordered = ordered.concat( unordered ); - - // Manually count the index up per group to ensure there - // are no gaps - var index = 0; - - // Push all fragments in their sorted order to an array, - // this flattens the groups - ordered.forEach( function( group ) { - group.forEach( function( fragment ) { - sorted.push( fragment ); - fragment.setAttribute( 'data-fragment-index', index ); - } ); - - index ++; - } ); - - return sorted; - - } - - /** - * Navigate to the specified slide fragment. - * - * @param {Number} index The index of the fragment that - * should be shown, -1 means all are invisible - * @param {Number} offset Integer offset to apply to the - * fragment index - * - * @return {Boolean} true if a change was made in any - * fragments visibility as part of this call - */ - function navigateFragment( index, offset ) { - - if( currentSlide && config.fragments ) { - - var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) ); - if( fragments.length ) { - - // If no index is specified, find the current - if( typeof index !== 'number' ) { - var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop(); - - if( lastVisibleFragment ) { - index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 ); - } - else { - index = -1; - } - } - - // If an offset is specified, apply it to the index - if( typeof offset === 'number' ) { - index += offset; - } - - var fragmentsShown = [], - fragmentsHidden = []; - - toArray( fragments ).forEach( function( element, i ) { - - if( element.hasAttribute( 'data-fragment-index' ) ) { - i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 ); - } - - // Visible fragments - if( i <= index ) { - if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element ); - element.classList.add( 'visible' ); - element.classList.remove( 'current-fragment' ); - - // Announce the fragments one by one to the Screen Reader - dom.statusDiv.textContent = element.textContent; - - if( i === index ) { - element.classList.add( 'current-fragment' ); - } - } - // Hidden fragments - else { - if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element ); - element.classList.remove( 'visible' ); - element.classList.remove( 'current-fragment' ); - } - - - } ); - - if( fragmentsHidden.length ) { - dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } ); - } - - if( fragmentsShown.length ) { - dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } ); - } - - updateControls(); - updateProgress(); - - return !!( fragmentsShown.length || fragmentsHidden.length ); - - } - - } - - return false; - - } - - /** - * Navigate to the next slide fragment. - * - * @return {Boolean} true if there was a next fragment, - * false otherwise - */ - function nextFragment() { - - return navigateFragment( null, 1 ); - - } - - /** - * Navigate to the previous slide fragment. - * - * @return {Boolean} true if there was a previous fragment, - * false otherwise - */ - function previousFragment() { - - return navigateFragment( null, -1 ); - - } - - /** - * Cues a new automated slide if enabled in the config. - */ - function cueAutoSlide() { - - cancelAutoSlide(); - - if( currentSlide ) { - - var currentFragment = currentSlide.querySelector( '.current-fragment' ); - - var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null; - var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null; - var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' ); - - // Pick value in the following priority order: - // 1. Current fragment's data-autoslide - // 2. Current slide's data-autoslide - // 3. Parent slide's data-autoslide - // 4. Global autoSlide setting - if( fragmentAutoSlide ) { - autoSlide = parseInt( fragmentAutoSlide, 10 ); - } - else if( slideAutoSlide ) { - autoSlide = parseInt( slideAutoSlide, 10 ); - } - else if( parentAutoSlide ) { - autoSlide = parseInt( parentAutoSlide, 10 ); - } - else { - autoSlide = config.autoSlide; - } - - // If there are media elements with data-autoplay, - // automatically set the autoSlide duration to the - // length of that media. Not applicable if the slide - // is divided up into fragments. - if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) { - toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { - if( el.hasAttribute( 'data-autoplay' ) ) { - if( autoSlide && el.duration * 1000 > autoSlide ) { - autoSlide = ( el.duration * 1000 ) + 1000; - } - } - } ); - } - - // Cue the next auto-slide if: - // - There is an autoSlide value - // - Auto-sliding isn't paused by the user - // - The presentation isn't paused - // - The overview isn't active - // - The presentation isn't over - if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) { - autoSlideTimeout = setTimeout( navigateNext, autoSlide ); - autoSlideStartTime = Date.now(); - } - - if( autoSlidePlayer ) { - autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 ); - } - - } - - } - - /** - * Cancels any ongoing request to auto-slide. - */ - function cancelAutoSlide() { - - clearTimeout( autoSlideTimeout ); - autoSlideTimeout = -1; - - } - - function pauseAutoSlide() { - - if( autoSlide && !autoSlidePaused ) { - autoSlidePaused = true; - dispatchEvent( 'autoslidepaused' ); - clearTimeout( autoSlideTimeout ); - - if( autoSlidePlayer ) { - autoSlidePlayer.setPlaying( false ); - } - } - - } - - function resumeAutoSlide() { - - if( autoSlide && autoSlidePaused ) { - autoSlidePaused = false; - dispatchEvent( 'autoslideresumed' ); - cueAutoSlide(); - } - - } - - function navigateLeft() { - - // Reverse for RTL - if( config.rtl ) { - if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) { - slide( indexh + 1 ); - } - } - // Normal navigation - else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) { - slide( indexh - 1 ); - } - - } - - function navigateRight() { - - // Reverse for RTL - if( config.rtl ) { - if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) { - slide( indexh - 1 ); - } - } - // Normal navigation - else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) { - slide( indexh + 1 ); - } - - } - - function navigateUp() { - - // Prioritize hiding fragments - if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) { - slide( indexh, indexv - 1 ); - } - - } - - function navigateDown() { - - // Prioritize revealing fragments - if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) { - slide( indexh, indexv + 1 ); - } - - } - - /** - * Navigates backwards, prioritized in the following order: - * 1) Previous fragment - * 2) Previous vertical slide - * 3) Previous horizontal slide - */ - function navigatePrev() { - - // Prioritize revealing fragments - if( previousFragment() === false ) { - if( availableRoutes().up ) { - navigateUp(); - } - else { - // Fetch the previous horizontal slide, if there is one - var previousSlide; - - if( config.rtl ) { - previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop(); - } - else { - previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop(); - } - - if( previousSlide ) { - var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined; - var h = indexh - 1; - slide( h, v ); - } - } - } - - } - - /** - * The reverse of #navigatePrev(). - */ - function navigateNext() { - - // Prioritize revealing fragments - if( nextFragment() === false ) { - if( availableRoutes().down ) { - navigateDown(); - } - else if( config.rtl ) { - navigateLeft(); - } - else { - navigateRight(); - } - } - - // If auto-sliding is enabled we need to cue up - // another timeout - cueAutoSlide(); - - } - - - // --------------------------------------------------------------------// - // ----------------------------- EVENTS -------------------------------// - // --------------------------------------------------------------------// - - /** - * Called by all event handlers that are based on user - * input. - */ - function onUserInput( event ) { - - if( config.autoSlideStoppable ) { - pauseAutoSlide(); - } - - } - - /** - * Handler for the document level 'keypress' event. - */ - function onDocumentKeyPress( event ) { - - // Check if the pressed key is question mark - if( event.shiftKey && event.charCode === 63 ) { - if( dom.overlay ) { - closeOverlay(); - } - else { - showHelp( true ); - } - } - - } - - /** - * Handler for the document level 'keydown' event. - */ - function onDocumentKeyDown( event ) { - - // If there's a condition specified and it returns false, - // ignore this event - if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) { - return true; - } - - // Remember if auto-sliding was paused so we can toggle it - var autoSlideWasPaused = autoSlidePaused; - - onUserInput( event ); - - // Check if there's a focused element that could be using - // the keyboard - var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit'; - var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName ); - - // Disregard the event if there's a focused element or a - // keyboard modifier key is present - if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return; - - // While paused only allow "unpausing" keyboard events (b and .) - if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) { - return false; - } - - var triggered = false; - - // 1. User defined key bindings - if( typeof config.keyboard === 'object' ) { - - for( var key in config.keyboard ) { - - // Check if this binding matches the pressed key - if( parseInt( key, 10 ) === event.keyCode ) { - - var value = config.keyboard[ key ]; - - // Callback function - if( typeof value === 'function' ) { - value.apply( null, [ event ] ); - } - // String shortcuts to reveal.js API - else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) { - Reveal[ value ].call(); - } - - triggered = true; - - } - - } - - } - - // 2. System defined key bindings - if( triggered === false ) { - - // Assume true and try to prove false - triggered = true; - - switch( event.keyCode ) { - // p, page up - case 80: case 33: navigatePrev(); break; - // n, page down - case 78: case 34: navigateNext(); break; - // h, left - case 72: case 37: navigateLeft(); break; - // l, right - case 76: case 39: navigateRight(); break; - // k, up - case 75: case 38: navigateUp(); break; - // j, down - case 74: case 40: navigateDown(); break; - // home - case 36: slide( 0 ); break; - // end - case 35: slide( Number.MAX_VALUE ); break; - // space - case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break; - // return - case 13: isOverview() ? deactivateOverview() : triggered = false; break; - // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button - case 58: case 59: case 66: case 190: case 191: togglePause(); break; - // f - case 70: enterFullscreen(); break; - // a - case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break; - default: - triggered = false; - } - - } - - // If the input resulted in a triggered action we should prevent - // the browsers default behavior - if( triggered ) { - event.preventDefault && event.preventDefault(); - } - // ESC or O key - else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) { - if( dom.overlay ) { - closeOverlay(); - } - else { - toggleOverview(); - } - - event.preventDefault && event.preventDefault(); - } - - // If auto-sliding is enabled we need to cue up - // another timeout - cueAutoSlide(); - - } - - /** - * Handler for the 'touchstart' event, enables support for - * swipe and pinch gestures. - */ - function onTouchStart( event ) { - - touch.startX = event.touches[0].clientX; - touch.startY = event.touches[0].clientY; - touch.startCount = event.touches.length; - - // If there's two touches we need to memorize the distance - // between those two points to detect pinching - if( event.touches.length === 2 && config.overview ) { - touch.startSpan = distanceBetween( { - x: event.touches[1].clientX, - y: event.touches[1].clientY - }, { - x: touch.startX, - y: touch.startY - } ); - } - - } - - /** - * Handler for the 'touchmove' event. - */ - function onTouchMove( event ) { - - // Each touch should only trigger one action - if( !touch.captured ) { - onUserInput( event ); - - var currentX = event.touches[0].clientX; - var currentY = event.touches[0].clientY; - - // If the touch started with two points and still has - // two active touches; test for the pinch gesture - if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) { - - // The current distance in pixels between the two touch points - var currentSpan = distanceBetween( { - x: event.touches[1].clientX, - y: event.touches[1].clientY - }, { - x: touch.startX, - y: touch.startY - } ); - - // If the span is larger than the desire amount we've got - // ourselves a pinch - if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) { - touch.captured = true; - - if( currentSpan < touch.startSpan ) { - activateOverview(); - } - else { - deactivateOverview(); - } - } - - event.preventDefault(); - - } - // There was only one touch point, look for a swipe - else if( event.touches.length === 1 && touch.startCount !== 2 ) { - - var deltaX = currentX - touch.startX, - deltaY = currentY - touch.startY; - - if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { - touch.captured = true; - navigateLeft(); - } - else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { - touch.captured = true; - navigateRight(); - } - else if( deltaY > touch.threshold ) { - touch.captured = true; - navigateUp(); - } - else if( deltaY < -touch.threshold ) { - touch.captured = true; - navigateDown(); - } - - // If we're embedded, only block touch events if they have - // triggered an action - if( config.embedded ) { - if( touch.captured || isVerticalSlide( currentSlide ) ) { - event.preventDefault(); - } - } - // Not embedded? Block them all to avoid needless tossing - // around of the viewport in iOS - else { - event.preventDefault(); - } - - } - } - // There's a bug with swiping on some Android devices unless - // the default action is always prevented - else if( navigator.userAgent.match( /android/gi ) ) { - event.preventDefault(); - } - - } - - /** - * Handler for the 'touchend' event. - */ - function onTouchEnd( event ) { - - touch.captured = false; - - } - - /** - * Convert pointer down to touch start. - */ - function onPointerDown( event ) { - - if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { - event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; - onTouchStart( event ); - } - - } - - /** - * Convert pointer move to touch move. - */ - function onPointerMove( event ) { - - if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { - event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; - onTouchMove( event ); - } - - } - - /** - * Convert pointer up to touch end. - */ - function onPointerUp( event ) { - - if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { - event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; - onTouchEnd( event ); - } - - } - - /** - * Handles mouse wheel scrolling, throttled to avoid skipping - * multiple slides. - */ - function onDocumentMouseScroll( event ) { - - if( Date.now() - lastMouseWheelStep > 600 ) { - - lastMouseWheelStep = Date.now(); - - var delta = event.detail || -event.wheelDelta; - if( delta > 0 ) { - navigateNext(); - } - else { - navigatePrev(); - } - - } - - } - - /** - * Clicking on the progress bar results in a navigation to the - * closest approximate horizontal slide using this equation: - * - * ( clickX / presentationWidth ) * numberOfSlides - */ - function onProgressClicked( event ) { - - onUserInput( event ); - - event.preventDefault(); - - var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length; - var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal ); - - if( config.rtl ) { - slideIndex = slidesTotal - slideIndex; - } - - slide( slideIndex ); - - } - - /** - * Event handler for navigation control buttons. - */ - function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); } - function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); } - function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); } - function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); } - function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); } - function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); } - - /** - * Handler for the window level 'hashchange' event. - */ - function onWindowHashChange( event ) { - - readURL(); - - } - - /** - * Handler for the window level 'resize' event. - */ - function onWindowResize( event ) { - - layout(); - - } - - /** - * Handle for the window level 'visibilitychange' event. - */ - function onPageVisibilityChange( event ) { - - var isHidden = document.webkitHidden || - document.msHidden || - document.hidden; - - // If, after clicking a link or similar and we're coming back, - // focus the document.body to ensure we can use keyboard shortcuts - if( isHidden === false && document.activeElement !== document.body ) { - // Not all elements support .blur() - SVGs among them. - if( typeof document.activeElement.blur === 'function' ) { - document.activeElement.blur(); - } - document.body.focus(); - } - - } - - /** - * Invoked when a slide is and we're in the overview. - */ - function onOverviewSlideClicked( event ) { - - // TODO There's a bug here where the event listeners are not - // removed after deactivating the overview. - if( eventsAreBound && isOverview() ) { - event.preventDefault(); - - var element = event.target; - - while( element && !element.nodeName.match( /section/gi ) ) { - element = element.parentNode; - } - - if( element && !element.classList.contains( 'disabled' ) ) { - - deactivateOverview(); - - if( element.nodeName.match( /section/gi ) ) { - var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ), - v = parseInt( element.getAttribute( 'data-index-v' ), 10 ); - - slide( h, v ); - } - - } - } - - } - - /** - * Handles clicks on links that are set to preview in the - * iframe overlay. - */ - function onPreviewLinkClicked( event ) { - - if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) { - var url = event.currentTarget.getAttribute( 'href' ); - if( url ) { - showPreview( url ); - event.preventDefault(); - } - } - - } - - /** - * Handles click on the auto-sliding controls element. - */ - function onAutoSlidePlayerClick( event ) { - - // Replay - if( Reveal.isLastSlide() && config.loop === false ) { - slide( 0, 0 ); - resumeAutoSlide(); - } - // Resume - else if( autoSlidePaused ) { - resumeAutoSlide(); - } - // Pause - else { - pauseAutoSlide(); - } - - } - - - // --------------------------------------------------------------------// - // ------------------------ PLAYBACK COMPONENT ------------------------// - // --------------------------------------------------------------------// - - - /** - * Constructor for the playback component, which displays - * play/pause/progress controls. - * - * @param {HTMLElement} container The component will append - * itself to this - * @param {Function} progressCheck A method which will be - * called frequently to get the current progress on a range - * of 0-1 - */ - function Playback( container, progressCheck ) { - - // Cosmetics - this.diameter = 50; - this.thickness = 3; - - // Flags if we are currently playing - this.playing = false; - - // Current progress on a 0-1 range - this.progress = 0; - - // Used to loop the animation smoothly - this.progressOffset = 1; - - this.container = container; - this.progressCheck = progressCheck; - - this.canvas = document.createElement( 'canvas' ); - this.canvas.className = 'playback'; - this.canvas.width = this.diameter; - this.canvas.height = this.diameter; - this.context = this.canvas.getContext( '2d' ); - - this.container.appendChild( this.canvas ); - - this.render(); - - } - - Playback.prototype.setPlaying = function( value ) { - - var wasPlaying = this.playing; - - this.playing = value; - - // Start repainting if we weren't already - if( !wasPlaying && this.playing ) { - this.animate(); - } - else { - this.render(); - } - - }; - - Playback.prototype.animate = function() { - - var progressBefore = this.progress; - - this.progress = this.progressCheck(); - - // When we loop, offset the progress so that it eases - // smoothly rather than immediately resetting - if( progressBefore > 0.8 && this.progress < 0.2 ) { - this.progressOffset = this.progress; - } - - this.render(); - - if( this.playing ) { - features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) ); - } - - }; - - /** - * Renders the current progress and playback state. - */ - Playback.prototype.render = function() { - - var progress = this.playing ? this.progress : 0, - radius = ( this.diameter / 2 ) - this.thickness, - x = this.diameter / 2, - y = this.diameter / 2, - iconSize = 14; - - // Ease towards 1 - this.progressOffset += ( 1 - this.progressOffset ) * 0.1; - - var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) ); - var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) ); - - this.context.save(); - this.context.clearRect( 0, 0, this.diameter, this.diameter ); - - // Solid background color - this.context.beginPath(); - this.context.arc( x, y, radius + 2, 0, Math.PI * 2, false ); - this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )'; - this.context.fill(); - - // Draw progress track - this.context.beginPath(); - this.context.arc( x, y, radius, 0, Math.PI * 2, false ); - this.context.lineWidth = this.thickness; - this.context.strokeStyle = '#666'; - this.context.stroke(); - - if( this.playing ) { - // Draw progress on top of track - this.context.beginPath(); - this.context.arc( x, y, radius, startAngle, endAngle, false ); - this.context.lineWidth = this.thickness; - this.context.strokeStyle = '#fff'; - this.context.stroke(); - } - - this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) ); - - // Draw play/pause icons - if( this.playing ) { - this.context.fillStyle = '#fff'; - this.context.fillRect( 0, 0, iconSize / 2 - 2, iconSize ); - this.context.fillRect( iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize ); - } - else { - this.context.beginPath(); - this.context.translate( 2, 0 ); - this.context.moveTo( 0, 0 ); - this.context.lineTo( iconSize - 2, iconSize / 2 ); - this.context.lineTo( 0, iconSize ); - this.context.fillStyle = '#fff'; - this.context.fill(); - } - - this.context.restore(); - - }; - - Playback.prototype.on = function( type, listener ) { - this.canvas.addEventListener( type, listener, false ); - }; - - Playback.prototype.off = function( type, listener ) { - this.canvas.removeEventListener( type, listener, false ); - }; - - Playback.prototype.destroy = function() { - - this.playing = false; - - if( this.canvas.parentNode ) { - this.container.removeChild( this.canvas ); - } - - }; - - - // --------------------------------------------------------------------// - // ------------------------------- API --------------------------------// - // --------------------------------------------------------------------// - - - Reveal = { - initialize: initialize, - configure: configure, - sync: sync, - - // Navigation methods - slide: slide, - left: navigateLeft, - right: navigateRight, - up: navigateUp, - down: navigateDown, - prev: navigatePrev, - next: navigateNext, - - // Fragment methods - navigateFragment: navigateFragment, - prevFragment: previousFragment, - nextFragment: nextFragment, - - // Deprecated aliases - navigateTo: slide, - navigateLeft: navigateLeft, - navigateRight: navigateRight, - navigateUp: navigateUp, - navigateDown: navigateDown, - navigatePrev: navigatePrev, - navigateNext: navigateNext, - - // Forces an update in slide layout - layout: layout, - - // Returns an object with the available routes as booleans (left/right/top/bottom) - availableRoutes: availableRoutes, - - // Returns an object with the available fragments as booleans (prev/next) - availableFragments: availableFragments, - - // Toggles the overview mode on/off - toggleOverview: toggleOverview, - - // Toggles the "black screen" mode on/off - togglePause: togglePause, - - // Toggles the auto slide mode on/off - toggleAutoSlide: toggleAutoSlide, - - // State checks - isOverview: isOverview, - isPaused: isPaused, - isAutoSliding: isAutoSliding, - - // Adds or removes all internal event listeners (such as keyboard) - addEventListeners: addEventListeners, - removeEventListeners: removeEventListeners, - - // Facility for persisting and restoring the presentation state - getState: getState, - setState: setState, - - // Presentation progress on range of 0-1 - getProgress: getProgress, - - // Returns the indices of the current, or specified, slide - getIndices: getIndices, - - getTotalSlides: getTotalSlides, - - // Returns the slide element at the specified index - getSlide: getSlide, - - // Returns the slide background element at the specified index - getSlideBackground: getSlideBackground, - - // Returns the previous slide element, may be null - getPreviousSlide: function() { - return previousSlide; - }, - - // Returns the current slide element - getCurrentSlide: function() { - return currentSlide; - }, - - // Returns the current scale of the presentation content - getScale: function() { - return scale; - }, - - // Returns the current configuration object - getConfig: function() { - return config; - }, - - // Helper method, retrieves query string as a key/value hash - getQueryHash: function() { - var query = {}; - - location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) { - query[ a.split( '=' ).shift() ] = a.split( '=' ).pop(); - } ); - - // Basic deserialization - for( var i in query ) { - var value = query[ i ]; - - query[ i ] = deserialize( unescape( value ) ); - } - - return query; - }, - - // Returns true if we're currently on the first slide - isFirstSlide: function() { - return ( indexh === 0 && indexv === 0 ); - }, - - // Returns true if we're currently on the last slide - isLastSlide: function() { - if( currentSlide ) { - // Does this slide has next a sibling? - if( currentSlide.nextElementSibling ) return false; - - // If it's vertical, does its parent have a next sibling? - if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false; - - return true; - } - - return false; - }, - - // Checks if reveal.js has been loaded and is ready for use - isReady: function() { - return loaded; - }, - - // Forward event binding to the reveal DOM element - addEventListener: function( type, listener, useCapture ) { - if( 'addEventListener' in window ) { - ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture ); - } - }, - removeEventListener: function( type, listener, useCapture ) { - if( 'addEventListener' in window ) { - ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture ); - } - }, - - // Programatically triggers a keyboard event - triggerKey: function( keyCode ) { - onDocumentKeyDown( { keyCode: keyCode } ); - } - }; - - return Reveal; - -})); diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/lib/css/zenburn.css b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/lib/css/zenburn.css deleted file mode 100644 index 163484b277..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/lib/css/zenburn.css +++ /dev/null @@ -1,116 +0,0 @@ -/* - -Zenburn style from voldmar.ru (c) Vladimir Epifanov -based on dark.css by Ivan Sagalaev - -*/ - -.hljs { - display: block; padding: 0.5em; - background: #3F3F3F; - color: #DCDCDC; -} - -.hljs-keyword, -.hljs-tag, -.css .hljs-class, -.css .hljs-id, -.lisp .hljs-title, -.nginx .hljs-title, -.hljs-request, -.hljs-status, -.clojure .hljs-attribute { - color: #E3CEAB; -} - -.django .hljs-template_tag, -.django .hljs-variable, -.django .hljs-filter .hljs-argument { - color: #DCDCDC; -} - -.hljs-number, -.hljs-date { - color: #8CD0D3; -} - -.dos .hljs-envvar, -.dos .hljs-stream, -.hljs-variable, -.apache .hljs-sqbracket { - color: #EFDCBC; -} - -.dos .hljs-flow, -.diff .hljs-change, -.python .exception, -.python .hljs-built_in, -.hljs-literal, -.tex .hljs-special { - color: #EFEFAF; -} - -.diff .hljs-chunk, -.hljs-subst { - color: #8F8F8F; -} - -.dos .hljs-keyword, -.python .hljs-decorator, -.hljs-title, -.haskell .hljs-type, -.diff .hljs-header, -.ruby .hljs-class .hljs-parent, -.apache .hljs-tag, -.nginx .hljs-built_in, -.tex .hljs-command, -.hljs-prompt { - color: #efef8f; -} - -.dos .hljs-winutils, -.ruby .hljs-symbol, -.ruby .hljs-symbol .hljs-string, -.ruby .hljs-string { - color: #DCA3A3; -} - -.diff .hljs-deletion, -.hljs-string, -.hljs-tag .hljs-value, -.hljs-preprocessor, -.hljs-pragma, -.hljs-built_in, -.sql .hljs-aggregate, -.hljs-javadoc, -.smalltalk .hljs-class, -.smalltalk .hljs-localvars, -.smalltalk .hljs-array, -.css .hljs-rules .hljs-value, -.hljs-attr_selector, -.hljs-pseudo, -.apache .hljs-cbracket, -.tex .hljs-formula, -.coffeescript .hljs-attribute { - color: #CC9393; -} - -.hljs-shebang, -.diff .hljs-addition, -.hljs-comment, -.java .hljs-annotation, -.hljs-template_comment, -.hljs-pi, -.hljs-doctype { - color: #7F9F7F; -} - -.coffeescript .javascript, -.javascript .xml, -.tex .hljs-formula, -.xml .javascript, -.xml .vbscript, -.xml .css, -.xml .hljs-cdata { - opacity: 0.5; -} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/lib/js/classList.js b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/lib/js/classList.js deleted file mode 100644 index 44f2b4ceca..0000000000 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/lib/js/classList.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ -if(typeof document!=="undefined"&&!("classList" in document.createElement("a"))){(function(j){var a="classList",f="prototype",m=(j.HTMLElement||j.Element)[f],b=Object,k=String[f].trim||function(){return this.replace(/^\s+|\s+$/g,"")},c=Array[f].indexOf||function(q){var p=0,o=this.length;for(;p - Copyright Tero Piirainen (tipiirai) - License MIT / http://bit.ly/mit-license - Version 0.96 - - http://headjs.com -*/(function(a){function z(){d||(d=!0,s(e,function(a){p(a)}))}function y(c,d){var e=a.createElement("script");e.type="text/"+(c.type||"javascript"),e.src=c.src||c,e.async=!1,e.onreadystatechange=e.onload=function(){var a=e.readyState;!d.done&&(!a||/loaded|complete/.test(a))&&(d.done=!0,d())},(a.body||b).appendChild(e)}function x(a,b){if(a.state==o)return b&&b();if(a.state==n)return k.ready(a.name,b);if(a.state==m)return a.onpreload.push(function(){x(a,b)});a.state=n,y(a.url,function(){a.state=o,b&&b(),s(g[a.name],function(a){p(a)}),u()&&d&&s(g.ALL,function(a){p(a)})})}function w(a,b){a.state===undefined&&(a.state=m,a.onpreload=[],y({src:a.url,type:"cache"},function(){v(a)}))}function v(a){a.state=l,s(a.onpreload,function(a){a.call()})}function u(a){a=a||h;var b;for(var c in a){if(a.hasOwnProperty(c)&&a[c].state!=o)return!1;b=!0}return b}function t(a){return Object.prototype.toString.call(a)=="[object Function]"}function s(a,b){if(!!a){typeof a=="object"&&(a=[].slice.call(a));for(var c=0;c - - - - - MITK Workbench - - - - - - -
- - -
-

Welcome to the MITK Workbench!

- -
-

This application was developed at the German Cancer Research Center (DKFZ). It is based on the well established, free open source Medical Imaging Interaction Toolkit MITK.

- -

Here you can find the Welcome Tutorial, to get a first overview!

-
- - -
- -
- - -
- - -
-
- - -
- - -
-
-
- - - - diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/WelcomeMITK.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/WelcomeMITK.png deleted file mode 100644 index 71e0a574a8..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/WelcomeMITK.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/background.jpg b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/background.jpg deleted file mode 100644 index c93f36df92..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/background.jpg and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/button_mitk.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/button_mitk.png deleted file mode 100644 index abb730a99c..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/button_mitk.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/button_mitka.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/button_mitka.png deleted file mode 100644 index 905b7ff8d5..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/button_mitka.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/experimental.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/experimental.png deleted file mode 100644 index 86573f48db..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/experimental.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg.png deleted file mode 100644 index f6bc2a3290..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_bottom.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_bottom.png deleted file mode 100644 index e05512e989..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_bottom.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_middle.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_middle.png deleted file mode 100644 index 59208da102..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_middle.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_top.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_top.png deleted file mode 100644 index 5ee8067cbb..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bg_top.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bttn_close.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bttn_close.png deleted file mode 100644 index d744ba4860..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/popup_bttn_close.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/shadow.png b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/shadow.png deleted file mode 100644 index 309d1af900..0000000000 Binary files a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/pics/shadow.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/script.js b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/script.js new file mode 100644 index 0000000000..45b56caa01 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/script.js @@ -0,0 +1,32 @@ +function showNextTip() { + var tips = document.querySelectorAll('.tip'); + for (let i = 0; i < tips.length; ++i) { + if (!tips[i].hasAttribute('hidden')) { + tips[i].setAttribute('hidden', ''); + tips[(i + 1) % tips.length].removeAttribute('hidden'); + break; + } + } +} + +function showRandomTip() { + var tips = document.querySelectorAll('.tip'); + var show = Math.floor(Math.random() * tips.length); + for (let i = 0; i < tips.length; ++i) { + if (i != show) { + tips[i].setAttribute('hidden', ''); + } else { + tips[i].removeAttribute('hidden'); + } + } +} + +function showTips() { + var tips = document.querySelector('.tips'); + tips.removeAttribute('hidden'); +} + +function hideTips() { + var tips = document.querySelector('.tips'); + tips.setAttribute('hidden', ''); +} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/style.css b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/style.css index 12bbd7a146..fe5931d940 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/style.css +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/resources/style.css @@ -1,207 +1,86 @@ -@charset "utf-8"; - -body{ - margin:0px 0px; - padding: 0px 0px; +* { + box-sizing: border-box; } -h1{ - margin: 0px; - padding: 5px; +body { + background-color: #202021; + color: #f1f1f1; + padding: 16px; font-family: "Open Sans", sans-serif; - color: rgb(255, 255, 255); - background: rgba(45, 92, 126, 1); -} - -img{border:none;} - -#screen{ - width:100%; - min-height:1060px; - height:100%; - padding-top: 1%; } -#welcome{ - min-width: 500px; - max-width: 700px; - height: 120px; - margin: 0px auto; - padding:5px; - color: #000; -} - -#welcomeText{ - margin-top: 2%; - font-family: "Open Sans", sans-serif; - margin-bottom:15px; - z-index:1; -} - -#manualButtonField { - min-width:500px; - max-width:700px; - margin: auto; -} - -#popupAnchor{ +.content { + max-width: 1000px; margin: auto; } -#generatedButtonField{ - min-width:500px; - max-width:700px; +.tips { + background-color: #3f3f46; + border-radius: 16px; + width: 100%; margin: auto; + margin-top: 32px; + padding: 8px 16px 8px 16px; } -.fontDefinition { - font-family: "Open Sans", sans-serif; -} - -.bttnWrap{ - position:relative; - float:left; - width:140px; - height:190px; - margin-right:32px; - margin-top:5px; - z-index:2; - text-align: center; +.tip-content { + overflow: hidden; } -.genericButton{ - background-size: 100% 100%; - background-repeat: no-repeat; - display: inline-block; - height: 92px; - width: 100px; - overflow: hidden; - text-indent: 100%; - white-space: nowrap; - border: 2px solid rgba(45, 92, 136, 0.5); - border-radius: 10px 10px 10px 10px; - margin: 20px; - transform: translateZ(0); - box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2); - backface-visibility: hidden; - transition-duration: 0.3s; - transition-property: transform; +.button { + background-color: #3f3f46; + border: 2px solid #f1f1f1; + color: #f1f1f1; + font-size: 24px; + margin-top: 16px; + padding: 8px 16px; + transition-duration: 0.2s; + cursor: pointer; } -.genericButton:hover, .genericButton:focus, .genericButton:active { - transform: scale(1.15); - border: 2px solid rgba(45, 92, 136, 1); +.button:hover { + background-color: #f1f1f1; + color: #252526; } -.welcomeTutorialButton { - background-image: url(qrc:/org.mitk.gui.qt.welcomescreen/pics/WelcomeMITK.png); -} - -.textLink{ - font-family: "Open Sans", sans-serif; - font-size: 15px; - font-weight: bold; - text-decoration: none; - cursor: pointer; - color: #2d5a88; - padding-left: 0px; - margin: auto; -} - -.textLink:hover{ - text-decoration: underline; -} - -.mitk-logo { - background-image: url(qrc:/org.mitk.gui.qt.welcomescreen/pics/button_mitk.png); - background-size: 100px; - display: inline-block; - height: 92px; - width: 100px; - overflow: hidden; - text-indent: 100%; - white-space: nowrap; - border: 2px solid rgba(45, 92, 136, 0.5); - border-radius: 10px 10px 10px 10px; - margin: 20px; - transform: translateZ(0); - box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2); - backface-visibility: hidden; - transition-duration: 0.3s; - transition-property: transform; -} - -.mitk-logo:hover, .mitk-logo:focus, .mitk-logo:active { - transform: scale(1.15); - border: 2px solid rgba(45, 92, 136, 1); +.center { + display: block; + margin: auto; } -#popup{ - position:relative; - margin-left: auto; - margin-right: auto; - max-width:690px; - min-width:150px; - background-color:#000000; - opacity: 0.8; - -webkit-border-radius: 1em; - font-family: "Open Sans", sans-serif; - color:#FFF; - z-index:2; +.table { + display: table; + border-collapse: separate; + border-spacing: 16px; + margin: 0 -16px; + width: calc(100% + 32px); } -#bttnClose{ - position:relative; - right:10px; - top:10px; - cursor:pointer; +.tr { + display: table-row; } -#contHeadline{ - max-width:690px; - min-width:150px; - margin-left:10px; - margin-right:10px; - font-weight:bold; - font-size:14px; - text-align:left; +.td { + display: table-cell; + background-color: #2d2d30; + padding: 0 16px; + max-width: 0; } -#contDescription{ - max-width:690px; - min-width:150px; - margin-top:15px; - margin-bottom:15px; - margin-left:10px; - margin-right:10px; - line-height:21px; - font-family: "Open Sans", sans-serif; - font-weight:normal; - font-size:14px; - text-align:left; +.td > h3 { + text-align: center; } -#contModLink{ - max-width:690px; - min-width:150px; - height:50px; - margin-left:10px; - margin-right:10px; - text-align:left; +.float-left { + float: left; + margin-right: 32px; } -.popUpLink{ - font-family: "Open Sans", sans-serif; - font-size:14px; - font-weight:normal; - line-height:16px; - padding-left: 10px; - color:#333; +a:link, a:visited { + color: #f1f1f1; + text-decoration: none; } -.popUpLink:hover{ - text-decoration:underline; - cursor:pointer; +a:hover, a:active { + color: #e02020; } - -.clearfloat{clear:both;} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp index 6e0cd7f0b0..c2fcf07cde 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp @@ -1,220 +1,223 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMitkWorkbenchIntroPart.h" +#include "QmitkMitkWorkbenchIntroPlugin.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 "QmitkMitkWorkbenchIntroPlugin.h" -#include "mitkDataStorageEditorInput.h" -#include - -#include #include -#include +#include class QmitkMitkWorkbenchIntroPart::Impl { public: Impl() : View(nullptr) { } ~Impl() { } QWebEngineView* View; private: Impl(const Impl&); Impl& operator=(const Impl&); }; namespace { class QmitkWebEnginePage final : public QWebEnginePage { public: explicit QmitkWebEnginePage(QmitkMitkWorkbenchIntroPart* introPart, QObject* parent = nullptr); ~QmitkWebEnginePage() override; private: bool acceptNavigationRequest(const QUrl& url, NavigationType type, bool isMainFrame) override; QmitkMitkWorkbenchIntroPart* m_IntroPart; }; QmitkWebEnginePage::QmitkWebEnginePage(QmitkMitkWorkbenchIntroPart* introPart, QObject* parent) : QWebEnginePage(parent), m_IntroPart(introPart) { } QmitkWebEnginePage::~QmitkWebEnginePage() { } bool QmitkWebEnginePage::acceptNavigationRequest(const QUrl& url, NavigationType, bool) { QString scheme = url.scheme(); if (scheme.contains("mitk")) { if (url.path().isEmpty()) return false; if (url.host().contains("perspectives")) { QString id = url.path().simplified().replace("/", ""); auto introSite = m_IntroPart->GetIntroSite(); auto workbenchWindow = introSite->GetWorkbenchWindow(); auto workbench = workbenchWindow->GetWorkbench(); workbench->ShowPerspective(id, workbenchWindow); auto context = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPluginContext(); auto serviceReference = context->getServiceReference(); mitk::IDataStorageService* service = serviceReference ? context->getService(serviceReference) : nullptr; if (service) { berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(service->GetActiveDataStorage())); auto page = introSite->GetPage(); auto editorPart = page->FindEditor(editorInput); if (editorPart.IsNotNull()) page->Activate(editorPart); } } } - else if (scheme.contains("http")) + else if (scheme.contains("https")) { QDesktopServices::openUrl(url); } else { return true; } return false; } } QmitkMitkWorkbenchIntroPart::QmitkMitkWorkbenchIntroPart() : m_Controls(nullptr), m_Impl(new Impl) { berry::IPreferences::Pointer workbenchPrefs = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } QmitkMitkWorkbenchIntroPart::~QmitkMitkWorkbenchIntroPart() { // 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 = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } else { berry::IPreferences::Pointer workbenchPrefs = QmitkMitkWorkbenchIntroPlugin::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.mitkworkbench.perspectives.editor" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.mitkworkbench.perspectives.editor"); if (perspective) { this->GetIntroSite()->GetPage()->SetPerspective(perspective); } } delete m_Impl; } void QmitkMitkWorkbenchIntroPart::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_Impl->View = new QWebEngineView(parent); + this->CreateConnections(); + auto page = new QmitkWebEnginePage(this, parent); m_Impl->View->setPage(page); - QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkworkbenchwelcomeview.html"), QUrl::TolerantMode ); + QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/index.html"), QUrl::TolerantMode); m_Impl->View->load( urlQtResource ); // adds the webview as a widget parent->layout()->addWidget(m_Impl->View); - - this->CreateConnections(); } } void QmitkMitkWorkbenchIntroPart::CreateConnections() { + connect(m_Impl->View, &QWebEngineView::loadFinished, this, &QmitkMitkWorkbenchIntroPart::OnLoadFinished); } void QmitkMitkWorkbenchIntroPart::StandbyStateChanged(bool /*standby*/) { } void QmitkMitkWorkbenchIntroPart::SetFocus() { } + +void QmitkMitkWorkbenchIntroPart::ReloadPage() +{ + if (m_Impl->View != nullptr) + m_Impl->View->reload(); +} + +void QmitkMitkWorkbenchIntroPart::OnLoadFinished(bool ok) +{ + if (!ok) + return; + + auto prefs = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.qt.extapplicationintro"); + bool showTips = prefs->GetBool("show tips", true); + + if (showTips) + { + m_Impl->View->page()->runJavaScript("showRandomTip(); showTips()"); + } + else + { + m_Impl->View->page()->runJavaScript("hideTips()"); + } +} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.h b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.h index df259e5983..4165230a60 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.h +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.h @@ -1,77 +1,75 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKWORKBENCHINTROPART_H_ #define QMITKWORKBENCHINTROPART_H_ #include #include #include /** * \ingroup org_mitk_gui_qt_welcomescreen_internal * \brief QmitkMitkWorkbenchIntroPart * The WelcomeView Module is an helpful feature to people new to MITK. The main idea is to provide first * information about the MITK Workbench. * The WelcomeView is realized by making use of the QTWebKit Module. The Qt WebKit module * provides an HTML browser engine that makes it easy to embed web content into native applications, and to enhance * web content with native controls. * For the welcome view of the application the QWebView, QWebPage classes have been used. The shown WelcomeView * html start page is styled by an external css stylesheet. The required resources as well as the html pages are integrated * into the QtResource system. The QT resource system allows the storage of files like html pages, css pages, jpgs etc. * as binaries within the executable. * This minimizes the risk of loosing resource files as well as the risk of getting files deleted. In order to use the Qt * resource system the resource files have to be added to the associated qrt resource file list. * * The foundation is set to design more complex html pages. The Q::WebPage gives options to set a * LinkDelegationPolicy. The used policy defines how links to external or internal resources are handled. To fit our needs * the delegate all links policy is used. This requires all external as well as internal links of the html pages to be handle * explicitly. In order to change mitk working modes (perspectives) a mitk url scheme has been designed. The url scheme * is set to mitk. The url host provides information about what's next to do. In our case, the case of switching to a * particular working mode the host is set to perspectives. The followed path provides information about the perspective id. * (e.g. mitk//::mitk.perspectives/org.mitk.qt.defaultperspective) The the generic design of the mitk url scheme allows to * execute other task depending on the mitk url host. * \sa QmitkWelcomePage Editor */ class QmitkMitkWorkbenchIntroPart : public berry::QtIntroPart { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: QmitkMitkWorkbenchIntroPart(); ~QmitkMitkWorkbenchIntroPart() override; - void CreateQtPartControl(QWidget *parent) override; - void StandbyStateChanged(bool) override; - void SetFocus() override; + void ReloadPage(); - virtual void CreateConnections(); - -protected: +private: + void CreateConnections(); + void OnLoadFinished(bool ok); Ui::QmitkWelcomeScreenViewControls* m_Controls; class Impl; Impl* m_Impl; }; #endif /* QMITKWORKBENCHINTROPART_H_ */ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp index c38924e45c..a0af12b0f1 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp @@ -1,53 +1,55 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMitkWorkbenchIntroPlugin.h" #include "QmitkMitkWorkbenchIntroPart.h" +#include "QmitkMitkWorkbenchIntroPreferencePage.h" #include #include #include #include #include #include QmitkMitkWorkbenchIntroPlugin* QmitkMitkWorkbenchIntroPlugin::inst = nullptr; QmitkMitkWorkbenchIntroPlugin::QmitkMitkWorkbenchIntroPlugin() { inst = this; } QmitkMitkWorkbenchIntroPlugin::~QmitkMitkWorkbenchIntroPlugin() { } QmitkMitkWorkbenchIntroPlugin* QmitkMitkWorkbenchIntroPlugin::GetDefault() { return inst; } void QmitkMitkWorkbenchIntroPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; - BERRY_REGISTER_EXTENSION_CLASS(QmitkMitkWorkbenchIntroPart, context); + BERRY_REGISTER_EXTENSION_CLASS(QmitkMitkWorkbenchIntroPart, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkMitkWorkbenchIntroPreferencePage, context) } ctkPluginContext* QmitkMitkWorkbenchIntroPlugin::GetPluginContext() const { return context; } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp new file mode 100644 index 0000000000..f1222ec90f --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp @@ -0,0 +1,76 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#include "QmitkMitkWorkbenchIntroPreferencePage.h" +#include "QmitkMitkWorkbenchIntroPart.h" + +#include +#include +#include + +#include + +QmitkMitkWorkbenchIntroPreferencePage::QmitkMitkWorkbenchIntroPreferencePage() + : m_Ui(new Ui::QmitkMitkWorkbenchIntroPreferencePage), + m_Control(nullptr) +{ +} + +QmitkMitkWorkbenchIntroPreferencePage::~QmitkMitkWorkbenchIntroPreferencePage() +{ +} + +void QmitkMitkWorkbenchIntroPreferencePage::Init(berry::IWorkbench::Pointer) +{ +} + +void QmitkMitkWorkbenchIntroPreferencePage::CreateQtControl(QWidget* parent) +{ + auto* prefService = berry::Platform::GetPreferencesService(); + m_MitkWorkbenchIntroPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.qt.extapplicationintro"); + + m_Control = new QWidget(parent); + m_Ui->setupUi(m_Control); + + this->Update(); +} + +QWidget* QmitkMitkWorkbenchIntroPreferencePage::GetQtControl() const +{ + return m_Control; +} + +bool QmitkMitkWorkbenchIntroPreferencePage::PerformOk() +{ + m_MitkWorkbenchIntroPreferencesNode->PutBool("show tips", m_Ui->showTipsCheckBox->isChecked()); + + auto intro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->GetIntro(); + + if (intro.IsNotNull()) + { + auto* workbenchIntro = dynamic_cast(intro.GetPointer()); + + if (workbenchIntro != nullptr) + workbenchIntro->ReloadPage(); + } + + return true; +} + +void QmitkMitkWorkbenchIntroPreferencePage::PerformCancel() +{ +} + +void QmitkMitkWorkbenchIntroPreferencePage::Update() +{ + m_Ui->showTipsCheckBox->setChecked(m_MitkWorkbenchIntroPreferencesNode->GetBool("show tips", true)); +} diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h new file mode 100644 index 0000000000..e41d1e0c89 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h @@ -0,0 +1,46 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef QmitkMitkWorkbenchIntroPreferencePage_h +#define QmitkMitkWorkbenchIntroPreferencePage_h + +#include + +namespace Ui +{ + class QmitkMitkWorkbenchIntroPreferencePage; +} + +class QmitkMitkWorkbenchIntroPreferencePage : public QObject, public berry::IQtPreferencePage +{ + Q_OBJECT + Q_INTERFACES(berry::IPreferencePage) + +public: + QmitkMitkWorkbenchIntroPreferencePage(); + ~QmitkMitkWorkbenchIntroPreferencePage() override; + + void Init(berry::IWorkbench::Pointer workbench) override; + void CreateQtControl(QWidget* parent) override; + QWidget* GetQtControl() const override; + bool PerformOk() override; + void PerformCancel() override; + void Update() override; + +private: + berry::IPreferences::Pointer m_MitkWorkbenchIntroPreferencesNode; + + Ui::QmitkMitkWorkbenchIntroPreferencePage* m_Ui; + QWidget* m_Control; +}; + +#endif diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.ui b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.ui new file mode 100644 index 0000000000..b56753d42f --- /dev/null +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.ui @@ -0,0 +1,44 @@ + + + QmitkMitkWorkbenchIntroPreferencePage + + + + 0 + 0 + 400 + 300 + + + + Welcome Page + + + + + + Show tips + + + true + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/CMakeLists.txt b/Plugins/org.mitk.gui.qt.multilabelsegmentation/CMakeLists.txt deleted file mode 100644 index 235d87da4b..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -project(org_mitk_gui_qt_multilabelsegmentation) - -include_directories(${CTK_INCLUDE_DIRS}) - -mitk_create_plugin( - EXPORT_DIRECTIVE MITK_QT_SEGMENTATION - EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS MitkSegmentation MitkSegmentationUI -) diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentation.dox b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentation.dox deleted file mode 100644 index bfd845dd11..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentation.dox +++ /dev/null @@ -1,99 +0,0 @@ -/** -\page org_mitk_views_multilabelsegmentation The Multilabel Segmentation - -\imageMacro{multilabelsegmentation_utilities.svg, "Icon of the Multilabel Segmentation Utilities Plugin", 5.00} - -The Multilabel Segmentation plugin consists of one view which can be used for: -
    -
  • multilabel segmentation postprocessing -
- -Hereinafter, a description is given on how multilabel segmentations can be modified. -Please refer to \ref org_mitk_views_segmentation for a description of the general segmentation tools. - -\tableofcontents - -\section org_mitk_views_multilabelsegmentationutilitiesoverview Overview - -The Multilabel Segmentation Utilities Plugin allows to postprocess existing segmentations. Currently five different operations exist: - -
    -
  • \ref org_mitk_views_multilabelsegmentationutilitiesbooleanoperations -
  • \ref org_mitk_views_multilabelsegmentationutilitiescontourtoimage -
  • \ref org_mitk_views_multilabelsegmentationutilitiesimagemasking -
  • \ref org_mitk_views_multilabelsegmentationutilitiesmorphologicaloperations -
  • \ref org_mitk_views_multilabelsegmentationutilitiessurfacetoimage -
  • \ref org_mitk_views_multilabelsegmentationutilitiesconverttomultilabel -
- -\imageMacro{QmitkMultiLabelSegmentationUtilities_Overview.png, "The Multilabel Segmentation Utilities View",16.00} - -\section org_mitk_views_multilabelsegmentationutilitiesdataselection Data Selection - -All postprocessing operations provide one or more selection widgets, which allow to select the data for the operation. - -\section org_mitk_views_multilabelsegmentationutilitiesbooleanoperations Boolean operations - -Boolean operations allow to perform the following fundamental operations on two segmentations: - -
    -
  • Difference: Subtracts the second segmentation from the first segmentation. -
  • Intersection: Extracts the overlapping areas of the two selected segmentations. -
  • Union: Combines the two existing segmentations. -
- -The selected segmentations must have the same geometry (size, spacing, ...) in order for the operations to work correctly. -The result will be stored in a new data node as a child node of the first selected segmentation. - -\imageMacro{QmitkMultiLabelSegmentationUtilities_BooleanOperations.png,"Boolean operations",6.00} - -\section org_mitk_views_multilabelsegmentationutilitiescontourtoimage Contour to image - -Contour to image allows to create a segmentation out of a given contour-model. -The operation requires a contour model set and a reference image. -The created segmentation image will have the same geometrical properties like the reference image (dimension, size and Geometry3D). - -\imageMacro{QmitkMultiLabelSegmentationUtilities_ContourToImage.png,"Contour to image",6.00} - -\section org_mitk_views_multilabelsegmentationutilitiesimagemasking Image masking - -Image masking allows to mask an image with either an existing segmentation or a surface. -The operation requires an image and a binary image mask or a surface. -The result will be an image containing only the pixels that are covered by the respective mask. -Depending on the selected mode ("make output binary" or "overwrite foreground" / "overwrite background") -the result will be a simple image or a binary image. - -\imageMacro{QmitkMultiLabelSegmentationUtilities_ImageMasking.png,"Image masking",6.00} - -\section org_mitk_views_multilabelsegmentationutilitiesmorphologicaloperations Morphological operations - -Morphological operations are applied to a single segmentation image. Based on a given structuring element the underlying segmentation will be modfied. -The plugin provides a ball and a cross as structuring elements. The follow operations are available: - -
    -
  • Dilation: Each labeled pixel within the segmentation will be dilated based on the selected structuring element. -
  • Erosion: Each labeled pixel within the segmentation will be eroded based on the selected structuring element. -
  • Opening: An erosion followed by a dilation, used for filling small holes. -
  • Closing: A dilation followed by an erosion, used for smoothing edges or eliminating small objects. -
  • Fill Holes: Fills bigger holes within a segmentation. -
- -\imageMacro{QmitkMultiLabelSegmentationUtilities_MorphologicalOperations.png,"Morphological operations",6.00} - -\section org_mitk_views_multilabelsegmentationutilitiessurfacetoimage Surface to image - -Surface to image allows to create a segmentation out of a given surface. -The operation requires a surface and a reference image. -The created segmentation image will have the same geometrical properties like the reference image (dimension, size and Geometry3D). -Depending on the selected mode ("make output binary" or "overwrite background") -the result will be a simple image or a binary image. - -\imageMacro{QmitkMultiLabelSegmentationUtilities_SurfaceToImage.png,"Surface to image",6.00} - -\section org_mitk_views_multilabelsegmentationutilitiesconverttomultilabel Convert to Multilabel - -Convert to multilabel allows to interpret the pixel values of a given image as label IDs and convert the image content into the respective Multilabel image. -The new segmentation will contain one layer with as many labels as the original image contains different pixel values. - -\imageMacro{QmitkMultiLabelSegmentationUtilities_ConvertToMultilabel.png,"Convert to Multilabel",6.00} -*/ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_BooleanOperations.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_BooleanOperations.png deleted file mode 100644 index d6ab9a24d2..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_BooleanOperations.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ContourToImage.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ContourToImage.png deleted file mode 100644 index 3d1bd4b980..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ContourToImage.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ConvertToMultilabel.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ConvertToMultilabel.png deleted file mode 100644 index cb7ab21d58..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ConvertToMultilabel.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ImageMasking.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ImageMasking.png deleted file mode 100644 index dc948cc0ab..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_ImageMasking.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_MorphologicalOperations.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_MorphologicalOperations.png deleted file mode 100644 index d11d3cf94c..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_MorphologicalOperations.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_Overview.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_Overview.png deleted file mode 100644 index 0a1a1a3990..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_Overview.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_SurfaceToImage.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_SurfaceToImage.png deleted file mode 100644 index 0c06b7191d..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/QmitkMultiLabelSegmentationUtilities_SurfaceToImage.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/multilabelsegmentation-dox.svg b/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/multilabelsegmentation-dox.svg deleted file mode 100644 index 9b24feb3b2..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/documentation/UserManual/multilabelsegmentation-dox.svg +++ /dev/null @@ -1,10683 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/files.cmake b/Plugins/org.mitk.gui.qt.multilabelsegmentation/files.cmake deleted file mode 100644 index b7307305ef..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/files.cmake +++ /dev/null @@ -1,85 +0,0 @@ -set(SRC_CPP_FILES -) - -set(INTERNAL_CPP_FILES - mitkPluginActivator.cpp - QmitkThresholdAction.cpp - QmitkConvertSurfaceToLabelAction.cpp - QmitkConvertMaskToLabelAction.cpp - QmitkConvertToMultiLabelSegmentationAction.cpp - QmitkCreateMultiLabelSegmentationAction.cpp - Common/QmitkDataSelectionWidget.cpp - SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.cpp - SegmentationUtilities/QmitkSegmentationUtilityWidget.cpp - SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.cpp - SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.cpp - SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.cpp - SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.cpp - SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.cpp - SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.cpp -) - -set(UI_FILES - src/internal/Common/QmitkDataSelectionWidgetControls.ui - src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesViewControls.ui - src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidgetControls.ui - src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidgetControls.ui - src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidgetControls.ui - src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidgetControls.ui - src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidgetControls.ui - src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidgetControls.ui -) - -set(MOC_H_FILES - src/internal/mitkPluginActivator.h - src/internal/QmitkThresholdAction.h - src/internal/QmitkConvertSurfaceToLabelAction.h - src/internal/QmitkConvertMaskToLabelAction.h - src/internal/QmitkConvertToMultiLabelSegmentationAction.h - src/internal/QmitkCreateMultiLabelSegmentationAction.h - src/internal/Common/QmitkDataSelectionWidget.h - src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.h - src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.h - src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.h - src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.h - src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.h - src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.h - src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.h - src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.h -) - -set(CACHED_RESOURCE_FILES - resources/BooleanDifference_48x48.png - resources/BooleanIntersection_48x48.png - resources/BooleanOperations_48x48.png - resources/BooleanUnion_48x48.png - resources/Closing_48x48.png - resources/CTKWidgets_48x48.png - resources/deformablePlane.png - resources/Dilate_48x48.png - resources/Erode_48x48.png - resources/FillHoles_48x48.png - resources/Icons.svg - resources/ImageMasking_48x48.png - resources/MorphologicalOperations_48x48.png - resources/multilabelsegmentation_utilities.svg - resources/Opening_48x48.png - resources/SurfaceToImage_48x48.png - plugin.xml -) - -set(QRC_FILES - resources/MultiLabelSegmentationUtilities.qrc - resources/MorphologicalOperationsWidget.qrc - resources/BooleanOperationsWidget.qrc -) - -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/Plugins/org.mitk.gui.qt.multilabelsegmentation/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.multilabelsegmentation/manifest_headers.cmake deleted file mode 100644 index 0821c13120..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/manifest_headers.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(Plugin-Name "MITK MultiLabelSegmentation") -set(Plugin-Version "1.0.0") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "https://www.mitk.org") -set(Require-Plugin org.mitk.gui.qt.common org.mitk.gui.qt.datamanager org.mitk.gui.qt.segmentation) diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/plugin.xml b/Plugins/org.mitk.gui.qt.multilabelsegmentation/plugin.xml deleted file mode 100644 index 183ccc3b53..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/plugin.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanDifference_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanDifference_48x48.png deleted file mode 100644 index 89a7c9322c..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanDifference_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanIntersection_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanIntersection_48x48.png deleted file mode 100644 index b7301f31f5..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanIntersection_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanOperationsWidget.qrc b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanOperationsWidget.qrc deleted file mode 100644 index ef0eab4b45..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanOperationsWidget.qrc +++ /dev/null @@ -1,7 +0,0 @@ - - - BooleanDifference_48x48.png - BooleanIntersection_48x48.png - BooleanUnion_48x48.png - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanOperations_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanOperations_48x48.png deleted file mode 100644 index 80d782df23..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanOperations_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanUnion_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanUnion_48x48.png deleted file mode 100644 index 4b01a6d74c..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/BooleanUnion_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/CTKWidgets_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/CTKWidgets_48x48.png deleted file mode 100644 index 34faebcdef..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/CTKWidgets_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Closing_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Closing_48x48.png deleted file mode 100644 index 15fe6abe6d..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Closing_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/ContourModelSetToImage_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/ContourModelSetToImage_48x48.png deleted file mode 100644 index 43b53ece52..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/ContourModelSetToImage_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Dilate_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Dilate_48x48.png deleted file mode 100644 index ac913b3e10..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Dilate_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Erode_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Erode_48x48.png deleted file mode 100644 index 9a1d09b660..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Erode_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/FillHoles_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/FillHoles_48x48.png deleted file mode 100644 index 8a326f3230..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/FillHoles_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Icons.svg b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Icons.svg deleted file mode 100644 index c1eb90def4..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Icons.svg +++ /dev/null @@ -1,3502 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - AND - OR - - - MULTI - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MULTI - MULTI - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/ImageMasking_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/ImageMasking_48x48.png deleted file mode 100644 index a35ade441e..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/ImageMasking_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MorphologicalOperationsWidget.qrc b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MorphologicalOperationsWidget.qrc deleted file mode 100644 index 3fe0afc1f8..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MorphologicalOperationsWidget.qrc +++ /dev/null @@ -1,9 +0,0 @@ - - - Dilate_48x48.png - Erode_48x48.png - Closing_48x48.png - Opening_48x48.png - FillHoles_48x48.png - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MorphologicalOperations_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MorphologicalOperations_48x48.png deleted file mode 100644 index 758b42cd4d..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MorphologicalOperations_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MultiLabelSegmentationUtilities.qrc b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MultiLabelSegmentationUtilities.qrc deleted file mode 100644 index 035549a939..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/MultiLabelSegmentationUtilities.qrc +++ /dev/null @@ -1,11 +0,0 @@ - - - BooleanOperations_48x48.png - ContourModelSetToImage_48x48.png - ImageMasking_48x48.png - MorphologicalOperations_48x48.png - SurfaceToImage_48x48.png - multilabelsegmentation_utilities.svg - CTKWidgets_48x48.png - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Opening_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Opening_48x48.png deleted file mode 100644 index 9f6fba8237..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/Opening_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/SurfaceToImage_48x48.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/SurfaceToImage_48x48.png deleted file mode 100644 index d7c89a0b3a..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/SurfaceToImage_48x48.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/deformablePlane.png b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/deformablePlane.png deleted file mode 100644 index 79a7d54ed7..0000000000 Binary files a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/deformablePlane.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/multilabelsegmentation_utilities.svg b/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/multilabelsegmentation_utilities.svg deleted file mode 100644 index ef34d33a6c..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/resources/multilabelsegmentation_utilities.svg +++ /dev/null @@ -1,9155 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidget.cpp deleted file mode 100644 index 1f41da6364..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidget.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkDataSelectionWidget.h" -#include "internal/mitkPluginActivator.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -static mitk::NodePredicateBase::Pointer CreatePredicate(QmitkDataSelectionWidget::PredicateType predicateType) -{ - auto nonHelperObject = mitk::NodePredicateNot::New(mitk::NodePredicateOr::New( - mitk::NodePredicateProperty::New("helper object"), - mitk::NodePredicateProperty::New("hidden object"))); - - auto imageType = mitk::TNodePredicateDataType::New(); - auto contourModelType = mitk::TNodePredicateDataType::New(); - auto contourModelSetType = mitk::TNodePredicateDataType::New(); - - auto segmentationPredicate = mitk::TNodePredicateDataType::New(); - - auto maskPredicate = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); - - auto isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); - auto isDti = mitk::NodePredicateDataType::New("TensorImage"); - auto isOdf = mitk::NodePredicateDataType::New("OdfImage"); - auto isImage = mitk::TNodePredicateDataType::New(); - - auto validImages = mitk::NodePredicateOr::New(); - validImages->AddPredicate(isImage); - validImages->AddPredicate(isDwi); - validImages->AddPredicate(isDti); - validImages->AddPredicate(isOdf); - - auto imagePredicate = mitk::NodePredicateAnd::New(); - imagePredicate->AddPredicate(validImages); - imagePredicate->AddPredicate(mitk::NodePredicateNot::New(segmentationPredicate)); - imagePredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)))); - - auto surfacePredicate = mitk::TNodePredicateDataType::New(); - - mitk::NodePredicateBase::Pointer result; - - switch(predicateType) - { - case QmitkDataSelectionWidget::ImagePredicate: - result = imagePredicate.GetPointer(); - break; - - case QmitkDataSelectionWidget::SegmentationPredicate: - result = segmentationPredicate.GetPointer(); - break; - - case QmitkDataSelectionWidget::SurfacePredicate: - result = surfacePredicate.GetPointer(); - break; - - case QmitkDataSelectionWidget::ImageAndSegmentationPredicate: - result = imageType.GetPointer(); - break; - - case QmitkDataSelectionWidget::ContourModelPredicate: - result = mitk::NodePredicateOr::New( - contourModelSetType, - contourModelSetType).GetPointer(); - break; - - case QmitkDataSelectionWidget::MaskPredicate: - result = maskPredicate.GetPointer(); - break; - - default: - assert(false && "Unknown predefined predicate!"); - return nullptr; - } - - return mitk::NodePredicateAnd::New(result, nonHelperObject).GetPointer(); -} - -QmitkDataSelectionWidget::QmitkDataSelectionWidget(QWidget* parent) - : QWidget(parent) -{ - m_Controls.setupUi(this); - m_Controls.helpLabel->hide(); -} - -QmitkDataSelectionWidget::~QmitkDataSelectionWidget() -{ -} - -unsigned int QmitkDataSelectionWidget::AddDataSelection(QmitkDataSelectionWidget::PredicateType predicate) -{ - QString hint = "Select node"; - - switch (predicate) - { - case QmitkDataSelectionWidget::ImagePredicate: - hint = "Select an image"; - break; - - case QmitkDataSelectionWidget::MaskPredicate: - hint = "Select a binary mask"; - break; - - case QmitkDataSelectionWidget::SegmentationPredicate: - hint = "Select an ML segmentation"; - break; - - case QmitkDataSelectionWidget::SurfacePredicate: - hint = "Select a surface"; - break; - - case QmitkDataSelectionWidget::ImageAndSegmentationPredicate: - hint = "Select an image or segmentation"; - break; - - case QmitkDataSelectionWidget::ContourModelPredicate: - hint = "Select a contour model"; - break; - } - - return this->AddDataSelection("", hint, hint, "", predicate); -} - -unsigned int QmitkDataSelectionWidget::AddDataSelection(mitk::NodePredicateBase* predicate) -{ - return this->AddDataSelection("", "Select a node", "Select a node", "", predicate); -} - -unsigned int QmitkDataSelectionWidget::AddDataSelection(const QString &labelText, const QString &info, const QString &popupTitel, const QString &popupHint, QmitkDataSelectionWidget::PredicateType predicate) -{ - return this->AddDataSelection(labelText, info, popupHint, popupTitel, CreatePredicate(predicate)); -} - -unsigned int QmitkDataSelectionWidget::AddDataSelection(const QString &labelText, const QString &info, const QString &popupTitel, const QString &popupHint, 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); - } - - QmitkSingleNodeSelectionWidget* nodeSelection = new QmitkSingleNodeSelectionWidget(m_Controls.dataSelectionWidget); - - nodeSelection->SetSelectionIsOptional(false); - nodeSelection->SetInvalidInfo(info); - nodeSelection->SetPopUpTitel(popupTitel); - nodeSelection->SetPopUpHint(popupHint); - nodeSelection->SetDataStorage(this->GetDataStorage()); - nodeSelection->SetNodePredicate(predicate); - nodeSelection->SetAutoSelectNewNodes(true); - nodeSelection->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); - nodeSelection->setMinimumSize(0, 40); - - connect(nodeSelection, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkDataSelectionWidget::OnSelectionChanged); - - m_Controls.gridLayout->addWidget(nodeSelection, row, 1); - - m_NodeSelectionWidgets.push_back(nodeSelection); - return static_cast(m_NodeSelectionWidgets.size() - 1); -} - -mitk::DataStorage::Pointer QmitkDataSelectionWidget::GetDataStorage() const -{ - ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference(); - assert(ref == true); - - mitk::IDataStorageService* service = mitk::PluginActivator::getContext()->getService(ref); - - assert(service); - - return service->GetDefaultDataStorage()->GetDataStorage(); -} - -mitk::DataNode::Pointer QmitkDataSelectionWidget::GetSelection(unsigned int index) -{ - assert(index < m_NodeSelectionWidgets.size()); - return m_NodeSelectionWidgets[index]->GetSelectedNode(); -} - -void QmitkDataSelectionWidget::SetPredicate(unsigned int index, PredicateType predicate) -{ - this->SetPredicate(index, CreatePredicate(predicate)); -} - -void QmitkDataSelectionWidget::SetPredicate(unsigned int index, mitk::NodePredicateBase* predicate) -{ - assert(index < m_NodeSelectionWidgets.size()); - m_NodeSelectionWidgets[index]->SetNodePredicate(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(QList selection) -{ - std::vector::iterator it = std::find(m_NodeSelectionWidgets.begin(), m_NodeSelectionWidgets.end(), sender()); - assert(it != m_NodeSelectionWidgets.end()); - - const mitk::DataNode* result = nullptr; - if (!selection.empty()) - { - result = selection.front(); - } - emit SelectionChanged(std::distance(m_NodeSelectionWidgets.begin(), it), result); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidget.h deleted file mode 100644 index 021ec73920..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidget.h +++ /dev/null @@ -1,68 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkDataSelectionWidget_h -#define QmitkDataSelectionWidget_h - -#include -#include -#include -#include - -namespace mitk -{ - class NodePredicateBase; -} - -class QmitkSingleNodeSelectionWidget; - -class QmitkDataSelectionWidget : public QWidget -{ - Q_OBJECT - -public: - enum PredicateType - { - ImagePredicate, - SegmentationPredicate, - SurfacePredicate, - ImageAndSegmentationPredicate, - ContourModelPredicate, - MaskPredicate - }; - - explicit QmitkDataSelectionWidget(QWidget* parent = nullptr); - ~QmitkDataSelectionWidget() override; - - unsigned int AddDataSelection(PredicateType predicate); - unsigned int AddDataSelection(mitk::NodePredicateBase* predicate = nullptr); - unsigned int AddDataSelection(const QString &labelText, const QString &info, const QString &popupTitel, const QString &popupHint, PredicateType predicate); - unsigned int AddDataSelection(const QString &labelText, const QString &info, const QString &popupTitel, const QString &popupHint, mitk::NodePredicateBase* predicate = nullptr); - - mitk::DataStorage::Pointer GetDataStorage() const; - mitk::DataNode::Pointer GetSelection(unsigned int index); - void SetPredicate(unsigned int index, PredicateType predicate); - void SetPredicate(unsigned int index, mitk::NodePredicateBase* predicate); - void SetHelpText(const QString& text); - -signals: - void SelectionChanged(unsigned int index, const mitk::DataNode* selection); - -private slots: - void OnSelectionChanged(QList selection); - -private: - Ui::QmitkDataSelectionWidgetControls m_Controls; - std::vector m_NodeSelectionWidgets; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidgetControls.ui deleted file mode 100644 index 95f4cf4bf3..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/Common/QmitkDataSelectionWidgetControls.ui +++ /dev/null @@ -1,82 +0,0 @@ - - - QmitkDataSelectionWidgetControls - - - - 0 - 0 - 333 - 191 - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - Data Selection - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - 0 - 0 - - - - color: red - - - - - - true - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkThresholdAction.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkThresholdAction.cpp deleted file mode 100644 index 124efb9682..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkThresholdAction.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include "QmitkThresholdAction.h" - -// MITK -#include -#include -#include - -// Qt -#include -#include -#include -#include - -using namespace berry; -using namespace mitk; -using namespace std; - -QmitkThresholdAction::QmitkThresholdAction() -{ -} - -QmitkThresholdAction::~QmitkThresholdAction() -{ -} - -void QmitkThresholdAction::Run(const QList &selectedNodes) -{ - m_ThresholdingToolManager = ToolManager::New(m_DataStorage); - - m_ThresholdingToolManager->RegisterClient(); - - Tool *binaryThresholdTool = m_ThresholdingToolManager->GetToolById(m_ThresholdingToolManager->GetToolIdByToolType()); - if (binaryThresholdTool != nullptr) - { - QmitkBinaryThresholdToolGUI *gui = dynamic_cast(binaryThresholdTool->GetGUI("Qmitk", "GUI").GetPointer()); - if (gui != nullptr) - { - QDialog thresholdingDialog(QApplication::activeWindow(), Qt::Window | Qt::WindowStaysOnTopHint); - - thresholdingDialog.setWindowFlags(thresholdingDialog.windowFlags() & ~Qt::WindowMinimizeButtonHint); - - QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(rejected()), &thresholdingDialog, SLOT(reject())); - connect(gui, SIGNAL(thresholdAccepted()), &thresholdingDialog, SLOT(reject())); - - QVBoxLayout *layout = new QVBoxLayout; - layout->setContentsMargins(3, 3, 3, 3); - - gui->SetTool(binaryThresholdTool); - gui->setParent(&thresholdingDialog); - - layout->addWidget(gui); - layout->addWidget(buttonBox); - - thresholdingDialog.setLayout(layout); - thresholdingDialog.setMinimumWidth(350); - - m_SelectedNode = selectedNodes[0]; - m_ThresholdingToolManager->SetReferenceData(selectedNodes[0]); - m_ThresholdingToolManager->ActivateTool(m_ThresholdingToolManager->GetToolIdByToolType()); - - m_ThresholdingToolManager->ActiveToolChanged += mitk::MessageDelegate(this, &QmitkThresholdAction::OnThresholdingToolManagerToolModified); - thresholdingDialog.exec(); - m_ThresholdingToolManager->ActiveToolChanged -= mitk::MessageDelegate(this, &QmitkThresholdAction::OnThresholdingToolManagerToolModified); - - m_ThresholdingToolManager->SetReferenceData(nullptr); - m_ThresholdingToolManager->ActivateTool(-1); - m_SelectedNode = nullptr; - } - } - - m_ThresholdingToolManager->UnregisterClient(); -} - -void QmitkThresholdAction::OnThresholdingToolManagerToolModified() -{ - if (m_ThresholdingToolManager.IsNotNull()) - { - if (m_ThresholdingToolManager->GetActiveToolID() < 0) - { - m_ThresholdingToolManager->SetReferenceData(m_SelectedNode); - m_ThresholdingToolManager->ActivateTool(m_ThresholdingToolManager->GetToolIdByToolType()); - } - } -} - -void QmitkThresholdAction::SetDataStorage(DataStorage *dataStorage) -{ - m_DataStorage = dataStorage; -} - -void QmitkThresholdAction::SetSmoothed(bool) -{ -} - -void QmitkThresholdAction::SetDecimated(bool) -{ -} - -void QmitkThresholdAction::SetFunctionality(QtViewPart* /*functionality*/) -{ -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkThresholdAction.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkThresholdAction.h deleted file mode 100644 index 11c36bb626..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkThresholdAction.h +++ /dev/null @@ -1,53 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef QMITKTHRESHOLDACTION_H -#define QMITKTHRESHOLDACTION_H - -#include - -// Parent classes -#include -#include - -// Data members -#include -#include - - -class MITK_QT_SEGMENTATION QmitkThresholdAction : public QObject, public mitk::IContextMenuAction -{ - Q_OBJECT - Q_INTERFACES(mitk::IContextMenuAction) - -public: - QmitkThresholdAction(); - ~QmitkThresholdAction() override; - - // IContextMenuAction - void Run(const QList &selectedNodes) override; - void SetDataStorage(mitk::DataStorage *dataStorage) override; - void SetSmoothed(bool smoothed) override; - void SetDecimated(bool decimated) override; - void SetFunctionality(berry::QtViewPart *functionality) override; - - void OnThresholdingToolManagerToolModified(); - -private: - QmitkThresholdAction(const QmitkThresholdAction &); - QmitkThresholdAction & operator=(const QmitkThresholdAction &); - - mitk::DataNode::Pointer m_SelectedNode; - mitk::DataStorage::Pointer m_DataStorage; - mitk::ToolManager::Pointer m_ThresholdingToolManager; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.cpp deleted file mode 100644 index 874d15aefb..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkBooleanOperationsWidget.h" -#include "../../Common/QmitkDataSelectionWidget.h" -#include -#include -#include - -static const char* const HelpText = "Select two different masks above"; - -namespace -{ - std::string GetPrefix(mitk::BooleanOperation::Type type) - { - switch (type) - { - case mitk::BooleanOperation::Difference: - return "DifferenceFrom_"; - - case mitk::BooleanOperation::Intersection: - return "IntersectionWith_"; - - case mitk::BooleanOperation::Union: - return "UnionWith_"; - - default: - assert(false && "Unknown boolean operation type"); - return "UNKNOWN_BOOLEAN_OPERATION_WITH_"; - } - } - - void AddToDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::Image::Pointer segmentation, const std::string& name, mitk::DataNode::Pointer parent = nullptr) - { - mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); - - dataNode->SetBoolProperty("binary", true); - dataNode->SetName(name); - dataNode->SetData(segmentation); - - dataStorage->Add(dataNode, parent); - } -} - -QmitkBooleanOperationsWidget::QmitkBooleanOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QmitkSegmentationUtilityWidget(timeNavigationController, parent) -{ - m_Controls.setupUi(this); - - m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::MaskPredicate); - m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::MaskPredicate); - - m_Controls.dataSelectionWidget->SetHelpText(HelpText); - - connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); - connect(m_Controls.differenceButton, SIGNAL(clicked()), this, SLOT(OnDifferenceButtonClicked())); - connect(m_Controls.intersectionButton, SIGNAL(clicked()), this, SLOT(OnIntersectionButtonClicked())); - connect(m_Controls.unionButton, SIGNAL(clicked()), this, SLOT(OnUnionButtonClicked())); -} - -QmitkBooleanOperationsWidget::~QmitkBooleanOperationsWidget() -{ -} - -void QmitkBooleanOperationsWidget::OnSelectionChanged(unsigned int, const mitk::DataNode*) -{ - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - - mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0); - mitk::DataNode::Pointer node1 = dataSelectionWidget->GetSelection(1); - - if (node0.IsNotNull() && node1.IsNotNull() && node0 != node1) - { - dataSelectionWidget->SetHelpText(""); - this->EnableButtons(); - } - else - { - dataSelectionWidget->SetHelpText(HelpText); - this->EnableButtons(false); - } -} - -void QmitkBooleanOperationsWidget::EnableButtons(bool enable) -{ - m_Controls.differenceButton->setEnabled(enable); - m_Controls.intersectionButton->setEnabled(enable); - m_Controls.unionButton->setEnabled(enable); -} - -void QmitkBooleanOperationsWidget::OnDifferenceButtonClicked() -{ - this->DoBooleanOperation(mitk::BooleanOperation::Difference); -} - -void QmitkBooleanOperationsWidget::OnIntersectionButtonClicked() -{ - this->DoBooleanOperation(mitk::BooleanOperation::Intersection); -} - -void QmitkBooleanOperationsWidget::OnUnionButtonClicked() -{ - this->DoBooleanOperation(mitk::BooleanOperation::Union); -} - -void QmitkBooleanOperationsWidget::DoBooleanOperation(mitk::BooleanOperation::Type type) -{ - mitk::SliceNavigationController* timeNavigationController = this->GetTimeNavigationController(); - assert(timeNavigationController != nullptr); - - mitk::Image::Pointer segmentation0 = static_cast(m_Controls.dataSelectionWidget->GetSelection(0)->GetData()); - mitk::Image::Pointer segmentation1 = static_cast(m_Controls.dataSelectionWidget->GetSelection(1)->GetData()); - mitk::Image::Pointer result; - - try - { - mitk::BooleanOperation booleanOperation(type, segmentation0, segmentation1, timeNavigationController->GetSelectedTimePoint()); - result = booleanOperation.GetResult(); - } - catch (const mitk::Exception &exception) - { - MITK_ERROR << "Boolean operation failed: " << exception.GetDescription(); - } - - assert(result.IsNotNull()); - - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - - AddToDataStorage( - dataSelectionWidget->GetDataStorage(), - result, - GetPrefix(type) + dataSelectionWidget->GetSelection(1)->GetName(), - dataSelectionWidget->GetSelection(0)); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.h deleted file mode 100644 index 76e56b16a8..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.h +++ /dev/null @@ -1,41 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkBooleanOperationsWidget_h -#define QmitkBooleanOperationsWidget_h - -#include "../QmitkSegmentationUtilityWidget.h" -#include -#include - -class QmitkBooleanOperationsWidget : public QmitkSegmentationUtilityWidget -{ - Q_OBJECT - -public: - explicit QmitkBooleanOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - ~QmitkBooleanOperationsWidget() override; - -private slots: - void OnSelectionChanged(unsigned int index, const mitk::DataNode* selection); - void OnDifferenceButtonClicked(); - void OnIntersectionButtonClicked(); - void OnUnionButtonClicked(); - -private: - void EnableButtons(bool enable = true); - void DoBooleanOperation(mitk::BooleanOperation::Type type); - - Ui::QmitkBooleanOperationsWidgetControls m_Controls; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidgetControls.ui deleted file mode 100644 index 48d2334831..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidgetControls.ui +++ /dev/null @@ -1,169 +0,0 @@ - - - QmitkBooleanOperationsWidgetControls - - - - 0 - 0 - 210 - 91 - - - - - - - - 0 - 0 - - - - - - - - - - false - - - - 0 - 0 - - - - Difference - - - - :/MultiLabelSegmentationUtilities/BooleanOperations/BooleanDifference_48x48.png:/MultiLabelSegmentationUtilities/BooleanOperations/BooleanDifference_48x48.png - - - - 24 - 24 - - - - false - - - false - - - Qt::ToolButtonTextUnderIcon - - - Qt::NoArrow - - - - - - - false - - - - 0 - 0 - - - - Intersection - - - - :/MultiLabelSegmentationUtilities/BooleanOperations/BooleanIntersection_48x48.png:/MultiLabelSegmentationUtilities/BooleanOperations/BooleanIntersection_48x48.png - - - - 24 - 24 - - - - false - - - false - - - Qt::ToolButtonTextUnderIcon - - - Qt::NoArrow - - - - - - - false - - - - 0 - 0 - - - - Union - - - - :/MultiLabelSegmentationUtilities/BooleanOperations/BooleanUnion_48x48.png:/MultiLabelSegmentationUtilities/BooleanOperations/BooleanUnion_48x48.png - - - - 24 - 24 - - - - false - - - false - - - Qt::ToolButtonTextUnderIcon - - - Qt::NoArrow - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - QmitkDataSelectionWidget - QWidget -
internal/Common/QmitkDataSelectionWidget.h
- 1 -
-
- - - - -
diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.cpp deleted file mode 100644 index 90e41d7aea..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkContourModelToImageWidget.h" -#include "mitkImage.h" -#include "../../Common/QmitkDataSelectionWidget.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -static const char* const HelpText = "Select a image and a contour(set)"; - -class QmitkContourModelToImageWidgetPrivate -{ -public: - QmitkContourModelToImageWidgetPrivate(); - ~QmitkContourModelToImageWidgetPrivate(); - - /** @brief Check if selections is valid. */ - void SelectionControl( unsigned int index, const mitk::DataNode* selection); - - /** @brief Enable buttons if data selction is valid. */ - void EnableButtons(bool enable = true); - - /** @brief Does the actual contour filling */ - mitk::LabelSetImage::Pointer FillContourModelSetIntoImage(mitk::Image *image, mitk::ContourModelSet *contourSet, mitk::TimePointType timePoint); - - Ui::QmitkContourModelToImageWidgetControls m_Controls; - QFutureWatcher m_Watcher; -}; - -QmitkContourModelToImageWidgetPrivate::QmitkContourModelToImageWidgetPrivate() -{ -} - -QmitkContourModelToImageWidgetPrivate::~QmitkContourModelToImageWidgetPrivate() -{ -} - -void QmitkContourModelToImageWidgetPrivate::EnableButtons(bool enable) -{ - m_Controls.btnProcess->setEnabled(enable); -} - -void QmitkContourModelToImageWidgetPrivate::SelectionControl(unsigned int index, const mitk::DataNode* /*selection*/) -{ - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(index); - - dataSelectionWidget->SetHelpText(""); - this->EnableButtons(); -} - -mitk::LabelSetImage::Pointer QmitkContourModelToImageWidgetPrivate::FillContourModelSetIntoImage(mitk::Image* image, mitk::ContourModelSet* contourSet, mitk::TimePointType timePoint) -{ - // Use mitk::ContourModelSetToImageFilter to fill the ContourModelSet into the image - mitk::ContourModelSetToImageFilter::Pointer contourFiller = mitk::ContourModelSetToImageFilter::New(); - auto timeStep = image->GetTimeGeometry()->TimePointToTimeStep(timePoint); - contourFiller->SetTimeStep(timeStep); - contourFiller->SetImage(image); - contourFiller->SetInput(contourSet); - contourFiller->MakeOutputBinaryOn(); - - try - { - contourFiller->Update(); - } - catch (const std::exception & e) - { - MITK_ERROR << "Error while converting contour model. "<< e.what(); - } - catch (...) - { - MITK_ERROR << "Unknown error while converting contour model."; - } - - if (nullptr == contourFiller->GetOutput()) - { - MITK_ERROR<<"Could not write the selected contours into the image!"; - } - - auto result = mitk::LabelSetImage::New(); - result->InitializeByLabeledImage(contourFiller->GetOutput()); - - return result; -} - -void QmitkContourModelToImageWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection) -{ - Q_D(QmitkContourModelToImageWidget); - QmitkDataSelectionWidget* dataSelectionWidget = d->m_Controls.dataSelectionWidget; - mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0); - mitk::DataNode::Pointer node1 = dataSelectionWidget->GetSelection(1); - - if (node0.IsNull() || node1.IsNull() ) - { - d->EnableButtons(false); - dataSelectionWidget->SetHelpText(HelpText); - } - else - { - d->SelectionControl(index, selection); - } -} - -void QmitkContourModelToImageWidget::OnProcessingFinished() -{ - // Called when processing finished - // Adding the result to the data storage - - Q_D(QmitkContourModelToImageWidget); - - // Adding the result to the data storage - auto result = d->m_Watcher.result(); - if (result.IsNotNull()) - { - QmitkDataSelectionWidget* dataSelectionWidget = d->m_Controls.dataSelectionWidget; - mitk::DataNode::Pointer imageNode = dataSelectionWidget->GetSelection(0); - mitk::DataNode::Pointer contourNode = dataSelectionWidget->GetSelection(1); - - mitk::DataNode::Pointer filled = mitk::DataNode::New(); - std::stringstream stream; - stream << imageNode->GetName(); - stream << "_"; - stream << contourNode->GetName(); - filled->SetName(stream.str()); - filled->SetData(result); - - dataSelectionWidget->GetDataStorage()->Add(filled, imageNode); - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - } - else - { - MITK_ERROR<<"Error filling contours into an image!"; - } - - d->EnableButtons(); -} - -void QmitkContourModelToImageWidget::OnProcessPressed() -{ - Q_D(QmitkContourModelToImageWidget); - - QmitkDataSelectionWidget* dataSelectionWidget = d->m_Controls.dataSelectionWidget; - - mitk::DataNode::Pointer imageNode = dataSelectionWidget->GetSelection(0); - mitk::DataNode::Pointer contourNode = dataSelectionWidget->GetSelection(1); - - // Check if data nodes are valid - if(imageNode.IsNull() || contourNode.IsNull() ) - { - MITK_ERROR << "Selection does not contain valid data"; - QMessageBox::information( this, "Contour To Image", - "Selection does not contain valid data, please select a binary image and a contour(set)", - QMessageBox::Ok ); - d->m_Controls.btnProcess->setEnabled(false); - return; - } - - mitk::Image::Pointer image = static_cast(imageNode->GetData()); - - // Check if the image is valid - if (image.IsNull()) - { - MITK_ERROR<<"Error writing contours into image! Invalid image data selected!"; - return; - } - - const auto timePoint = this->GetTimeNavigationController()->GetSelectedTimePoint(); - if (!image->GetTimeGeometry()->IsValidTimePoint(timePoint)) - { - MITK_ERROR << "Error writing contours into image! Currently selected time point is not supported by selected image data."; - return; - } - - // Check if the selected contours are valid - mitk::ContourModelSet::Pointer contourSet; - mitk::ContourModel::Pointer contour = dynamic_cast(contourNode->GetData()); - if (contour.IsNotNull()) - { - contourSet = mitk::ContourModelSet::New(); - contourSet->AddContourModel(contour); - } - else - { - contourSet = static_cast(contourNode->GetData()); - if (contourSet.IsNull()) - { - MITK_ERROR<<"Error writing contours into binary image! Invalid contour data selected!"; - return; - } - } - - //Disable Buttons during calculation and initialize Progressbar - d->EnableButtons(false); - - // Start the computation in a background thread - QFuture< mitk::LabelSetImage::Pointer > future = QtConcurrent::run(d, &QmitkContourModelToImageWidgetPrivate::FillContourModelSetIntoImage, image, contourSet, timePoint); - d->m_Watcher.setFuture(future); -} - -QmitkContourModelToImageWidget::QmitkContourModelToImageWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QmitkSegmentationUtilityWidget(timeNavigationController, parent), - d_ptr(new QmitkContourModelToImageWidgetPrivate()) -{ - Q_D(QmitkContourModelToImageWidget); - - // Set up UI - d->m_Controls.setupUi(this); - d->m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ImageAndSegmentationPredicate); - d->m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ContourModelPredicate); - d->m_Controls.dataSelectionWidget->SetHelpText(HelpText); - d->EnableButtons(false); - - // Create connections - connect (d->m_Controls.btnProcess, SIGNAL(pressed()), this, SLOT(OnProcessPressed())); - connect(d->m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), - this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); - connect(&d->m_Watcher, SIGNAL(finished()), this, SLOT(OnProcessingFinished())); - - if( d->m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull() && - d->m_Controls.dataSelectionWidget->GetSelection(1).IsNotNull() ) - { - OnSelectionChanged(0, d->m_Controls.dataSelectionWidget->GetSelection(0)); - } -} - -QmitkContourModelToImageWidget::~QmitkContourModelToImageWidget() -{ -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.h deleted file mode 100644 index c31fb9f4dc..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.h +++ /dev/null @@ -1,70 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkContourModelToImageWidget_h -#define QmitkContourModelToImageWidget_h - -#include "../QmitkSegmentationUtilityWidget.h" -#include - -#include - -class QmitkContourModelToImageWidgetPrivate; - -namespace mitk { - class Image; - class ContourModelSet; - class ContourModel; - class Geometry3D; - class PlaneGeometry; -} - -/*! - \brief QmitkContourModelToImageWidget - - Tool masks an image with a binary image or a surface. The Method requires - an image and a binary image mask or a surface. The input image and the binary - image mask must be of the same size. Masking with a surface creates first a - binary image of the surface and then use this for the masking of the input image. -*/ -class QmitkContourModelToImageWidget : public QmitkSegmentationUtilityWidget -{ - Q_OBJECT - -public: - - /** @brief Default constructor, including creation of GUI elements and signals/slots connections. */ - explicit QmitkContourModelToImageWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - - /** @brief Defaul destructor. */ - ~QmitkContourModelToImageWidget() override; - -private slots: - - /** @brief This slot is called if the selection in the workbench is changed. */ - void OnSelectionChanged(unsigned int index, const mitk::DataNode* selection); - - /** @brief This slot is called if user activates the button to mask an image. */ - void OnProcessPressed(); - - /** @brief This slot is called after processing is finished */ - void OnProcessingFinished(); - -private: - - QScopedPointer d_ptr; - - Q_DECLARE_PRIVATE(QmitkContourModelToImageWidget) - Q_DISABLE_COPY(QmitkContourModelToImageWidget) -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidgetControls.ui deleted file mode 100644 index 4f9be6b5bf..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidgetControls.ui +++ /dev/null @@ -1,56 +0,0 @@ - - - QmitkContourModelToImageWidgetControls - - - - 0 - 0 - 98 - 62 - - - - - - - - 0 - 0 - - - - - - - - Process - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - QmitkDataSelectionWidget - QWidget -
internal/Common/QmitkDataSelectionWidget.h
- 1 -
-
- - -
diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.cpp deleted file mode 100644 index 5a1017530d..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkConvertToMlWidget.h" -#include "../../Common/QmitkDataSelectionWidget.h" -#include -#include -#include -#include -#include "src/internal/QmitkConvertToMultiLabelSegmentationAction.h" - -QmitkConvertToMlWidget::QmitkConvertToMlWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QmitkSegmentationUtilityWidget(timeNavigationController, parent) -{ - m_Controls.setupUi(this); - - m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ImagePredicate); - - connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(SelectionChanged())); - connect(m_Controls.pushButton, SIGNAL(clicked()), this, SLOT(Convert())); -} - -QmitkConvertToMlWidget::~QmitkConvertToMlWidget() -{ -} - -void QmitkConvertToMlWidget::SelectionChanged() -{ - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - - mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0); - - if (node0.IsNotNull()) - { - this->EnableButtons(); - } - else - { - this->EnableButtons(false); - } -} - -void QmitkConvertToMlWidget::EnableButtons(bool enable) -{ - m_Controls.pushButton->setEnabled(enable); -} - -void QmitkConvertToMlWidget::Convert() -{ - auto node = m_Controls.dataSelectionWidget->GetSelection(0); - - QmitkConvertToMultiLabelSegmentationAction converter; - QList list; list.append(node); - converter.SetDataStorage(m_Controls.dataSelectionWidget->GetDataStorage()); - converter.Run(list); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.h deleted file mode 100644 index c169618774..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidget.h +++ /dev/null @@ -1,37 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkConvertToMlWidget_h -#define QmitkConvertToMlWidget_h - -#include "../QmitkSegmentationUtilityWidget.h" -#include - -class QmitkConvertToMlWidget : public QmitkSegmentationUtilityWidget -{ - Q_OBJECT - -public: - explicit QmitkConvertToMlWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - ~QmitkConvertToMlWidget() override; - -private slots: - void SelectionChanged(); - void Convert(); - -private: - void EnableButtons(bool enable = true); - - Ui::QmitkConvertToMlWidgetControls m_Controls; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidgetControls.ui deleted file mode 100644 index acb4531419..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ConvertToMl/QmitkConvertToMlWidgetControls.ui +++ /dev/null @@ -1,58 +0,0 @@ - - - QmitkConvertToMlWidgetControls - - - - 0 - 0 - 98 - 62 - - - - - - - - 0 - 0 - - - - - - - - Convert - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - QmitkDataSelectionWidget - QWidget -
internal/Common/QmitkDataSelectionWidget.h
- 1 -
-
- - - - -
diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.cpp deleted file mode 100644 index c56528a31e..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkImageMaskingWidget.h" -#include "../../Common/QmitkDataSelectionWidget.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -static const char* const HelpText = "Select a patient image and a mask"; - -QmitkImageMaskingWidget::QmitkImageMaskingWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QmitkSegmentationUtilityWidget(timeNavigationController, parent) -{ - m_Controls.setupUi(this); - - m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ImagePredicate); - m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::MaskPredicate); - m_Controls.dataSelectionWidget->SetHelpText(HelpText); - -// mitk::IDataStorageService::Pointer service = -// berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); - -// assert(service.IsNotNull()); - - mitk::DataStorage::Pointer ds = m_Controls.dataSelectionWidget->GetDataStorage(); - m_Controls.m_LabelSetWidget->SetDataStorage(ds); - m_Controls.m_LabelSetWidget->setEnabled(true); - - m_Controls.m_MaskStampWidget->SetDataStorage(ds); - - this->EnableButtons(false); - - connect (m_Controls.rbMaskImage, SIGNAL(toggled(bool)), this, SLOT(OnImageMaskingToggled(bool))); - connect (m_Controls.rbMaskSurface, SIGNAL(toggled(bool)), this, SLOT(OnSurfaceMaskingToggled(bool))); - connect (m_Controls.btnMaskImage, SIGNAL(pressed()), this, SLOT(OnMaskImagePressed())); - - connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), - this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); - - if( m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull() && - m_Controls.dataSelectionWidget->GetSelection(1).IsNotNull() ) - { - this->OnSelectionChanged( 0, m_Controls.dataSelectionWidget->GetSelection(0)); - } -} - -QmitkImageMaskingWidget::~QmitkImageMaskingWidget() -{ -} - -void QmitkImageMaskingWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection) -{ - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0); - mitk::DataNode::Pointer node1 = dataSelectionWidget->GetSelection(1); - - if (node0.IsNull() || node1.IsNull() ) - { - if( m_Controls.rbMaskImage->isChecked() ) - { - dataSelectionWidget->SetHelpText(HelpText); - } - else - { - dataSelectionWidget->SetHelpText("Select a patient image and a surface"); - } - this->EnableButtons(false); - } - else - { - this->SelectionControl(index, selection); - } -} - -void QmitkImageMaskingWidget::SelectionControl(unsigned int index, const mitk::DataNode*) -{ - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(index); - - //if Image-Masking is enabled, check if image-dimension of reference and binary image is identical - if( m_Controls.rbMaskImage->isChecked() ) - { - if( dataSelectionWidget->GetSelection(0) == dataSelectionWidget->GetSelection(1) ) - { - dataSelectionWidget->SetHelpText("Select two different images above"); - this->EnableButtons(false); - return; - } - } - - dataSelectionWidget->SetHelpText(""); - this->EnableButtons(); -} - -void QmitkImageMaskingWidget::EnableButtons(bool enable) -{ - m_Controls.btnMaskImage->setEnabled(enable); -} - -void QmitkImageMaskingWidget::OnImageMaskingToggled(bool status) -{ - if (status) - { - m_Controls.dataSelectionWidget->SetHelpText("Select a patient image and a mask"); - m_Controls.dataSelectionWidget->SetPredicate(1, QmitkDataSelectionWidget::MaskPredicate); - } -} - -void QmitkImageMaskingWidget::OnSurfaceMaskingToggled(bool status) -{ - if (status) - { - m_Controls.dataSelectionWidget->SetHelpText("Select a patient image and a surface"); - m_Controls.dataSelectionWidget->SetPredicate(1, QmitkDataSelectionWidget::SurfacePredicate); - } -} - - -void QmitkImageMaskingWidget::OnMaskImagePressed() -{ - //Disable Buttons during calculation and initialize Progressbar - this->EnableButtons(false); - mitk::ProgressBar::GetInstance()->AddStepsToDo(4); - mitk::ProgressBar::GetInstance()->Progress(); - - QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget; - - //create result image, get mask node and reference image - mitk::Image::Pointer resultImage(nullptr); - mitk::DataNode::Pointer maskingNode = dataSelectionWidget->GetSelection(1); - mitk::Image::Pointer referenceImage = static_cast(dataSelectionWidget->GetSelection(0)->GetData()); - - if(referenceImage.IsNull() || maskingNode.IsNull() ) - { - MITK_ERROR << "Selection does not contain an image"; - QMessageBox::information( this, "Image and Surface Masking", "Selection does not contain an image", QMessageBox::Ok ); - m_Controls.btnMaskImage->setEnabled(true); - return; - } - - //Do Image-Masking - if (m_Controls.rbMaskImage->isChecked()) - { - mitk::ProgressBar::GetInstance()->Progress(); - - mitk::Image::Pointer maskImage = dynamic_cast ( maskingNode->GetData() ); - - if( referenceImage->GetLargestPossibleRegion().GetSize() != maskImage->GetLargestPossibleRegion().GetSize() ) - { - mitk::PadImageFilter::Pointer padImageFilter = mitk::PadImageFilter::New(); - padImageFilter->SetInput(0, maskImage); - padImageFilter->SetInput(1, referenceImage); - padImageFilter->SetPadConstant(0); - padImageFilter->SetBinaryFilter(false); - padImageFilter->SetLowerThreshold(0); - padImageFilter->SetUpperThreshold(1); - - MITK_INFO << "Padding mask ..."; - - padImageFilter->Update(); - - maskImage = padImageFilter->GetOutput(); - } - - if(maskImage.IsNull() ) - { - MITK_ERROR << "Selection does not contain a binary image"; - QMessageBox::information( this, "Image and Surface Masking", "Selection does not contain a binary image", QMessageBox::Ok ); - this->EnableButtons(); - return; - } - - resultImage = this->MaskImage( referenceImage, maskImage ); - } - - //Do Surface-Masking - else - { - mitk::ProgressBar::GetInstance()->Progress(); - - //1. convert surface to image - mitk::Surface::Pointer surface = dynamic_cast ( maskingNode->GetData() ); - - //TODO Get 3D Surface of current time step - - if(surface.IsNull()) - { - MITK_ERROR << "Selection does not contain a surface"; - QMessageBox::information( this, "Image and Surface Masking", "Selection does not contain a surface", QMessageBox::Ok ); - this->EnableButtons(); - return; - } - - mitk::Image::Pointer maskImage = this->ConvertSurfaceToImage( referenceImage, surface ); - - //2. mask reference image with mask image - if(maskImage.IsNotNull() && - referenceImage->GetLargestPossibleRegion().GetSize() == maskImage->GetLargestPossibleRegion().GetSize() ) - { - resultImage = this->MaskImage( referenceImage, maskImage ); - } - } - - mitk::ProgressBar::GetInstance()->Progress(); - - if( resultImage.IsNull() ) - { - MITK_ERROR << "Masking failed"; - QMessageBox::information( this, "Image and Surface Masking", "Masking failed. For more information please see logging window.", QMessageBox::Ok ); - this->EnableButtons(); - mitk::ProgressBar::GetInstance()->Progress(4); - return; - } - - //Add result to data storage - this->AddToDataStorage( - dataSelectionWidget->GetDataStorage(), - resultImage, - dataSelectionWidget->GetSelection(0)->GetName() + "_" + dataSelectionWidget->GetSelection(1)->GetName(), - dataSelectionWidget->GetSelection(0)); - - this->EnableButtons(); - - mitk::ProgressBar::GetInstance()->Progress(); -} - -mitk::Image::Pointer QmitkImageMaskingWidget::MaskImage(mitk::Image::Pointer referenceImage, mitk::Image::Pointer maskImage ) -{ - mitk::Image::Pointer resultImage(nullptr); - - mitk::MaskImageFilter::Pointer maskFilter = mitk::MaskImageFilter::New(); - maskFilter->SetInput( referenceImage ); - maskFilter->SetMask( maskImage ); - //MLI TODO - //if ( m_Controls.m_chkMakeOutputBinary->isChecked() ) - //{ - // maskFilter->SetInsideValue(1.0); - // maskFilter->SetOutsideValue(0.0); - // maskFilter->SetOverrideOutsideValue(true); - // maskFilter->SetOverrideInsideValue(true); - //} - - //maskFilter->SetOverrideOutsideValue( m_Controls.m_chkOverwriteBackground->isChecked() ); - //maskFilter->SetOverrideInsideValue( m_Controls.m_chkOverwriteForeground->isChecked() ); - //maskFilter->SetInsideValue( m_Controls.m_leForegroundValue->text().toFloat() );//referenceImage->GetStatistics()->GetScalarValueMin() ); - //maskFilter->SetOutsideValue( m_Controls.m_leBackgroundValue->text().toFloat() );//referenceImage->GetStatistics()->GetScalarValueMin() ); - - try - { - maskFilter->Update(); - } - catch(itk::ExceptionObject& excpt) - { - MITK_ERROR << excpt.GetDescription(); - return nullptr; - } - - resultImage = maskFilter->GetOutput(); - - return resultImage; -} - -mitk::Image::Pointer QmitkImageMaskingWidget::ConvertSurfaceToImage( mitk::Image::Pointer image, mitk::Surface::Pointer surface ) -{ - mitk::ProgressBar::GetInstance()->AddStepsToDo(2); - mitk::ProgressBar::GetInstance()->Progress(); - - mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); - surfaceToImageFilter->MakeOutputBinaryOn(); - surfaceToImageFilter->SetInput(surface); - surfaceToImageFilter->SetImage(image); - try - { - surfaceToImageFilter->Update(); - } - catch(itk::ExceptionObject& excpt) - { - MITK_ERROR << excpt.GetDescription(); - return nullptr; - } - - mitk::ProgressBar::GetInstance()->Progress(); - mitk::Image::Pointer resultImage = mitk::Image::New(); - resultImage = surfaceToImageFilter->GetOutput(); - - return resultImage; -} - -void QmitkImageMaskingWidget::AddToDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::Image::Pointer segmentation, const std::string& name, mitk::DataNode::Pointer parent ) -{ - mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); - - dataNode->SetName(name); - dataNode->SetData(segmentation); - - dataStorage->Add(dataNode, parent); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.h deleted file mode 100644 index 5055aa5445..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.h +++ /dev/null @@ -1,77 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkImageMaskingWidget_h -#define QmitkImageMaskingWidget_h - -#include "../QmitkSegmentationUtilityWidget.h" -#include - -#include -#include - -/*! - \brief QmitkImageMaskingWidget - - Tool masks an image with a binary image or a surface. The Method requires - an image and a binary image mask or a surface. The input image and the binary - image mask must be of the same size. Masking with a surface creates first a - binary image of the surface and then use this for the masking of the input image. -*/ -class QmitkImageMaskingWidget : public QmitkSegmentationUtilityWidget -{ - Q_OBJECT - -public: - - /** @brief Default constructor, including creation of GUI elements and signals/slots connections. */ - explicit QmitkImageMaskingWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - - /** @brief Defaul destructor. */ - ~QmitkImageMaskingWidget() override; - -private slots: - - /** @brief This slot is called if the selection in the workbench is changed. */ - void OnSelectionChanged(unsigned int index, const mitk::DataNode* selection); - - /** @brief This slot is called if user activates the radio button for masking an image with a binary image mask. */ - void OnImageMaskingToggled(bool); - - /** @brief This slot is called if user activates the radio button for masking an image with a surface. */ - void OnSurfaceMaskingToggled(bool); - - /** @brief This slot is called if user activates the button to mask an image. */ - void OnMaskImagePressed(); - -private: - - /** @brief Check if selections is valid. */ - void SelectionControl( unsigned int index, const mitk::DataNode* selection); - - /** @brief Enable buttons if data selction is valid. */ - void EnableButtons(bool enable = true); - - /** @brief Mask an image with a given binary mask. Note that the input image and the mask image must be of the same size. */ - mitk::Image::Pointer MaskImage(mitk::Image::Pointer referenceImage, mitk::Image::Pointer maskImage ); - - /** @brief Convert a surface into an binary image. */ - mitk::Image::Pointer ConvertSurfaceToImage( mitk::Image::Pointer image, mitk::Surface::Pointer surface ); - - /** @brief Adds a new data object to the DataStorage.*/ - void AddToDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::Image::Pointer segmentation, - const std::string& name, mitk::DataNode::Pointer parent = nullptr); - - Ui::QmitkImageMaskingWidgetControls m_Controls; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidgetControls.ui deleted file mode 100644 index 2d8cf565c5..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidgetControls.ui +++ /dev/null @@ -1,274 +0,0 @@ - - - QmitkImageMaskingWidgetControls - - - - 0 - 0 - 179 - 296 - - - - - 2 - - - 4 - - - - - 0 - - - - Masks - - - - 3 - - - 4 - - - - - - 0 - 0 - - - - - - - - Masking Mode - - - - - - Image Masking - - - true - - - - - - - Surface Masking - - - - - - - - - - Mask - - - - - - - make output binary - - - - - - - overwrite foreground - - - - - - - overwrite background - - - - - - - - - Background Value: - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 50 - 0 - - - - - 50 - 16777215 - - - - 0.0 - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - - - - Foreground Value: - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 50 - 0 - - - - - 50 - 16777215 - - - - 1.0 - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Labels - - - - 4 - - - - - - 0 - 0 - - - - - 0 - 50 - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - QmitkDataSelectionWidget - QWidget -
internal/Common/QmitkDataSelectionWidget.h
-
- - QmitkLabelSetWidget - QWidget -
QmitkLabelSetWidget.h
- 1 -
- - QmitkMaskStampWidget - QWidget -
QmitkMaskStampWidget.h
- 1 -
-
- - -
diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.cpp deleted file mode 100644 index 185b773c1c..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkMorphologicalOperationsWidget.h" -#include -#include -#include -#include -#include -#include - -static const char* const HelpText = "Select a mask above"; - -QmitkMorphologicalOperationsWidget::QmitkMorphologicalOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QmitkSegmentationUtilityWidget(timeNavigationController, parent) -{ - m_Controls.setupUi(this); - - m_Controls.m_DataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::MaskPredicate); - m_Controls.m_DataSelectionWidget->SetHelpText(HelpText); - - mitk::DataStorage::Pointer ds = m_Controls.m_DataSelectionWidget->GetDataStorage(); - m_Controls.m_LabelSetWidget->SetDataStorage(ds); - m_Controls.m_LabelSetWidget->setEnabled(true); - - m_Controls.m_ToolSelectionBox->SetToolManager(*mitk::ToolManagerProvider::GetInstance()->GetToolManager()); - m_Controls.m_ToolSelectionBox->SetGenerateAccelerators(true); - m_Controls.m_ToolSelectionBox->SetToolGUIArea( m_Controls.m_ToolGUIContainer ); - m_Controls.m_ToolSelectionBox->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); - m_Controls.m_ToolSelectionBox->SetDisplayedToolGroups("Median Dilate Erode Open Close 'Fill Holes' 'Keep N Largest' 'Split' 'Region Selector'"); - - connect(m_Controls.btnClosing, SIGNAL(clicked()), this, SLOT(OnClosingButtonClicked())); - connect(m_Controls.btnOpening, SIGNAL(clicked()), this, SLOT(OnOpeningButtonClicked())); - connect(m_Controls.btnDilatation, SIGNAL(clicked()), this, SLOT(OnDilatationButtonClicked())); - connect(m_Controls.btnErosion, SIGNAL(clicked()), this, SLOT(OnErosionButtonClicked())); - connect(m_Controls.btnFillHoles, SIGNAL(clicked()), this, SLOT(OnFillHolesButtonClicked())); - connect(m_Controls.radioButtonMorphoCross, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked())); - connect(m_Controls.radioButtonMorphoBall, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked())); - connect(m_Controls.m_DataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); - - if (m_Controls.m_DataSelectionWidget->GetSelection(0).IsNotNull()) - this->OnSelectionChanged(0, m_Controls.m_DataSelectionWidget->GetSelection(0)); -} - -QmitkMorphologicalOperationsWidget::~QmitkMorphologicalOperationsWidget() -{ -} - -void QmitkMorphologicalOperationsWidget::OnSelectionChanged(unsigned int, const mitk::DataNode*) -{ - QmitkDataSelectionWidget* m_DataSelectionWidget = m_Controls.m_DataSelectionWidget; - mitk::DataNode::Pointer node = m_DataSelectionWidget->GetSelection(0); - - if (node.IsNotNull()) - { - m_Controls.m_DataSelectionWidget->SetHelpText(""); - this->EnableButtons(true); - } - else - { - m_Controls.m_DataSelectionWidget->SetHelpText(HelpText); - this->EnableButtons(false); - } -} - -void QmitkMorphologicalOperationsWidget::EnableButtons(bool enable) -{ - m_Controls.btnClosing->setEnabled(enable); - m_Controls.btnDilatation->setEnabled(enable); - m_Controls.btnErosion->setEnabled(enable); - m_Controls.btnFillHoles->setEnabled(enable); - m_Controls.btnOpening->setEnabled(enable); -} - -void QmitkMorphologicalOperationsWidget::OnRadioButtonsClicked() -{ - bool enable = m_Controls.radioButtonMorphoBall->isChecked(); - - m_Controls.sliderMorphFactor->setEnabled(enable); - m_Controls.spinBoxMorphFactor->setEnabled(enable); -} - -void QmitkMorphologicalOperationsWidget::OnClosingButtonClicked() -{ - QApplication::setOverrideCursor(QCursor(Qt::BusyCursor)); - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - - QmitkDataSelectionWidget* m_DataSelectionWidget = m_Controls.m_DataSelectionWidget; - mitk::DataNode::Pointer node = m_DataSelectionWidget->GetSelection(0); - mitk::Image::Pointer image = static_cast(node->GetData()); - bool ball = m_Controls.radioButtonMorphoBall->isChecked(); - - mitk::MorphologicalOperations::StructuralElementType structuralElement = ball - ? mitk::MorphologicalOperations::Ball - : mitk::MorphologicalOperations::Cross; - - try - { - mitk::MorphologicalOperations::Closing(image, m_Controls.spinBoxMorphFactor->value(), structuralElement); - } - catch (const itk::ExceptionObject& exception) - { - MITK_WARN << "Exception caught: " << exception.GetDescription(); - - QApplication::restoreOverrideCursor(); - return; - } - - node->SetData(image); - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - QApplication::restoreOverrideCursor(); -} - -void QmitkMorphologicalOperationsWidget::OnOpeningButtonClicked() -{ - QApplication::setOverrideCursor(QCursor(Qt::BusyCursor)); - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - - QmitkDataSelectionWidget* m_DataSelectionWidget = m_Controls.m_DataSelectionWidget; - mitk::DataNode::Pointer node = m_DataSelectionWidget->GetSelection(0); - mitk::Image::Pointer image = static_cast(node->GetData()); - bool ball = m_Controls.radioButtonMorphoBall->isChecked(); - - mitk::MorphologicalOperations::StructuralElementType structuralElement = ball - ? mitk::MorphologicalOperations::Ball - : mitk::MorphologicalOperations::Cross; - - try - { - mitk::MorphologicalOperations::Opening(image, m_Controls.spinBoxMorphFactor->value(), structuralElement); - } - catch (const itk::ExceptionObject& exception) - { - MITK_WARN << "Exception caught: " << exception.GetDescription(); - - QApplication::restoreOverrideCursor(); - return; - } - - node->SetData(image); - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - QApplication::restoreOverrideCursor(); -} - -void QmitkMorphologicalOperationsWidget::OnDilatationButtonClicked() -{ - QApplication::setOverrideCursor(QCursor(Qt::BusyCursor)); - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - - QmitkDataSelectionWidget* m_DataSelectionWidget = m_Controls.m_DataSelectionWidget; - mitk::DataNode::Pointer node = m_DataSelectionWidget->GetSelection(0); - mitk::Image::Pointer image = static_cast(node->GetData()); - bool ball = m_Controls.radioButtonMorphoBall->isChecked(); - - mitk::MorphologicalOperations::StructuralElementType structuralElement = ball - ? mitk::MorphologicalOperations::Ball - : mitk::MorphologicalOperations::Cross; - - try - { - mitk::MorphologicalOperations::Dilate(image, m_Controls.spinBoxMorphFactor->value(), structuralElement); - } - catch (const itk::ExceptionObject& exception) - { - MITK_WARN << "Exception caught: " << exception.GetDescription(); - - QApplication::restoreOverrideCursor(); - return; - } - - node->SetData(image); - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - QApplication::restoreOverrideCursor(); -} - -void QmitkMorphologicalOperationsWidget::OnErosionButtonClicked() -{ - QApplication::setOverrideCursor(QCursor(Qt::BusyCursor)); - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - - QmitkDataSelectionWidget* m_DataSelectionWidget = m_Controls.m_DataSelectionWidget; - mitk::DataNode::Pointer node = m_DataSelectionWidget->GetSelection(0); - mitk::Image::Pointer image = static_cast(node->GetData()); - bool ball = m_Controls.radioButtonMorphoBall->isChecked(); - - mitk::MorphologicalOperations::StructuralElementType structuralElement = ball - ? mitk::MorphologicalOperations::Ball - : mitk::MorphologicalOperations::Cross; - - try - { - mitk::MorphologicalOperations::Erode(image, m_Controls.spinBoxMorphFactor->value(), structuralElement); - } - catch (const itk::ExceptionObject& exception) - { - MITK_WARN << "Exception caught: " << exception.GetDescription(); - - QApplication::restoreOverrideCursor(); - return; - } - - node->SetData(image); - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - QApplication::restoreOverrideCursor(); -} - -void QmitkMorphologicalOperationsWidget::OnFillHolesButtonClicked() -{ - QApplication::setOverrideCursor(QCursor(Qt::BusyCursor)); - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - - QmitkDataSelectionWidget* m_DataSelectionWidget = m_Controls.m_DataSelectionWidget; - mitk::DataNode::Pointer node = m_DataSelectionWidget->GetSelection(0); - mitk::Image::Pointer image = static_cast(node->GetData()); - - try - { - mitk::MorphologicalOperations::FillHoles(image); - } - catch (const itk::ExceptionObject& exception) - { - MITK_WARN << "Exception caught: " << exception.GetDescription(); - - QApplication::restoreOverrideCursor(); - return; - } - - node->SetData(image); - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - QApplication::restoreOverrideCursor(); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.h deleted file mode 100644 index 1935769186..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.h +++ /dev/null @@ -1,45 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkMorphologicalOperationsWidget_h -#define QmitkMorphologicalOperationsWidget_h - -#include "../QmitkSegmentationUtilityWidget.h" -#include - -/** \brief GUI class for morphological segmentation tools. - */ -class QmitkMorphologicalOperationsWidget : public QmitkSegmentationUtilityWidget -{ - Q_OBJECT - -public: - explicit QmitkMorphologicalOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - ~QmitkMorphologicalOperationsWidget() override; - -public slots: - void OnClosingButtonClicked(); - void OnOpeningButtonClicked(); - void OnDilatationButtonClicked(); - void OnErosionButtonClicked(); - void OnFillHolesButtonClicked(); - void OnSelectionChanged(unsigned int index, const mitk::DataNode* selection); - void OnRadioButtonsClicked(); - -protected: - void EnableButtons(bool enable); - -private: - Ui::QmitkMorphologicalOperationsWidgetControls m_Controls; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidgetControls.ui deleted file mode 100644 index 0e8a3c92b5..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidgetControls.ui +++ /dev/null @@ -1,427 +0,0 @@ - - - QmitkMorphologicalOperationsWidgetControls - - - - 0 - 0 - 155 - 414 - - - - - - - - 0 - 0 - - - - 0 - - - - Masks - - - - 3 - - - 4 - - - - - - 0 - 0 - - - - - - - - Structuring Element - - - - - - Ball - - - true - - - - - - - Cross - - - - - - - - - - - - Radius - - - - - - - 1 - - - 20 - - - 1 - - - Qt::Horizontal - - - - - - - 1 - - - 20 - - - - - - - - - - - false - - - - 0 - 0 - - - - Dilatation - - - - :/SegmentationUtilities/MorphologicalOperations/Dilate_48x48.png:/SegmentationUtilities/MorphologicalOperations/Dilate_48x48.png - - - - 32 - 32 - - - - Qt::ToolButtonTextUnderIcon - - - - - - - false - - - - 0 - 0 - - - - Globally fills holes in segmentation (radius not required) - - - Fill Holes - - - - :/SegmentationUtilities/MorphologicalOperations/FillHoles_48x48.png:/SegmentationUtilities/MorphologicalOperations/FillHoles_48x48.png - - - - 32 - 32 - - - - Qt::ToolButtonTextUnderIcon - - - - - - - false - - - - 0 - 0 - - - - Erosion - - - - :/SegmentationUtilities/MorphologicalOperations/Erode_48x48.png:/SegmentationUtilities/MorphologicalOperations/Erode_48x48.png - - - - 32 - 32 - - - - Qt::ToolButtonTextUnderIcon - - - - - - - false - - - - 0 - 0 - - - - Closing - - - - :/SegmentationUtilities/MorphologicalOperations/Closing_48x48.png:/SegmentationUtilities/MorphologicalOperations/Closing_48x48.png - - - - 32 - 32 - - - - Qt::ToolButtonTextUnderIcon - - - - - - - false - - - - 0 - 0 - - - - Opening - - - - :/SegmentationUtilities/MorphologicalOperations/Opening_48x48.png:/SegmentationUtilities/MorphologicalOperations/Opening_48x48.png - - - - 32 - 32 - - - - Qt::ToolButtonTextUnderIcon - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Labels - - - - 3 - - - 4 - - - - - - 0 - 0 - - - - - 0 - 50 - - - - - - - - - 0 - 0 - - - - - 15 - 0 - - - - - 50 - false - - - - - - - - - 0 - 0 - - - - - 0 - 15 - - - - - 50 - false - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - QmitkDataSelectionWidget - QWidget -
internal/Common/QmitkDataSelectionWidget.h
- 1 -
- - QmitkToolSelectionBox - QWidget -
QmitkToolSelectionBox.h
-
- - QmitkToolGUIArea - QWidget -
QmitkToolGUIArea.h
-
- - QmitkLabelSetWidget - QWidget -
QmitkLabelSetWidget.h
- 1 -
-
- - - - - - sliderMorphFactor - valueChanged(int) - spinBoxMorphFactor - setValue(int) - - - 240 - 27 - - - 766 - 36 - - - - - spinBoxMorphFactor - valueChanged(int) - sliderMorphFactor - setValue(int) - - - 784 - 38 - - - 657 - 38 - - - - -
diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.cpp deleted file mode 100644 index 3ccaa49638..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -// #define ENABLE_CTK_WIDGETS_WIDGET - -#include -#include "QmitkMultiLabelSegmentationUtilitiesView.h" -#include "BooleanOperations/QmitkBooleanOperationsWidget.h" -#include "ContourModelToImage/QmitkContourModelToImageWidget.h" -#include "MorphologicalOperations/QmitkMorphologicalOperationsWidget.h" -#include "SurfaceToImage/QmitkSurfaceToImageWidget.h" -#include "ImageMasking/QmitkImageMaskingWidget.h" -#include "ConvertToMl/QmitkConvertToMlWidget.h" - -QmitkMultiLabelSegmentationUtilitiesView::QmitkMultiLabelSegmentationUtilitiesView() : - m_BooleanOperationsWidget(nullptr), - m_ContourModelToImageWidget(nullptr), - m_MorphologicalOperationsWidget(nullptr), - m_SurfaceToImageWidget(nullptr), - m_ImageMaskingWidget(nullptr), - m_ConvertToMlWidget(nullptr) -{ -} - -QmitkMultiLabelSegmentationUtilitiesView::~QmitkMultiLabelSegmentationUtilitiesView() -{ -} - -void QmitkMultiLabelSegmentationUtilitiesView::CreateQtPartControl(QWidget* parent) -{ - m_Controls.setupUi(parent); - - mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); - - mitk::SliceNavigationController* timeNavigationController = renderWindowPart != nullptr - ? renderWindowPart->GetTimeNavigationController() - : nullptr; - - m_BooleanOperationsWidget = new QmitkBooleanOperationsWidget(timeNavigationController, parent); - m_ContourModelToImageWidget = new QmitkContourModelToImageWidget(timeNavigationController, parent); - m_MorphologicalOperationsWidget = new QmitkMorphologicalOperationsWidget(timeNavigationController, parent); - m_SurfaceToImageWidget = new QmitkSurfaceToImageWidget(timeNavigationController, parent); - m_ImageMaskingWidget = new QmitkImageMaskingWidget(timeNavigationController, parent); - m_ConvertToMlWidget = new QmitkConvertToMlWidget(timeNavigationController, parent); - - this->AddUtilityWidget(m_BooleanOperationsWidget, QIcon(":/MultiLabelSegmentationUtilities/BooleanOperations_48x48.png"), "Boolean Operations"); - this->AddUtilityWidget(m_ContourModelToImageWidget, QIcon(":/MultiLabelSegmentationUtilities/ContourModelSetToImage_48x48.png"), "Contour to Image"); - this->AddUtilityWidget(m_ImageMaskingWidget, QIcon(":/MultiLabelSegmentationUtilities/ImageMasking_48x48.png"), "Image Masking"); - this->AddUtilityWidget(m_MorphologicalOperationsWidget, QIcon(":/MultiLabelSegmentationUtilities/MorphologicalOperations_48x48.png"), "Morphological Operations"); - this->AddUtilityWidget(m_SurfaceToImageWidget, QIcon(":/MultiLabelSegmentationUtilities/SurfaceToImage_48x48.png"), "Surface To Image"); - this->AddUtilityWidget(m_ConvertToMlWidget, QmitkStyleManager::ThemeIcon(QStringLiteral(":/MultiLabelSegmentationUtilities/multilabelsegmentation.svg")), "Convert to MultiLabel"); -} - -void QmitkMultiLabelSegmentationUtilitiesView::AddUtilityWidget(QWidget* widget, const QIcon& icon, const QString& text) -{ - m_Controls.toolBox->addItem(widget, icon, text); -} - -void QmitkMultiLabelSegmentationUtilitiesView::SetFocus() -{ - m_Controls.toolBox->setFocus(); -} - -void QmitkMultiLabelSegmentationUtilitiesView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) -{ - mitk::SliceNavigationController* timeNavigationController = renderWindowPart->GetTimeNavigationController(); - - m_BooleanOperationsWidget->SetTimeNavigationController(timeNavigationController); - m_ContourModelToImageWidget->SetTimeNavigationController(timeNavigationController); - m_ImageMaskingWidget->SetTimeNavigationController(timeNavigationController); - m_MorphologicalOperationsWidget->SetTimeNavigationController(timeNavigationController); - m_SurfaceToImageWidget->SetTimeNavigationController(timeNavigationController); - m_ConvertToMlWidget->SetTimeNavigationController(timeNavigationController); -} - -void QmitkMultiLabelSegmentationUtilitiesView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) -{ - m_BooleanOperationsWidget->SetTimeNavigationController(nullptr); - m_ContourModelToImageWidget->SetTimeNavigationController(nullptr); - m_ImageMaskingWidget->SetTimeNavigationController(nullptr); - m_MorphologicalOperationsWidget->SetTimeNavigationController(nullptr); - m_SurfaceToImageWidget->SetTimeNavigationController(nullptr); - m_ConvertToMlWidget->SetTimeNavigationController(nullptr); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.h deleted file mode 100644 index 31ae381d04..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.h +++ /dev/null @@ -1,59 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkMultiLabelSegmentationUtilitiesView_h -#define QmitkMultiLabelSegmentationUtilitiesView_h - -#include -#include -#include - -class QmitkBooleanOperationsWidget; -class QmitkContourModelToImageWidget; -class QmitkSurfaceToImageWidget; -class QmitkImageMaskingWidget; -class QmitkMorphologicalOperationsWidget; -class QmitkConvertToMlWidget; - -class QmitkMultiLabelSegmentationUtilitiesView : public QmitkAbstractView, public mitk::IRenderWindowPartListener -{ - Q_OBJECT - -public: - QmitkMultiLabelSegmentationUtilitiesView(); - ~QmitkMultiLabelSegmentationUtilitiesView() override; - - void CreateQtPartControl(QWidget* parent) override; - void SetFocus() override; - - void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; - void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override; - -private: - void AddUtilityWidget(QWidget* widget, const QIcon& icon, const QString& text); - - QmitkBooleanOperationsWidget* m_BooleanOperationsWidget; - - QmitkContourModelToImageWidget* m_ContourModelToImageWidget; - - QmitkMorphologicalOperationsWidget* m_MorphologicalOperationsWidget; - - QmitkSurfaceToImageWidget* m_SurfaceToImageWidget; - - QmitkImageMaskingWidget* m_ImageMaskingWidget; - - QmitkConvertToMlWidget* m_ConvertToMlWidget; - - Ui::QmitkMultiLabelSegmentationUtilitiesViewControls m_Controls; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesViewControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesViewControls.ui deleted file mode 100644 index b3ed23046b..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesViewControls.ui +++ /dev/null @@ -1,52 +0,0 @@ - - - QmitkMultiLabelSegmentationUtilitiesViewControls - - - - 0 - 0 - 289 - 418 - - - - - 0 - 0 - - - - QmitkTemplate - - - icon-size: 32px 32px - - - - 0 - - - - - - - - - - - -1 - - - 0 - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.cpp deleted file mode 100644 index 2389dda82b..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkSegmentationUtilityWidget.h" - -QmitkSegmentationUtilityWidget::QmitkSegmentationUtilityWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QWidget(parent) -{ - this->SetTimeNavigationController(timeNavigationController); -} - -QmitkSegmentationUtilityWidget::~QmitkSegmentationUtilityWidget() -{ -} - -mitk::SliceNavigationController* QmitkSegmentationUtilityWidget::GetTimeNavigationController() const -{ - return m_TimeNavigationController; -} - -void QmitkSegmentationUtilityWidget::SetTimeNavigationController(mitk::SliceNavigationController* timeNavigationController) -{ - m_TimeNavigationController = timeNavigationController; - this->setEnabled(timeNavigationController != nullptr); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.h deleted file mode 100644 index 80e988c1ea..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.h +++ /dev/null @@ -1,51 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkSegmentationUtilityWidget_h -#define QmitkSegmentationUtilityWidget_h - -#include - -namespace mitk -{ - class SliceNavigationController; -} - -/** \brief Base class for segmentation utility widgets that need access to the time navigation controller. - * - * Call GetTimeNavigationController() in your derived class to gain access to the time navigation controller. - * The time navigation controller is not not available at all times and hence this method can return nullptr. - */ -class QmitkSegmentationUtilityWidget : public QWidget -{ - Q_OBJECT - -public: - explicit QmitkSegmentationUtilityWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - ~QmitkSegmentationUtilityWidget() override; - - /** \brief Usually called only from QmitkSegmentationUtilitiesView::RenderWindowPartActivated() and QmitkSegmentationUtilitiesView::RenderWindowPartDeactivated(). - */ - void SetTimeNavigationController(mitk::SliceNavigationController* timeNavigationController); - -protected: - /** \brief Call this method to access the time navigation controller. - * - * \return Pointer to the time navigation controller or nullptr, if it is not available. - */ - mitk::SliceNavigationController* GetTimeNavigationController() const; - -private: - mitk::SliceNavigationController* m_TimeNavigationController; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.cpp deleted file mode 100644 index fe8e47e8e8..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkSurfaceToImageWidget.h" - -#include -#include -#include -#include -#include -#include - -#include - -#include - -static const char* const HelpText = "Select a patient image and a surface"; - -QmitkSurfaceToImageWidget::QmitkSurfaceToImageWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent) - : QmitkSegmentationUtilityWidget(timeNavigationController, parent) -{ - m_Controls.setupUi(this); - - m_Controls.m_DataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ImagePredicate); - m_Controls.m_DataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::SurfacePredicate); - m_Controls.m_DataSelectionWidget->SetHelpText(HelpText); - -// mitk::IDataStorageService* service = -// berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); - -// assert(service.IsNotNull()); - - mitk::DataStorage::Pointer ds = m_Controls.m_DataSelectionWidget->GetDataStorage(); - m_Controls.m_LabelSetWidget->SetDataStorage(ds); - m_Controls.m_LabelSetWidget->setEnabled(true); - - m_Controls.m_SurfaceStampWidget->SetDataStorage(ds); - - this->EnableButtons(false); - - m_Controls.m_chkMakeOutputBinary->setChecked(true); - - connect (m_Controls.btnSurface2Image, SIGNAL(pressed()), this, SLOT(OnSurface2ImagePressed())); - connect(m_Controls.m_DataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), - this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*))); - connect (m_Controls.m_chkMakeOutputBinary, SIGNAL(toggled(bool)), this, SLOT(OnMakeOutputBinaryChanged(bool))); - - if( m_Controls.m_DataSelectionWidget->GetSelection(0).IsNotNull() && - m_Controls.m_DataSelectionWidget->GetSelection(1).IsNotNull() ) - { - this->OnSelectionChanged( 0, m_Controls.m_DataSelectionWidget->GetSelection(0)); - } -} - -QmitkSurfaceToImageWidget::~QmitkSurfaceToImageWidget() -{ -} - -void QmitkSurfaceToImageWidget::EnableButtons(bool enable) -{ - m_Controls.btnSurface2Image->setEnabled(enable); - m_Controls.m_chkMakeOutputBinary->setEnabled(enable); - m_Controls.m_chkOverwriteBackground->setEnabled(enable && !m_Controls.m_chkMakeOutputBinary->isChecked()); - m_Controls.m_leForegroundValue->setEnabled(enable && !m_Controls.m_chkMakeOutputBinary->isChecked()); - m_Controls.m_leBackgroundValue->setEnabled(enable && !m_Controls.m_chkMakeOutputBinary->isChecked()); -} - -void QmitkSurfaceToImageWidget::OnSelectionChanged(unsigned int, const mitk::DataNode*) -{ - mitk::DataNode::Pointer imageNode = m_Controls.m_DataSelectionWidget->GetSelection(0); - mitk::DataNode::Pointer surfaceNode = m_Controls.m_DataSelectionWidget->GetSelection(1); - - if (imageNode.IsNull() || surfaceNode.IsNull() ) - { - m_Controls.m_DataSelectionWidget->SetHelpText(HelpText); - this->EnableButtons(false); - } - else - { - mitk::Image::Pointer image = dynamic_cast( m_Controls.m_DataSelectionWidget->GetSelection(0)->GetData() ); - mitk::Surface::Pointer surface = dynamic_cast( m_Controls.m_DataSelectionWidget->GetSelection(1)->GetData() ); - if( image->GetTimeSteps() != surface->GetTimeSteps() ) - { - m_Controls.m_DataSelectionWidget->SetHelpText("Image and surface are of different size"); - this->EnableButtons(false); - } - else - { - m_Controls.m_DataSelectionWidget->SetHelpText(""); - this->EnableButtons(); - } - } -} - -void QmitkSurfaceToImageWidget::OnSurface2ImagePressed() -{ - this->EnableButtons(false); - - mitk::Image::Pointer image = dynamic_cast( m_Controls.m_DataSelectionWidget->GetSelection(0)->GetData() ); - mitk::Surface::Pointer surface = dynamic_cast( m_Controls.m_DataSelectionWidget->GetSelection(1)->GetData() ); - - if( image.IsNull() || surface.IsNull()) - { - MITK_ERROR << "Selection does not contain an image and/or a surface"; - QMessageBox::information( this, "Surface To Image", "Selection does not contain an image and/or a surface", QMessageBox::Ok ); - this->EnableButtons(); - return; - } - - mitk::Image::Pointer resultImage(nullptr); - resultImage = this->ConvertSurfaceToImage( image, surface ); - - if( resultImage.IsNull() ) - { - QMessageBox::information( this, "Surface to Image", "Could not stamp surface.\n See error log for details.", QMessageBox::Ok ); - this->EnableButtons(); - return; - } - - //create name for result node - std::string nameOfResultImage = m_Controls.m_DataSelectionWidget->GetSelection(0)->GetName(); - nameOfResultImage.append("_"); - nameOfResultImage.append(m_Controls.m_DataSelectionWidget->GetSelection(1)->GetName()); - - //create data node and add to data storage - mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); - resultNode->SetData( resultImage ); - resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); - resultNode->SetProperty("binary", mitk::BoolProperty::New(m_Controls.m_chkMakeOutputBinary->isChecked()) ); - - m_Controls.m_DataSelectionWidget->GetDataStorage()->Add(resultNode, m_Controls.m_DataSelectionWidget->GetSelection(0)); - - this->EnableButtons(); -} - -mitk::Image::Pointer QmitkSurfaceToImageWidget::ConvertSurfaceToImage( mitk::Image::Pointer image, mitk::Surface::Pointer surface ) -{ - mitk::SurfaceStampImageFilter::Pointer filter = mitk::SurfaceStampImageFilter::New(); - filter->SetInput(image); - filter->SetSurface(surface); - filter->SetMakeOutputBinary(m_Controls.m_chkMakeOutputBinary->isChecked()); - filter->SetOverwriteBackground(m_Controls.m_chkOverwriteBackground->isChecked()); - filter->SetForegroundValue(m_Controls.m_leForegroundValue->text().toFloat()); - filter->SetBackgroundValue(m_Controls.m_leBackgroundValue->text().toFloat()); - - try - { - filter->Update(); - } - catch(mitk::Exception& e) - { - MITK_ERROR << "exception caught: " << e.GetDescription(); - return nullptr; - } - - mitk::Image::Pointer resultImage = filter->GetOutput(); - - return resultImage; -} - -void QmitkSurfaceToImageWidget::OnMakeOutputBinaryChanged(bool value) -{ - m_Controls.m_chkOverwriteBackground->setEnabled(!value); - m_Controls.m_leForegroundValue->setEnabled(!value); - m_Controls.m_leBackgroundValue->setEnabled(!value); -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.h b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.h deleted file mode 100644 index 70e006a2ba..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.h +++ /dev/null @@ -1,63 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkSurfaceToImageWidget_h -#define QmitkSurfaceToImageWidget_h - -#include "../QmitkSegmentationUtilityWidget.h" -#include - -#include -#include - -/*! - \brief QmitkSurfaceToImageWidget - - The Tool converts a surface to a binary image. The Method requires - a surface and an image, which header information defines the output - image. The resulting binary image has the same dimension, size, and - Geometry3D as the input image. -*/ -class QmitkSurfaceToImageWidget : public QmitkSegmentationUtilityWidget -{ - Q_OBJECT - -public: - - /** @brief Default constructor, including creation of GUI elements and signals/slots connections. */ - explicit QmitkSurfaceToImageWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent = nullptr); - - /** @brief Defaul destructor. */ - ~QmitkSurfaceToImageWidget() override; - -private slots: - - /** @brief This slot is called if the selection in the workbench is changed. */ - void OnSelectionChanged(unsigned int index, const mitk::DataNode* selection); - - /** @brief This slot is called if user activates the button to convert a surface into a binary image. */ - void OnSurface2ImagePressed(); - - void OnMakeOutputBinaryChanged(bool value); - -private: - - /** @brief Enable buttons if data selction is valid. */ - void EnableButtons(bool enable = true); - - /** @brief Convert a surface into an binary image. */ - mitk::Image::Pointer ConvertSurfaceToImage( mitk::Image::Pointer image, mitk::Surface::Pointer surface ); - - Ui::QmitkSurfaceToImageWidgetControls m_Controls; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidgetControls.ui b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidgetControls.ui deleted file mode 100644 index 52b7fc86e4..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidgetControls.ui +++ /dev/null @@ -1,252 +0,0 @@ - - - QmitkSurfaceToImageWidgetControls - - - - 0 - 0 - 179 - 183 - - - - - 3 - - - 4 - - - - - 0 - - - - Masks - - - - 3 - - - 4 - - - - - - 0 - 0 - - - - - - - - make output binary - - - - - - - overwrite background - - - - - - - - - Background Value: - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 50 - 0 - - - - - 50 - 16777215 - - - - 0.0 - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - - - - Foreground Value: - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 50 - 0 - - - - - 50 - 16777215 - - - - 1.0 - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - - Convert - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Labels - - - - 2 - - - 2 - - - - - - 0 - 0 - - - - - 0 - 50 - - - - - - - - - 0 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - QmitkDataSelectionWidget - QWidget -
internal/Common/QmitkDataSelectionWidget.h
- 1 -
- - QmitkLabelSetWidget - QWidget -
QmitkLabelSetWidget.h
- 1 -
- - QmitkSurfaceStampWidget - QWidget -
QmitkSurfaceStampWidget.h
- 1 -
-
- - -
diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/mitkPluginActivator.cpp deleted file mode 100644 index b699458957..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/mitkPluginActivator.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "mitkPluginActivator.h" - -#include "QmitkThresholdAction.h" -#include "QmitkConvertSurfaceToLabelAction.h" -#include "QmitkConvertMaskToLabelAction.h" -#include "QmitkConvertToMultiLabelSegmentationAction.h" -#include "QmitkCreateMultiLabelSegmentationAction.h" - -#include "SegmentationUtilities/QmitkMultiLabelSegmentationUtilitiesView.h" - -#include - -ctkPluginContext* mitk::PluginActivator::m_Context = nullptr; - -//MLI TODO -US_INITIALIZE_MODULE //("MultiLabelSegmentation", "liborg_mitk_gui_qt_multilabelsegmentation") - -void mitk::PluginActivator::start(ctkPluginContext *context) -{ - BERRY_REGISTER_EXTENSION_CLASS(QmitkThresholdAction, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertSurfaceToLabelAction, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertMaskToLabelAction, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertToMultiLabelSegmentationAction, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkCreateMultiLabelSegmentationAction, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkMultiLabelSegmentationUtilitiesView, context) - - m_Context = context; -} - -void mitk::PluginActivator::stop(ctkPluginContext*) -{ -} - -ctkPluginContext* mitk::PluginActivator::getContext() -{ - return m_Context; -} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/target_libraries.cmake b/Plugins/org.mitk.gui.qt.multilabelsegmentation/target_libraries.cmake deleted file mode 100644 index 6c71bbbf08..0000000000 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/target_libraries.cmake +++ /dev/null @@ -1,3 +0,0 @@ -set(target_libraries - CTKWidgets -) diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/CMakeLists.txt b/Plugins/org.mitk.gui.qt.pixelvalue/CMakeLists.txt new file mode 100644 index 0000000000..02482dcdf5 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/CMakeLists.txt @@ -0,0 +1,7 @@ +project(org_mitk_gui_qt_pixelvalue) + +mitk_create_plugin( + EXPORT_DIRECTIVE MITK_QT_PIXELVALUE + EXPORTED_INCLUDE_SUFFIXES src + MODULE_DEPENDS MitkQtWidgets +) diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/documentation/UserManual/PixelValueIcon.png b/Plugins/org.mitk.gui.qt.pixelvalue/documentation/UserManual/PixelValueIcon.png new file mode 100644 index 0000000000..563f128049 Binary files /dev/null and b/Plugins/org.mitk.gui.qt.pixelvalue/documentation/UserManual/PixelValueIcon.png differ diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/documentation/UserManual/QmitkPixelValue.dox b/Plugins/org.mitk.gui.qt.pixelvalue/documentation/UserManual/QmitkPixelValue.dox new file mode 100644 index 0000000000..df1a050900 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/documentation/UserManual/QmitkPixelValue.dox @@ -0,0 +1,7 @@ +/** +\page org_mitk_views_pixelvalue The Pixel Value View + +\imageMacro{PixelValueIcon.png,"Icon of the Pixel Value Plugin.",2.00} + +This is the pixel value plugin. It shows the value of the selected pixel in images. +*/ diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/files.cmake b/Plugins/org.mitk.gui.qt.pixelvalue/files.cmake new file mode 100644 index 0000000000..6e6ccf65c4 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/files.cmake @@ -0,0 +1,31 @@ +set(INTERNAL_CPP_FILES + mitkPluginActivator.cpp + QmitkPixelValueView.cpp +) + +set(UI_FILES + src/internal/QmitkPixelValueView.ui +) + +set(MOC_H_FILES + src/internal/mitkPluginActivator.h + src/internal/QmitkPixelValueView.h +) + +set(CACHED_RESOURCE_FILES + resources/PixelValueIcon.svg + plugin.xml +) + +set(QRC_FILES +) + +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/Plugins/org.mitk.gui.qt.pixelvalue/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.pixelvalue/manifest_headers.cmake new file mode 100644 index 0000000000..77bcd70869 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/manifest_headers.cmake @@ -0,0 +1,5 @@ +set(Plugin-Name "MITK Pixel Value") +set(Plugin-Version "0.1") +set(Plugin-Vendor "German Cancer Research Center (DKFZ)") +set(Plugin-ContactAddress "https://www.mitk.org") +set(Require-Plugin org.mitk.gui.qt.common) diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/plugin.xml b/Plugins/org.mitk.gui.qt.pixelvalue/plugin.xml new file mode 100644 index 0000000000..71019f28df --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/plugin.xml @@ -0,0 +1,10 @@ + + + + + + diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/resources/PixelValueIcon.svg b/Plugins/org.mitk.gui.qt.pixelvalue/resources/PixelValueIcon.svg new file mode 100644 index 0000000000..a7def0a8f9 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/resources/PixelValueIcon.svg @@ -0,0 +1 @@ + diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.cpp b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.cpp new file mode 100644 index 0000000000..be39b1f658 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.cpp @@ -0,0 +1,187 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#include "QmitkPixelValueView.h" + +#include +#include +#include +#include +#include + +#include + +const std::string QmitkPixelValueView::VIEW_ID = "org.mitk.views.pixelvalue"; + +QmitkPixelValueView::QmitkPixelValueView(QObject*) + : m_Ui(new Ui::QmitkPixelValueView) +{ +} + +QmitkPixelValueView::~QmitkPixelValueView() +{ +} + +void QmitkPixelValueView::CreateQtPartControl(QWidget* parent) +{ + m_Ui->setupUi(parent); + + this->m_SliceNavigationListener.RenderWindowPartActivated(this->GetRenderWindowPart()); + connect(&m_SliceNavigationListener, &QmitkSliceNavigationListener::SelectedPositionChanged, this, &QmitkPixelValueView::OnSelectedPositionChanged); + connect(&m_SliceNavigationListener, &QmitkSliceNavigationListener::SelectedTimePointChanged, this, &QmitkPixelValueView::OnSelectedTimePointChanged); + + this->Update(); +} + +void QmitkPixelValueView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) +{ + this->m_SliceNavigationListener.RenderWindowPartActivated(renderWindowPart); +} + +void QmitkPixelValueView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) +{ + this->m_SliceNavigationListener.RenderWindowPartDeactivated(renderWindowPart); +} + +void QmitkPixelValueView::OnSelectedPositionChanged(const mitk::Point3D&) +{ + this->Update(); +} + +void QmitkPixelValueView::OnSelectedTimePointChanged(const mitk::TimePointType&) +{ + this->Update(); +} + +void QmitkPixelValueView::NodeChanged(const mitk::DataNode*) +{ + this->Update(); +} + +void QmitkPixelValueView::Update() +{ + const auto position = m_SliceNavigationListener.GetCurrentSelectedPosition(); + const auto timePoint = m_SliceNavigationListener.GetCurrentSelectedTimePoint(); + + auto isImageData = mitk::TNodePredicateDataType::New(); + auto nodes = GetDataStorage()->GetSubset(isImageData); + + if (nodes.IsNull()) + { + this->Clear(); + return; + } + + mitk::Image::Pointer image; + mitk::DataNode::Pointer topParentNode; + + int component = 0; + + auto node = mitk::FindTopmostVisibleNode(nodes, position, timePoint, nullptr); + + if (node.IsNull()) + { + this->Clear(); + return; + } + + bool isBinary = false; + node->GetBoolProperty("binary", isBinary); + + if (isBinary) + { + auto parentNodes = GetDataStorage()->GetSources(node, nullptr, true); + + if (!parentNodes->empty()) + topParentNode = FindTopmostVisibleNode(nodes, position, timePoint, nullptr); + + if (topParentNode.IsNotNull()) + { + image = dynamic_cast(topParentNode->GetData()); + topParentNode->GetIntProperty("Image.Displayed Component", component); + } + else + { + image = dynamic_cast(node->GetData()); + node->GetIntProperty("Image.Displayed Component", component); + } + } + else + { + image = dynamic_cast(node->GetData()); + node->GetIntProperty("Image.Displayed Component", component); + } + + if (image.IsNotNull()) + { + m_Ui->imageNameLineEdit->setText(QString::fromStdString(node->GetName())); + + itk::Index<3> index; + image->GetGeometry()->WorldToIndex(position, index); + + auto pixelType = image->GetChannelDescriptor().GetPixelType().GetPixelType(); + + if (pixelType == itk::IOPixelEnum::RGB || pixelType == itk::IOPixelEnum::RGBA) + { + m_Ui->pixelValueLineEdit->setText(QString::fromStdString(mitk::ConvertCompositePixelValueToString(image, index))); + return; + } + + if (pixelType == itk::IOPixelEnum::DIFFUSIONTENSOR3D || pixelType == itk::IOPixelEnum::SYMMETRICSECONDRANKTENSOR) + { + m_Ui->pixelValueLineEdit->setText(QStringLiteral("See ODF Details view.")); + return; + } + + mitk::ScalarType pixelValue = 0.0; + + mitkPixelTypeMultiplex5( + mitk::FastSinglePixelAccess, + image->GetChannelDescriptor().GetPixelType(), + image, + image->GetVolumeData(image->GetTimeGeometry()->TimePointToTimeStep(timePoint)), + index, + pixelValue, + component); + + std::ostringstream stream; + stream.imbue(std::locale::classic()); + stream.precision(2); + + if (fabs(pixelValue) > 1000000 || fabs(pixelValue) < 0.01) + { + stream << std::scientific; + } + else + { + stream << std::fixed; + } + + stream << pixelValue; + + m_Ui->pixelValueLineEdit->setText(QString::fromStdString(stream.str())); + } + else + { + this->Clear(); + } +} + +void QmitkPixelValueView::Clear() +{ + m_Ui->imageNameLineEdit->clear(); + m_Ui->pixelValueLineEdit->clear(); +} + +void QmitkPixelValueView::SetFocus() +{ +} diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.h b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.h new file mode 100644 index 0000000000..0066df315e --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.h @@ -0,0 +1,56 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef QmitkPixelValueView_h +#define QmitkPixelValueView_h + +#include +#include +#include + +namespace Ui +{ + class QmitkPixelValueView; +} + +class QmitkPixelValueView : public QmitkAbstractView, public mitk::IRenderWindowPartListener +{ + Q_OBJECT + +public: + static const std::string VIEW_ID; + + QmitkPixelValueView(QObject* parent = nullptr); + + ~QmitkPixelValueView() override; + + void CreateQtPartControl(QWidget* parent) override; + + void SetFocus() override; + +private: + void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; + void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override; + + void OnSelectedPositionChanged(const mitk::Point3D& position); + void OnSelectedTimePointChanged(const mitk::TimePointType& timePoint); + + void NodeChanged(const mitk::DataNode* node) override; + + void Clear(); + void Update(); + + QmitkSliceNavigationListener m_SliceNavigationListener; + Ui::QmitkPixelValueView* m_Ui; +}; + +#endif diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.ui b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.ui new file mode 100644 index 0000000000..eb3ab2723a --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/QmitkPixelValueView.ui @@ -0,0 +1,59 @@ + + + QmitkPixelValueView + + + + 0 + 0 + 400 + 300 + + + + Pixel Value + + + + + + + + Image name + + + Qt::PlainText + + + + + + + true + + + + + + + Pixel value + + + Qt::PlainText + + + + + + + true + + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/mitkPluginActivator.cpp new file mode 100644 index 0000000000..e1ff080825 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/mitkPluginActivator.cpp @@ -0,0 +1,23 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#include "mitkPluginActivator.h" +#include "QmitkPixelValueView.h" + +void mitk::mitkPluginActivator::start(ctkPluginContext* context) +{ + BERRY_REGISTER_EXTENSION_CLASS(QmitkPixelValueView, context) +} + +void mitk::mitkPluginActivator::stop(ctkPluginContext*) +{ +} diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/mitkPluginActivator.h similarity index 53% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/mitkPluginActivator.h rename to Plugins/org.mitk.gui.qt.pixelvalue/src/internal/mitkPluginActivator.h index 1a97dd3e6f..1eaae47868 100644 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.pixelvalue/src/internal/mitkPluginActivator.h @@ -1,37 +1,32 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#ifndef org_mitk_gui_qt_multilabelsegmentation_Activator_h -#define org_mitk_gui_qt_multilabelsegmentation_Activator_h +#ifndef org_mitk_gui_qt_voxelvalue_Activator_h +#define org_mitk_gui_qt_voxelvalue_Activator_h #include namespace mitk { - class PluginActivator : public QObject, public ctkPluginActivator + class mitkPluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT - Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_multilabelsegmentation") + Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_pixelvalue") Q_INTERFACES(ctkPluginActivator) public: - void start(ctkPluginContext *context) override; - void stop(ctkPluginContext *context) override; - - static ctkPluginContext* getContext(); - - private: - static ctkPluginContext* m_Context; + void start(ctkPluginContext* context) override; + void stop(ctkPluginContext* context) override; }; } #endif diff --git a/Plugins/org.mitk.gui.qt.radiomics/documentation/UserManual/QmitkPhenotypingPortalPage.dox b/Plugins/org.mitk.gui.qt.radiomics/documentation/UserManual/QmitkPhenotypingPortalPage.dox index c9afa60b63..a5f247508a 100644 --- a/Plugins/org.mitk.gui.qt.radiomics/documentation/UserManual/QmitkPhenotypingPortalPage.dox +++ b/Plugins/org.mitk.gui.qt.radiomics/documentation/UserManual/QmitkPhenotypingPortalPage.dox @@ -1,40 +1,39 @@ /** \page org_mitk_gui_qt_mitkphenotyping The Phenotyping \tableofcontents MITK Phenotyping is a selection of algorithms that can be used to extract image-based phenotypes, for example using a radiomics approach. The software is part of the research of the Division of Medical Image Computing of the German Cancer Research Center (DKFZ). MITK Phenotyping is not intended to be a single application, it is rather a collection of the necessary plugins within the offical MITK releases. The functionality of MITK Phenotyping can be accessed in different ways: Using the graphical interface using the Plugins listed below, using command line applications, or using one of the programming interfaces. \section org_mitk_gui_qt_mitkphenotyping_Tutorials Tutorials \li \subpage org_mitk_views_radiomicstutorial_gui_portal A tutorial on how to use the grapical interface of MITK Phenotying \section org_mitk_gui_qt_mitkphenotyping_Views Views \subsection sub2 Specific Views: Views that were developed with the main focus on Radiomics. They still might be used in other use-cases as well: \li \subpage org_mitk_views_radiomicstransformationview : Image transformations like Resampling, Laplacian of Gaussian, and Wavelet Transformations \li \subpage org_mitk_views_radiomicsmaskprocessingview : Processing and Cleaning of Masks \li \subpage org_mitk_views_radiomicsarithmetricview : Processing images using mathematical operations \li \subpage org_mitk_views_radiomicsstatisticview : Calculate Radiomics Features \subsection sub1 Non-Specific Views: This section contains views that are included within MITK Phenotyping, but were developed with a broader application in mind. \li \ref org_mitk_views_basicimageprocessing : Deprecated plugin for performing different image-related tasks like subtraction, mutliplaction, filtering etc. \li \ref org_mitk_views_matchpoint_algorithm_browser : Selection of MatchPoint (Registration) Algorithm \li \ref org_mitk_views_matchpoint_algorithm_control : Configuring and Controlling MatchPoint (Registration) Algorithm \li \ref org_mitk_views_matchpoint_evaluator : Evaluate the Registration performance using MatchPoint \li \ref org_mitk_views_matchpoint_manipulator : Adapt a registration calculated using MatchPoint \li \ref org_mitk_views_matchpoint_mapper : Apply a MatchPoint Registration to a specific image \li \ref org_mitk_views_matchpoint_visualizer : Visualize a Registration obtained with MatchPoint \li \ref org_mitk_views_segmentation : Creating Multilabel Segmentations \li \ref org_mitk_views_segmentationutilities : Utilities for the processing of simple segmentations -\li \ref org_mitk_views_multilabelsegmentation : Utilities for the processing of Multilabel Segmentations \section radiomics_miniapps MiniApps (Command line Tools) \li \subpage MiniAppExplainPage Explanation of the Command Line App concept in MITK \li \subpage mitkBasicImageProcessingMiniAppsPortalPage : List of common preprocessing MiniApps \li \subpage mitkClassificationMiniAppsPortalPage : (Incomplete) list of MITK Classification MiniApps */ diff --git a/Plugins/org.mitk.gui.qt.segmentation/documentation/UserManual/QmitkSegmentation.dox b/Plugins/org.mitk.gui.qt.segmentation/documentation/UserManual/QmitkSegmentation.dox index 600bec623f..a49ee5a91c 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/documentation/UserManual/QmitkSegmentation.dox +++ b/Plugins/org.mitk.gui.qt.segmentation/documentation/UserManual/QmitkSegmentation.dox @@ -1,432 +1,432 @@ /** \page org_mitk_views_segmentation The Segmentation View \imageMacro{segmentation-dox.svg,"Icon of the segmentation view",2.00} Some of the features described below are closed source additions to the open source toolkit MITK and are not available in every application. \tableofcontents \section org_mitk_views_segmentationoverview Overview Segmentation is the act of partitioning an image into subsets by either manual or automated delineation to create i.e. a distinction between foreground and background. A multilabel segmentation can contain more than one label and more than one layer. This allows you to create different labels for different regions of interest encapsulated in one single image. The difference between labels and layers is that labels on one layer cannot overlap but labels on different layers can. The MITK segmentation plugin allows you to create multilabel segmentations of anatomical and pathological structures in medical images. The plugin consists of two views:
  • Segmentation View: Manual and (semi-)automatic segmentation
  • \subpage org_mitk_views_segmentationutilities : Segmentation post-processing
In this documentation, the features and usage of the segmentation view will be described. For an introduction to the segmentation utilities please be referred to the respective documentation pages. \imageMacro{QmitkSegmentationPlugin_Overview.png,"Segmentation plugin overview", 16.00} \section org_mitk_views_segmentationpreferences Preferences The segmentation plugin offers a number of preferences which can be set via the MITK Workbench application preferences: \imageMacro{QmitkSegmentationPreferences.png,"Segmentation preferences", 10.00}
  • Slim view: Allows to show or hide the tool button description of the segmentation view
  • 2D display: Specify whether the segmentation is drawn as outline or as a transparent overlay
  • Show only selected nodes: Enable if only the selected segmentation and the reference image should be visible
  • Smoothed surface creation: Set certain smoothing parameters for surface creation
  • Default label set preset: Start a new segmentation with this preset instead of a default label
  • Label creation: Assign default names and colors to new labels or ask users for them
  • Label suggestions: Specify custom suggestions for label names and colors
\section org_mitk_views_segmentationtechnicalissues Technical issues The segmentation plugin makes a number of assumptions:
  • Images must be 2D, 3D, or 3D+t.
  • Images must be single-values, i.e. CT, MRI or "normal" ultrasound. Images from color doppler or photographic (RGB) images are only partially supported (please be aware that some tools might not be compatible with this image type).
  • Segmentations are handled as multilabel images of the same extent as the original image.
\section org_mitk_views_segmentationdataselection Data selection & creating new segmentations To select a reference image for the segmentation, click on the Selected image selection widget and choose a suitable image from the selection available in the data manager. Once an image is selected, a new segmentation can be created on this reference image by clicking the button to the right of the Selected segmentation selection widget. A new multilabel segmentation with an initial label is automatically generated. The new segmentation will be added to the data manager as sub-node of the reference image. This item is then automatically selected in the data selection, which allows to start editing the new segmentation right away. \imageMacro{"QmitkSegmentation_DataSelection.png","Data selection",12} Alternatively to creating a new segmentation, an existing one can be edited as well. If a reference image is selected for which a segmentation already exists in the data manager, the auto selection mode will automatically select a fitting segmentation. Clicking on the segmentation selection widget a drop down list will open, containing all suitable segmentations for the selected reference dataset available in the data manager. \section org_mitk_views_segmentationlayers Segmentation layers For each multilabel segmentation different layers can be added or deleted. The layers can be used independently and layers can be switched using the left and right arrows. A layer is a set of labels that occupy a non-overlapping anatomical space. The best way to describe them is by a real use case: Imagine you are working on a radiotherapy planning application. In the first layer of your segmentation session, you would like to trace the contours of the liver and neighboring organs. You can accommodate all these segmentations in separate labels because they all occupy different anatomical regions and do not overlap. Now say you would like to segment the arteries and veins inside the liver. If you don't trace them in a different layer, you will overwrite the previous ones. You may also need a third layer for segmenting the different irrigation territories in the liver and a fourth layer to contain the lesion you would like to treat. \imageMacro{"QmitkSegmentation_LayerSelection.png","Layer selection",12} \section org_mitk_views_segmentationlabels Segmentation labels For each layer, one or more labels can be added. Pressing the double arrow on the right, all created labels are shown in the 'Label Table'. The following label properties are available:
  • Name:
  • the name of the label. Can be a predefined one or any other.
  • Locked:
  • whether the label is locked or editable. A locked label cannot be overwritten by another.
  • Color:
  • the color of the label.
  • Visible:
  • whether the label is currently visible or hidden.
\imageMacro{"QmitkSegmentation_LabelTable.png","The 'Label Table' shows all labels in the current segmentation session",12} The 'New Label' button can be used to add a new label. This will automatically add a new label with a distinct name and color to the list of available labels.\n In the current implementation of the plugin, the maximum number of labels is restricted to 255. If you need more, you will have to create a new segmentation session. \subsection org_mitk_views_segmentationlabelsuggestions Label name and color suggestions When renaming labels or creating new labels with enforced manual naming in the Segmentation preferences, entering names is supported by auto-completion for common label names. The list of predefined label names and colors for the auto-completion feature can be either extented or replaced by a custom list of label name and color suggestions. This custom list must be specified as a JSON file, just containing an array of objects, each with a mandatory "name" string and an optional "color" string. The JSON file can be set in the Segmentation preferences as well as a few options on how to apply these suggestions. \subsection org_mitk_views_segmentationlabelpresets Saving and loading label set presets Label set presets are useful to share a certain style or scheme between different segmentation sessions or to provide templates for new segmentation sessions. The properties of all labels in all layers like their names, colors, and visibilities are saved as a label set preset by clicking on the 'Save label set preset' button. Label set presets are applied to any segmentation session by clicking on the 'Load label set preset' button. If a label for a certain value already exists, its properties are overridden by the preset. If a label for a certain value does not yet exist, an empty label with the label properties of the preset is created. The actual segmentations of labels are unaffected as label set presets only store label properties. \subsubsection org_mitk_views_segmentationdefaultlabelpresets Applying label set presets by default If you work on a repetetive segmentation task, manually loading the same label set preset for each and every new segmentation can be tedious. To streamline your workflow, you can set a default label set preset in the Segmentation preferences (Ctrl+P). When set, this label set preset will be applied to all new segmentations instead of creating the default red "New label 1" label. \subsection org_mitk_views_segmentationlabelsearch Searching for a label It may happen that many labels (e.g. > 200) are present in a segmentation session and therefore manual searching can be time-consuming. The 'Label Search' edit box allows for quickly finding a label by providing assistance for label name completion. If the label is found, it will become the active one after pressing 'enter'. To start editing a label needs to be activated by clicking on the corresponding row in the 'Label Table'. Only one label can be active at the time. Then the segmentation tools in the toolbox can be used for mask generation. \subsection org_mitk_views_multilabelsegmentationoperationsonlabels Operations on labels Depending on the selection in the 'Label Table', several actions are offered: \subsubsection org_mitk_views_segmentationoperationssingleselection Operations with single label selection Right-clicking on any label opens a pop-up menu that offers the following actions to be performed on the selected label:
  • Rename...
  • : change the name and / or color of the selected label.
  • Remove...
  • : delete the selected label.
  • Erase...
  • : only clear the contents of the selected label.
  • Merge...
  • : merge two labels by selecting a second label.
  • Random color
  • : assign a random color to the label.
  • View only
  • : make all labels except the current selected label invisible.
  • View/Hide all
  • : make all labels visible / invisible
  • Lock/Unlock all
  • : lock or unlock all labels.
  • Create surface
  • : generate a surface out of the selected label.
  • Create mask
  • : generate a mask out of the selected label. A mask is a binary image with "1" inside and "0" outside.
  • Create cropped mask
  • : generate a binary mask out of the selected label. Crop changes the extent of the resulting image to the extent of the label.
\imageMacro{"QmitkSegmentation_OperationsSingleSelection.png","Context menu for single label selection",12} \subsubsection org_mitk_views_segmentationoperationsmultiselection Operations with multiple label selection Shift-clickink on multiple labels allows to select more than one label. If more than one label is selected, different options will appear in the menu:
  • Merge selection on current label
  • : transfer the contents of the selected labels in the 'Label Table' into the current one.
  • Remove selected labels
  • : delete the selected labels.
  • Erase selected labels
  • : only clear the contents of the selected labels.
\imageMacro{"QmitkSegmentation_OperationsMultiSelection.png","Context menu for multiple label selection",12} \section org_mitk_views_segmentationtooloverview Segmentation tool overview MITK offers a comprehensive set of slice-based 2D and (semi-)automated 3D segmentation tools. The manual 2D tools require some user interaction and can only be applied to a single image slice whereas the 3D tools operate on the whole image. The 3D tools usually only require a small amount of user interaction, i.e. placing seed points or setting / adjusting parameters. You can switch between the different toolsets by selecting the 2D or 3D tab in the segmentation view. \imageMacro{QmitkSegmentation_ToolOverview.png,"An overview of the existing 2D and 3D tools in MITK.",5.50} \section org_mitk_views_segmentation2dsegmentation 2D segmentation tools With 2D manual contouring you define which voxels are part of the segmentation and which are not. This allows you to create segmentations of any structures of interest in an image. You can also use manual contouring to correct segmentations that result from sub-optimal automatic methods. The drawback of manual contouring is that you might need to define contours on many 2D slices. However, this is mitigated by the interpolation feature, which will make suggestions for a segmentation. To start using one of the editing tools, click its button from the displayed toolbox. The selected editing tool will be active and its corresponding button will stay pressed until you click the button again. Selecting a different tool also deactivates the previous one.\n If you have to delineate a lot of images, shortcuts to switch between tools becomes convenient. For that, just hit the first letter of each tool to activate it (A for Add, S for Subtract, etc.). All of the editing tools work by the same principle: using the mouse (left button) to click anywhere in a 2D window (any of the orientations axial, sagittal, or coronal), moving the mouse while holding the mouse button and releasing the button to finish the editing action. Multi-step undo and redo is fully supported by all editing tools by using the application-wide undo / redo buttons in the toolbar. Remark: Clicking and moving the mouse in any of the 2D render windows will move the crosshair that defines what part of the image is displayed. This behavior is disabled as long as any of the manual segmentation tools are active - otherwise you might have a hard time concentrating on the contour you are drawing. \subsection org_mitk_views_segmentationaddsubtracttools Add and subtract tools \imageMacro{QmitkSegmentation_IMGIconAddSubtract.png,"Add and subtract tools",7.70} Use the left mouse button to draw a closed contour. When releasing the mouse button, the contour will be added (Add tool) to or removed (Subtract tool) from the current segmentation. Adding and subtracting voxels can be iteratively repeated for the same segmentation. Holding CTRL / CMD while drawing will invert the current tool's behavior (i.e. instead of adding voxels, they will be subtracted). \subsection org_mitk_views_segmentationlassotool Lasso tool \imageMacro{QmitkSegmentation_Lasso.png,"Lasso tool",7.70} -The tool is a more advanced version of the add/substract tool. It offers you the following features: +The tool is a more advanced version of the add/subtract tool. It offers you the following features:
  1. Generating a polygon segmentation (click left mouse button to set ancor point)
  2. Freehand contouring (like the add tool; press left mouse button while moving the mouse)
  3. Move ancor points (select an ancor point, press left mouse button while moving the mouse)
  4. Add new ancor points (press CTRL while click left mouse to add an ancor to the contour)
  5. Delete an ancor point (press Del while ancor point is selected) -
  6. Segmentation can be added to the label (Add mode) or substracted (Substract mode) +
  7. Segmentation can be added to the label (Add mode) or subtracted (Subtract mode)
To start a segmentation double left click where the first ancor point should be. To end the segmentation double left click where the last ancor point should be. Please note that:
  • feature 3-6 are only available, if auto confirm is *not* activated
  • feature 3-5 is not available for freehand contour segments
\subsection org_mitk_views_segmentationpaintwipetools Paint and wipe tools \imageMacro{QmitkSegmentation_IMGIconPaintWipe.png,"Paint and wipe tools",7.68} Use the Size slider to change the radius of the round paintbrush tool. Move the mouse in any 2D window and press the left button to draw or erase pixels. Holding CTRL / CMD while drawing will invert the current tool's behavior (i.e. instead of painting voxels, they will be wiped). \subsection org_mitk_views_segmentationregiongrowingtool Region growing tool \imageMacro{QmitkSegmentation_IMGIconRegionGrowing.png,"Region growing tool",3.81} Click at one point in a 2D slice widget to add an image region to the segmentation with the region growing tool. Region Growing selects all pixels around the mouse cursor that have a similar gray value as the pixel below the mouse cursor. This allows to quickly create segmentations of structures that have a good contrast to surrounding tissue. The tool operates based on the current level window, so changing the level window to optimize the contrast for the ROI is encouraged. Moving the mouse up / down is different from left / right: Moving up the cursor while holding the left mouse button widens the range for the included grey values; moving it down narrows it. Moving the mouse left and right will shift the range. The tool will select more or less pixels, corresponding to the changing gray value range. \if THISISNOTIMPLEMENTEDATTHEMOMENT A common issue with region growing is the so called "leakage" which happens when the structure of interest is connected to other pixels, of similar gray values, through a narrow "bridge" at the border of the structure. The Region Growing tool comes with a "leakage detection/removal" feature. If leakage happens, you can left-click into the leakage region and the tool will try to automatically remove this region (see illustration below). \imageMacro{QmitkSegmentation_Leakage.png,"Leakage correction feature of the region growing tool",11.28} \endif \subsection org_mitk_views_segmentationfilltool Fill tool \imageMacro{QmitkSegmentation_IMGIconFill.png,"Fill tool",3.81} Left-click inside a region/segmentation to flood fill all connected pixels that have the same label with the active label. This tool will only work on regions of unlocked labels or on regions that are not labeled at all. \subsection org_mitk_views_segmentationerasetool Erase tool \imageMacro{QmitkSegmentation_IMGIconErase.png,"Erase tool",3.79} This tool removes a connected part of pixels that form a segmentation. You may use it to remove single segmented regions (left-click on specific segmentation) or to clear a whole slice at once (left-click at the non-labeled background). This tool will only work and regions of unlocked labels or on regions of the active label. \subsection org_mitk_views_segmentationclosetool Close tool \imageMacro{QmitkSegmentation_IMGIconClose.png,"Close tool",3.79} Left-click inside the region/segmentation to fill all "holes" (pixels labelled with another label or no label) inside the region. Therefore this tool behaves like a local closing operation. This tool will not work, when a non-labeled region is selected and holes of locked labels will not be filled. \remark This tool always uses the label of the selected region (even if this label is not the active label). Therefore you can use this tool on regions of the active label and of none locked labels (without the need to change the active label). \subsection org_mitk_views_segmentationlivewiretool Live wire tool \imageMacro{QmitkSegmentation_IMGIconLiveWire.png,"Live wire tool",3.01} The Live Wire Tool acts as a magnetic lasso with a contour snapping to edges of objects. \imageMacro{QmitkSegmentation_IMGLiveWireUsage.PNG,"Steps for using the Live Wire Tool",16.00} The tool handling is the same like the Lasso tool (see for more info), except it generates live wire contours instead of straight lines. \subsection org_mitk_views_segmentationinterpolation 2D and 3D Interpolation Creating segmentations using 2D manual contouring for large image volumes may be very time-consuming, because structures of interest may cover a large range of slices. Note: Interpolation is currently disabled for segmentations containing more than one label. The segmentation view offers two helpful features to mitigate this drawback:
  • 2D Interpolation
  • 3D Interpolation
The 2D Interpolation creates suggestions for a segmentation whenever you have a slice that
  • has got neighboring slices with segmentations (these do not need to be direct neighbors but could also be a couple of slices away) AND
  • is completely clear of a manual segmentation, i.e. there will be no suggestion if there is even only a single pixel of segmentation in the current slice.
\imageMacro{QmitkSegmentation_2DInterpolation.png,"2D interpolation usage",3.01} Interpolated suggestions are displayed as outlines, until you confirm them as part of the segmentation. To confirm single slices, click the Confirm for single slice button below the toolbox. You may also review the interpolations visually and then accept all of them at once by selecting Confirm for all slices. The 3D interpolation creates suggestions for 3D segmentations. That means if you start contouring, from the second contour onwards, the surface of the segmented area will be interpolated based on the given contour information. The interpolation works with all available manual tools. Please note that this is currently a pure mathematical interpolation, i.e. image intensity information is not taken into account. With each further contour the interpolation result will be improved, but the more contours you provide the longer the recalculation will take. To achieve an optimal interpolation result and in this way a most accurate segmentation you should try to describe the surface with sparse contours by segmenting in arbitrary oriented planes. The 3D interpolation is not meant to be used for parallel slice-wise segmentation, but rather segmentations in i.e. the axial, coronal and sagittal plane. \imageMacro{QmitkSegmentation_3DInterpolationWrongRight.png,"3D interpolation usage",16.00} You can accept the interpolation result by clicking the Confirm-button below the tool buttons. In this case the 3D interpolation will be deactivated automatically so that the result can be post-processed without any interpolation running in the background. Additional to the surface, black contours are shown in the 3D render window, which mark all the drawn contours used for the interpolation. You can navigate between the drawn contours by clicking on the corresponding position nodes in the data manager which are stored as sub-nodes of the selected segmentation. If you do not want to see these nodes just uncheck the Show Position Nodes checkbox and these nodes will be hidden. If you want to delete a drawn contour we recommend to use the Erase-Tool since undo / redo is not yet working for 3D interpolation. The current state of the 3D interpolation can be saved across application restart. For that, just click on save project during the interpolation is active. After restarting the application and load your project you can click on "Reinit Interpolation" within the 3D interpolation GUI area. \section org_mitk_views_segmentation3dsegmentation 3D segmentation tools The 3D tools operate on the whole image and require usually a small amount of interaction like placing seed-points or specifying certain parameters. All 3D tools provide an immediate segmentation feedback, which is displayed as a transparent green overlay. For accepting a preview you have to press the Confirm button of the selected tool. The following 3D tools are available: \subsection org_mitk_views_segmentation3dthresholdtool 3D Threshold tool The thresholding tool simply applies a 3D threshold to the patient image. All pixels with values equal or above the selected threshold are labeled as part of the segmentation. You can change the threshold by either moving the slider of setting a certain value in the spinbox. \imageMacro{QmitkSegmentation_3DThresholdTool.png,"3D Threshold tool",10.00} \subsection org_mitk_views_segmentation3dulthresholdTool 3D upper / lower threshold tool The Upper/Lower Thresholding tool works similar to the simple 3D threshold tool but allows you to define an upper and lower threshold. All pixels with values within this threshold interval will be labeled as part of the segmentation. \imageMacro{QmitkSegmentation_3DULThresholdTool.png,"3D upper / lower threshold tool",10.00} \subsection org_mitk_views_segmentation3dotsutool 3D Otsu tool The 3D Otsu tool provides a more sophisticated thresholding algorithm. It allows you to define a number of regions. Based on the image histogram the pixels will then be divided into different regions. The more regions you define the longer the calculation will take. You can select afterwards which of these regions you want to confirm as segmentation. \imageMacro{QmitkSegmentation_3DOtsuTool.png,"3D Otsu tool",10.00} \subsection org_mitk_views_segmentation3dgrowcuttool 3D GrowCut tool The 3D GrowCut tool uses previously created segmentation labels (e.g. by the "Add"-tool) stored in the segmentation layer 0. The GrowCut tool will use these segmentation labels to create a seedimage that will serve as input to the algorithm. As an advanced setting option, a Distance penalty can be set, which increases the cohesion in the immediate surroundings of the initial labels. Based on the seedimage and the Distance penalty, a growing is started, which includes all areas that are not initially assigned to a specific label. During this process, initially unassigned areas are assigned to the best fitting labels. After the segmentation process, the user can decide which newly generated labels should be confirmed. \imageMacro{QmitkSegmentation_3DGrowCutTool.png,"3D GrowCut tool",16.00} \subsection org_mitk_views_segmentation3drgtool 3D Region growing tool The 3D Region Growing tool works similar to the 2D pendant. At the beginning you have to place a seedpoint and define a threshold interval. If you press Run Segmentation a preview is calculated. By moving the Adapt region growing slider you can interactively adapt the segmentation result. \imageMacro{QmitkSegmentation_3DRGTool.png,"3D Region growing tool",10.00} \subsection org_mitk_views_segmentationpickingtool Picking Tool The Picking tool offers two modes that allow you to manipulate "islands" within your segmentation. This is especially useful if e.g. a thresholding provided you with several areas within your image but you are just interested in one special region. - Picking mode: Allows you to select certain "islands". When the pick is confirmed, the complete content of the active label will be removed except the pick. This mode is beneficial if you have a lot segmentation noise and want to pick the relevant parts and dismiss the rest. Hint: You can also pick from other labels, but this will only work if these labels are unlocked. - Relabel mode: Allows you to select certain "islands". When the pick is confirmed, it will be relabeled and added to the active label content. Hint: This mode ignores the locks of other labels, hence you do not need to unlock them explicitly. \imageMacro{QmitkSegmentation_PickingTool.png,"Picking tool",10.00} \subsection org_mitk_views_segmentationnnUNetTool nnU-Net Tool (Ubuntu only) \imageMacro{QmitkSegmentation_nnUnetTool.png,"nnUNet tool",10.00} This tool provides a GUI to the deep learning-based segmentation algorithm called the nnUNet. With this tool, you can get a segmentation mask predicted for the loaded image in MITK. Be ready with the pre-trained weights (a.k.a RESULTS_FOLDER) for your organ or task concerned, before using the tool. For a detailed explanation of the parameters and pre-trained weights folder structure etc., please refer to https://github.com/MIC-DKFZ/nnUNet.
Remark: The tool assumes that you have a Python3 environment with nnUNet (pip) installed. Your machine should be also equipped with a CUDA enabled GPU. \subsubsection org_mitk_views_segmentationnnUNetToolWorkflow Workflow: -# Select the "Python Path" drop-down to see if MITK has automatically detected other Python environments. Click on a fitting environment for the nnUNet inference or click "Select" in the dropdown to choose an unlisted python environment. Note that, while selecting an arbitrary environment folder, only select the base folder, e.g. "myenv". No need to select all the way until "../myenv/bin/python", for example. -# Click on the "nnUNet Results Folder" directory icon to navigate to the results folder on your hard disk. This is equivalent to setting the RESULTS_FOLDER environment variable. If your results folder is as per the nnUNet required folder structure, the configuration, trainers, tasks and folds are automatically parsed and correspondingly loaded in the drop-down boxes as shown below. Note that MITK automatically checks for the RESULTS_FOLDER environment variable value and, if found, auto parses that directory when the tool is started. \imageMacro{QmitkSegmentation_nnUNet_Settings.png,"nnUNet Segmentation Settings",10} -# Choose your required Task-Configuration-Trainer-Planner-Fold parameters, sequentially. By default, all entries are selected inside the "Fold" dropdown (shown: "All"). Note that, even if you uncheck all entries from the "Fold" dropdown (shown: "None"), then too, all folds would be considered for inferencing. -# For ensemble predictions, you will get the option to select parameters irrespective on postprocessing files available in the ensembles folder of RESULTS_FOLDER. Note that, if a postprocessing json file exists for the selected combination then it will used for ensembling, by default. To choose not to, uncheck the "Use PostProcessing JSON" in the "Advanced" section. \imageMacro{QmitkSegmentation_nnUNet_ensemble.png,"nnUNet Segmentation Settings",10} -# If your task is trained with multi-modal inputs, then "Multi-Modal" checkbox is checked and the no.of modalities are preloaded and shown next to "Required Modalities". Instantly, as much node selectors with corresponding modality names should appear below to select the Data Manager along including a selector with preselected with the reference node. Now, select the image nodes in the node selectors accordingly for accurate inferencing. \imageMacro{QmitkSegmentation_nnUNet_multimodal.png,"nnUNet Multi Modal Settings",10.00} -# Click on "Preview". -# In the "Advanced" section, you can also activate other options like "Mixed Precision" and "Enable Mirroring" (for test time data augmentation) pertaining to nnUNet. \imageMacro{QmitkSegmentation_nnUNet_Advanced.png,"nnUNet Advanced Settings",10.00} -# Use "Advanced" > "GPU Id" combobox to change the preferred GPU for inferencing. This is internally equivalent to setting the CUDA_VISIBLE_DEVICES environment variable. -# Every inferred segmentation is cached to prevent a redundant computation. In case, a user doesn't wish to cache a Preview, uncheck the "Enable Caching" in the "Advanced" section. This will ensure that the current parameters will neither be checked against the existing cache nor a segmentation be loaded from it when Preview is clicked. -# You may always clear all the cached segmentations by clicking "Clear Cache" button. \subsubsection org_mitk_views_segmentationnnUNetToolMisc Miscellaneous: -# In case you want to reload/reparse the folders in the "nnUNet Results Folder", eg. after adding new tasks into it, you may do so without reselecting the folder again by clicking the "Refresh Results Folder" button. -# The "Advanced" > "GPU Id" combobox lists the Nvidia GPUs available by parsing the nvidia-smi utility output. In case your machine has Nvidia CUDA enabled GPUs but the nvidia-smi fails for some reason, the "GPU Id" combobox will show no entries. In such a situation, it's still possible to execute inferencing by manually entering the preferred GPU Id, eg. 0 in the combobox. -# The "Advanced" > "Available Models" lists the available pre-trained tasks for download. Make sure you have internet connection. Then, choose a Task from the dropdown and click the Download button. The pre-trained models for the selected Task will be downloaded and placed to the RESULTS_FOLDER directory automatically. -# In the RESULTS_FOLDER directory, inside the trainer-planner folder of every task, MITK keeps a "mitk_export.json" file for fast loading for multi-modal information. It is recommended not to delete this file(s) for a fast responsive UI. Tip: If multi-modal information shown on MITK is not correct for a given task, you may modify this JSON file and try again. \section org_mitk_views_segmentationpostprocessing Additional things you can do with segmentations Segmentations are never an end in themselves. Consequently, the segmentation view adds a couple of "post-processing" actions, accessible through the context-menu of the data manager. \imageMacro{QmitkSegmentation_IMGDataManagerContextMenu.png,"Context menu items for segmentations",10.58}
  • Create polygon %model applies the marching cubes algorithm to the segmentation. This polygon %model can be used for visualization in 3D or other applications such as stereolithography (3D printing).
  • Create smoothed polygon %model uses smoothing in addition to the marching cubes algorithm, which creates models that do not follow the exact outlines of the segmentation, but look smoother.
  • Autocrop can save memory. Manual segmentations have the same extent as the patient image, even if the segmentation comprises only a small sub-volume. This invisible and meaningless margin is removed by autocropping.
\section org_mitk_views_segmentationof3dtimages Segmentation of 3D+t images For segmentation of 3D+t images, some tools give you the option to choose between creating dynamic and static masks.
  • Dynamic masks can be created on each time frame individually.
  • Static masks will be defined on one time frame and will be the same for all other time frames.
In general, segmentation is applied on the time frame that is selected when execution is performed. If you alter the time frame, the segmentation preview is adapted. \section org_mitk_views_segmentationtechnicaldetail Technical information for developers For technical specifications see \subpage QmitkSegmentationTechnicalPage and for information on the extensions of the tools system \subpage toolextensions. */ diff --git a/Plugins/org.mitk.gui.qt.segmentation/files.cmake b/Plugins/org.mitk.gui.qt.segmentation/files.cmake index 584a0cf103..ee2f6186bf 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/files.cmake +++ b/Plugins/org.mitk.gui.qt.segmentation/files.cmake @@ -1,87 +1,95 @@ set(SRC_CPP_FILES QmitkSegmentationPreferencePage.cpp QmitkNewSegmentationDialog.cpp QmitkLabelSetWidget.cpp ) set(INTERNAL_CPP_FILES mitkPluginActivator.cpp QmitkSegmentationView.cpp QmitkAutocropAction.cpp QmitkAutocropLabelSetImageAction.cpp QmitkCreatePolygonModelAction.cpp QmitkLoadMultiLabelPresetAction.cpp QmitkSaveMultiLabelPresetAction.cpp + QmitkConvertSurfaceToLabelAction.cpp + QmitkConvertMaskToLabelAction.cpp + QmitkConvertToMultiLabelSegmentationAction.cpp + QmitkCreateMultiLabelSegmentationAction.cpp Common/QmitkDataSelectionWidget.cpp Common/QmitkLabelsWidget.cpp Common/QmitkLayersWidget.cpp SegmentationUtilities/QmitkSegmentationUtilitiesView.cpp SegmentationUtilities/QmitkSegmentationUtilityWidget.cpp SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.cpp SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.cpp SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.cpp SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.cpp SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.cpp ) set(UI_FILES src/QmitkSegmentationPreferencePageControls.ui src/QmitkNewSegmentationDialog.ui src/QmitkLabelSetWidgetControls.ui src/internal/QmitkSegmentationViewControls.ui src/internal/Common/QmitkDataSelectionWidgetControls.ui src/internal/Common/QmitkLabelsWidgetControls.ui src/internal/Common/QmitkLayersWidgetControls.ui src/internal/SegmentationUtilities/QmitkSegmentationUtilitiesViewControls.ui src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidgetControls.ui src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidgetControls.ui src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidgetControls.ui src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidgetControls.ui src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidgetControls.ui ) set(MOC_H_FILES src/QmitkSegmentationPreferencePage.h src/QmitkNewSegmentationDialog.h src/QmitkLabelSetWidget.h src/internal/mitkPluginActivator.h src/internal/QmitkSegmentationView.h src/internal/QmitkAutocropAction.h src/internal/QmitkAutocropLabelSetImageAction.h src/internal/QmitkCreatePolygonModelAction.h src/internal/QmitkLoadMultiLabelPresetAction.h src/internal/QmitkSaveMultiLabelPresetAction.h + src/internal/QmitkConvertSurfaceToLabelAction.h + src/internal/QmitkConvertMaskToLabelAction.h + src/internal/QmitkConvertToMultiLabelSegmentationAction.h + src/internal/QmitkCreateMultiLabelSegmentationAction.h src/internal/Common/QmitkDataSelectionWidget.h src/internal/Common/QmitkLabelsWidget.h src/internal/Common/QmitkLayersWidget.h src/internal/SegmentationUtilities/QmitkSegmentationUtilitiesView.h src/internal/SegmentationUtilities/QmitkSegmentationUtilityWidget.h src/internal/SegmentationUtilities/BooleanOperations/QmitkBooleanOperationsWidget.h src/internal/SegmentationUtilities/ImageMasking/QmitkImageMaskingWidget.h src/internal/SegmentationUtilities/ContourModelToImage/QmitkContourModelToImageWidget.h src/internal/SegmentationUtilities/MorphologicalOperations/QmitkMorphologicalOperationsWidget.h src/internal/SegmentationUtilities/SurfaceToImage/QmitkSurfaceToImageWidget.h ) set(CACHED_RESOURCE_FILES resources/segmentation.svg resources/segmentation_utilities.svg plugin.xml ) set(QRC_FILES resources/segmentation.qrc resources/SegmentationUtilities.qrc resources/BooleanOperationsWidget.qrc resources/MorphologicalOperationsWidget.qrc ) 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/Plugins/org.mitk.gui.qt.segmentation/plugin.xml b/Plugins/org.mitk.gui.qt.segmentation/plugin.xml index 7da109cf6a..d761442833 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/plugin.xml +++ b/Plugins/org.mitk.gui.qt.segmentation/plugin.xml @@ -1,80 +1,84 @@ Allows the segmentation of images using different tools. Edit segmentations using standard operations. + + + + diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkLabelSetWidget.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkLabelSetWidget.cpp index ee964c22aa..95449f48a1 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkLabelSetWidget.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkLabelSetWidget.cpp @@ -1,1157 +1,1163 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkLabelSetWidget.h" // mitk #include #include #include #include #include #include #include #include #include #include #include // Qmitk #include #include #include // Qt #include #include #include #include #include #include #include #include #include #include // itk #include QmitkLabelSetWidget::QmitkLabelSetWidget(QWidget *parent) : QWidget(parent), m_DataStorage(nullptr), m_Completer(nullptr), m_ToolManager(nullptr), m_ProcessingManualSelection(false) { m_Controls.setupUi(this); m_ColorSequenceRainbow.GoToBegin(); m_ToolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); m_Controls.m_LabelSearchBox->setAlwaysShowClearIcon(true); m_Controls.m_LabelSearchBox->setShowSearchIcon(true); QStringList completionList; completionList << ""; m_Completer = new QCompleter(completionList, this); m_Completer->setCaseSensitivity(Qt::CaseInsensitive); m_Controls.m_LabelSearchBox->setCompleter(m_Completer); connect(m_Controls.m_LabelSearchBox, SIGNAL(returnPressed()), this, SLOT(OnSearchLabel())); auto* renameLabelShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key::Key_L, Qt::CTRL | Qt::Key::Key_R), this); connect(renameLabelShortcut, &QShortcut::activated, this, &QmitkLabelSetWidget::OnRenameLabelShortcutActivated); QStringListModel *completeModel = static_cast(m_Completer->model()); completeModel->setStringList(GetLabelStringList()); m_Controls.m_LabelSearchBox->setEnabled(false); m_Controls.m_lblCaption->setText(""); InitializeTableWidget(); } QmitkLabelSetWidget::~QmitkLabelSetWidget() {} void QmitkLabelSetWidget::OnTableViewContextMenuRequested(const QPoint & /*pos*/) { int pixelValue = GetPixelValueOfSelectedItem(); if (-1 == pixelValue) return; QMenu *menu = new QMenu(m_Controls.m_LabelSetTableWidget); if (m_Controls.m_LabelSetTableWidget->selectedItems().size() > 1) { QAction *mergeAction = new QAction(QIcon(":/Qmitk/MergeLabels.png"), "Merge selection on current label", this); mergeAction->setEnabled(true); QObject::connect(mergeAction, SIGNAL(triggered(bool)), this, SLOT(OnMergeLabels(bool))); menu->addAction(mergeAction); QAction *removeLabelsAction = new QAction(QIcon(":/Qmitk/RemoveLabel.png"), "Remove selected labels", this); removeLabelsAction->setEnabled(true); QObject::connect(removeLabelsAction, SIGNAL(triggered(bool)), this, SLOT(OnRemoveLabels(bool))); menu->addAction(removeLabelsAction); QAction *eraseLabelsAction = new QAction(QIcon(":/Qmitk/EraseLabel.png"), "Erase selected labels", this); eraseLabelsAction->setEnabled(true); QObject::connect(eraseLabelsAction, SIGNAL(triggered(bool)), this, SLOT(OnEraseLabels(bool))); menu->addAction(eraseLabelsAction); } else { QAction *renameAction = new QAction(QIcon(":/Qmitk/RenameLabel.png"), "Rename...", this); renameAction->setEnabled(true); QObject::connect(renameAction, SIGNAL(triggered(bool)), this, SLOT(OnRenameLabel(bool))); menu->addAction(renameAction); QAction *removeAction = new QAction(QIcon(":/Qmitk/RemoveLabel.png"), "Remove...", this); removeAction->setEnabled(true); QObject::connect(removeAction, SIGNAL(triggered(bool)), this, SLOT(OnRemoveLabel(bool))); menu->addAction(removeAction); QAction *eraseAction = new QAction(QIcon(":/Qmitk/EraseLabel.png"), "Erase...", this); eraseAction->setEnabled(true); QObject::connect(eraseAction, SIGNAL(triggered(bool)), this, SLOT(OnEraseLabel(bool))); menu->addAction(eraseAction); QAction *randomColorAction = new QAction(QIcon(":/Qmitk/RandomColor.png"), "Random color", this); randomColorAction->setEnabled(true); QObject::connect(randomColorAction, SIGNAL(triggered(bool)), this, SLOT(OnRandomColor(bool))); menu->addAction(randomColorAction); QAction *viewOnlyAction = new QAction(QIcon(":/Qmitk/visible.png"), "View only", this); viewOnlyAction->setEnabled(true); QObject::connect(viewOnlyAction, SIGNAL(triggered(bool)), this, SLOT(OnSetOnlyActiveLabelVisible(bool))); menu->addAction(viewOnlyAction); QAction *viewAllAction = new QAction(QIcon(":/Qmitk/visible.png"), "View all", this); viewAllAction->setEnabled(true); QObject::connect(viewAllAction, SIGNAL(triggered(bool)), this, SLOT(OnSetAllLabelsVisible(bool))); menu->addAction(viewAllAction); QAction *hideAllAction = new QAction(QIcon(":/Qmitk/invisible.png"), "Hide all", this); hideAllAction->setEnabled(true); QObject::connect(hideAllAction, SIGNAL(triggered(bool)), this, SLOT(OnSetAllLabelsInvisible(bool))); menu->addAction(hideAllAction); QAction *lockAllAction = new QAction(QIcon(":/Qmitk/lock.png"), "Lock all", this); lockAllAction->setEnabled(true); QObject::connect(lockAllAction, SIGNAL(triggered(bool)), this, SLOT(OnLockAllLabels(bool))); menu->addAction(lockAllAction); QAction *unlockAllAction = new QAction(QIcon(":/Qmitk/unlock.png"), "Unlock all", this); unlockAllAction->setEnabled(true); QObject::connect(unlockAllAction, SIGNAL(triggered(bool)), this, SLOT(OnUnlockAllLabels(bool))); menu->addAction(unlockAllAction); QAction *createSurfaceAction = new QAction(QIcon(":/Qmitk/CreateSurface.png"), "Create surface", this); createSurfaceAction->setEnabled(true); createSurfaceAction->setMenu(new QMenu()); QAction *tmp1 = createSurfaceAction->menu()->addAction(QString("Detailed")); QAction *tmp2 = createSurfaceAction->menu()->addAction(QString("Smoothed")); QObject::connect(tmp1, SIGNAL(triggered(bool)), this, SLOT(OnCreateDetailedSurface(bool))); QObject::connect(tmp2, SIGNAL(triggered(bool)), this, SLOT(OnCreateSmoothedSurface(bool))); menu->addAction(createSurfaceAction); QAction *createMaskAction = new QAction(QIcon(":/Qmitk/CreateMask.png"), "Create mask", this); createMaskAction->setEnabled(true); QObject::connect(createMaskAction, SIGNAL(triggered(bool)), this, SLOT(OnCreateMask(bool))); menu->addAction(createMaskAction); QAction *createCroppedMaskAction = new QAction(QIcon(":/Qmitk/CreateMask.png"), "Create cropped mask", this); createCroppedMaskAction->setEnabled(true); QObject::connect(createCroppedMaskAction, SIGNAL(triggered(bool)), this, SLOT(OnCreateCroppedMask(bool))); menu->addAction(createCroppedMaskAction); QSlider *opacitySlider = new QSlider; opacitySlider->setMinimum(0); opacitySlider->setMaximum(100); opacitySlider->setOrientation(Qt::Horizontal); QObject::connect(opacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OnOpacityChanged(int))); QLabel *_OpacityLabel = new QLabel("Opacity: "); QVBoxLayout *_OpacityWidgetLayout = new QVBoxLayout; _OpacityWidgetLayout->setContentsMargins(4, 4, 4, 4); _OpacityWidgetLayout->addWidget(_OpacityLabel); _OpacityWidgetLayout->addWidget(opacitySlider); QWidget *_OpacityWidget = new QWidget; _OpacityWidget->setLayout(_OpacityWidgetLayout); QWidgetAction *OpacityAction = new QWidgetAction(this); OpacityAction->setDefaultWidget(_OpacityWidget); // QObject::connect( m_OpacityAction, SIGNAL( changed() ), this, SLOT( OpacityActionChanged() ) ); auto workingImage = this->GetWorkingImage(); auto activeLayer = workingImage->GetActiveLayer(); auto label = workingImage->GetLabel(pixelValue, activeLayer); if (nullptr != label) { auto opacity = label->GetOpacity(); opacitySlider->setValue(static_cast(opacity * 100)); } menu->addAction(OpacityAction); } menu->popup(QCursor::pos()); } void QmitkLabelSetWidget::OnUnlockAllLabels(bool /*value*/) { GetWorkingImage()->GetActiveLabelSet()->SetAllLabelsLocked(false); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::OnLockAllLabels(bool /*value*/) { GetWorkingImage()->GetActiveLabelSet()->SetAllLabelsLocked(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::OnSetAllLabelsVisible(bool /*value*/) { GetWorkingImage()->GetActiveLabelSet()->SetAllLabelsVisible(true); UpdateAllTableWidgetItems(); } void QmitkLabelSetWidget::OnSetAllLabelsInvisible(bool /*value*/) { GetWorkingImage()->GetActiveLabelSet()->SetAllLabelsVisible(false); UpdateAllTableWidgetItems(); } void QmitkLabelSetWidget::OnSetOnlyActiveLabelVisible(bool /*value*/) { mitk::LabelSetImage *workingImage = GetWorkingImage(); int pixelValue = GetPixelValueOfSelectedItem(); workingImage->GetActiveLabelSet()->SetAllLabelsVisible(false); workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->SetVisible(true); workingImage->GetActiveLabelSet()->UpdateLookupTable(pixelValue); this->WaitCursorOn(); const mitk::Point3D &pos = workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->GetCenterOfMassCoordinates(); this->WaitCursorOff(); if (pos.GetVnlVector().max_value() > 0.0) { emit goToLabel(pos); } UpdateAllTableWidgetItems(); } void QmitkLabelSetWidget::OnEraseLabel(bool /*value*/) { int pixelValue = GetPixelValueOfSelectedItem(); QString question = "Do you really want to erase the contents of label \""; question.append( QString::fromStdString(GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetName())); question.append("\"?"); QMessageBox::StandardButton answerButton = QMessageBox::question(this, "Erase label", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); if (answerButton == QMessageBox::Yes) { this->WaitCursorOn(); GetWorkingImage()->EraseLabel(pixelValue); this->WaitCursorOff(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkLabelSetWidget::OnRemoveLabel(bool /*value*/) { int pixelValue = GetPixelValueOfSelectedItem(); QString question = "Do you really want to remove label \""; question.append( QString::fromStdString(GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetName())); question.append("\"?"); QMessageBox::StandardButton answerButton = QMessageBox::question(this, "Remove label", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); if (answerButton == QMessageBox::Yes) { this->WaitCursorOn(); GetWorkingImage()->RemoveLabel(pixelValue, GetWorkingImage()->GetActiveLayer()); this->WaitCursorOff(); } ResetAllTableWidgetItems(); } void QmitkLabelSetWidget::OnRenameLabel(bool /*value*/) { int pixelValue = GetPixelValueOfSelectedItem(); QmitkNewSegmentationDialog dialog(this, this->GetWorkingImage(), QmitkNewSegmentationDialog::RenameLabel); dialog.SetColor(GetWorkingImage()->GetActiveLabelSet()->GetLabel(pixelValue)->GetColor()); dialog.SetName(QString::fromStdString(GetWorkingImage()->GetActiveLabelSet()->GetLabel(pixelValue)->GetName())); if (dialog.exec() == QDialog::Rejected) { return; } QString segmentationName = dialog.GetName(); if (segmentationName.isEmpty()) { segmentationName = "Unnamed"; } GetWorkingImage()->GetActiveLabelSet()->RenameLabel(pixelValue, segmentationName.toStdString(), dialog.GetColor()); GetWorkingImage()->GetActiveLabelSet()->UpdateLookupTable(pixelValue); UpdateAllTableWidgetItems(); } void QmitkLabelSetWidget::OnRenameLabelShortcutActivated() { if (m_Controls.m_LabelSetTableWidget->selectedItems().size() == 1) this->OnRenameLabel(true); } void QmitkLabelSetWidget::OnCombineAndCreateMask(bool /*value*/) { m_Controls.m_LabelSetTableWidget->selectedRanges(); // ...to do... // } void QmitkLabelSetWidget::OnCreateMasks(bool /*value*/) { m_Controls.m_LabelSetTableWidget->selectedRanges(); // ..to do.. // } void QmitkLabelSetWidget::OnCombineAndCreateSurface(bool /*value*/) { m_Controls.m_LabelSetTableWidget->selectedRanges(); // ..to do.. // } void QmitkLabelSetWidget::OnEraseLabels(bool /*value*/) { QString question = "Do you really want to erase the selected labels?"; QMessageBox::StandardButton answerButton = QMessageBox::question( this, "Erase selected labels", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); if (answerButton == QMessageBox::Yes) { QList ranges = m_Controls.m_LabelSetTableWidget->selectedRanges(); if (ranges.isEmpty()) return; std::vector VectorOfLablePixelValues; foreach (QTableWidgetSelectionRange a, ranges) for (int i = a.topRow(); i <= a.bottomRow(); i++) VectorOfLablePixelValues.push_back(m_Controls.m_LabelSetTableWidget->item(i, 0)->data(Qt::UserRole).toInt()); this->WaitCursorOn(); GetWorkingImage()->EraseLabels(VectorOfLablePixelValues); this->WaitCursorOff(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkLabelSetWidget::OnRemoveLabels(bool /*value*/) { QString question = "Do you really want to remove the selected labels?"; QMessageBox::StandardButton answerButton = QMessageBox::question( this, "Remove selected labels", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); if (answerButton == QMessageBox::Yes) { QList ranges = m_Controls.m_LabelSetTableWidget->selectedRanges(); if (ranges.isEmpty()) { return; } std::vector VectorOfLablePixelValues; foreach (QTableWidgetSelectionRange a, ranges) { for (int i = a.topRow(); i <= a.bottomRow(); ++i) { VectorOfLablePixelValues.push_back(m_Controls.m_LabelSetTableWidget->item(i, 0)->data(Qt::UserRole).toInt()); } } this->WaitCursorOn(); GetWorkingImage()->RemoveLabels(VectorOfLablePixelValues, GetWorkingImage()->GetActiveLayer()); this->WaitCursorOff(); } ResetAllTableWidgetItems(); } void QmitkLabelSetWidget::OnMergeLabels(bool /*value*/) { int pixelValue = GetPixelValueOfSelectedItem(); QString question = "Do you really want to merge selected labels into \""; question.append( QString::fromStdString(GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetName())); question.append("\"?"); QMessageBox::StandardButton answerButton = QMessageBox::question( this, "Merge selected label", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); if (answerButton == QMessageBox::Yes) { QList ranges = m_Controls.m_LabelSetTableWidget->selectedRanges(); if (ranges.isEmpty()) { return; } std::vector vectorOfSourcePixelValues; foreach (QTableWidgetSelectionRange a, ranges) { for (int i = a.topRow(); i <= a.bottomRow(); ++i) { vectorOfSourcePixelValues.push_back(m_Controls.m_LabelSetTableWidget->item(i, 0)->data(Qt::UserRole).toInt()); } } this->WaitCursorOn(); GetWorkingImage()->MergeLabels(pixelValue, vectorOfSourcePixelValues, GetWorkingImage()->GetActiveLayer()); this->WaitCursorOff(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkLabelSetWidget::OnLockedButtonClicked() { int row = -1; for (int i = 0; i < m_Controls.m_LabelSetTableWidget->rowCount(); ++i) { if (sender() == m_Controls.m_LabelSetTableWidget->cellWidget(i, LOCKED_COL)) { row = i; } } if (row >= 0 && row < m_Controls.m_LabelSetTableWidget->rowCount()) { int pixelValue = m_Controls.m_LabelSetTableWidget->item(row, 0)->data(Qt::UserRole).toInt(); GetWorkingImage() ->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer()) ->SetLocked(!GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetLocked()); } } void QmitkLabelSetWidget::OnVisibleButtonClicked() { int row = -1; for (int i = 0; i < m_Controls.m_LabelSetTableWidget->rowCount(); ++i) { if (sender() == m_Controls.m_LabelSetTableWidget->cellWidget(i, VISIBLE_COL)) { row = i; break; } } if (row >= 0 && row < m_Controls.m_LabelSetTableWidget->rowCount()) { QTableWidgetItem *item = m_Controls.m_LabelSetTableWidget->item(row, 0); int pixelValue = item->data(Qt::UserRole).toInt(); GetWorkingImage() ->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer()) ->SetVisible(!GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetVisible()); GetWorkingImage()->GetActiveLabelSet()->UpdateLookupTable(pixelValue); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::OnColorButtonClicked() { int row = -1; for (int i = 0; i < m_Controls.m_LabelSetTableWidget->rowCount(); ++i) { if (sender() == m_Controls.m_LabelSetTableWidget->cellWidget(i, COLOR_COL)) { row = i; } } if (row >= 0 && row < m_Controls.m_LabelSetTableWidget->rowCount()) { int pixelValue = m_Controls.m_LabelSetTableWidget->item(row, 0)->data(Qt::UserRole).toInt(); const mitk::Color &color = GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetColor(); QColor initial(color.GetRed() * 255, color.GetGreen() * 255, color.GetBlue() * 255); QColor qcolor = QColorDialog::getColor(initial, nullptr, QString("Change color")); if (!qcolor.isValid()) { return; } QPushButton *button = static_cast(m_Controls.m_LabelSetTableWidget->cellWidget(row, COLOR_COL)); if (!button) { return; } button->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(qcolor.red())); styleSheet.append(","); styleSheet.append(QString::number(qcolor.green())); styleSheet.append(","); styleSheet.append(QString::number(qcolor.blue())); styleSheet.append("); border: 0;"); button->setStyleSheet(styleSheet); mitk::Color newColor; newColor.SetRed(qcolor.red() / 255.0); newColor.SetGreen(qcolor.green() / 255.0); newColor.SetBlue(qcolor.blue() / 255.0); GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->SetColor(newColor); GetWorkingImage()->GetActiveLabelSet()->UpdateLookupTable(pixelValue); } } void QmitkLabelSetWidget::OnRandomColor(bool /*value*/) { int pixelValue = GetPixelValueOfSelectedItem(); GetWorkingImage() ->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer()) ->SetColor(m_ColorSequenceRainbow.GetNextColor()); GetWorkingImage()->GetActiveLabelSet()->UpdateLookupTable(pixelValue); UpdateAllTableWidgetItems(); } void QmitkLabelSetWidget::OnActiveLabelChanged(int pixelValue) { mitk::LabelSetImage *workingImage = GetWorkingImage(); assert(workingImage); workingImage->GetActiveLabelSet()->SetActiveLabel(pixelValue); // MITK_INFO << "Active Label set to << " << pixelValue; mitk::SurfaceBasedInterpolationController *interpolator = mitk::SurfaceBasedInterpolationController::GetInstance(); if (interpolator) { interpolator->SetActiveLabel(pixelValue); } workingImage->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::OnItemClicked(QTableWidgetItem *item) { if (!item) return; int pixelValue = item->data(Qt::UserRole).toInt(); QList ranges = m_Controls.m_LabelSetTableWidget->selectedRanges(); if (!ranges.empty() && ranges.back().rowCount() == 1) { m_ProcessingManualSelection = true; OnActiveLabelChanged(pixelValue); m_ProcessingManualSelection = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkLabelSetWidget::OnItemDoubleClicked(QTableWidgetItem *item) { if (!item) return; + if (QApplication::queryKeyboardModifiers().testFlag(Qt::AltModifier)) + { + this->OnRenameLabelShortcutActivated(); + return; + } + int pixelValue = item->data(Qt::UserRole).toInt(); // OnItemClicked(item); <<-- Double click first call OnItemClicked WaitCursorOn(); mitk::LabelSetImage *workingImage = GetWorkingImage(); workingImage->UpdateCenterOfMass(pixelValue, workingImage->GetActiveLayer()); const mitk::Point3D &pos = workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->GetCenterOfMassCoordinates(); WaitCursorOff(); if (pos.GetVnlVector().max_value() > 0.0) { emit goToLabel(pos); } workingImage->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::SelectLabelByPixelValue(mitk::Label::PixelType pixelValue) { if (m_ProcessingManualSelection || !GetWorkingImage()->ExistLabel(pixelValue)) return; for (int row = 0; row < m_Controls.m_LabelSetTableWidget->rowCount(); row++) { if (m_Controls.m_LabelSetTableWidget->item(row, 0)->data(Qt::UserRole).toInt() == pixelValue) { m_Controls.m_LabelSetTableWidget->clearSelection(); m_Controls.m_LabelSetTableWidget->selectRow(row); m_Controls.m_LabelSetTableWidget->scrollToItem(m_Controls.m_LabelSetTableWidget->item(row, 0)); return; } } } void QmitkLabelSetWidget::InsertTableWidgetItem(mitk::Label *label) { const mitk::Color &color = label->GetColor(); 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("); border: 0;"); QTableWidget *tableWidget = m_Controls.m_LabelSetTableWidget; int colWidth = (tableWidget->columnWidth(NAME_COL) < 180) ? 180 : tableWidget->columnWidth(NAME_COL) - 2; QString text = fontMetrics().elidedText(label->GetName().c_str(), Qt::ElideMiddle, colWidth); QTableWidgetItem *nameItem = new QTableWidgetItem(text); nameItem->setTextAlignment(Qt::AlignCenter | Qt::AlignLeft); // ---!--- // IMPORTANT: ADD PIXELVALUE TO TABLEWIDGETITEM.DATA nameItem->setData(Qt::UserRole, QVariant(label->GetValue())); // ---!--- QPushButton *pbColor = new QPushButton(tableWidget); pbColor->setFixedSize(24, 24); pbColor->setCheckable(false); pbColor->setAutoFillBackground(true); pbColor->setToolTip("Change label color"); pbColor->setStyleSheet(styleSheet); connect(pbColor, SIGNAL(clicked()), this, SLOT(OnColorButtonClicked())); QString transparentStyleSheet = QLatin1String("background-color: transparent; border: 0;"); QPushButton *pbLocked = new QPushButton(tableWidget); pbLocked->setFixedSize(24, 24); QIcon *iconLocked = new QIcon(); auto lockIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/lock.svg")); auto unlockIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/unlock.svg")); iconLocked->addPixmap(lockIcon.pixmap(64), QIcon::Normal, QIcon::Off); iconLocked->addPixmap(unlockIcon.pixmap(64), QIcon::Normal, QIcon::On); pbLocked->setIcon(*iconLocked); pbLocked->setIconSize(QSize(24, 24)); pbLocked->setCheckable(true); pbLocked->setToolTip("Lock/unlock label"); pbLocked->setChecked(!label->GetLocked()); pbLocked->setStyleSheet(transparentStyleSheet); connect(pbLocked, SIGNAL(clicked()), this, SLOT(OnLockedButtonClicked())); QPushButton *pbVisible = new QPushButton(tableWidget); pbVisible->setFixedSize(24, 24); pbVisible->setAutoRepeat(false); QIcon *iconVisible = new QIcon(); auto visibleIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/visible.svg")); auto invisibleIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/invisible.svg")); iconVisible->addPixmap(visibleIcon.pixmap(64), QIcon::Normal, QIcon::Off); iconVisible->addPixmap(invisibleIcon.pixmap(64), QIcon::Normal, QIcon::On); pbVisible->setIcon(*iconVisible); pbVisible->setIconSize(QSize(24, 24)); pbVisible->setCheckable(true); pbVisible->setToolTip("Show/hide label"); pbVisible->setChecked(!label->GetVisible()); pbVisible->setStyleSheet(transparentStyleSheet); connect(pbVisible, SIGNAL(clicked()), this, SLOT(OnVisibleButtonClicked())); int row = tableWidget->rowCount(); tableWidget->insertRow(row); tableWidget->setRowHeight(row, 24); tableWidget->setItem(row, 0, nameItem); tableWidget->setCellWidget(row, 1, pbLocked); tableWidget->setCellWidget(row, 2, pbColor); tableWidget->setCellWidget(row, 3, pbVisible); tableWidget->selectRow(row); // m_LabelSetImage->SetActiveLabel(label->GetPixelValue()); // m_ToolManager->WorkingDataModified.Send(); // emit activeLabelChanged(label->GetPixelValue()); if (row == 0) { tableWidget->hideRow(row); // hide exterior label } } void QmitkLabelSetWidget::UpdateAllTableWidgetItems() { mitk::LabelSetImage *workingImage = GetWorkingImage(); if (!workingImage) return; // add all labels QTableWidget *tableWidget = m_Controls.m_LabelSetTableWidget; m_LabelStringList.clear(); for (int i = 0; i < tableWidget->rowCount(); ++i) { UpdateTableWidgetItem(tableWidget->item(i, 0)); m_LabelStringList.append(tableWidget->item(i, 0)->text()); } OnLabelListModified(m_LabelStringList); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::UpdateTableWidgetItem(QTableWidgetItem *item) { mitk::LabelSetImage *workingImage = GetWorkingImage(); mitk::Label *label = workingImage->GetLabel(item->data(Qt::UserRole).toInt(), workingImage->GetActiveLayer()); const mitk::Color &color = label->GetColor(); 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("); border: 0;"); QTableWidget *tableWidget = m_Controls.m_LabelSetTableWidget; int colWidth = (tableWidget->columnWidth(NAME_COL) < 180) ? 180 : tableWidget->columnWidth(NAME_COL) - 2; QString text = fontMetrics().elidedText(label->GetName().c_str(), Qt::ElideMiddle, colWidth); item->setText(text); QPushButton *pbLocked = dynamic_cast(tableWidget->cellWidget(item->row(), 1)); pbLocked->setChecked(!label->GetLocked()); QPushButton *pbColor = dynamic_cast(tableWidget->cellWidget(item->row(), 2)); pbColor->setStyleSheet(styleSheet); QPushButton *pbVisible = dynamic_cast(tableWidget->cellWidget(item->row(), 3)); pbVisible->setChecked(!label->GetVisible()); if (item->row() == 0) { tableWidget->hideRow(item->row()); // hide exterior label } } void QmitkLabelSetWidget::ResetAllTableWidgetItems() { QTableWidget *tableWidget = m_Controls.m_LabelSetTableWidget; // remove all rows while (tableWidget->rowCount()) { tableWidget->removeRow(0); } mitk::DataNode * workingNode = GetWorkingNode(); auto workingImage = dynamic_cast(workingNode->GetData()); if (nullptr == workingImage) { return; } // add all labels m_LabelStringList.clear(); mitk::LabelSet::LabelContainerConstIteratorType it = workingImage->GetActiveLabelSet()->IteratorConstBegin(); mitk::LabelSet::LabelContainerConstIteratorType end = workingImage->GetActiveLabelSet()->IteratorConstEnd(); int pixelValue = -1; while (it != end) { InsertTableWidgetItem(it->second); if (workingImage->GetActiveLabel(workingImage->GetActiveLayer()) == it->second) // get active pixelValue = it->first; m_LabelStringList.append(QString(it->second->GetName().c_str())); it++; } SelectLabelByPixelValue(pixelValue); OnLabelListModified(m_LabelStringList); std::stringstream captionText; captionText << "Number of labels: " << workingImage->GetNumberOfLabels(workingImage->GetActiveLayer()) - 1; m_Controls.m_lblCaption->setText(captionText.str().c_str()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit LabelSetWidgetReset(); } int QmitkLabelSetWidget::GetPixelValueOfSelectedItem() { if (m_Controls.m_LabelSetTableWidget->currentItem()) { return m_Controls.m_LabelSetTableWidget->currentItem()->data(Qt::UserRole).toInt(); } return -1; } QStringList &QmitkLabelSetWidget::GetLabelStringList() { return m_LabelStringList; } void QmitkLabelSetWidget::InitializeTableWidget() { QTableWidget *tableWidget = m_Controls.m_LabelSetTableWidget; tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); tableWidget->setTabKeyNavigation(false); tableWidget->setAlternatingRowColors(false); tableWidget->setFocusPolicy(Qt::NoFocus); tableWidget->setColumnCount(4); tableWidget->resizeColumnToContents(NAME_COL); tableWidget->setColumnWidth(LOCKED_COL, 25); tableWidget->setColumnWidth(COLOR_COL, 25); tableWidget->setColumnWidth(VISIBLE_COL, 25); tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); tableWidget->setContextMenuPolicy(Qt::CustomContextMenu); tableWidget->horizontalHeader()->hide(); tableWidget->setSortingEnabled(false); tableWidget->verticalHeader()->hide(); tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); connect(tableWidget, SIGNAL(itemClicked(QTableWidgetItem *)), this, SLOT(OnItemClicked(QTableWidgetItem *))); connect( tableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem *)), this, SLOT(OnItemDoubleClicked(QTableWidgetItem *))); connect(tableWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(OnTableViewContextMenuRequested(const QPoint &))); } void QmitkLabelSetWidget::OnOpacityChanged(int value) { int pixelValue = GetPixelValueOfSelectedItem(); float opacity = static_cast(value) / 100.0f; GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->SetOpacity(opacity); GetWorkingImage()->GetActiveLabelSet()->UpdateLookupTable(pixelValue); } void QmitkLabelSetWidget::setEnabled(bool enabled) { QWidget::setEnabled(enabled); UpdateControls(); } void QmitkLabelSetWidget::SetDataStorage(mitk::DataStorage *storage) { m_DataStorage = storage; } void QmitkLabelSetWidget::OnSearchLabel() { std::string text = m_Controls.m_LabelSearchBox->text().toStdString(); int pixelValue = -1; int row = -1; for (int i = 0; i < m_Controls.m_LabelSetTableWidget->rowCount(); ++i) { if (m_Controls.m_LabelSetTableWidget->item(i, 0)->text().toStdString().compare(text) == 0) { pixelValue = m_Controls.m_LabelSetTableWidget->item(i, 0)->data(Qt::UserRole).toInt(); row = i; break; } } if (pixelValue == -1) { return; } GetWorkingImage()->GetActiveLabelSet()->SetActiveLabel(pixelValue); QTableWidgetItem *nameItem = m_Controls.m_LabelSetTableWidget->item(row, NAME_COL); if (!nameItem) { return; } m_Controls.m_LabelSetTableWidget->clearSelection(); m_Controls.m_LabelSetTableWidget->selectRow(row); m_Controls.m_LabelSetTableWidget->scrollToItem(nameItem); GetWorkingImage()->GetActiveLabelSet()->SetActiveLabel(pixelValue); this->WaitCursorOn(); mitk::Point3D pos = GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetCenterOfMassCoordinates(); m_ToolManager->WorkingDataChanged(); if (pos.GetVnlVector().max_value() > 0.0) { emit goToLabel(pos); } else { GetWorkingImage()->UpdateCenterOfMass(pixelValue, GetWorkingImage()->GetActiveLayer()); mitk::Point3D pos = GetWorkingImage()->GetLabel(pixelValue, GetWorkingImage()->GetActiveLayer())->GetCenterOfMassCoordinates(); emit goToLabel(pos); } this->WaitCursorOff(); } void QmitkLabelSetWidget::OnLabelListModified(const QStringList &list) { QStringListModel *completeModel = static_cast(m_Completer->model()); completeModel->setStringList(list); } mitk::LabelSetImage *QmitkLabelSetWidget::GetWorkingImage() { mitk::DataNode *workingNode = GetWorkingNode(); mitk::LabelSetImage *workingImage = dynamic_cast(workingNode->GetData()); assert(workingImage); return workingImage; } mitk::DataNode *QmitkLabelSetWidget::GetWorkingNode() { mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); assert(workingNode); return workingNode; } void QmitkLabelSetWidget::UpdateControls() { mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); bool hasWorkingData = (workingNode != nullptr); m_Controls.m_LabelSetTableWidget->setEnabled(hasWorkingData); m_Controls.m_LabelSearchBox->setEnabled(hasWorkingData); if (!hasWorkingData) return; QStringListModel *completeModel = static_cast(m_Completer->model()); completeModel->setStringList(GetLabelStringList()); } void QmitkLabelSetWidget::OnCreateCroppedMask(bool) { m_ToolManager->ActivateTool(-1); mitk::LabelSetImage *workingImage = GetWorkingImage(); mitk::Image::Pointer maskImage; int pixelValue = GetPixelValueOfSelectedItem(); try { this->WaitCursorOn(); mitk::AutoCropImageFilter::Pointer cropFilter = mitk::AutoCropImageFilter::New(); cropFilter->SetInput(workingImage->CreateLabelMask(pixelValue)); cropFilter->SetBackgroundValue(0); cropFilter->SetMarginFactor(1.15); cropFilter->Update(); maskImage = cropFilter->GetOutput(); this->WaitCursorOff(); } catch (mitk::Exception &e) { this->WaitCursorOff(); MITK_ERROR << "Exception caught: " << e.GetDescription(); QMessageBox::information(this, "Create Mask", "Could not create a mask out of the selected label.\n"); return; } if (maskImage.IsNull()) { QMessageBox::information(this, "Create Mask", "Could not create a mask out of the selected label.\n"); return; } mitk::DataNode::Pointer maskNode = mitk::DataNode::New(); std::string name = workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->GetName(); name += "-mask"; maskNode->SetName(name); maskNode->SetData(maskImage); maskNode->SetBoolProperty("binary", true); maskNode->SetBoolProperty("outline binary", true); maskNode->SetBoolProperty("outline binary shadow", true); maskNode->SetFloatProperty("outline width", 2.0); maskNode->SetColor(workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->GetColor()); maskNode->SetOpacity(1.0); m_DataStorage->Add(maskNode, GetWorkingNode()); } void QmitkLabelSetWidget::OnCreateMask(bool /*triggered*/) { m_ToolManager->ActivateTool(-1); mitk::LabelSetImage *workingImage = GetWorkingImage(); mitk::Image::Pointer maskImage; int pixelValue = GetPixelValueOfSelectedItem(); try { this->WaitCursorOn(); maskImage = workingImage->CreateLabelMask(pixelValue); this->WaitCursorOff(); } catch (mitk::Exception &e) { this->WaitCursorOff(); MITK_ERROR << "Exception caught: " << e.GetDescription(); QMessageBox::information(this, "Create Mask", "Could not create a mask out of the selected label.\n"); return; } if (maskImage.IsNull()) { QMessageBox::information(this, "Create Mask", "Could not create a mask out of the selected label.\n"); return; } mitk::DataNode::Pointer maskNode = mitk::DataNode::New(); std::string name = workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->GetName(); name += "-mask"; maskNode->SetName(name); maskNode->SetData(maskImage); maskNode->SetBoolProperty("binary", true); maskNode->SetBoolProperty("outline binary", true); maskNode->SetBoolProperty("outline binary shadow", true); maskNode->SetFloatProperty("outline width", 2.0); maskNode->SetColor(workingImage->GetLabel(pixelValue, workingImage->GetActiveLayer())->GetColor()); maskNode->SetOpacity(1.0); m_DataStorage->Add(maskNode, GetWorkingNode()); } void QmitkLabelSetWidget::OnToggleOutline(bool value) { mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0); assert(workingNode); workingNode->SetBoolProperty("labelset.contour.active", value); workingNode->GetData()->Modified(); // fixme: workaround to force data-type rendering (and not only property-type) mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkLabelSetWidget::OnCreateSmoothedSurface(bool /*triggered*/) { m_ToolManager->ActivateTool(-1); mitk::DataNode::Pointer workingNode = GetWorkingNode(); mitk::LabelSetImage *workingImage = GetWorkingImage(); int pixelValue = GetPixelValueOfSelectedItem(); mitk::LabelSetImageToSurfaceThreadedFilter::Pointer surfaceFilter = mitk::LabelSetImageToSurfaceThreadedFilter::New(); itk::SimpleMemberCommand::Pointer successCommand = itk::SimpleMemberCommand::New(); successCommand->SetCallbackFunction(this, &QmitkLabelSetWidget::OnThreadedCalculationDone); surfaceFilter->AddObserver(mitk::ResultAvailable(), successCommand); itk::SimpleMemberCommand::Pointer errorCommand = itk::SimpleMemberCommand::New(); errorCommand->SetCallbackFunction(this, &QmitkLabelSetWidget::OnThreadedCalculationDone); surfaceFilter->AddObserver(mitk::ProcessingError(), errorCommand); mitk::DataNode::Pointer groupNode = workingNode; surfaceFilter->SetPointerParameter("Group node", groupNode); surfaceFilter->SetPointerParameter("Input", workingImage); surfaceFilter->SetParameter("RequestedLabel", pixelValue); surfaceFilter->SetParameter("Smooth", true); surfaceFilter->SetDataStorage(*m_DataStorage); mitk::StatusBar::GetInstance()->DisplayText("Surface creation is running in background..."); try { surfaceFilter->StartAlgorithm(); } catch (mitk::Exception &e) { MITK_ERROR << "Exception caught: " << e.GetDescription(); QMessageBox::information(this, "Create Surface", "Could not create a surface mesh out of the selected label. See error log for details.\n"); } } void QmitkLabelSetWidget::OnCreateDetailedSurface(bool /*triggered*/) { m_ToolManager->ActivateTool(-1); mitk::DataNode::Pointer workingNode = GetWorkingNode(); mitk::LabelSetImage *workingImage = GetWorkingImage(); int pixelValue = GetPixelValueOfSelectedItem(); mitk::LabelSetImageToSurfaceThreadedFilter::Pointer surfaceFilter = mitk::LabelSetImageToSurfaceThreadedFilter::New(); itk::SimpleMemberCommand::Pointer successCommand = itk::SimpleMemberCommand::New(); successCommand->SetCallbackFunction(this, &QmitkLabelSetWidget::OnThreadedCalculationDone); surfaceFilter->AddObserver(mitk::ResultAvailable(), successCommand); itk::SimpleMemberCommand::Pointer errorCommand = itk::SimpleMemberCommand::New(); errorCommand->SetCallbackFunction(this, &QmitkLabelSetWidget::OnThreadedCalculationDone); surfaceFilter->AddObserver(mitk::ProcessingError(), errorCommand); mitk::DataNode::Pointer groupNode = workingNode; surfaceFilter->SetPointerParameter("Group node", groupNode); surfaceFilter->SetPointerParameter("Input", workingImage); surfaceFilter->SetParameter("RequestedLabel", pixelValue); surfaceFilter->SetParameter("Smooth", false); surfaceFilter->SetDataStorage(*m_DataStorage); mitk::StatusBar::GetInstance()->DisplayText("Surface creation is running in background..."); try { surfaceFilter->StartAlgorithm(); } catch (mitk::Exception &e) { MITK_ERROR << "Exception caught: " << e.GetDescription(); QMessageBox::information(this, "Create Surface", "Could not create a surface mesh out of the selected label. See error log for details.\n"); } } void QmitkLabelSetWidget::WaitCursorOn() { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); } void QmitkLabelSetWidget::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkLabelSetWidget::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } void QmitkLabelSetWidget::OnThreadedCalculationDone() { mitk::StatusBar::GetInstance()->Clear(); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp index b4b03fff35..b9733bb2cf 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp @@ -1,328 +1,370 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkNewSegmentationDialog.h" #include #include #include #include #include #include #include #include -#include #include #include #include #include namespace { // Get standard label name and color suggestions from embedded XML preset file for anatomical structures. QmitkNewSegmentationDialog::SuggestionsType GetStandardSuggestions() { - QmitkNewSegmentationDialog::SuggestionsType standardSuggestions; - vtkNew presets; presets->LoadPreset(); - for (const auto& preset : presets->GetColorPresets()) + auto colorPresets = presets->GetColorPresets(); + + QmitkNewSegmentationDialog::SuggestionsType standardSuggestions; + standardSuggestions.reserve(colorPresets.size()); + + for (const auto& preset : colorPresets) { auto name = QString::fromStdString(preset.first); auto color = QColor::fromRgbF(preset.second.GetRed(), preset.second.GetGreen(), preset.second.GetBlue()); - standardSuggestions.emplace(name, color); + standardSuggestions.emplace_back(name, color); } + std::sort(begin(standardSuggestions), end(standardSuggestions), [](const auto& lhs, const auto& rhs) { + return lhs.first < rhs.first; + }); + return standardSuggestions; } // Parse label name and color suggestions from a JSON file. An array of objects is expected, each consisting // of a "name" string and an optional "color" string. If present, the "color" string must follow the conventions // of QColor::setNamedColor(), i.e., #rrggbb or any SVG color keyword name like CornflowerBlue. Everything else // in the JSON file is simply ignored. In case of any error, an empty map is returned. QmitkNewSegmentationDialog::SuggestionsType ParseSuggestions(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { MITK_ERROR << "Could not open \"" << filename << "\"!"; return {}; } auto json = nlohmann::json::parse(file, nullptr, false); if (json.is_discarded() || !json.is_array()) { MITK_ERROR << "Could not parse \"" << filename << "\" as JSON array!"; return {}; } QmitkNewSegmentationDialog::SuggestionsType parsedSuggestions; for (const auto& obj : json) { if (!obj.is_object() || !obj.contains("name")) continue; auto name = QString::fromStdString(obj["name"]); - - QColor color(QColor::Invalid); + QColor color; if (obj.contains("color")) color.setNamedColor(QString::fromStdString(obj["color"])); - parsedSuggestions.emplace(name, color); + auto it = std::find_if(begin(parsedSuggestions), end(parsedSuggestions), [&name](const auto& suggestion) { + return name == suggestion.first; + }); + + // Ignore duplicates... + if (it != parsedSuggestions.end()) + { + // unless we can complete the original suggestion with a valid color. + if (!it->second.isValid() && color.isValid()) + { + it->second = color; + } + else + { + MITK_WARN << "Ignoring duplicate of suggestion \"" << name.toStdString() << "\"!"; + } + + continue; + } + + parsedSuggestions.emplace_back(name, color); } if (parsedSuggestions.empty()) MITK_WARN << "Could not parse any suggestions from \"" << filename << "\"!"; return parsedSuggestions; } struct Preferences { QString labelSuggestions; bool replaceStandardSuggestions; bool suggestOnce; + QByteArray geometry; }; // Get all relevant preferences and consider command-line arguments overrides. Preferences GetPreferences() { auto nodePrefs = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); Preferences prefs; prefs.labelSuggestions = QString::fromStdString(mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), "")); if (prefs.labelSuggestions.isEmpty()) prefs.labelSuggestions = nodePrefs->Get("label suggestions", ""); prefs.replaceStandardSuggestions = nodePrefs->GetBool("replace standard suggestions", true); prefs.suggestOnce = nodePrefs->GetBool("suggest once", true); + prefs.geometry = nodePrefs->GetByteArray("QmitkNewSegmentationDialog geometry", QByteArray()); return prefs; } + void SaveGeometry(QByteArray geometry) + { + auto nodePrefs = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); + nodePrefs->PutByteArray("QmitkNewSegmentationDialog geometry", geometry); + } + // Get names of all labels in all layers of a LabelSetImage. QStringList GetExistingLabelNames(mitk::LabelSetImage* labelSetImage) { QStringList existingLabelNames; existingLabelNames.reserve(labelSetImage->GetTotalNumberOfLabels()); const auto numLayers = labelSetImage->GetNumberOfLayers(); for (std::remove_const_t layerIndex = 0; layerIndex < numLayers; ++layerIndex) { const auto* labelSet = labelSetImage->GetLabelSet(layerIndex); for (auto labelIter = labelSet->IteratorConstBegin(); labelIter != labelSet->IteratorConstEnd(); ++labelIter) { if (0 == labelIter->first) continue; // Ignore background label auto name = QString::fromStdString(labelIter->second->GetName()); if (!name.isEmpty()) // Potential duplicates do not matter for our purpose existingLabelNames.push_back(name); } } return existingLabelNames; } // Remove blacklisted suggestions. QmitkNewSegmentationDialog::SuggestionsType FilterSuggestions(const QmitkNewSegmentationDialog::SuggestionsType& suggestions, const QStringList& blacklist) { QmitkNewSegmentationDialog::SuggestionsType filteredSuggestions; - std::remove_copy_if(suggestions.begin(), suggestions.end(), std::inserter(filteredSuggestions, filteredSuggestions.end()), [&blacklist](const auto& suggestion) { + std::remove_copy_if(begin(suggestions), end(suggestions), std::inserter(filteredSuggestions, end(filteredSuggestions)), [&blacklist](const auto& suggestion) { return blacklist.contains(suggestion.first); }); return filteredSuggestions; } } QmitkNewSegmentationDialog::QmitkNewSegmentationDialog(QWidget *parent, mitk::LabelSetImage* labelSetImage, Mode mode) : QDialog(parent), m_Ui(new Ui::QmitkNewSegmentationDialog), m_SuggestOnce(true), m_Color(Qt::red) { m_Ui->setupUi(this); if (RenameLabel == mode) { this->setWindowTitle("Rename Label"); m_Ui->label->setText("New name and color of the label"); m_Ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Rename label"); } else { m_Ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Create label"); } m_Ui->nameLineEdit->setFocus(); + connect(this, &QDialog::finished, this, &QmitkNewSegmentationDialog::OnFinished); connect(m_Ui->colorButton, &QToolButton::clicked, this, &QmitkNewSegmentationDialog::OnColorButtonClicked); connect(m_Ui->nameLineEdit, &QLineEdit::textChanged, this, &QmitkNewSegmentationDialog::OnTextChanged); connect(m_Ui->nameList, &QListWidget::itemSelectionChanged, this, &QmitkNewSegmentationDialog::OnSuggestionSelected); connect(m_Ui->nameList, &QListWidget::itemDoubleClicked, this, &QmitkNewSegmentationDialog::OnAccept); connect(m_Ui->buttonBox, &QDialogButtonBox::accepted, this, &QmitkNewSegmentationDialog::OnAccept); this->UpdateColorButtonBackground(); auto prefs = GetPreferences(); if (!prefs.labelSuggestions.isEmpty()) { auto suggestions = ParseSuggestions(prefs.labelSuggestions.toStdString()); this->SetSuggestions(suggestions, prefs.replaceStandardSuggestions && !suggestions.empty()); } else { this->SetSuggestions(GetStandardSuggestions(), true); } if (nullptr != labelSetImage && prefs.suggestOnce) { auto existingLabelNames = GetExistingLabelNames(labelSetImage); m_Suggestions = FilterSuggestions(m_Suggestions, existingLabelNames); this->UpdateNameList(); } + + if (!(prefs.geometry.isNull() || prefs.geometry.isEmpty())) + this->restoreGeometry(prefs.geometry); } QmitkNewSegmentationDialog::~QmitkNewSegmentationDialog() { } +void QmitkNewSegmentationDialog::OnFinished(int) +{ + SaveGeometry(this->saveGeometry()); +} + void QmitkNewSegmentationDialog::UpdateColorButtonBackground() { m_Ui->colorButton->setStyleSheet("background-color:" + m_Color.name()); } QString QmitkNewSegmentationDialog::GetName() const { return m_Name; } mitk::Color QmitkNewSegmentationDialog::GetColor() const { mitk::Color color; if (m_Color.isValid()) { color.SetRed(m_Color.redF()); color.SetGreen(m_Color.greenF()); color.SetBlue(m_Color.blueF()); } else { color.Set(1.0f, 0.0f, 0.0f); } return color; } void QmitkNewSegmentationDialog::SetName(const QString& name) { m_Ui->nameLineEdit->setText(name); } void QmitkNewSegmentationDialog::SetColor(const mitk::Color& color) { m_Color.setRgbF(color.GetRed(), color.GetGreen(), color.GetBlue()); this->UpdateColorButtonBackground(); } void QmitkNewSegmentationDialog::SetSuggestions(const SuggestionsType& suggestions, bool replaceStandardSuggestions) { - if (replaceStandardSuggestions) - { - m_Suggestions = suggestions; - } - else + m_Suggestions = suggestions; + + if (!replaceStandardSuggestions) { - m_Suggestions = GetStandardSuggestions(); + auto standardSuggestions = GetStandardSuggestions(); - for (const auto& [name, color] : suggestions) - { - if (m_Suggestions.end() == m_Suggestions.find(name)) - m_Suggestions[name] = color; - } + // Append all standard suggestions with unique names to the list of custom suggestions + std::remove_copy_if(begin(standardSuggestions), end(standardSuggestions), std::inserter(m_Suggestions, end(m_Suggestions)), [this](const auto& suggestion) { + return m_Suggestions.end() != std::find_if(begin(m_Suggestions), end(m_Suggestions), [&suggestion](const auto& otherSuggestion) { + return suggestion.first == otherSuggestion.first; + }); + }); } this->UpdateNameList(); } void QmitkNewSegmentationDialog::UpdateNameList() { QStringList names; for (const auto& suggestion : m_Suggestions) names << suggestion.first; m_Ui->nameList->clear(); m_Ui->nameList->addItems(names); } void QmitkNewSegmentationDialog::OnAccept() { m_Name = m_Ui->nameLineEdit->text(); this->accept(); } void QmitkNewSegmentationDialog::OnTextChanged(const QString& text) { auto finding = m_Ui->nameList->findItems(text, Qt::MatchFlag::MatchExactly); if (!finding.isEmpty()) m_Ui->nameList->setCurrentItem(finding.first()); } void QmitkNewSegmentationDialog::OnColorButtonClicked() { auto color = QColorDialog::getColor(m_Color); if (color.isValid()) { m_Color = color; this->UpdateColorButtonBackground(); } } void QmitkNewSegmentationDialog::OnSuggestionSelected() { const auto* currentItem = m_Ui->nameList->currentItem(); if (currentItem == nullptr) return; - const auto name = currentItem->text(); - m_Ui->nameLineEdit->setText(name); - auto color = m_Suggestions[name]; + auto row = m_Ui->nameList->selectionModel()->selectedIndexes().first().row(); + + m_Ui->nameLineEdit->setText(m_Suggestions[row].first); + auto color = m_Suggestions[row].second; if (color.isValid()) { m_Color = color; this->UpdateColorButtonBackground(); } } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.h b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.h index a2dae77786..84793f6f61 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.h @@ -1,81 +1,83 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkNewSegmentationDialog_h #define QmitkNewSegmentationDialog_h #include #include -#include +#include +#include #include #include #include namespace mitk { class LabelSetImage; } namespace Ui { class QmitkNewSegmentationDialog; } /** \brief Dialog for naming labels. */ class MITK_QT_SEGMENTATION QmitkNewSegmentationDialog : public QDialog { Q_OBJECT public: - using SuggestionsType = std::map; + using SuggestionsType = std::vector>; enum Mode { NewLabel, RenameLabel }; explicit QmitkNewSegmentationDialog(QWidget *parent = nullptr, mitk::LabelSetImage* labelSetImage = nullptr, Mode mode = NewLabel); ~QmitkNewSegmentationDialog() override; QString GetName() const; mitk::Color GetColor() const; void SetName(const QString& name); void SetColor(const mitk::Color& color); private: void OnAccept(); + void OnFinished(int result); void OnSuggestionSelected(); void OnColorButtonClicked(); void OnTextChanged(const QString& text); void SetSuggestions(const SuggestionsType& suggestions, bool replaceStandardSuggestions = false); void UpdateColorButtonBackground(); void UpdateNameList(); Ui::QmitkNewSegmentationDialog* m_Ui; bool m_SuggestOnce; QString m_Name; QColor m_Color; SuggestionsType m_Suggestions; }; #endif diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp index 0ea32131f3..803a62ff55 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp @@ -1,174 +1,146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationPreferencePage.h" #include #include #include #include #include QmitkSegmentationPreferencePage::QmitkSegmentationPreferencePage() : m_Ui(new Ui::QmitkSegmentationPreferencePageControls), m_Control(nullptr), m_Initializing(false) { } QmitkSegmentationPreferencePage::~QmitkSegmentationPreferencePage() { } void QmitkSegmentationPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkSegmentationPreferencePage::CreateQtControl(QWidget* parent) { m_Initializing = true; berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_SegmentationPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); - connect(m_Ui->smoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnSmoothingCheckboxChecked(int))); connect(m_Ui->labelSetPresetToolButton, SIGNAL(clicked()), this, SLOT(OnLabelSetPresetButtonClicked())); connect(m_Ui->suggestionsToolButton, SIGNAL(clicked()), this, SLOT(OnSuggestionsButtonClicked())); this->Update(); m_Initializing = false; } QWidget* QmitkSegmentationPreferencePage::GetQtControl() const { return m_Control; } bool QmitkSegmentationPreferencePage::PerformOk() { m_SegmentationPreferencesNode->PutBool("slim view", m_Ui->slimViewCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("draw outline", m_Ui->outlineRadioButton->isChecked()); m_SegmentationPreferencesNode->PutBool("selection mode", m_Ui->selectionModeCheckBox->isChecked()); - m_SegmentationPreferencesNode->PutBool("smoothing hint", m_Ui->smoothingCheckBox->isChecked()); - m_SegmentationPreferencesNode->PutDouble("smoothing value", m_Ui->smoothingSpinBox->value()); - m_SegmentationPreferencesNode->PutDouble("decimation rate", m_Ui->decimationSpinBox->value()); - m_SegmentationPreferencesNode->PutDouble("closing ratio", m_Ui->closingSpinBox->value()); m_SegmentationPreferencesNode->Put("label set preset", m_Ui->labelSetPresetLineEdit->text()); m_SegmentationPreferencesNode->PutBool("default label naming", m_Ui->defaultNameRadioButton->isChecked()); m_SegmentationPreferencesNode->Put("label suggestions", m_Ui->suggestionsLineEdit->text()); m_SegmentationPreferencesNode->PutBool("replace standard suggestions", m_Ui->replaceStandardSuggestionsCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("suggest once", m_Ui->suggestOnceCheckBox->isChecked()); return true; } void QmitkSegmentationPreferencePage::PerformCancel() { } void QmitkSegmentationPreferencePage::Update() { m_Ui->slimViewCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("slim view", false)); if (m_SegmentationPreferencesNode->GetBool("draw outline", true)) { m_Ui->outlineRadioButton->setChecked(true); } else { m_Ui->overlayRadioButton->setChecked(true); } m_Ui->selectionModeCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("selection mode", false)); - if (m_SegmentationPreferencesNode->GetBool("smoothing hint", true)) - { - m_Ui->smoothingCheckBox->setChecked(true); - m_Ui->smoothingSpinBox->setDisabled(true); - } - else - { - m_Ui->smoothingCheckBox->setChecked(false); - m_Ui->smoothingSpinBox->setEnabled(true); - } - - m_Ui->smoothingSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("smoothing value", 1.0)); - m_Ui->decimationSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("decimation rate", 0.5)); - m_Ui->closingSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("closing ratio", 0.0)); - auto labelSetPreset = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), ""); bool isOverriddenByCmdLineArg = !labelSetPreset.empty(); if (!isOverriddenByCmdLineArg) labelSetPreset = m_SegmentationPreferencesNode->Get("label set preset", "").toStdString(); m_Ui->labelSetPresetLineEdit->setDisabled(isOverriddenByCmdLineArg); m_Ui->labelSetPresetToolButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->labelSetPresetCmdLineArgLabel->setVisible(isOverriddenByCmdLineArg); m_Ui->labelSetPresetLineEdit->setText(QString::fromStdString(labelSetPreset)); if (m_SegmentationPreferencesNode->GetBool("default label naming", true)) { m_Ui->defaultNameRadioButton->setChecked(true); } else { m_Ui->askForNameRadioButton->setChecked(true); } auto labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), ""); isOverriddenByCmdLineArg = !labelSuggestions.empty(); if (!isOverriddenByCmdLineArg) labelSuggestions = m_SegmentationPreferencesNode->Get("label suggestions", "").toStdString(); m_Ui->defaultNameRadioButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->askForNameRadioButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsLineEdit->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsToolButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsCmdLineArgLabel->setVisible(isOverriddenByCmdLineArg); m_Ui->suggestionsLineEdit->setText(QString::fromStdString(labelSuggestions)); m_Ui->replaceStandardSuggestionsCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("replace standard suggestions", true)); m_Ui->suggestOnceCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("suggest once", true)); } -void QmitkSegmentationPreferencePage::OnSmoothingCheckboxChecked(int state) -{ - if (state != Qt::Unchecked) - m_Ui->smoothingSpinBox->setDisabled(true); - else - m_Ui->smoothingSpinBox->setEnabled(true); -} - void QmitkSegmentationPreferencePage::OnLabelSetPresetButtonClicked() { const auto filename = QFileDialog::getOpenFileName(m_Control, QStringLiteral("Load Label Set Preset"), QString(), QStringLiteral("Label set preset (*.lsetp)")); if (!filename.isEmpty()) m_Ui->labelSetPresetLineEdit->setText(filename); } void QmitkSegmentationPreferencePage::OnSuggestionsButtonClicked() { const auto filename = QFileDialog::getOpenFileName(m_Control, QStringLiteral("Load Label Suggestions"), QString(), QStringLiteral("Label suggestions (*.json)")); if (!filename.isEmpty()) m_Ui->suggestionsLineEdit->setText(filename); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h index 8c04073a86..cd54461ba2 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h @@ -1,66 +1,65 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSEGMENTATIONPREFERENCEPAGE_H #define QMITKSEGMENTATIONPREFERENCEPAGE_H #include "org_mitk_gui_qt_segmentation_Export.h" #include #include class QWidget; namespace Ui { class QmitkSegmentationPreferencePageControls; } class MITK_QT_SEGMENTATION QmitkSegmentationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkSegmentationPreferencePage(); ~QmitkSegmentationPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; protected Q_SLOTS: - void OnSmoothingCheckboxChecked(int); void OnLabelSetPresetButtonClicked(); void OnSuggestionsButtonClicked(); protected: Ui::QmitkSegmentationPreferencePageControls* m_Ui; QWidget* m_Control; bool m_Initializing; berry::IPreferences::Pointer m_SegmentationPreferencesNode; }; #endif // QMITKSEGMENTATIONPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePageControls.ui b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePageControls.ui index ee4674f966..d465bab8fd 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePageControls.ui +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePageControls.ui @@ -1,323 +1,233 @@ QmitkSegmentationPreferencePageControls 0 0 656 779 Form Slim view Hide tool button texts and increase icon size 2D display Draw as outline true displayButtonGroup Draw as transparent overlay displayButtonGroup Data node selection mode If checked the segmentation plugin ensures that only the selected segmentation and the reference image are visible at one time. Show only selected nodes - - - Smoothed surface creation - - - - - - - 8 - - - 8 - - - - - Smoothing value (mm) - - - - - - - The Smoothing value is used as variance for a gaussian blur. - - - 0.500000000000000 - - - 1.000000000000000 - - - - - - - Decimation rate - - - - - - - Valid range is [0, 1). High values increase decimation, especially when very close to 1. A value of 0 disables decimation. - - - 0.990000000000000 - - - 0.100000000000000 - - - 0.500000000000000 - - - - - - - Closing Ratio - - - - - - - Valid range is [0, 1]. Higher values increase closing. A value of 0 disables closing. - - - 1.000000000000000 - - - 0.100000000000000 - - - - - - - If checked the segmentation plugin ensures that only the selected segmentation and the reference image are visible at one time. - - - Use image spacing as smoothing value hint - - - - - - Default label set preset - + true ... <html><head/><body><p><span style=" color:#ff0000;">The default label set preset is currently overriden by the </span><span style=" font-family:'Courier New'; color:#ff0000;">Segmentation.labelSetPreset</span><span style=" color:#ff0000;"> command-line argument.</span></p></body></html> Qt::RichText true - + Label creation - + Assign default name and color true labelCreationButtonGroup Ask for name and color labelCreationButtonGroup - + Label suggestions - + true ... <html><head/><body><p><span style=" color:#ff0000;">Suggestions are currently enforced by the </span><span style=" font-family:'Courier New'; color:#ff0000;">Segmentation.labelSuggestions</span><span style=" color:#ff0000;"> command-line argument.</span></p></body></html> Qt::RichText true - + Replace standard organ suggestions true - + Suggest once per segmentation true - + Qt::Vertical 20 40 - + diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertMaskToLabelAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertMaskToLabelAction.cpp similarity index 100% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertMaskToLabelAction.cpp rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertMaskToLabelAction.cpp diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertMaskToLabelAction.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertMaskToLabelAction.h similarity index 95% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertMaskToLabelAction.h rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertMaskToLabelAction.h index ad082d9ea7..4c9561b816 100644 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertMaskToLabelAction.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertMaskToLabelAction.h @@ -1,48 +1,48 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __QmitkConvertMaskToLabelAction_H_ #define __QmitkConvertMaskToLabelAction_H_ #include "mitkIContextMenuAction.h" -#include "org_mitk_gui_qt_multilabelsegmentation_Export.h" +#include #include "vector" #include "mitkDataNode.h" #include "mitkImage.h" class MITK_QT_SEGMENTATION QmitkConvertMaskToLabelAction : public QObject, public mitk::IContextMenuAction { Q_OBJECT Q_INTERFACES(mitk::IContextMenuAction) public: QmitkConvertMaskToLabelAction(); ~QmitkConvertMaskToLabelAction() override; //interface methods void Run( const QList& selectedNodes ) override; void SetDataStorage(mitk::DataStorage* dataStorage) override; void SetSmoothed(bool smoothed) override; void SetDecimated(bool decimated) override; void SetFunctionality(berry::QtViewPart* functionality) override; protected: private: typedef QList NodeList; }; #endif // __QmitkConvertMaskToLabelAction_H_ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertSurfaceToLabelAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertSurfaceToLabelAction.cpp similarity index 100% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertSurfaceToLabelAction.cpp rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertSurfaceToLabelAction.cpp diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertSurfaceToLabelAction.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertSurfaceToLabelAction.h similarity index 95% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertSurfaceToLabelAction.h rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertSurfaceToLabelAction.h index 08eb613b2b..d39e8622f1 100644 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertSurfaceToLabelAction.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertSurfaceToLabelAction.h @@ -1,48 +1,48 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __QmitkConvertSurfaceToLabelAction_H_ #define __QmitkConvertSurfaceToLabelAction_H_ #include "mitkIContextMenuAction.h" -#include "org_mitk_gui_qt_multilabelsegmentation_Export.h" +#include #include "vector" #include "mitkDataNode.h" #include "mitkImage.h" class MITK_QT_SEGMENTATION QmitkConvertSurfaceToLabelAction : public QObject, public mitk::IContextMenuAction { Q_OBJECT Q_INTERFACES(mitk::IContextMenuAction) public: QmitkConvertSurfaceToLabelAction(); ~QmitkConvertSurfaceToLabelAction() override; //interface methods void Run( const QList& selectedNodes ) override; void SetDataStorage(mitk::DataStorage* dataStorage) override; void SetSmoothed(bool smoothed) override; void SetDecimated(bool decimated) override; void SetFunctionality(berry::QtViewPart* functionality) override; protected: private: typedef QList NodeList; }; #endif // __QmitkConvertSurfaceToLabelAction_H_ diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.cpp similarity index 100% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.cpp rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.cpp diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.h similarity index 95% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.h rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.h index aa6fddfb93..e535fbd4f4 100644 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkConvertToMultiLabelSegmentationAction.h @@ -1,47 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITK_ConvertToMultiLabelSegmentation_H #define QMITK_ConvertToMultiLabelSegmentation_H #include "mitkIContextMenuAction.h" -#include "org_mitk_gui_qt_multilabelsegmentation_Export.h" +#include #include "vector" #include "mitkDataNode.h" //#include "mitkImage.h" class MITK_QT_SEGMENTATION QmitkConvertToMultiLabelSegmentationAction : public QObject, public mitk::IContextMenuAction { Q_OBJECT Q_INTERFACES(mitk::IContextMenuAction) public: QmitkConvertToMultiLabelSegmentationAction(); ~QmitkConvertToMultiLabelSegmentationAction() override; //interface methods void Run( const QList& selectedNodes ) override; void SetDataStorage(mitk::DataStorage* dataStorage) override; void SetFunctionality(berry::QtViewPart* functionality) override; void SetSmoothed(bool smoothed) override; void SetDecimated(bool decimated) override; private: typedef QList NodeList; mitk::DataStorage::Pointer m_DataStorage; }; #endif // QMITK_ConvertToMultiLabelSegmentation_H diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.cpp similarity index 100% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.cpp rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.cpp diff --git a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.h similarity index 95% rename from Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.h rename to Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.h index a70a5802dd..e5543be96f 100644 --- a/Plugins/org.mitk.gui.qt.multilabelsegmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreateMultiLabelSegmentationAction.h @@ -1,46 +1,46 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITK_CreateMultiLabelSegmentation_H #define QMITK_CreateMultiLabelSegmentation_H #include "mitkIContextMenuAction.h" -#include "org_mitk_gui_qt_multilabelsegmentation_Export.h" +#include #include "vector" #include "mitkDataNode.h" class MITK_QT_SEGMENTATION QmitkCreateMultiLabelSegmentationAction : public QObject, public mitk::IContextMenuAction { Q_OBJECT Q_INTERFACES(mitk::IContextMenuAction) public: QmitkCreateMultiLabelSegmentationAction(); ~QmitkCreateMultiLabelSegmentationAction() override; //interface methods void Run( const QList& selectedNodes ) override; void SetDataStorage(mitk::DataStorage* dataStorage) override; void SetFunctionality(berry::QtViewPart* functionality) override; void SetSmoothed(bool smoothed) override; void SetDecimated(bool decimated) override; private: typedef QList NodeList; mitk::DataStorage::Pointer m_DataStorage; }; #endif // QMITK_CreateMultiLabelSegmentation_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.h index db2e07bc70..f5bf6fd4ee 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.h @@ -1,51 +1,51 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKCREATEPOLYGONMODELACTION_H #define QMITKCREATEPOLYGONMODELACTION_H #include // Parent classes #include #include // Data members #include class MITK_QT_SEGMENTATION QmitkCreatePolygonModelAction : public QObject, public mitk::IContextMenuAction { Q_OBJECT Q_INTERFACES(mitk::IContextMenuAction) public: QmitkCreatePolygonModelAction(); ~QmitkCreatePolygonModelAction() override; // IContextMenuAction void Run(const QList &selectedNodes) override; void SetDataStorage(mitk::DataStorage *dataStorage) override; void SetSmoothed(bool smoothed) override; void SetDecimated(bool decimated) override; void SetFunctionality(berry::QtViewPart* view) override; void OnSurfaceCalculationDone(); private: QmitkCreatePolygonModelAction(const QmitkCreatePolygonModelAction &); QmitkCreatePolygonModelAction & operator=(const QmitkCreatePolygonModelAction &); mitk::DataStorage::Pointer m_DataStorage; - bool m_IsSmoothed; - bool m_IsDecimated; + bool m_IsSmoothed = false; + bool m_IsDecimated = true; }; #endif 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 bd093a5ff8..5d9a9bf351 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp @@ -1,1123 +1,1137 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationView.h" #include "mitkPluginActivator.h" // blueberry #include // mitk #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Qmitk #include #include #include // us #include #include // Qt #include #include #include // vtk #include #include const std::string QmitkSegmentationView::VIEW_ID = "org.mitk.views.segmentation"; QmitkSegmentationView::QmitkSegmentationView() : m_Parent(nullptr) , m_Controls(nullptr) , m_RenderWindowPart(nullptr) , m_ToolManager(nullptr) , m_ReferenceNode(nullptr) , m_WorkingNode(nullptr) - , m_RendererAnnotation(mitk::LogoAnnotation::New()) , m_DrawOutline(true) , m_SelectionMode(false) , m_MouseCursorSet(false) , m_DefaultLabelNaming(true) + , m_SelectionChangeIsAlreadyBeingHandled(false) { auto isImage = mitk::TNodePredicateDataType::New(); auto isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); auto isDti = mitk::NodePredicateDataType::New("TensorImage"); auto isOdf = mitk::NodePredicateDataType::New("OdfImage"); auto isSegment = mitk::NodePredicateDataType::New("Segment"); auto validImages = mitk::NodePredicateOr::New(); validImages->AddPredicate(mitk::NodePredicateAnd::New(isImage, mitk::NodePredicateNot::New(isSegment))); validImages->AddPredicate(isDwi); validImages->AddPredicate(isDti); validImages->AddPredicate(isOdf); auto isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); auto isMask = mitk::NodePredicateAnd::New(isBinary, isImage); auto validSegmentations = mitk::NodePredicateOr::New(); validSegmentations->AddPredicate(mitk::TNodePredicateDataType::New()); validSegmentations->AddPredicate(isMask); m_SegmentationPredicate = mitk::NodePredicateAnd::New(); m_SegmentationPredicate->AddPredicate(validSegmentations); m_SegmentationPredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))); m_SegmentationPredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("hidden object"))); m_ReferencePredicate = mitk::NodePredicateAnd::New(); m_ReferencePredicate->AddPredicate(validImages); m_ReferencePredicate->AddPredicate(mitk::NodePredicateNot::New(m_SegmentationPredicate)); m_ReferencePredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))); m_ReferencePredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("hidden object"))); - // setup annotation for an overlay image to indicated a blocked renderer - m_RendererAnnotation->SetOpacity(0.5); - m_RendererAnnotation->SetRelativeSize(0.25); - m_RendererAnnotation->SetCornerPosition(4); - - QImage* qimage = new QImage(qPrintable(":/Qmitk/Cancel_48x48.png")); - vtkSmartPointer qImageToVtk; - qImageToVtk = vtkSmartPointer::New(); - - qImageToVtk->SetQImage(qimage); - qImageToVtk->Update(); - vtkSmartPointer vtkLogo = qImageToVtk->GetOutput(); - m_RendererAnnotation->SetLogoImage(vtkLogo); - m_SegmentationInteractor = mitk::SegmentationInteractor::New(); // add observer for the 'SegmentationInteractionEvent' itk::ReceptorMemberCommand::Pointer geometryNotAlignedCommand = itk::ReceptorMemberCommand::New(); geometryNotAlignedCommand->SetCallbackFunction(this, &QmitkSegmentationView::ValidateRendererGeometry); m_SegmentationInteractor->AddObserver(mitk::SegmentationInteractionEvent(nullptr, true), geometryNotAlignedCommand); m_SegmentationInteractor->Disable(); } QmitkSegmentationView::~QmitkSegmentationView() { if (nullptr != m_Controls) { - OnLooseLabelSetConnection(); + this->LooseLabelSetConnection(); // deactivate all tools m_ToolManager->ActivateTool(-1); // removing all observers from working data for (NodeTagMapType::iterator dataIter = m_WorkingDataObserverTags.begin(); dataIter != m_WorkingDataObserverTags.end(); ++dataIter) { (*dataIter).first->GetProperty("visible")->RemoveObserver((*dataIter).second); } m_WorkingDataObserverTags.clear(); // removing all observers from reference data for (NodeTagMapType::iterator dataIter = m_ReferenceDataObserverTags.begin(); dataIter != m_ReferenceDataObserverTags.end(); ++dataIter) { (*dataIter).first->GetProperty("visible")->RemoveObserver((*dataIter).second); } m_ReferenceDataObserverTags.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); m_ToolManager->SetReferenceData(nullptr); m_ToolManager->SetWorkingData(nullptr); } m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); delete m_Controls; } /**********************************************************************/ /* private Q_SLOTS */ /**********************************************************************/ -void QmitkSegmentationView::OnReferenceSelectionChanged(QList nodes) +void QmitkSegmentationView::OnReferenceSelectionChanged(QList) { - m_ToolManager->ActivateTool(-1); + this->OnAnySelectionChanged(); +} - // Remove observer if one was registered to the reference node - auto finding = m_ReferenceDataObserverTags.find(m_ReferenceNode); - if (finding != m_ReferenceDataObserverTags.end()) - { - m_ReferenceNode->GetProperty("visible")->RemoveObserver(m_ReferenceDataObserverTags[m_ReferenceNode]); - m_ReferenceDataObserverTags.erase(m_ReferenceNode); - } +void QmitkSegmentationView::OnSegmentationSelectionChanged(QList) +{ + this->OnAnySelectionChanged(); +} - if (nodes.empty()) - { - m_Controls->workingNodeSelector->SetNodePredicate(m_SegmentationPredicate); - m_ReferenceNode = nullptr; - m_ToolManager->SetReferenceData(m_ReferenceNode); - this->UpdateGUI(); +void QmitkSegmentationView::OnAnySelectionChanged() +{ + // When only a segmentation has been selected and the method is then called by a reference image selection, + // the already selected segmentation may not match the geometry predicate of the new reference image anymore. + // This will trigger a recursive call of this method further below. While it would be resolved gracefully, we + // can spare the extra call with an early-out. The original call of this method will handle the segmentation + // selection change afterwards anyway. + + if (m_SelectionChangeIsAlreadyBeingHandled) return; - } - m_ReferenceNode = nodes.first(); - m_ToolManager->SetReferenceData(m_ReferenceNode); - if (m_ReferenceNode.IsNotNull()) + auto selectedReferenceNode = m_Controls->referenceNodeSelector->GetSelectedNode(); + bool referenceNodeChanged = false; + + m_ToolManager->ActivateTool(-1); + + if (m_ReferenceNode != selectedReferenceNode) { - // set a predicate such that a segmentation fits the selected reference image geometry - auto segPredicate = mitk::NodePredicateAnd::New(m_SegmentationPredicate.GetPointer(), - mitk::NodePredicateSubGeometry::New(m_ReferenceNode->GetData()->GetGeometry())); + referenceNodeChanged = true; - m_Controls->workingNodeSelector->SetNodePredicate(segPredicate); + // Remove visibility observer for the current reference node + if (m_ReferenceDataObserverTags.find(m_ReferenceNode) != m_ReferenceDataObserverTags.end()) + { + m_ReferenceNode->GetProperty("visible")->RemoveObserver(m_ReferenceDataObserverTags[m_ReferenceNode]); + m_ReferenceDataObserverTags.erase(m_ReferenceNode); + } + + // Set new reference node + m_ReferenceNode = selectedReferenceNode; + m_ToolManager->SetReferenceData(m_ReferenceNode); - if (m_SelectionMode) + // Prepare for a potential recursive call when changing node predicates of the working node selector + m_SelectionChangeIsAlreadyBeingHandled = true; + + if (m_ReferenceNode.IsNull()) { - // hide all image nodes to later show only the automatically selected ones - mitk::DataStorage::SetOfObjects::ConstPointer imageNodes = - this->GetDataStorage()->GetSubset(m_ReferencePredicate); - for (mitk::DataStorage::SetOfObjects::const_iterator iter = imageNodes->begin(); iter != imageNodes->end(); ++iter) - { - (*iter)->SetVisibility(false); - } + // Without a reference image, allow all segmentations to be selected + m_Controls->workingNodeSelector->SetNodePredicate(m_SegmentationPredicate); + m_SelectionChangeIsAlreadyBeingHandled = false; } - m_ReferenceNode->SetVisibility(true); + else + { + // With a reference image, only allow segmentations that fit the geometry of the reference image to be selected. + m_Controls->workingNodeSelector->SetNodePredicate(mitk::NodePredicateAnd::New( + mitk::NodePredicateSubGeometry::New(m_ReferenceNode->GetData()->GetGeometry()), + m_SegmentationPredicate.GetPointer())); - auto command = itk::SimpleMemberCommand::New(); - command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); - m_ReferenceDataObserverTags[m_ReferenceNode] = - m_ReferenceNode->GetProperty("visible")->AddObserver(itk::ModifiedEvent(), command); - } + m_SelectionChangeIsAlreadyBeingHandled = false; - this->UpdateGUI(); -} + this->ApplySelectionModeOnReferenceNode(); -void QmitkSegmentationView::OnSegmentationSelectionChanged(QList nodes) -{ - m_ToolManager->ActivateTool(-1); + // Add visibility observer for the new reference node + auto command = itk::SimpleMemberCommand::New(); + command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); - // Remove observer if one was registered - auto finding = m_WorkingDataObserverTags.find(m_WorkingNode); - if (finding != m_WorkingDataObserverTags.end()) - { - m_WorkingNode->GetProperty("visible")->RemoveObserver(m_WorkingDataObserverTags[m_WorkingNode]); - m_WorkingDataObserverTags.erase(m_WorkingNode); + m_ReferenceDataObserverTags[m_ReferenceNode] = + m_ReferenceNode->GetProperty("visible")->AddObserver(itk::ModifiedEvent(), command); + } } - if (nodes.empty()) + auto selectedWorkingNode = m_Controls->workingNodeSelector->GetSelectedNode(); + bool workingNodeChanged = false; + + if (m_WorkingNode != selectedWorkingNode) { - m_WorkingNode = nullptr; + workingNodeChanged = true; + + // Remove visibility observer for the current working node + if (m_WorkingDataObserverTags.find(m_WorkingNode) != m_WorkingDataObserverTags.end()) + { + m_WorkingNode->GetProperty("visible")->RemoveObserver(m_WorkingDataObserverTags[m_WorkingNode]); + m_WorkingDataObserverTags.erase(m_WorkingNode); + } + + // Disconnect from current label set image + this->LooseLabelSetConnection(); + + // Set new working node + m_WorkingNode = selectedWorkingNode; m_ToolManager->SetWorkingData(m_WorkingNode); - this->UpdateGUI(); - return; - } - if (m_ReferenceNode.IsNull()) - { - this->UpdateGUI(); - return; - } + if (m_WorkingNode.IsNotNull()) + { + this->ApplySelectionModeOnWorkingNode(); - mitk::Image::ConstPointer referenceImage = dynamic_cast(m_ReferenceNode->GetData()); - if (referenceImage.IsNull()) - { - this->UpdateGUI(); - return; + // Connect to new label set image + this->EstablishLabelSetConnection(); + m_Controls->labelSetWidget->ResetAllTableWidgetItems(); + + // Add visibility observer for the new segmentation node + auto command = itk::SimpleMemberCommand::New(); + command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); + + m_WorkingDataObserverTags[m_WorkingNode] = + m_WorkingNode->GetProperty("visible")->AddObserver(itk::ModifiedEvent(), command); + } } - m_WorkingNode = nodes.first(); - m_ToolManager->SetWorkingData(m_WorkingNode); - if (m_WorkingNode.IsNotNull()) + // Reset camera if any selection changed but only if both reference node and working node are set + if ((referenceNodeChanged || workingNodeChanged) && (m_ReferenceNode.IsNotNull() && m_WorkingNode.IsNotNull())) { - if (m_SelectionMode) + if (nullptr != m_RenderWindowPart) { - // hide all segmentation nodes to later show only the selected ones - mitk::DataStorage::SetOfObjects::ConstPointer segmentationNodes = - this->GetDataStorage()->GetSubset(m_SegmentationPredicate); - for (mitk::DataStorage::SetOfObjects::const_iterator iter = segmentationNodes->begin(); iter != segmentationNodes->end(); ++iter) - { - (*iter)->SetVisibility(false); - } + m_RenderWindowPart->SetReferenceGeometry(m_ReferenceNode->GetData()->GetTimeGeometry(), false); } - m_WorkingNode->SetVisibility(true); - - this->OnEstablishLabelSetConnection(); - m_Controls->labelSetWidget->ResetAllTableWidgetItems(); - - auto command = itk::SimpleMemberCommand::New(); - command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); - m_WorkingDataObserverTags[m_WorkingNode] = - m_WorkingNode->GetProperty("visible")->AddObserver(itk::ModifiedEvent(), command); - - this->InitializeRenderWindows(referenceImage->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, false); } this->UpdateGUI(); } void QmitkSegmentationView::OnVisibilityShortcutActivated() { if (m_WorkingNode.IsNull()) { return; } bool isVisible = false; m_WorkingNode->GetBoolProperty("visible", isVisible); m_WorkingNode->SetVisibility(!isVisible); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::OnLabelToggleShortcutActivated() { if (m_WorkingNode.IsNull()) { return; } auto workingImage = dynamic_cast(m_WorkingNode->GetData()); if (nullptr == workingImage) { return; } this->WaitCursorOn(); workingImage->GetActiveLabelSet()->SetNextActiveLabel(); workingImage->Modified(); this->WaitCursorOff(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::OnNewSegmentation() { m_ToolManager->ActivateTool(-1); if (m_ReferenceNode.IsNull()) { MITK_ERROR << "'Create new segmentation' button should never be clickable unless a reference image is selected."; return; } mitk::Image::ConstPointer referenceImage = dynamic_cast(m_ReferenceNode->GetData()); if (referenceImage.IsNull()) { QMessageBox::information( m_Parent, "New segmentation", "Please load and select an image before starting some action."); return; } if (referenceImage->GetDimension() <= 1) { QMessageBox::information( m_Parent, "New segmentation", "Segmentation is currently not supported for 2D images"); return; } auto segTemplateImage = referenceImage; if (referenceImage->GetDimension() > 3) { QmitkStaticDynamicSegmentationDialog dialog(m_Parent); dialog.SetReferenceImage(referenceImage.GetPointer()); dialog.exec(); segTemplateImage = dialog.GetSegmentationTemplate(); } mitk::DataNode::Pointer newSegmentationNode; try { this->WaitCursorOn(); newSegmentationNode = mitk::LabelSetImageHelper::CreateNewSegmentationNode(m_ReferenceNode, segTemplateImage); this->WaitCursorOff(); } catch (mitk::Exception& e) { this->WaitCursorOff(); MITK_ERROR << "Exception caught: " << e.GetDescription(); QMessageBox::warning(m_Parent, "New segmentation", "Could not create a new segmentation."); return; } auto newLabelSetImage = dynamic_cast(newSegmentationNode->GetData()); if (nullptr == newLabelSetImage) { // something went wrong return; } const auto labelSetPreset = this->GetDefaultLabelSetPreset(); if (labelSetPreset.empty() || !mitk::LabelSetIOHelper::LoadLabelSetImagePreset(labelSetPreset, newLabelSetImage)) { auto newLabel = mitk::LabelSetImageHelper::CreateNewLabel(newLabelSetImage); if (!m_DefaultLabelNaming) { QmitkNewSegmentationDialog dialog(m_Parent); dialog.SetName(QString::fromStdString(newLabel->GetName())); dialog.SetColor(newLabel->GetColor()); if (QDialog::Rejected == dialog.exec()) return; auto name = dialog.GetName(); if (!name.isEmpty()) newLabel->SetName(name.toStdString()); newLabel->SetColor(dialog.GetColor()); } newLabelSetImage->GetActiveLabelSet()->AddLabel(newLabel); } if (!this->GetDataStorage()->Exists(newSegmentationNode)) { this->GetDataStorage()->Add(newSegmentationNode, m_ReferenceNode); } if (m_ToolManager->GetWorkingData(0)) { m_ToolManager->GetWorkingData(0)->SetSelected(false); } newSegmentationNode->SetSelected(true); m_Controls->workingNodeSelector->SetCurrentSelectedNode(newSegmentationNode); } std::string QmitkSegmentationView::GetDefaultLabelSetPreset() const { auto labelSetPreset = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), ""); if (labelSetPreset.empty()) labelSetPreset = m_LabelSetPresetPreference.toStdString(); return labelSetPreset; } void QmitkSegmentationView::OnManualTool2DSelected(int id) { this->ResetMouseCursor(); mitk::StatusBar::GetInstance()->DisplayText(""); if (id >= 0) { std::string text = "Active Tool: \""; text += m_ToolManager->GetToolById(id)->GetName(); text += "\""; mitk::StatusBar::GetInstance()->DisplayText(text.c_str()); us::ModuleResource resource = m_ToolManager->GetToolById(id)->GetCursorIconResource(); this->SetMouseCursor(resource, 0, 0); } } void QmitkSegmentationView::OnShowMarkerNodes(bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = m_ToolManager->GetTools().size(); for (unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(m_ToolManager->GetToolById(i)); if (nullptr == manualSegmentationTool) { continue; } manualSegmentationTool->SetShowMarkerNodes(state); } } void QmitkSegmentationView::OnLayersChanged() { - this->OnEstablishLabelSetConnection(); + this->EstablishLabelSetConnection(); m_Controls->labelSetWidget->ResetAllTableWidgetItems(); } void QmitkSegmentationView::OnShowLabelTable(bool value) { m_Controls->labelSetWidget->setVisible(value); } void QmitkSegmentationView::OnGoToLabel(const mitk::Point3D& pos) { if (m_RenderWindowPart) { m_RenderWindowPart->SetSelectedPosition(pos); } } void QmitkSegmentationView::OnLabelSetWidgetReset() { this->ValidateSelectionInput(); } /**********************************************************************/ /* private */ /**********************************************************************/ void QmitkSegmentationView::CreateQtPartControl(QWidget* parent) { m_Parent = parent; m_Controls = new Ui::QmitkSegmentationViewControls; m_Controls->setupUi(parent); // *------------------------ // * SHORTCUTS // *------------------------ QShortcut* visibilityShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key::Key_H), parent); connect(visibilityShortcut, &QShortcut::activated, this, &QmitkSegmentationView::OnVisibilityShortcutActivated); QShortcut* labelToggleShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key::Key_L, Qt::CTRL | Qt::Key::Key_I), parent); connect(labelToggleShortcut, &QShortcut::activated, this, &QmitkSegmentationView::OnLabelToggleShortcutActivated); // *------------------------ // * DATA SELECTION WIDGETS // *------------------------ m_Controls->referenceNodeSelector->SetDataStorage(GetDataStorage()); m_Controls->referenceNodeSelector->SetNodePredicate(m_ReferencePredicate); m_Controls->referenceNodeSelector->SetInvalidInfo("Select an image"); m_Controls->referenceNodeSelector->SetPopUpTitel("Select an image"); m_Controls->referenceNodeSelector->SetPopUpHint("Select an image that should be used to define the geometry and bounds of the segmentation."); m_Controls->workingNodeSelector->SetDataStorage(GetDataStorage()); m_Controls->workingNodeSelector->SetNodePredicate(m_SegmentationPredicate); m_Controls->workingNodeSelector->SetInvalidInfo("Select a segmentation"); m_Controls->workingNodeSelector->SetPopUpTitel("Select a segmentation"); m_Controls->workingNodeSelector->SetPopUpHint("Select a segmentation that should be modified. Only segmentation with the same geometry and within the bounds of the reference image are selected."); connect(m_Controls->referenceNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkSegmentationView::OnReferenceSelectionChanged); connect(m_Controls->workingNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkSegmentationView::OnSegmentationSelectionChanged); // *------------------------ // * TOOLMANAGER // *------------------------ m_ToolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); m_ToolManager->SetDataStorage(*(this->GetDataStorage())); m_ToolManager->InitializeTools(); - // react if the active tool changed - m_ToolManager->ActiveToolChanged += - mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); - QString segTools2D = tr("Add Subtract Lasso Fill Erase Close Paint Wipe 'Region Growing' 'Live Wire'"); QString segTools3D = tr("Threshold 'UL Threshold' Otsu 'Region Growing 3D' Picking GrowCut"); #ifdef __linux__ segTools3D.append(" nnUNet"); // plugin not enabled for MacOS / Windows #endif std::regex extSegTool2DRegEx("SegTool2D$"); std::regex extSegTool3DRegEx("SegTool3D$"); auto tools = m_ToolManager->GetTools(); for (const auto &tool : tools) { if (std::regex_search(tool->GetNameOfClass(), extSegTool2DRegEx)) { segTools2D.append(QString(" '%1'").arg(tool->GetName())); } else if (std::regex_search(tool->GetNameOfClass(), extSegTool3DRegEx)) { segTools3D.append(QString(" '%1'").arg(tool->GetName())); } } // setup 2D tools m_Controls->toolSelectionBox2D->SetToolManager(*m_ToolManager); m_Controls->toolSelectionBox2D->SetGenerateAccelerators(true); m_Controls->toolSelectionBox2D->SetToolGUIArea(m_Controls->toolGUIArea2D); m_Controls->toolSelectionBox2D->SetDisplayedToolGroups(segTools2D.toStdString()); m_Controls->toolSelectionBox2D->SetLayoutColumns(3); - m_Controls->toolSelectionBox2D->SetEnabledMode( - QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible); connect(m_Controls->toolSelectionBox2D, &QmitkToolSelectionBox::ToolSelected, this, &QmitkSegmentationView::OnManualTool2DSelected); // setup 3D Tools m_Controls->toolSelectionBox3D->SetToolManager(*m_ToolManager); m_Controls->toolSelectionBox3D->SetGenerateAccelerators(true); m_Controls->toolSelectionBox3D->SetToolGUIArea(m_Controls->toolGUIArea3D); m_Controls->toolSelectionBox3D->SetDisplayedToolGroups(segTools3D.toStdString()); m_Controls->toolSelectionBox3D->SetLayoutColumns(3); - m_Controls->toolSelectionBox3D->SetEnabledMode( - QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible); m_Controls->slicesInterpolator->SetDataStorage(this->GetDataStorage()); // create general signal / slot connections connect(m_Controls->newSegmentationButton, &QToolButton::clicked, this, &QmitkSegmentationView::OnNewSegmentation); connect(m_Controls->slicesInterpolator, &QmitkSlicesInterpolator::SignalShowMarkerNodes, this, &QmitkSegmentationView::OnShowMarkerNodes); connect(m_Controls->layersWidget, &QmitkLayersWidget::LayersChanged, this, &QmitkSegmentationView::OnLayersChanged); connect(m_Controls->labelsWidget, &QmitkLabelsWidget::ShowLabelTable, this, &QmitkSegmentationView::OnShowLabelTable); // *------------------------ // * LABELSETWIDGET // *------------------------ connect(m_Controls->labelSetWidget, &QmitkLabelSetWidget::goToLabel, this, &QmitkSegmentationView::OnGoToLabel); connect(m_Controls->labelSetWidget, &QmitkLabelSetWidget::LabelSetWidgetReset, this, &QmitkSegmentationView::OnLabelSetWidgetReset); m_Controls->labelSetWidget->SetDataStorage(this->GetDataStorage()); m_Controls->labelSetWidget->hide(); auto command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); m_RenderingManagerObserverTag = mitk::RenderingManager::GetInstance()->AddObserver(mitk::RenderingManagerViewsInitializedEvent(), command); m_RenderWindowPart = this->GetRenderWindowPart(); if (nullptr != m_RenderWindowPart) { this->RenderWindowPartActivated(m_RenderWindowPart); } // Make sure the GUI notices if appropriate data is already present on creation. // Should be done last, if everything else is configured because it triggers the autoselection of data. m_Controls->referenceNodeSelector->SetAutoSelectNewNodes(true); m_Controls->workingNodeSelector->SetAutoSelectNewNodes(true); this->UpdateGUI(); } void QmitkSegmentationView::ActiveToolChanged() { auto activeTool = m_ToolManager->GetActiveTool(); if (nullptr == activeTool) { // no tool activated, deactivate the segmentation interactor m_SegmentationInteractor->Disable(); return; } // activate segmentation interactor to get informed about render window entered / left events m_SegmentationInteractor->Enable(); } void QmitkSegmentationView::ValidateRendererGeometry(const itk::EventObject& event) { if (!mitk::SegmentationInteractionEvent().CheckEvent(&event)) { return; } const auto* segmentationInteractionEvent = dynamic_cast(&event); const mitk::BaseRenderer::Pointer sendingRenderer = segmentationInteractionEvent->GetSender(); if (nullptr == sendingRenderer) { return; } bool entered = segmentationInteractionEvent->HasEnteredRenderWindow(); if (entered) { // mouse cursor of tool inside render window // check if tool can be used: reference geometry needs to be aligned with renderer geometry const auto* referenceDataNode = m_ToolManager->GetReferenceData(0); if (nullptr != referenceDataNode) { const auto workingImage = dynamic_cast(referenceDataNode->GetData()); if (nullptr != workingImage) { const mitk::TimeGeometry* workingImageGeometry = workingImage->GetTimeGeometry(); if (nullptr != workingImageGeometry) { - bool isGeometryAligned = - mitk::BaseRendererHelper::IsRendererAlignedWithSegmentation(sendingRenderer, workingImageGeometry); + bool isGeometryAligned = false; + try + { + isGeometryAligned = + mitk::BaseRendererHelper::IsRendererAlignedWithSegmentation(sendingRenderer, workingImageGeometry); + } + catch (const mitk::Exception& e) + { + MITK_ERROR << "Unable to validate renderer geometry\n" + << "Reason: " << e.GetDescription(); + this->ShowRenderWindowWarning(sendingRenderer, true); + this->UpdateWarningLabel( + tr("Unable to validate renderer geometry. Please see log!")); + return; + } if (!isGeometryAligned) { - this->BlockRenderer(sendingRenderer, true); + this->ShowRenderWindowWarning(sendingRenderer, true); this->UpdateWarningLabel( tr("Please perform a reinit on the segmentation image inside the entered Render Window!")); return; } } } } } - this->BlockRenderer(sendingRenderer, false); + this->ShowRenderWindowWarning(sendingRenderer, false); this->UpdateWarningLabel(tr("")); } -void QmitkSegmentationView::BlockRenderer(mitk::BaseRenderer* baseRenderer, bool blocked) +void QmitkSegmentationView::ShowRenderWindowWarning(mitk::BaseRenderer* baseRenderer, bool show) { - if (blocked) - { - mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_RendererAnnotation.GetPointer(), baseRenderer); - m_RendererAnnotation->Update(baseRenderer); - baseRenderer->RequestUpdate(); - } - else - { - m_RendererAnnotation->RemoveFromBaseRenderer(baseRenderer); - } + const auto* rendererName = baseRenderer->GetName(); + auto* renderWindow = m_RenderWindowPart->GetQmitkRenderWindow(rendererName); + renderWindow->ShowOverlayMessage(show); } void QmitkSegmentationView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_RenderWindowPart != renderWindowPart) { m_RenderWindowPart = renderWindowPart; } if (nullptr != m_Parent) { m_Parent->setEnabled(true); } if (nullptr == m_Controls) { return; } - // tell the interpolation about tool manager, data storage and render window part if (nullptr != m_RenderWindowPart) { + // tell the interpolation about tool manager, data storage and render window part QList controllers; controllers.push_back(m_RenderWindowPart->GetQmitkRenderWindow("axial")->GetSliceNavigationController()); controllers.push_back(m_RenderWindowPart->GetQmitkRenderWindow("sagittal")->GetSliceNavigationController()); controllers.push_back(m_RenderWindowPart->GetQmitkRenderWindow("coronal")->GetSliceNavigationController()); m_Controls->slicesInterpolator->Initialize(m_ToolManager, controllers); + + if (!m_RenderWindowPart->HasCoupledRenderWindows()) + { + // react if the active tool changed, only if a render window part with decoupled render windows is used + m_ToolManager->ActiveToolChanged += + mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); + } } } void QmitkSegmentationView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* /*renderWindowPart*/) { m_RenderWindowPart = nullptr; if (nullptr != m_Parent) { m_Parent->setEnabled(false); } + + // remove message-connection to make sure no message is processed if no render window part is available + m_ToolManager->ActiveToolChanged -= + mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); } void QmitkSegmentationView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { auto labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), ""); m_DefaultLabelNaming = labelSuggestions.empty() ? prefs->GetBool("default label naming", true) : false; // No default label naming when label suggestions are enforced via command-line argument if (nullptr != m_Controls) { m_Controls->labelsWidget->SetDefaultLabelNaming(m_DefaultLabelNaming); bool slimView = prefs->GetBool("slim view", false); m_Controls->toolSelectionBox2D->SetShowNames(!slimView); m_Controls->toolSelectionBox3D->SetShowNames(!slimView); } m_DrawOutline = prefs->GetBool("draw outline", true); m_SelectionMode = prefs->GetBool("selection mode", false); m_LabelSetPresetPreference = prefs->Get("label set preset", ""); this->ApplyDisplayOptions(); + this->ApplySelectionMode(); } void QmitkSegmentationView::NodeAdded(const mitk::DataNode* node) { if (m_SegmentationPredicate->CheckNode(node)) - { this->ApplyDisplayOptions(const_cast(node)); - } + + this->ApplySelectionMode(); } void QmitkSegmentationView::NodeRemoved(const mitk::DataNode* node) { if (!m_SegmentationPredicate->CheckNode(node)) { return; } // 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 = nullptr; mitk::Image* image = dynamic_cast(node->GetData()); mitk::SurfaceInterpolationController::GetInstance()->RemoveInterpolationSession(image); } -void QmitkSegmentationView::OnEstablishLabelSetConnection() +void QmitkSegmentationView::EstablishLabelSetConnection() { if (m_WorkingNode.IsNull()) - { return; - } auto workingImage = dynamic_cast(m_WorkingNode->GetData()); - if (nullptr == workingImage) - { - return; - } workingImage->GetActiveLabelSet()->AddLabelEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->RemoveLabelEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->ModifyLabelEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->AllLabelsModifiedEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->ActiveLabelEvent += mitk::MessageDelegate1(m_Controls->labelSetWidget, &QmitkLabelSetWidget::SelectLabelByPixelValue); - - // Removed in T27851 to have a chance to react to AfterChangeLayerEvent. Did it brake something? - // workingImage->BeforeChangeLayerEvent += mitk::MessageDelegate( - // this, &QmitkMultiLabelSegmentationView::OnLooseLabelSetConnection); - workingImage->AfterChangeLayerEvent += mitk::MessageDelegate( this, &QmitkSegmentationView::UpdateGUI); } -void QmitkSegmentationView::OnLooseLabelSetConnection() +void QmitkSegmentationView::LooseLabelSetConnection() { if (m_WorkingNode.IsNull()) - { return; - } auto workingImage = dynamic_cast(m_WorkingNode->GetData()); - if (nullptr == workingImage) - { - return; - } - // Reset LabelSetWidget Events workingImage->GetActiveLabelSet()->AddLabelEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->RemoveLabelEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->ModifyLabelEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->AllLabelsModifiedEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->ActiveLabelEvent -= mitk::MessageDelegate1(m_Controls->labelSetWidget, &QmitkLabelSetWidget::SelectLabelByPixelValue); - - // Removed in T27851 to have a chance to react to AfterChangeLayerEvent. Did it brake something? - // workingImage->BeforeChangeLayerEvent -= mitk::MessageDelegate( - // this, &QmitkMultiLabelSegmentationView::OnLooseLabelSetConnection); - workingImage->AfterChangeLayerEvent -= mitk::MessageDelegate( this, &QmitkSegmentationView::UpdateGUI); } void QmitkSegmentationView::ApplyDisplayOptions() { if (nullptr == m_Parent) { return; } if (nullptr == m_Controls) { return; // might happen on initialization (preferences loaded) } mitk::DataStorage::SetOfObjects::ConstPointer allImages = this->GetDataStorage()->GetSubset(m_SegmentationPredicate); for (mitk::DataStorage::SetOfObjects::const_iterator iter = allImages->begin(); iter != allImages->end(); ++iter) { this->ApplyDisplayOptions(*iter); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::ApplyDisplayOptions(mitk::DataNode* node) { if (nullptr == node) { return; } auto labelSetImage = dynamic_cast(node->GetData()); if (nullptr != labelSetImage) { // node is a multi label segmentation // its outline property can be set in the segmentation preference page node->SetProperty("labelset.contour.active", mitk::BoolProperty::New(m_DrawOutline)); // force render window update to show outline node->GetData()->Modified(); } else if (nullptr != node->GetData()) { // node is a legacy binary segmentation bool isBinary = false; node->GetBoolProperty("binary", isBinary); if (isBinary) { node->SetProperty("outline binary", mitk::BoolProperty::New(m_DrawOutline)); node->SetProperty("outline width", mitk::FloatProperty::New(2.0)); // force render window update to show outline node->GetData()->Modified(); } } } +void QmitkSegmentationView::ApplySelectionMode() +{ + if (!m_SelectionMode) + return; + + this->ApplySelectionModeOnReferenceNode(); + this->ApplySelectionModeOnWorkingNode(); +} + +void QmitkSegmentationView::ApplySelectionModeOnReferenceNode() +{ + this->ApplySelectionMode(m_ReferenceNode, m_ReferencePredicate); +} + +void QmitkSegmentationView::ApplySelectionModeOnWorkingNode() +{ + this->ApplySelectionMode(m_WorkingNode, m_SegmentationPredicate); +} + +void QmitkSegmentationView::ApplySelectionMode(mitk::DataNode* node, mitk::NodePredicateBase* predicate) +{ + if (!m_SelectionMode || node == nullptr || predicate == nullptr) + return; + + auto nodes = this->GetDataStorage()->GetSubset(predicate); + + for (auto iter = nodes->begin(); iter != nodes->end(); ++iter) + (*iter)->SetVisibility(*iter == node); +} + void QmitkSegmentationView::OnContourMarkerSelected(const mitk::DataNode* node) { QmitkRenderWindow* selectedRenderWindow = nullptr; auto* renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN); auto* axialRenderWindow = renderWindowPart->GetQmitkRenderWindow("axial"); auto* sagittalRenderWindow = renderWindowPart->GetQmitkRenderWindow("sagittal"); auto* coronalRenderWindow = renderWindowPart->GetQmitkRenderWindow("coronal"); auto* threeDRenderWindow = renderWindowPart->GetQmitkRenderWindow("3d"); bool PlanarFigureInitializedWindow = false; // find initialized renderwindow if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, axialRenderWindow->GetRenderer())) { selectedRenderWindow = axialRenderWindow; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, sagittalRenderWindow->GetRenderer())) { selectedRenderWindow = sagittalRenderWindow; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, coronalRenderWindow->GetRenderer())) { selectedRenderWindow = coronalRenderWindow; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, threeDRenderWindow->GetRenderer())) { selectedRenderWindow = threeDRenderWindow; } // make node visible if (nullptr != 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()->GetCameraController()->Fit(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSegmentationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& nodes) { if (0 == nodes.size()) { return; } 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; } } void QmitkSegmentationView::ResetMouseCursor() { if (m_MouseCursorSet) { mitk::ApplicationCursor::GetInstance()->PopCursor(); m_MouseCursorSet = false; } } void QmitkSegmentationView::SetMouseCursor(const us::ModuleResource& resource, int hotspotX, int hotspotY) { // Remove previously set mouse cursor if (m_MouseCursorSet) { this->ResetMouseCursor(); } if (resource) { us::ModuleResourceStream cursor(resource, std::ios::binary); mitk::ApplicationCursor::GetInstance()->PushCursor(cursor, hotspotX, hotspotY); m_MouseCursorSet = true; } } void QmitkSegmentationView::UpdateGUI() { mitk::DataNode* referenceNode = m_ToolManager->GetReferenceData(0); bool hasReferenceNode = referenceNode != nullptr; mitk::DataNode* workingNode = m_ToolManager->GetWorkingData(0); bool hasWorkingNode = workingNode != nullptr; m_Controls->newSegmentationButton->setEnabled(false); if (hasReferenceNode) { m_Controls->newSegmentationButton->setEnabled(true); } if (hasWorkingNode && hasReferenceNode) { int layer = -1; referenceNode->GetIntProperty("layer", layer); workingNode->SetIntProperty("layer", layer + 1); } m_Controls->layersWidget->UpdateGUI(); m_Controls->labelsWidget->UpdateGUI(); this->ValidateSelectionInput(); } void QmitkSegmentationView::ValidateSelectionInput() { - this->UpdateWarningLabel(""); + auto referenceNode = m_Controls->referenceNodeSelector->GetSelectedNode(); + auto workingNode = m_Controls->workingNodeSelector->GetSelectedNode(); + + bool hasReferenceNode = referenceNode.IsNotNull(); + bool hasWorkingNode = workingNode.IsNotNull(); + bool hasBothNodes = hasReferenceNode && hasWorkingNode; + + QString warning; + bool toolSelectionBoxesEnabled = hasReferenceNode && hasWorkingNode; + unsigned int numberOfLabels = 0; + + m_Controls->layersWidget->setEnabled(hasWorkingNode); + m_Controls->labelsWidget->setEnabled(hasWorkingNode); + m_Controls->labelSetWidget->setEnabled(hasWorkingNode); - m_Controls->layersWidget->setEnabled(false); - m_Controls->labelsWidget->setEnabled(false); - m_Controls->labelSetWidget->setEnabled(false); + m_Controls->toolSelectionBox2D->setEnabled(hasBothNodes); + m_Controls->toolSelectionBox3D->setEnabled(hasBothNodes); - // the argument is actually not used - // enable status depends on the tool manager selection - m_Controls->toolSelectionBox2D->setEnabled(false); - m_Controls->toolSelectionBox3D->setEnabled(false); m_Controls->slicesInterpolator->setEnabled(false); m_Controls->interpolatorWarningLabel->hide(); - mitk::DataNode* referenceNode = m_Controls->referenceNodeSelector->GetSelectedNode(); - mitk::DataNode* workingNode = m_Controls->workingNodeSelector->GetSelectedNode(); - - if (nullptr == referenceNode) + if (hasReferenceNode) { - return; + if (!referenceNode->IsVisible(nullptr)) + { + warning += tr("The selected reference image is currently not visible!"); + toolSelectionBoxesEnabled = false; + } } - if (nullptr == workingNode) + if (hasWorkingNode) { - return; - } + if (!workingNode->IsVisible(nullptr)) + { + warning += (!warning.isEmpty() ? "
" : "") + tr("The selected segmentation is currently not visible!"); + toolSelectionBoxesEnabled = false; + } - mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); - auto workingNodeIsVisible = renderWindowPart && - workingNode->IsVisible(renderWindowPart->GetQmitkRenderWindow("axial")->GetRenderer()); - if (!workingNodeIsVisible) - { - this->UpdateWarningLabel(tr("The selected segmentation is currently not visible!")); - return; + auto labelSetImage = dynamic_cast(workingNode->GetData()); + auto activeLayer = labelSetImage->GetActiveLayer(); + numberOfLabels = labelSetImage->GetNumberOfLabels(activeLayer); + + if (2 == numberOfLabels) + { + m_Controls->slicesInterpolator->setEnabled(true); + } + else if (2 < numberOfLabels) + { + m_Controls->interpolatorWarningLabel->setText( + "Interpolation only works for single label segmentations."); + m_Controls->interpolatorWarningLabel->show(); + } } - /* - * Here we check whether the geometry of the selected segmentation image is 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 - */ - const mitk::BaseGeometry* workingNodeGeo = workingNode->GetData()->GetGeometry(); - const mitk::BaseGeometry* worldGeo = - renderWindowPart->GetQmitkRenderWindow("3d")->GetSliceNavigationController()->GetCurrentGeometry3D(); - if (nullptr != workingNodeGeo && nullptr != worldGeo) + toolSelectionBoxesEnabled &= numberOfLabels > 1; + + // Here we need to check whether the geometry of the selected segmentation image (working image geometry) + // is aligned with the geometry of the 3D render window. + // It is not allowed to use a geometry different from the working image geometry for segmenting. + // We only need to this if the tool selection box would be enabled without this check. + if (toolSelectionBoxesEnabled && nullptr != m_RenderWindowPart && m_RenderWindowPart->HasCoupledRenderWindows()) { - if (/*mitk::Equal(*workingNodeGeo->GetBoundingBox(), *worldGeo->GetBoundingBox(), mitk::eps, true)*/true) + const mitk::BaseGeometry* workingNodeGeometry = workingNode->GetData()->GetGeometry(); + const mitk::BaseGeometry* renderWindowGeometry = + m_RenderWindowPart->GetQmitkRenderWindow("3d")->GetSliceNavigationController()->GetCurrentGeometry3D(); + if (nullptr != workingNodeGeometry && nullptr != renderWindowGeometry) { - m_ToolManager->SetReferenceData(referenceNode); - m_ToolManager->SetWorkingData(workingNode); - m_Controls->layersWidget->setEnabled(true); - m_Controls->labelsWidget->setEnabled(true); - m_Controls->labelSetWidget->setEnabled(true); - m_Controls->toolSelectionBox2D->setEnabled(true); - m_Controls->toolSelectionBox3D->setEnabled(true); - - auto labelSetImage = dynamic_cast(workingNode->GetData()); - if (nullptr != labelSetImage) + if (!mitk::Equal(*workingNodeGeometry->GetBoundingBox(), *renderWindowGeometry->GetBoundingBox(), mitk::eps, true)) { - int numberOfLabels = labelSetImage->GetNumberOfLabels(labelSetImage->GetActiveLayer()); - if (2 == numberOfLabels) // fix for T27319: exterior is label 0, first label is label 1 - { - m_Controls->slicesInterpolator->setEnabled(true); - } - else - { - m_Controls->interpolatorWarningLabel->show(); - m_Controls->interpolatorWarningLabel->setText("Interpolation only works for single label segmentations."); - } + warning += (!warning.isEmpty() ? "
" : "") + tr("Please reinitialize the selected segmentation image!"); + toolSelectionBoxesEnabled = false; } - return; } } + m_Controls->toolSelectionBox2D->setEnabled(toolSelectionBoxesEnabled); + m_Controls->toolSelectionBox3D->setEnabled(toolSelectionBoxesEnabled); + + this->UpdateWarningLabel(warning); + m_ToolManager->SetReferenceData(referenceNode); - m_ToolManager->SetWorkingData(nullptr); - this->UpdateWarningLabel(tr("Please perform a reinit on the segmentation image!")); + m_ToolManager->SetWorkingData(workingNode); } void QmitkSegmentationView::UpdateWarningLabel(QString text) { - if (text.size() == 0) + if (text.isEmpty()) { m_Controls->selectionWarningLabel->hide(); } else { - m_Controls->selectionWarningLabel->show(); m_Controls->selectionWarningLabel->setText("" + text + ""); + m_Controls->selectionWarningLabel->show(); } } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h index 4e17fd4f66..721db55df7 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h @@ -1,204 +1,206 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSEGMENTATIONVIEW_H #define QMITKSEGMENTATIONVIEW_H #include "ui_QmitkSegmentationViewControls.h" #include #include #include #include -// mitk annotation -#include - /** * @brief The segmentation view provides a set of tool to use different segmentation algorithms. * It provides two selection widgets to load an image node and a segmentation node * on which to perform the segmentation. Creating new segmentation nodes is also possible. * The available segmentation tools are grouped into "2D"- and "3D"-tools. * * Most segmentation tools / algorithms need some kind of user interaction, where the * user is asked to draw something in the image display or set some seed points / start values. * The tools also often provide additional propeties so that a user can modify the * algorithm's behavior. * * This class additionally provides options to work with different layers (create new layers, * switch between layers). * Moreover, a multilabel widget displays all the existing labels of a multilabel segmentation * for the currently active layer. * The multilabel widget allows to control the labels by creatin new one, removing existing ones, * showing / hiding single labels, merging labels, (re-)naming them etc. * * Additionally the view provides an option to create "2D"- and "3D"-interpolations between * neighboring segmentation masks on unsegmented slices. * Interpolation for multilabel segmentations is currently not implemented. */ class QmitkSegmentationView : public QmitkAbstractView, public mitk::IRenderWindowPartListener { Q_OBJECT public: static const std::string VIEW_ID; QmitkSegmentationView(); ~QmitkSegmentationView() override; private Q_SLOTS: // reaction to the selection of a new reference image in the selection widget void OnReferenceSelectionChanged(QList nodes); // reaction to the selection of a new segmentation image in the selection widget void OnSegmentationSelectionChanged(QList nodes); // reaction to the shortcut ("CTRL+H") for toggling the visibility of the working node void OnVisibilityShortcutActivated(); // reaction to the shortcut ("CTRL+L") for iterating over all labels void OnLabelToggleShortcutActivated(); // reaction to the button "New segmentation" void OnNewSegmentation(); void OnManualTool2DSelected(int id); void OnShowMarkerNodes(bool); void OnLayersChanged(); void OnShowLabelTable(bool); void OnGoToLabel(const mitk::Point3D &pos); void OnLabelSetWidgetReset(); private: void CreateQtPartControl(QWidget* parent) override; void SetFocus() override {} /** - * @brief Add an observer for the mitk::Tool::ToolEnteredRenderWindow-event - * to the currently active tool. + * @brief Enable or disable the SegmentationInteractor. * * The active tool is retrieved from the tool manager. - * If the event is not already observerd by the active tool, - * an observer for this event is added, using a 'ReceptorMemberCommand'. - * This command uses 'ValidateRendererGeometry' as a callback function, - * and will call this function, if the event is invoked. + * If the active tool is valid, the SegmentationInteractor is enabled + * to listen to 'SegmentationInteractionEvent's. */ void ActiveToolChanged(); /** * @brief Test whether the geometry of the reference image * fits the world geometry of the respective renderer. * * The respective renderer is retrieved from the given event, which - * needs to be a 'ToolEnteredRenderWindow'. This event provides not only - * the sending base renderer but also a bool that indicates whether - * the mouse cursor entered or left the base renderer. + * needs to be a 'SegmentationInteractionEvent'. + * This event provides not only the sending base renderer but also a + * bool that indicates whether the mouse cursor entered or left the + * base renderer. * This information is used to compare the renderer's world geometry * with the oriented time geometry of the current reference image. * If the geometries align, the renderer is not blocked anymore and the * view's warning message is removed. - * If the geometries do not align, 'BlockRenderer' is called and a - * warning message is added to the top of the plugin view. + * If the geometries do not align, 'ShowRenderWindowWarning' is called + * and a warning message is added to the top of this plugin view. * - * @param event The observed mitk::Tool::ToolEnteredRenderWindow-event. + * @param event The observed mitk::SegmentationInteractionEvent. */ void ValidateRendererGeometry(const itk::EventObject& event); /** - * @brief Block a base renderer for segmentation. + * @brief Show a warning on the given base renderer. * - * This function will add an overlay image to the given base renderer - * to indicate that the renderer should not be used for interactive - * image segmentation. + * This function will show the overlay on the QmitkRenderWindow + * corresponding to the given base renderer to indicate that the + * renderer should not be used for interactive image segmentation. * * @param baseRenderer The base renderer to "block" - * @param blocked If true, the overlay image will be added. - * If false, the overlay image will be removed. + * @param show If true, the overlay widget will be shown. + * If false, the overlay widget will be hid. */ - void BlockRenderer(mitk::BaseRenderer* baseRenderer, bool blocked); + void ShowRenderWindowWarning(mitk::BaseRenderer* baseRenderer, bool show); void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override; void OnPreferencesChanged(const berry::IBerryPreferences* prefs) override; void NodeAdded(const mitk::DataNode* node) override; void NodeRemoved(const mitk::DataNode* node) override; - void OnEstablishLabelSetConnection(); + void EstablishLabelSetConnection(); + + void LooseLabelSetConnection(); - void OnLooseLabelSetConnection(); + void OnAnySelectionChanged(); // make sure all images / segmentations look according to the user preference settings void ApplyDisplayOptions(); // decorates a DataNode according to the user preference settings void ApplyDisplayOptions(mitk::DataNode* node); + void ApplySelectionMode(); + void ApplySelectionModeOnReferenceNode(); + void ApplySelectionModeOnWorkingNode(); + void ApplySelectionMode(mitk::DataNode* node, mitk::NodePredicateBase* predicate); + // If a contourmarker is selected, the plane in the related widget will be reoriented according to the marker`s geometry void OnContourMarkerSelected(const mitk::DataNode* node); void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) override; void ResetMouseCursor(); void SetMouseCursor(const us::ModuleResource&, int hotspotX, int hotspotY); void UpdateGUI(); void ValidateSelectionInput(); void UpdateWarningLabel(QString text); std::string GetDefaultLabelSetPreset() const; QWidget* m_Parent; Ui::QmitkSegmentationViewControls* m_Controls; mitk::IRenderWindowPart* m_RenderWindowPart; mitk::ToolManager* m_ToolManager; mitk::DataNode::Pointer m_ReferenceNode; mitk::DataNode::Pointer m_WorkingNode; mitk::SegmentationInteractor::Pointer m_SegmentationInteractor; typedef std::map NodeTagMapType; NodeTagMapType m_WorkingDataObserverTags; NodeTagMapType m_ReferenceDataObserverTags; unsigned int m_RenderingManagerObserverTag; mitk::NodePredicateAnd::Pointer m_ReferencePredicate; mitk::NodePredicateAnd::Pointer m_SegmentationPredicate; - mitk::LogoAnnotation::Pointer m_RendererAnnotation; - bool m_DrawOutline; bool m_SelectionMode; bool m_MouseCursorSet; QString m_LabelSetPresetPreference; bool m_DefaultLabelNaming; + + bool m_SelectionChangeIsAlreadyBeingHandled; }; #endif // QMITKSEGMENTATIONVIEW_H 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 2e080b5c7e..e50a27bfcd 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp @@ -1,66 +1,74 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "QmitkSegmentationView.h" #include "QmitkSegmentationPreferencePage.h" #include "SegmentationUtilities/QmitkSegmentationUtilitiesView.h" #include "QmitkAutocropAction.h" #include "QmitkAutocropLabelSetImageAction.h" #include "QmitkCreatePolygonModelAction.h" #include "QmitkLoadMultiLabelPresetAction.h" #include "QmitkSaveMultiLabelPresetAction.h" +#include "QmitkConvertSurfaceToLabelAction.h" +#include "QmitkConvertMaskToLabelAction.h" +#include "QmitkConvertToMultiLabelSegmentationAction.h" +#include "QmitkCreateMultiLabelSegmentationAction.h" using namespace mitk; 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(QmitkSegmentationPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationUtilitiesView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAutocropAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAutocropLabelSetImageAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkCreatePolygonModelAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkLoadMultiLabelPresetAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSaveMultiLabelPresetAction, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertSurfaceToLabelAction, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertMaskToLabelAction, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertToMultiLabelSegmentationAction, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkCreateMultiLabelSegmentationAction, context) this->m_context = context; } void PluginActivator::stop(ctkPluginContext *) { this->m_context = nullptr; } PluginActivator* PluginActivator::getDefault() { return m_Instance; } ctkPluginContext*PluginActivator::getContext() { return m_context; } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.svg b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.svg index 31d6ae02ac..2c2425815d 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.svg +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.svg @@ -1,55 +1,80 @@ + inkscape:current-layer="svg2" + inkscape:showpageshadow="false" /> image/svg+xml - + + + + diff --git a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport_old.cpp b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport_old.cpp index f44e8b0d7b..defaa02d66 100644 --- a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport_old.cpp +++ b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport_old.cpp @@ -1,606 +1,603 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Blueberry #include #include #include //Mitk #include #include #include #include #include #include #include #include "QmitkRegisterClasses.h" #include "QmitkRenderWindow.h" #include #include // Qmitk #include "QmitkUltrasoundSupport.h" // Qt #include #include #include // Ultrasound #include "mitkUSDevice.h" #include "QmitkUSAbstractCustomWidget.h" #include #include #include "usServiceReference.h" #include "internal/org_mitk_gui_qt_ultrasound_Activator.h" #include "mitkNodePredicateDataType.h" #include const std::string QmitkUltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport"; void QmitkUltrasoundSupport::SetFocus() { } void QmitkUltrasoundSupport::CreateQtPartControl(QWidget *parent) { //initialize timers m_UpdateTimer = new QTimer(this); m_RenderingTimer2d = new QTimer(this); m_RenderingTimer3d = new QTimer(this); // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); //load persistence data before connecting slots (so no slots are called in this phase...) LoadUISettings(); //connect signals and slots... connect(m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice())); // Change Widget Visibilities connect(m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice())); // Init NewDeviceWidget connect(m_Controls.m_ActiveVideoDevices, SIGNAL(ServiceSelectionChanged(us::ServiceReferenceU)), this, SLOT(OnChangedActiveDevice())); connect(m_Controls.m_RunImageTimer, SIGNAL(clicked()), this, SLOT(OnChangedActiveDevice())); connect(m_Controls.m_ShowImageStream, SIGNAL(clicked()), this, SLOT(OnChangedActiveDevice())); connect(m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone())); // After NewDeviceWidget finished editing connect(m_Controls.m_FrameRatePipeline, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit())); connect(m_Controls.m_FrameRate2d, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit())); connect(m_Controls.m_FrameRate3d, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit())); connect(m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton())); connect(m_UpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateImage())); connect(m_RenderingTimer2d, SIGNAL(timeout()), this, SLOT(RenderImage2d())); connect(m_RenderingTimer3d, SIGNAL(timeout()), this, SLOT(RenderImage3d())); connect(m_Controls.m_Update2DView, SIGNAL(clicked()), this, SLOT(StartTimers())); connect(m_Controls.m_Update3DView, SIGNAL(clicked()), this, SLOT(StartTimers())); connect(m_Controls.m_DeviceManagerWidget, SIGNAL(EditDeviceButtonClicked(mitk::USDevice::Pointer)), this, SLOT(OnClickedEditDevice())); //Change Widget Visibilities connect(m_Controls.m_DeviceManagerWidget, SIGNAL(EditDeviceButtonClicked(mitk::USDevice::Pointer)), this->m_Controls.m_NewVideoDeviceWidget, SLOT(EditDevice(mitk::USDevice::Pointer))); // Initializations m_Controls.m_NewVideoDeviceWidget->setVisible(false); std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + "=true))"; m_Controls.m_ActiveVideoDevices->Initialize( mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL, filter); m_Controls.m_ActiveVideoDevices->SetAutomaticallySelectFirstEntry(true); m_FrameCounterPipeline = 0; m_FrameCounter2d = 0; m_FrameCounter3d = 0; m_Controls.tabWidget->setTabEnabled(1, false); } void QmitkUltrasoundSupport::InitNewNode() { m_Node.push_back(nullptr); auto& Node = m_Node.back(); Node = mitk::DataNode::New(); char name[30]; sprintf(name, "US Viewing Stream - Image %d", (unsigned int)(m_Node.size() - 1)); Node->SetName(name); //create a dummy image (gray values 0..255) for correct initialization of level window, etc. mitk::Image::Pointer dummyImage = mitk::ImageGenerator::GenerateRandomImage(100, 100, 1, 1, 1, 1, 1, 255, 0); Node->SetData(dummyImage); m_OldGeometry = dynamic_cast(dummyImage->GetGeometry()); this->GetDataStorage()->Add(Node); } void QmitkUltrasoundSupport::DestroyLastNode() { auto& Node = m_Node.back(); this->GetDataStorage()->Remove(Node); // clean up Node->ReleaseData(); m_Node.pop_back(); } void QmitkUltrasoundSupport::UpdateLevelWindows() { mitk::LevelWindow levelWindow; if (m_Node.size() > 0) { for (unsigned int index = 0; index < m_AmountOfOutputs; ++index) { m_Node[index]->GetLevelWindow(levelWindow); if (!m_curOutput[index]->IsEmpty()) levelWindow.SetToImageRange(m_curOutput[index]); m_Node[index]->SetLevelWindow(levelWindow); } } } void QmitkUltrasoundSupport::SetColormap(mitk::DataNode::Pointer node, mitk::LookupTable::LookupTableType type) { mitk::LookupTable::Pointer lookupTable = mitk::LookupTable::New(); mitk::LookupTableProperty::Pointer lookupTableProperty = mitk::LookupTableProperty::New(); lookupTable->SetType(type); lookupTableProperty->SetLookupTable(lookupTable); node->SetProperty("LookupTable", lookupTableProperty); mitk::RenderingModeProperty::Pointer renderingMode = dynamic_cast(node->GetProperty("Image Rendering.Mode")); renderingMode->SetValue(mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR); } void QmitkUltrasoundSupport::OnClickedAddNewDevice() { m_Controls.m_NewVideoDeviceWidget->setVisible(true); m_Controls.m_DeviceManagerWidget->setVisible(false); m_Controls.m_Headline->setText("Add New Video Device:"); m_Controls.m_WidgetActiveDevices->setVisible(false); } void QmitkUltrasoundSupport::OnClickedEditDevice() { m_Controls.m_NewVideoDeviceWidget->setVisible(true); m_Controls.m_DeviceManagerWidget->setVisible(false); m_Controls.m_WidgetActiveDevices->setVisible(false); m_Controls.m_Headline->setText("Edit Video Device:"); } void QmitkUltrasoundSupport::UpdateAmountOfOutputs() { // correct the amount of Nodes to display data while (m_Node.size() < m_AmountOfOutputs) { InitNewNode(); } while (m_Node.size() > m_AmountOfOutputs) { DestroyLastNode(); } // correct the amount of image outputs that we feed the nodes with while (m_curOutput.size() < m_AmountOfOutputs) { m_curOutput.push_back(mitk::Image::New()); unsigned int dim[3] = { 2, 2, 1}; m_curOutput.back()->Initialize(mitk::MakeScalarPixelType(), 3, dim); } while (m_curOutput.size() > m_AmountOfOutputs) { m_curOutput.pop_back(); } } void QmitkUltrasoundSupport::UpdateImage() { if (m_Controls.m_ShowImageStream->isChecked()) { m_Device->Modified(); m_Device->Update(); // Update device if (m_AmountOfOutputs == 0) return; // if there is no image to be displayed, skip the rest of this method for (unsigned int index = 0; index < m_AmountOfOutputs; ++index) { auto image = m_Device->GetOutput(index); // get the Image data to display if (!image->IsEmpty()) { if (m_curOutput[index]->GetDimension(0) != image->GetDimension(0) || m_curOutput[index]->GetDimension(1) != image->GetDimension(1) || m_curOutput[index]->GetDimension(2) != image->GetDimension(2) || m_curOutput[index]->GetPixelType() != image->GetPixelType()) { m_curOutput[index]->Initialize(image->GetPixelType(), image->GetDimension(), image->GetDimensions()); // if we switched image resolution or type the outputs must be reinitialized! } // copy the contents of the device output into the image the data storage will display mitk::ImageReadAccessor inputReadAccessor(image); m_curOutput[index]->SetImportVolume(inputReadAccessor.GetData()); m_curOutput[index]->GetGeometry()->SetIndexToWorldTransform(image->GetSlicedGeometry()->GetIndexToWorldTransform()); } if (m_curOutput[index]->IsEmpty()) { // create a noise image for correct initialization of level window, etc. mitk::Image::Pointer randomImage = mitk::ImageGenerator::GenerateRandomImage(32, 32, 1, 1, 1, 1, 1, 255, 0); m_Node[index]->SetData(randomImage); m_curOutput[index]->SetGeometry(randomImage->GetGeometry()); } else { m_Node[index]->SetData(m_curOutput[index]); } } float eps = 0.000001f; // if the geometry changed: reinitialize the ultrasound image. we use the m_curOutput[0] to readjust the geometry if (((m_OldGeometry.IsNotNull()) && (m_curOutput[0]->GetGeometry() != nullptr)) && ( (abs(m_OldGeometry->GetSpacing()[0] - m_curOutput[0]->GetGeometry()->GetSpacing()[0]) > eps) || (abs(m_OldGeometry->GetSpacing()[1] - m_curOutput[0]->GetGeometry()->GetSpacing()[1]) > eps) || (abs(m_OldGeometry->GetCenter()[0] - m_curOutput[0]->GetGeometry()->GetCenter()[0]) > eps) || (abs(m_OldGeometry->GetCenter()[1] - m_curOutput[0]->GetGeometry()->GetCenter()[1]) > eps) || m_ForceRequestUpdateAll)) { mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if ((renderWindow != nullptr) && (m_curOutput[0]->GetTimeGeometry()->IsValid()) && (m_Controls.m_ShowImageStream->isChecked())) { renderWindow->GetRenderingManager()->InitializeViews(m_curOutput[0]->GetGeometry()); } m_CurrentImageWidth = m_curOutput[0]->GetDimension(0); m_CurrentImageHeight = m_curOutput[0]->GetDimension(1); m_OldGeometry = dynamic_cast(m_curOutput[0]->GetGeometry()); UpdateLevelWindows(); m_ForceRequestUpdateAll = false; } } //Update frame counter m_FrameCounterPipeline++; if (m_FrameCounterPipeline >= 10) { // compute framerate of pipeline update int nMilliseconds = m_Clock.restart(); int fps = 10000.0f / (nMilliseconds); m_FPSPipeline = fps; m_FrameCounterPipeline = 0; // display lowest framerate in UI int lowestFPS = m_FPSPipeline; if (m_Controls.m_Update2DView->isChecked() && (m_FPS2d < lowestFPS)) { lowestFPS = m_FPS2d; } if (m_Controls.m_Update3DView->isChecked() && (m_FPS3d < lowestFPS)) { lowestFPS = m_FPS3d; } m_Controls.m_FramerateLabel->setText("Current Framerate: " + QString::number(lowestFPS) + " FPS"); } } void QmitkUltrasoundSupport::RenderImage2d() { if (!m_Controls.m_Update2DView->isChecked()) return; - //mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); - //renderWindow->GetRenderingManager()->RequestUpdate(mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))->GetRenderWindow()); - this->RequestRenderWindowUpdate(mitk::RenderingManager::REQUEST_UPDATE_2DWINDOWS); m_FrameCounter2d++; if (m_FrameCounter2d >= 10) { // compute framerate of 2d render window update int nMilliseconds = m_Clock2d.restart(); int fps = 10000.0f / (nMilliseconds); m_FPS2d = fps; m_FrameCounter2d = 0; } } void QmitkUltrasoundSupport::RenderImage3d() { if (!m_Controls.m_Update3DView->isChecked()) return; this->RequestRenderWindowUpdate(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS); m_FrameCounter3d++; if (m_FrameCounter3d >= 10) { // compute framerate of 2d render window update int nMilliseconds = m_Clock3d.restart(); int fps = 10000.0f / (nMilliseconds); m_FPS3d = fps; m_FrameCounter3d = 0; } } void QmitkUltrasoundSupport::OnChangedFramerateLimit() { StopTimers(); int intervalPipeline = (1000 / m_Controls.m_FrameRatePipeline->value()); int interval2D = (1000 / m_Controls.m_FrameRate2d->value()); int interval3D = (1000 / m_Controls.m_FrameRate3d->value()); SetTimerIntervals(intervalPipeline, interval2D, interval3D); StartTimers(); } void QmitkUltrasoundSupport::OnClickedFreezeButton() { if (m_Device.IsNull()) { MITK_WARN("UltrasoundSupport") << "Freeze button clicked though no device is selected."; return; } if (m_Device->GetIsFreezed()) { m_Device->SetIsFreezed(false); m_Controls.m_FreezeButton->setText("Freeze"); } else { m_Device->SetIsFreezed(true); m_Controls.m_FreezeButton->setText("Start Viewing Again"); } } void QmitkUltrasoundSupport::OnChangedActiveDevice() { //clean up, delete nodes and stop timer StopTimers(); this->RemoveControlWidgets(); for (auto& Node : m_Node) { this->GetDataStorage()->Remove(Node); Node->ReleaseData(); } m_Node.clear(); //get current device, abort if it is invalid m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService(); if (m_Device.IsNull()) { m_Controls.tabWidget->setTabEnabled(1, false); return; } //create the widgets for this device and enable the widget tab this->CreateControlWidgets(); m_Controls.tabWidget->setTabEnabled(1, true); //start timer if (m_Controls.m_RunImageTimer->isChecked()) { int intervalPipeline = (1000 / m_Controls.m_FrameRatePipeline->value()); int interval2D = (1000 / m_Controls.m_FrameRate2d->value()); int interval3D = (1000 / m_Controls.m_FrameRate3d->value()); SetTimerIntervals(intervalPipeline, interval2D, interval3D); StartTimers(); m_Controls.m_TimerWidget->setEnabled(true); } else { m_Controls.m_TimerWidget->setEnabled(false); } m_AmountOfOutputs = m_Device->GetNumberOfIndexedOutputs(); // create as many nodes and image outputs as needed UpdateAmountOfOutputs(); } void QmitkUltrasoundSupport::OnNewDeviceWidgetDone() { m_Controls.m_NewVideoDeviceWidget->setVisible(false); m_Controls.m_DeviceManagerWidget->setVisible(true); m_Controls.m_Headline->setText("Ultrasound Devices:"); m_Controls.m_WidgetActiveDevices->setVisible(true); } void QmitkUltrasoundSupport::CreateControlWidgets() { m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets); m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget); // create b mode widget for current device m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets); if (m_Device->GetControlInterfaceBMode()) { m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls"); //m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count() - 1, false); } // create doppler widget for current device m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets); if (m_Device->GetControlInterfaceDoppler()) { m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls"); //m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count() - 1, false); } ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); if (pluginContext) { std::string filter = "(org.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")"; QString interfaceName = QString::fromStdString(us_service_interface_iid()); m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter)); if (m_CustomWidgetServiceReference.size() > 0) { m_ControlCustomWidget = pluginContext->getService (m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2); m_ControlCustomWidget->SetDevice(m_Device); m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls"); } else { m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls"); m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count() - 1, false); } } // select first enabled control widget for (int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n) { if (m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n)) { m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n); break; } } } void QmitkUltrasoundSupport::RemoveControlWidgets() { if (!m_ControlProbesWidget) { return; } //widgets do not exist... nothing to do // remove all control widgets from the tool box widget while (m_Controls.m_ToolBoxControlWidgets->count() > 0) { m_Controls.m_ToolBoxControlWidgets->removeItem(0); } // remove probes widget (which is not part of the tool box widget) m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget); delete m_ControlProbesWidget; m_ControlProbesWidget = 0; delete m_ControlBModeWidget; m_ControlBModeWidget = 0; delete m_ControlDopplerWidget; m_ControlDopplerWidget = 0; // delete custom widget if it is present if (m_ControlCustomWidget) { ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); delete m_ControlCustomWidget; m_ControlCustomWidget = 0; if (m_CustomWidgetServiceReference.size() > 0) { pluginContext->ungetService(m_CustomWidgetServiceReference.at(0)); } } } void QmitkUltrasoundSupport::OnDeviceServiceEvent(const ctkServiceEvent event) { if (m_Device.IsNull() || event.getType() != static_cast(us::ServiceEvent::MODIFIED)) { return; } ctkServiceReference service = event.getServiceReference(); if (m_Device->GetManufacturer() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_MANUFACTURER)).toString().toStdString() && m_Device->GetName() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_NAME)).toString().toStdString()) { return; } if (!m_Device->GetIsActive() && m_UpdateTimer->isActive()) { StopTimers(); } if (m_CurrentDynamicRange != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DYNAMIC_RANGE)).toDouble()) { m_CurrentDynamicRange = service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DYNAMIC_RANGE)).toDouble(); UpdateLevelWindows(); } } QmitkUltrasoundSupport::QmitkUltrasoundSupport() : m_ControlCustomWidget(0), m_ControlBModeWidget(0), m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false), m_CurrentImageWidth(0), m_CurrentImageHeight(0), m_AmountOfOutputs(0), m_ForceRequestUpdateAll(false) { ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); if (pluginContext) { // to be notified about service event of an USDevice pluginContext->connectServiceListener(this, "OnDeviceServiceEvent", QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid() + ")")); } } QmitkUltrasoundSupport::~QmitkUltrasoundSupport() { try { StoreUISettings(); StopTimers(); // Get all active devicesand deactivate them to prevent freeze for (auto device : this->m_Controls.m_ActiveVideoDevices->GetAllServices()) { if (device != nullptr && device->GetIsActive()) { device->Deactivate(); device->Disconnect(); } } } catch (std::exception &e) { MITK_ERROR << "Exception during call of destructor! Message: " << e.what(); } } void QmitkUltrasoundSupport::StoreUISettings() { QSettings settings; settings.beginGroup(QString::fromStdString(VIEW_ID)); settings.setValue("DisplayImage", QVariant(m_Controls.m_ShowImageStream->isChecked())); settings.setValue("RunImageTimer", QVariant(m_Controls.m_RunImageTimer->isChecked())); settings.setValue("Update2DView", QVariant(m_Controls.m_Update2DView->isChecked())); settings.setValue("Update3DView", QVariant(m_Controls.m_Update3DView->isChecked())); settings.setValue("UpdateRatePipeline", QVariant(m_Controls.m_FrameRatePipeline->value())); settings.setValue("UpdateRate2d", QVariant(m_Controls.m_FrameRate2d->value())); settings.setValue("UpdateRate3d", QVariant(m_Controls.m_FrameRate3d->value())); settings.endGroup(); } void QmitkUltrasoundSupport::LoadUISettings() { QSettings settings; settings.beginGroup(QString::fromStdString(VIEW_ID)); m_Controls.m_ShowImageStream->setChecked(settings.value("DisplayImage", true).toBool()); m_Controls.m_RunImageTimer->setChecked(settings.value("RunImageTimer", true).toBool()); m_Controls.m_Update2DView->setChecked(settings.value("Update2DView", true).toBool()); m_Controls.m_Update3DView->setChecked(settings.value("Update3DView", true).toBool()); m_Controls.m_FrameRatePipeline->setValue(settings.value("UpdateRatePipeline", 50).toInt()); m_Controls.m_FrameRate2d->setValue(settings.value("UpdateRate2d", 20).toInt()); m_Controls.m_FrameRate3d->setValue(settings.value("UpdateRate3d", 5).toInt()); settings.endGroup(); } void QmitkUltrasoundSupport::StartTimers() { m_UpdateTimer->start(); if (m_Controls.m_Update2DView->isChecked()) { m_RenderingTimer2d->start(); } if (m_Controls.m_Update3DView->isChecked()) { m_RenderingTimer3d->start(); } } void QmitkUltrasoundSupport::StopTimers() { m_UpdateTimer->stop(); m_RenderingTimer2d->stop(); m_RenderingTimer3d->stop(); } void QmitkUltrasoundSupport::SetTimerIntervals(int intervalPipeline, int interval2D, int interval3D) { m_UpdateTimer->setInterval(intervalPipeline); m_RenderingTimer2d->setInterval(interval2D); m_RenderingTimer3d->setInterval(interval3D); } diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/documentation/UserManual/QmitkViewNavigator.dox b/Plugins/org.mitk.gui.qt.viewnavigator/documentation/UserManual/QmitkViewNavigator.dox index e3fc8577b8..15584ad31d 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/documentation/UserManual/QmitkViewNavigator.dox +++ b/Plugins/org.mitk.gui.qt.viewnavigator/documentation/UserManual/QmitkViewNavigator.dox @@ -1,43 +1,43 @@ /** -\page org_mitk_views_viewnavigatorview The View Navigator +\page org_mitk_views_viewnavigator The View Navigator \imageMacro{view-manager.png,"Icon of the view navigator",2.00} \tableofcontents -\section org_mitk_views_viewnavigatorviewOverview Overview +\section org_mitk_views_viewnavigatorOverview Overview This view allows for the easy navigation of the available views. You can select which view to open by double-clicking the name of the view in the view navigator. It provides a keyworded, grouped and searchable list of views. -\section org_mitk_views_viewnavigatorviewUsage Usage +\section org_mitk_views_viewnavigatorUsage Usage You can toggle the View Navigator on and off by clicking on its icon in the menu bar. Alternatively it is also available via the Window->Show Views dialog. \imageMacro{QmitkViewNavigatorGUI.png,"The View Navigator GUI",6.00} Once the View Navigator has been opened you will see a list divided in workflows/perspectives and views. Via this list you can access any view or perspective provided by the application. They are further organized based on their associated category. An entry on the list is opened by a double left-click. -\subsection org_mitk_views_viewnavigatorviewSearch Search +\subsection org_mitk_views_viewnavigatorSearch Search You can search the lists for view/workflow names, keywords or categories. \imageMacro{QmitkViewNavigatorSearch.png,"Search the View Navigator",4.00} -\subsection org_mitk_views_viewnavigatorviewCustomWorkflows Custom Workflows +\subsection org_mitk_views_viewnavigatorCustomWorkflows Custom Workflows \imageMacro{QmitkViewNavigatorContextMenuWorkflows.png,"The workflow context menu",4.00} A right click on a workflow opens a context menu that allows you to copy that workflow to create your own custom one. \note The duplicated workflow will look like the basic state of the original workflow. Any changes to the original workflow will not be copied. \imageMacro{QmitkViewNavigatorNewWorkflow.png,"Custom workflow creation dialog",4.00} Your new workflow will appear in the list and you can modify it independently of the original workflow. Any changes will be stored for future sessions unless the workflow is deleted. \note Resetting a custom perspective will return it to the original state after duplicating. \imageMacro{QmitkViewNavigatorContextMenuCustomWorkflow.png,"Custom workflow context menu",4.00} */ diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp index 7eb70248fd..975285c71a 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp @@ -1,716 +1,716 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // View navigator plugin #include #include #include // Blueberry #include #include #include #include #include #include #include #include // MITK #include // Qt #include #include #include #include #include class KeywordRegistry { public: KeywordRegistry() { berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry(); auto keywordExts = extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords"); for (auto keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) { QString keywordId = (*keywordExtsIt)->GetAttribute("id"); QString keywordLabels = (*keywordExtsIt)->GetAttribute("label"); m_Keywords[keywordId].push_back(keywordLabels); } } QStringList GetKeywords(const QString& id) { return m_Keywords[id]; } QStringList GetKeywords(const QStringList& ids) { QStringList result; for (const auto& id : ids) { result.append(this->GetKeywords(id)); } return result; } private: QHash m_Keywords; }; class ClassFilterProxyModel : public QSortFilterProxyModel { public: ClassFilterProxyModel(QObject* parent = nullptr) : QSortFilterProxyModel(parent) { } bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); return hasToBeDisplayed(index); } private: bool displayElement(const QModelIndex index) const { QString type = sourceModel()->data(index, Qt::DisplayRole).toString(); QStandardItem* item = dynamic_cast(sourceModel())->itemFromIndex(index); if (type.contains(filterRegExp())) { return true; } QmitkViewItem* viewItem = dynamic_cast(item); if (nullptr != viewItem) { for (const auto& tag : viewItem->m_Tags) { if (tag.contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { for (const auto& tag : perspectiveItem->m_Tags) { if (tag.contains(filterRegExp())) { return true; } } if (perspectiveItem->m_Description.contains(filterRegExp())) { return true; } } return false; } bool hasToBeDisplayed(const QModelIndex index) const { bool result = false; if (sourceModel()->rowCount(index) > 0) { for (int i = 0; i < sourceModel()->rowCount(index); i++) { QModelIndex childIndex = sourceModel()->index(i, 0, index); if (!childIndex.isValid()) { break; } result = hasToBeDisplayed(childIndex); result |= displayElement(index); if (result) { break; } } } else { result = displayElement(index); } return result; } }; class ViewNavigatorPerspectiveListener: public berry::IPerspectiveListener { public: ViewNavigatorPerspectiveListener(QmitkViewNavigatorWidget* parent) : m_ParentWidget(parent) { } Events::Types GetPerspectiveEventTypes() const override { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED | Events::PART_CHANGED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->UpdateTreeList(); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override { m_ParentWidget->UpdateTreeList(); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->m_ActivePerspective = nullptr; } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->UpdateTreeList(); } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->m_ActivePerspective = nullptr; } using IPerspectiveListener::PerspectiveChanged; void PerspectiveChanged(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/, const berry::IWorkbenchPartReference::Pointer& partRef, const std::string& changeId) { if (changeId == "viewHide" && partRef->GetId() == "org.mitk.views.viewnavigator") berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(m_ParentWidget->m_PerspectiveListener.data()); else m_ParentWidget->UpdateTreeList(); } private: QmitkViewNavigatorWidget* m_ParentWidget; }; class ViewNavigatorViewListener: public berry::IPartListener { public: ViewNavigatorViewListener(QmitkViewNavigatorWidget* parent) : m_ParentWidget(parent) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) override { if (partRef->GetId() != "org.mitk.views.viewnavigator") { m_ParentWidget->UpdateTreeList((partRef->GetPart(false)).GetPointer()); } else { m_ParentWidget->FillTreeList(); m_ParentWidget->UpdateTreeList(); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) override { if (partRef->GetId() != "org.mitk.views.viewnavigator") { m_ParentWidget->UpdateTreeList(); } } private: QmitkViewNavigatorWidget* m_ParentWidget; }; bool compareViews(const berry::IViewDescriptor::Pointer& a, const berry::IViewDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) { return false; } return a->GetLabel().compare(b->GetLabel()) < 0; } bool comparePerspectives(const berry::IPerspectiveDescriptor::Pointer& a, const berry::IPerspectiveDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) { return false; } return a->GetLabel().compare(b->GetLabel()) < 0; } bool compareQStandardItems(const QStandardItem* a, const QStandardItem* b) { if (nullptr == a || nullptr== b) { return false; } return a->text().compare(b->text()) < 0; } QmitkViewNavigatorWidget::QmitkViewNavigatorWidget(berry::IWorkbenchWindow::Pointer window, QWidget* parent, Qt::WindowFlags) : QWidget(parent) , m_Window(window) { this->CreateQtPartControl(this); } QmitkViewNavigatorWidget::~QmitkViewNavigatorWidget() { m_Window->RemovePerspectiveListener(m_PerspectiveListener.data()); m_Window->GetPartService()->RemovePartListener(m_ViewPartListener.data()); } void QmitkViewNavigatorWidget::SetFocus() { m_Controls.lineEdit->setFocus(); } void QmitkViewNavigatorWidget::UpdateTreeList(berry::IWorkbenchPart* workbenchPart) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); if (page.IsNull()) { return; } m_ActivePerspective = page->GetPerspective(); QList viewParts = page->GetViews(); // iterate over all tree items for (const auto& item : m_TreeModel->findItems("*", Qt::MatchWildcard | Qt::MatchRecursive)) { QFont font; // check if the item is a view item and if it is equal to any opened view QmitkViewItem* viewItem = dynamic_cast(item); if (nullptr != viewItem) { if (nullptr != workbenchPart && workbenchPart->GetPartName() == viewItem->m_ItemDescriptor->GetLabel()) { font.setBold(true); } else { for (const auto& viewPart : viewParts) { if (viewPart->GetPartName() == viewItem->m_ItemDescriptor->GetLabel()) { font.setBold(true); break; } } } viewItem->setFont(font); } else { // check if the item is a perspective item and if it is equal to the current perspective QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { if (m_ActivePerspective.IsNotNull() && m_ActivePerspective->GetId() == perspectiveItem->m_ItemDescriptor->GetId()) { font.setBold(true); } perspectiveItem->setFont(font); } } } } bool QmitkViewNavigatorWidget::FillTreeList() { // initialize tree model m_TreeModel->clear(); - // add all available perspectives - this->AddPerspectivesToTree(); - // add all available views this->AddViewsToTree(); + // add all available perspectives + this->AddPerspectivesToTree(); + m_Controls.m_PluginTreeView->expandAll(); return true; } void QmitkViewNavigatorWidget::FilterChanged() { QString filterString = m_Controls.lineEdit->text(); m_Controls.m_PluginTreeView->expandAll(); 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)); QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { try { berry::PlatformUI::GetWorkbench()->ShowPerspective( perspectiveItem->m_ItemDescriptor->GetId(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } catch (...) { QMessageBox::critical(nullptr, "Opening Perspective Failed", QString("The requested perspective could not be opened.\nSee the log for details.")); } return; } QmitkViewItem* viewItem = dynamic_cast(item); if (nullptr != viewItem) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { try { page->ShowView(viewItem->m_ItemDescriptor->GetId()); } catch (const berry::PartInitException& e) { BERRY_ERROR << "Error: " << e.what() << std::endl; } } } } void QmitkViewNavigatorWidget::SaveCurrentPerspectiveAs() { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer currentPerspective = page->GetPerspective(); bool ok = false; QString perspectiveLabel = QInputDialog::getText(this, "Save perspective as ...", "New perspective name:", QLineEdit::Normal, "", &ok); if (!ok) { return; } if (perspectiveLabel.isEmpty()) { QMessageBox::information(this, "Save perspective as ...", "Please select a valid perspective name."); return; } berry::IPerspectiveRegistry* perspectiveRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); berry::IPerspectiveDescriptor::Pointer newPerspective = perspectiveRegistry->CreatePerspective(perspectiveLabel, currentPerspective); if (nullptr == newPerspective) { QMessageBox::information(this, "Save perspective as ...", "The selected perspective name is already in use."); return; } page->SavePerspectiveAs(newPerspective); this->FillTreeList(); this->UpdateTreeList(); } void QmitkViewNavigatorWidget::ResetCurrentPerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to reset the current perspective?", QMessageBox::Yes | QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); page->ResetPerspective(); } } void QmitkViewNavigatorWidget::ClosePerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close the current perspective?", QMessageBox::Yes | QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } } void QmitkViewNavigatorWidget::CloseAllPerspectives() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close all perspectives?", QMessageBox::Yes | QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); page->CloseAllPerspectives(true, true); } } void QmitkViewNavigatorWidget::ExpandAll() { m_Controls.m_PluginTreeView->expandAll(); } void QmitkViewNavigatorWidget::CollapseAll() { m_Controls.m_PluginTreeView->collapseAll(); } void QmitkViewNavigatorWidget::CustomMenuRequested(QPoint pos) { QModelIndex index = m_Controls.m_PluginTreeView->indexAt(pos); QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if (nullptr == m_ContextMenu) return; m_ContextMenu->clear(); QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { berry::IPerspectiveDescriptor::Pointer perspectiveDescriptor = perspectiveItem->m_ItemDescriptor; if (this->m_ActivePerspective.IsNotNull() && this->m_ActivePerspective == perspectiveDescriptor) { QAction* saveAsAction = new QAction("Save perspective as ...", this); m_ContextMenu->addAction(saveAsAction); connect(saveAsAction, SIGNAL(triggered()), SLOT(SaveCurrentPerspectiveAs())); m_ContextMenu->addSeparator(); } } QAction* resetAction = new QAction("Reset current perspective", this); m_ContextMenu->addAction(resetAction); connect(resetAction, SIGNAL(triggered()), SLOT(ResetCurrentPerspective())); QAction* closeAction = new QAction("Close perspective", this); m_ContextMenu->addAction(closeAction); connect(closeAction, SIGNAL(triggered()), SLOT(ClosePerspective())); QAction* closeAllAction = new QAction("Close all perspectives", this); m_ContextMenu->addAction(closeAllAction); connect(closeAllAction, SIGNAL(triggered()), SLOT(CloseAllPerspectives())); m_ContextMenu->addSeparator(); QAction* expandAction = new QAction("Expand tree", this); m_ContextMenu->addAction(expandAction); connect(expandAction, SIGNAL(triggered()), SLOT(ExpandAll())); QAction* collapseAction = new QAction("Collapse tree", this); m_ContextMenu->addAction(collapseAction); connect(collapseAction, SIGNAL(triggered()), SLOT(CollapseAll())); m_ContextMenu->popup(m_Controls.m_PluginTreeView->viewport()->mapToGlobal(pos)); } void QmitkViewNavigatorWidget::CreateQtPartControl(QWidget* parent) { // active workbench window available? if (m_Window.IsNull()) { return; } m_Controls.setupUi(parent); connect(m_Controls.m_PluginTreeView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(CustomMenuRequested(QPoint))); connect(m_Controls.m_PluginTreeView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(ItemClicked(const QModelIndex&))); connect(m_Controls.lineEdit, SIGNAL(textChanged(QString)), SLOT(FilterChanged())); m_ContextMenu = new QMenu(m_Controls.m_PluginTreeView); m_Controls.m_PluginTreeView->setContextMenuPolicy(Qt::CustomContextMenu); // Create a new TreeModel for the data m_TreeModel = new QStandardItemModel(); m_FilterProxyModel = new ClassFilterProxyModel(this); m_FilterProxyModel->setSourceModel(m_TreeModel); m_Controls.m_PluginTreeView->setModel(m_FilterProxyModel); m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this)); m_Window->AddPerspectiveListener(m_PerspectiveListener.data()); m_ViewPartListener.reset(new ViewNavigatorViewListener(this)); m_Window->GetPartService()->AddPartListener(m_ViewPartListener.data()); } void QmitkViewNavigatorWidget::AddPerspectivesToTree() { berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); QList perspectiveDescriptors(perspRegistry->GetPerspectives()); qSort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); QStandardItem* perspectiveRootItem = new QStandardItem("Perspectives"); perspectiveRootItem->setFont(QFont("", 12, QFont::Normal)); perspectiveRootItem->setEditable(false); QStandardItem* treeRootItem = m_TreeModel->invisibleRootItem(); treeRootItem->appendRow(perspectiveRootItem); this->AddItemsToTree, QmitkPerspectiveItem>( perspectiveDescriptors, perspectiveRootItem); } void QmitkViewNavigatorWidget::AddViewsToTree() { berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); QList viewDescriptors(viewRegistry->GetViews()); qSort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); QStandardItem* viewRootItem = new QStandardItem("Views"); viewRootItem->setFont(QFont("", 12, QFont::Normal)); viewRootItem->setEditable(false); QStandardItem* treeRootItem = m_TreeModel->invisibleRootItem(); treeRootItem->appendRow(viewRootItem); QStandardItem* miscellaneousCategoryItem = new QStandardItem("Miscellaneous"); miscellaneousCategoryItem->setFont(QFont("", 12, QFont::Normal)); miscellaneousCategoryItem->setEditable(false); QStringList viewExcludeList; // internal view used for the intro screen, will crash when opened directly, see T22352 viewExcludeList.append(QString("org.blueberry.ui.internal.introview")); viewExcludeList.append(QString("org.mitk.views.controlvisualizationpropertiesview")); viewExcludeList.append(QString("org.mitk.views.modules")); viewExcludeList.append(QString("org.mitk.views.viewnavigator")); this->AddItemsToTree, QmitkViewItem>( viewDescriptors, viewRootItem, miscellaneousCategoryItem, viewExcludeList); } template void QmitkViewNavigatorWidget::AddItemsToTree(D itemDescriptors, QStandardItem* rootItem, QStandardItem* miscellaneousItem, const QStringList& itemExcludeList) { KeywordRegistry keywordRegistry; std::vector categoryItems; for (const auto& itemDescriptor : itemDescriptors) { bool excludeView = itemExcludeList.contains(itemDescriptor->GetId()); if (excludeView) { continue; } QIcon icon = itemDescriptor->GetImageDescriptor(); I* item = new I(icon, itemDescriptor->GetLabel()); item->m_ItemDescriptor = itemDescriptor; item->m_Description = itemDescriptor->GetDescription(); item->setToolTip(itemDescriptor->GetDescription()); QStringList keylist = itemDescriptor->GetKeywordReferences(); item->m_Tags = keywordRegistry.GetKeywords(keylist); item->setEditable(false); QStringList categoryPath = itemDescriptor->GetCategoryPath(); if (categoryPath.empty()) { // If a root item for general / non-categorized item views is given, use it. // Otherwise put the non-categorized item views into the top root item. if (nullptr != miscellaneousItem) { miscellaneousItem->appendRow(item); } else { rootItem->appendRow(item); } } else { QStandardItem* categoryItem = nullptr; for (const auto& currentCategoryItem : categoryItems) { if (currentCategoryItem->text() == categoryPath.front()) { categoryItem = currentCategoryItem; break; } } if (nullptr == categoryItem) { categoryItem = new QStandardItem(QIcon(), categoryPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setFont(QFont("", 12, QFont::Normal)); categoryItem->setEditable(false); categoryItem->appendRow(item); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (const auto& categoryItem : categoryItems) { rootItem->appendRow(categoryItem); } if (nullptr != miscellaneousItem && miscellaneousItem->hasChildren()) { rootItem->appendRow(miscellaneousItem); } }