diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp index 8624badffe..b94f5a09ee 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp @@ -1,126 +1,126 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryParameterType.h" #include "internal/berryCommandUtils.h" #include "common/berryCommandExceptions.h" #include "berryParameterTypeEvent.h" #include "berryIParameterValueConverter.h" #include namespace berry { void ParameterType::AddListener(IParameterTypeListener* listener) { parameterTypeEvents.AddListener(listener); } bool ParameterType::operator<(const Object* object) const { const ParameterType* castedObject = dynamic_cast(object); int compareTo = CommandUtils::Compare(defined, castedObject->defined); if (compareTo == 0) { compareTo = CommandUtils::Compare(id, castedObject->id); } return compareTo < 0; } void ParameterType::Define(const QString& type, const QSharedPointer& parameterTypeConverter) { const bool definedChanged = !this->defined; this->defined = true; this->type = type.isNull() ? QObject::staticMetaObject.className() : type; this->parameterTypeConverter = parameterTypeConverter; ParameterTypeEvent::Pointer event( new ParameterTypeEvent(ParameterType::Pointer(this), definedChanged)); this->FireParameterTypeChanged(event); } -#include + IParameterValueConverter* ParameterType::GetValueConverter() const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot use GetValueConverter() with an undefined ParameterType"); //$NON-NLS-1$ } return parameterTypeConverter.data(); } bool ParameterType::IsCompatible(const QObject* const value) const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot use IsCompatible() with an undefined ParameterType"); } return value->inherits(qPrintable(type)); } void ParameterType::RemoveListener(IParameterTypeListener* listener) { parameterTypeEvents.RemoveListener(listener); } QString ParameterType::ToString() const { if (str.isEmpty()) { QTextStream stringBuffer(&str); stringBuffer << "ParameterType(" << id << "," << defined << ")"; } return str; } void ParameterType::Undefine() { str = ""; const bool definedChanged = defined; defined = false; parameterTypeConverter.clear(); ParameterTypeEvent::Pointer event( new ParameterTypeEvent(ParameterType::Pointer(this), definedChanged)); this->FireParameterTypeChanged(event); } ParameterType::ParameterType(const QString& id) : HandleObject(id) { } void ParameterType::FireParameterTypeChanged(const SmartPointer< ParameterTypeEvent> event) { if (!event) { throw ctkInvalidArgumentException("Cannot send a null event to listeners."); } parameterTypeEvents.parameterTypeChanged(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp index 332ad54626..86eb8f468a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp @@ -1,152 +1,152 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryExpressionInfo.h" -#include +#include namespace berry { bool ExpressionInfo::HasDefaultVariableAccess() const { return fHasDefaultVariableAccess; } void ExpressionInfo::MarkDefaultVariableAccessed() { fHasDefaultVariableAccess= true; } bool ExpressionInfo::HasSystemPropertyAccess() const { return fHasSystemPropertyAccess; } void ExpressionInfo::MarkSystemPropertyAccessed() { fHasSystemPropertyAccess= true; } QSet ExpressionInfo::GetAccessedVariableNames() const { return fAccessedVariableNames; } void ExpressionInfo::AddVariableNameAccess(const QString &name) { fAccessedVariableNames.insert(name); } QSet ExpressionInfo::GetAccessedPropertyNames() const { return fAccessedPropertyNames; } void ExpressionInfo::AddAccessedPropertyName(const QString &name) { fAccessedPropertyNames.insert(name); } QSet ExpressionInfo::GetMisbehavingExpressionTypes() const { return fMisbehavingExpressionTypes; } void ExpressionInfo::AddMisBehavingExpressionType(const std::type_info& clazz) { - fMisbehavingExpressionTypes.insert(clazz.name()); + fMisbehavingExpressionTypes.insert(QString(clazz.name())); } void ExpressionInfo::Merge(ExpressionInfo* other) { this->MergeDefaultVariableAccess(other); this->MergeSystemPropertyAccess(other); this->MergeAccessedVariableNames(other); this->MergeAccessedPropertyNames(other); this->MergeMisbehavingExpressionTypes(other); } void ExpressionInfo::MergeExceptDefaultVariable(ExpressionInfo* other) { this->MergeSystemPropertyAccess(other); this->MergeAccessedVariableNames(other); this->MergeAccessedPropertyNames(other); this->MergeMisbehavingExpressionTypes(other); } void ExpressionInfo::MergeDefaultVariableAccess(ExpressionInfo* other) { fHasDefaultVariableAccess= fHasDefaultVariableAccess || other->fHasDefaultVariableAccess; } void ExpressionInfo::MergeSystemPropertyAccess(ExpressionInfo* other) { fHasSystemPropertyAccess= fHasSystemPropertyAccess || other->fHasSystemPropertyAccess; } void ExpressionInfo::MergeAccessedVariableNames(ExpressionInfo* other) { if (fAccessedVariableNames.size() == 0) { fAccessedVariableNames= other->fAccessedVariableNames; } else { fAccessedVariableNames.unite(other->fAccessedVariableNames); } } void ExpressionInfo::MergeAccessedPropertyNames(ExpressionInfo* other) { if (fAccessedPropertyNames.size() == 0) { fAccessedPropertyNames = other->fAccessedPropertyNames; } else { fAccessedPropertyNames.unite(other->fAccessedPropertyNames); } } void ExpressionInfo::MergeMisbehavingExpressionTypes(ExpressionInfo* other) { if (fMisbehavingExpressionTypes.size() == 0) { fMisbehavingExpressionTypes= other->fMisbehavingExpressionTypes; } else { fMisbehavingExpressionTypes.unite(other->fMisbehavingExpressionTypes); } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp index 615f0cebb2..e4e1aeaf0a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp @@ -1,59 +1,61 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryExpressionPlugin.h" #include namespace berry { QObject* ExpressionPlugin::m_PluginListener = NULL; ExpressionPlugin* ExpressionPlugin::m_Default = NULL; ExpressionPlugin::ExpressionPlugin() { m_Default = this; } ExpressionPlugin* ExpressionPlugin::GetDefault() { return m_Default; } QString ExpressionPlugin::GetPluginId() { return "org.blueberry.core.expressions"; } void ExpressionPlugin::stop(ctkPluginContext* context) { if (m_PluginListener != NULL) { context->disconnectPluginListener(m_PluginListener); } m_PluginListener = NULL; Plugin::stop(context); } ctkPluginContext* ExpressionPlugin::GetPluginContext() const { return m_Context; } } -Q_EXPORT_PLUGIN2(org_blueberry_core_expressions, berry::ExpressionPlugin) +#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) + Q_EXPORT_PLUGIN2(org_blueberry_core_expressions, berry::ExpressionPlugin) +#endif diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt b/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt index 2944414751..32f6774ed7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt @@ -1,38 +1,45 @@ project(org_blueberry_core_runtime) set(QT_USE_QTXML 1) MACRO_CREATE_CTK_PLUGIN(EXPORT_DIRECTIVE org_blueberry_core_runtime_EXPORT EXPORTED_INCLUDE_SUFFIXES src src/application src/service src/registry) target_link_libraries(${PLUGIN_TARGET} PUBLIC Poco::Foundation Poco::Util Poco::XML) +if(MITK_USE_Qt5) + target_link_libraries(${PLUGIN_TARGET} PRIVATE Qt5::Gui Qt5::Xml) +endif() # Set compiler flags target_compile_definitions(${PLUGIN_TARGET} PUBLIC "$<$:POCO_NO_UNWINDOWS;WIN32_LEAN_AND_MEAN>") add_executable(${OSGI_APP} MACOSX_BUNDLE "src/application/berryMain.cpp") target_link_libraries(${OSGI_APP} PRIVATE ${PROJECT_NAME} mbilog) if(_ctk_test_plugins) add_dependencies(${OSGI_APP} ${_ctk_test_plugins}) add_dependencies(BlueBerry ${OSGI_APP}) set_property(TARGET ${OSGI_APP} APPEND PROPERTY LABELS BlueBerry) endif() configure_file(src/application/solstice.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_APP}.ini) add_executable(${OSGI_UI_APP} MACOSX_BUNDLE "src/application/berryMainUI.cpp") target_link_libraries(${OSGI_UI_APP} PRIVATE ${PROJECT_NAME} mbilog) +if(MITK_USE_Qt5) + target_link_libraries(${OSGI_UI_APP} PRIVATE Qt5::Widgets) +endif() + if(_ctk_test_plugins) add_dependencies(${OSGI_UI_APP} ${_ctk_test_plugins}) add_dependencies(BlueBerry ${OSGI_UI_APP}) set_property(TARGET ${OSGI_UI_APP} APPEND PROPERTY LABELS BlueBerry) endif() configure_file(src/application/solstice.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_UI_APP}.ini) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/berryConfig.h.in" "${CMAKE_CURRENT_BINARY_DIR}/berryConfig.h" @ONLY) diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp index c93f129407..b55ab7ab43 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp @@ -1,308 +1,322 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryObject.h" #ifdef BLUEBERRY_DEBUG_SMARTPOINTER #include "berryDebugUtil.h" #endif #include "berryLog.h" #include #include #include #include // Better name demangling for gcc #if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 ) #define GCC_USEDEMANGLE #endif #ifdef GCC_USEDEMANGLE #include #include #endif #if defined(_WIN32) && defined(NDEBUG) // exported from VC CRT extern "C" char * __unDName(char * outputString, const char * name, int maxStringLength, void * (* pAlloc )(size_t), void (* pFree )(void *), unsigned short disableFlags); #endif namespace berry { void Object::Delete() { this->UnRegister(); } QString Object::DemangleName(const char* mangledName) { QString name(mangledName); #ifdef GCC_USEDEMANGLE int status; char* unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status); if(status == 0) { name = QString(unmangled); free(unmangled); } #elif defined(_WIN32) && defined(NDEBUG) char * const unmangled = __unDName(0, mangledName, 0, malloc, free, 0x2800); if (unmangled) { name = QString(unmangled); free(unmangled); } #endif return name; } #ifdef _WIN32 void* Object ::operator new(size_t n) { return new char[n]; } void* Object ::operator new[](size_t n) { return new char[n]; } void Object ::operator delete(void* m) { delete [] (char*)m; } void Object ::operator delete[](void* m, size_t) { delete [] (char*)m; } #endif const char* Object::GetStaticClassName() { return "berry::Object"; } QString Object::GetClassName() const { return DemangleName(typeid(*this).name()); } QDebug Object::Print(QDebug os, Indent indent) const { os = this->PrintHeader(os, indent); os = this->PrintSelf(os, indent.GetNextIndent()); return this->PrintTrailer(os, indent); } QString Object::ToString() const { QString str; QDebug ss(&str); this->Print(ss); return str; } uint Object::HashCode() const { return qHash(this); } bool Object::operator<(const Object* o) const { return this < o; } void Object::Register() const { m_ReferenceCount.ref(); } void Object::UnRegister(bool del) const { if (!m_ReferenceCount.deref() && del) { delete this; } } void Object::SetReferenceCount(int ref) { QMutexLocker lock(&m_ReferenceCountLock); +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + m_ReferenceCount.store(ref); +#else m_ReferenceCount = ref; +#endif if (ref == 0) { delete this; } } bool Object::operator==(const Object* o) const { return this == o; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER unsigned int Object::GetTraceId() const { return m_TraceId; } unsigned int& Object::GetTraceIdCounter() const { static unsigned int traceId = 0; return traceId; } #endif Object::Object() : m_ReferenceCount(0) { #ifdef BLUEBERRY_DEBUG_SMARTPOINTER unsigned int& id = GetTraceIdCounter(); m_TraceId = ++id; DebugUtil::RegisterObject(this); #endif } Object::~Object() { /** * warn user if reference counting is on and the object is being referenced * by another object. */ +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + if (m_ReferenceCount.load() > 0) +#else if (m_ReferenceCount > 0) +#endif { // A general exception safety rule is that destructors should // never throw. Something is wrong with a program that reaches // this point anyway. Also this is the least-derived class so the // whole object has been destroyed by this point anyway. Just // issue a warning. BERRY_WARN << "WARNING: In " __FILE__ ", line " << __LINE__ << "\n" << this->GetClassName() << " (" << this << "): Trying to delete object with non-zero reference count."; } /** * notifies the registered functions that the object is being destroyed */ m_DestroyMessage.Send(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::UnregisterObject(this); #endif } QDebug Object::PrintSelf(QDebug os, Indent Indent) const { QString demangledName = DemangleName(typeid(*this).name()); os << Indent << "RTTI typeinfo: " << demangledName << '\n'; - os << Indent << "Reference Count: " << m_ReferenceCount << '\n'; + os << Indent << "Reference Count: " << +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + m_ReferenceCount.load() +#else + m_ReferenceCount +#endif + << '\n'; return os; } /** * Define a default print header for all objects. */ QDebug Object::PrintHeader(QDebug os, Indent Indent) const { os << Indent << this->GetClassName() << " (" << this << ")\n"; return os; } /** * Define a default print trailer for all objects. */ QDebug Object::PrintTrailer(QDebug os, Indent /*Indent*/) const { return os; } // ============== Indent related implementations ============== static const char blanks[41] = " "; Indent Indent::GetNextIndent() { int Indent = m_Indent + 2; if (Indent > 40) { Indent = 40; } return Indent; } QDebug operator<<(QDebug os, const berry::Indent& ind) { os.nospace() << blanks + (40 - ind.m_Indent); return os; } } // namespace berry QDebug operator<<(QDebug os, const berry::Object& o) { return o.Print(os); } QDebug operator<<(QDebug os, const berry::SmartPointer& o) { return o->Print(os); } QDebug operator<<(QDebug os, const berry::SmartPointer& o) { return o->Print(os); } QTextStream& operator<<(QTextStream& os, const berry::Object& o) { os << o.ToString(); return os; } QTextStream& operator<<(QTextStream& os, const berry::SmartPointer& o) { os << o->ToString(); return os; } //QTextStream& operator<<(QTextStream& os, const berry::SmartPointer& o) //{ // os << o->ToString(); // return os; //} uint qHash(const berry::Object& o) { return o.HashCode(); } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp index 235ccb5ea6..fbdd25eecd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp @@ -1,57 +1,57 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryObjectString.h" namespace berry { ObjectString::ObjectString() {} ObjectString::ObjectString(const QString& s) : QString(s) {} bool ObjectString::operator==(const Object* other) const { if (const ObjectString* otherStr = dynamic_cast(other)) { - return QString::operator ==(*otherStr); + return static_cast(*this) == static_cast(*otherStr); } return false; } bool ObjectString::operator==(const QString& other) const { - return QString::operator==(other); + return static_cast(*this) == other; } QString ObjectString::ToString() const { return *this; } ObjectString::~ObjectString() { } berry::ObjectString &berry::ObjectString::operator =(const QString &other) { QString::operator =(other); return *this; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp index 991041e7a6..423418f7a4 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp @@ -1,221 +1,223 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryCTKPluginActivator.h" #include "berryPlatform.h" #include "berryInternalPlatform.h" //#include "berryCTKPluginListener_p.h" #include "berryPreferencesService.h" #include "berryExtensionRegistry.h" #include "berryRegistryConstants.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include #include #include namespace berry { ctkPluginContext* org_blueberry_core_runtime_Activator::context = 0; void org_blueberry_core_runtime_Activator::start(ctkPluginContext* context) { this->context = context; RegistryProperties::SetContext(context); //ProcessCommandLine(); this->startRegistry(); preferencesService.reset(new PreferencesService(context->getDataFile("").absolutePath())); prefServiceReg = context->registerService(preferencesService.data()); // // register a listener to catch new plugin installations/resolutions. // pluginListener.reset(new CTKPluginListener(m_ExtensionPointService)); // context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // // populate the registry with all the currently installed plugins. // // There is a small window here while processPlugins is being // // called where the pluginListener may receive a ctkPluginEvent // // to add/remove a plugin from the registry. This is ok since // // the registry is a synchronized object and will not add the // // same bundle twice. // pluginListener->processPlugins(context->getPlugins()); } void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) //pluginListener.reset(); //Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID); prefServiceReg.unregister(); preferencesService->ShutDown(); preferencesService.reset(); prefServiceReg = 0; this->stopRegistry(); RegistryProperties::SetContext(NULL); this->context = 0; } ctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext() { return context; } #if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) || defined(Q_CC_MINGW) #include QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == NULL) return QString(); Dl_info info = {0,0,0,0}; if(dladdr(symbol, &info) == 0) { return QString(); } else if(info.dli_fname) { QFile soPath(info.dli_fname); int index = soPath.fileName().lastIndexOf('.'); QString pluginId = soPath.fileName().left(index); if (pluginId.startsWith("lib")) pluginId = pluginId.mid(3); return pluginId.replace('_', '.'); } return QString(); } #elif defined(Q_CC_MSVC) #include #include #include QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == NULL) return QString(); if (ctk::DebugSymInitialize()) { std::vector moduleBuffer(sizeof(IMAGEHLP_MODULE64)); PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front(); pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64); if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo)) { QString pluginId = pModuleInfo->ModuleName; return pluginId.replace('_', '.'); } } return QString(); } #endif org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator() : userRegistryKey(new QObject()) , masterRegistryKey(new QObject()) { } org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator() { } void org_blueberry_core_runtime_Activator::startRegistry() { // see if the customer suppressed the creation of default registry QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString(); if (property.compare("false", Qt::CaseInsensitive) == 0) return; // check to see if we need to use null as a userToken if (context->getProperty(RegistryConstants::PROP_REGISTRY_NULL_USER_TOKEN).toString().compare("true", Qt::CaseInsensitive) == 0) { userRegistryKey.reset(0); } // Determine primary and alternative registry locations. BlueBerry extension registry cache // can be found in one of the two locations: // a) in the local configuration area (standard location passed in by the platform) -> priority // b) in the shared configuration area (typically, shared install is used) QList registryLocations; QList readOnlyLocations; RegistryStrategy* strategy = NULL; //Location configuration = OSGIUtils.getDefault().getConfigurationLocation(); QString configuration = context->getDataFile("").absoluteFilePath(); if (configuration.isEmpty()) { RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, "true"); RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_CACHE_LOADING, "true"); strategy = new RegistryStrategy(QList(), QList(), masterRegistryKey.data()); } else { //File primaryDir = new File(configuration.getURL().getPath() + '/' + STORAGE_DIR); //bool primaryReadOnly = configuration.isReadOnly(); QString primaryDir = configuration; bool primaryReadOnly = false; //Location parentLocation = configuration.getParentLocation(); QString parentLocation; if (!parentLocation.isEmpty()) { // File secondaryDir = new File(parentLocation.getURL().getFile() + '/' + IRegistryConstants.RUNTIME_NAME); // registryLocations << primaryDir << secondaryDir; // readOnlyLocations << primaryReadOnly << true; // secondary BlueBerry location is always read only } else { registryLocations << primaryDir; readOnlyLocations << primaryReadOnly; } strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data()); } ExtensionRegistry* registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data()); defaultRegistry.reset(registry); registryServiceReg = context->registerService(registry); //commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext()); } void org_blueberry_core_runtime_Activator::stopRegistry() { if (!defaultRegistry.isNull()) { registryServiceReg.unregister(); defaultRegistry->Stop(masterRegistryKey.data()); } // if (!commandRegistration.isNull()) // { // commandRegistration.unregister(); // } } } -Q_EXPORT_PLUGIN2(org_blueberry_core_runtime, berry::org_blueberry_core_runtime_Activator) +#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) + Q_EXPORT_PLUGIN2(org_blueberry_core_runtime, berry::org_blueberry_core_runtime_Activator) +#endif diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h index cedb78f70d..de5679f01f 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h @@ -1,81 +1,81 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYCTKPLUGINACTIVATOR_H #define BERRYCTKPLUGINACTIVATOR_H #include #include #include namespace berry { //class CTKPluginListener; class PreferencesService; struct IExtensionRegistry; class org_blueberry_core_runtime_Activator : public QObject, public ctkPluginActivator { Q_OBJECT -#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - Q_PLUGIN_METADATA(IID "org_blueberry_osgi") +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + Q_PLUGIN_METADATA(IID "org_blueberry_core_runtime") #endif Q_INTERFACES(ctkPluginActivator) public: org_blueberry_core_runtime_Activator(); ~org_blueberry_core_runtime_Activator(); void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static ctkPluginContext* getPluginContext(); /** * Returns the plug-in id of the plug-in that contains the provided symbol, or * a null QString if the plug-in could not be determined. */ static QString getPluginId(void* symbol); private: void startRegistry(); void stopRegistry(); static ctkPluginContext* context; //QScopedPointer pluginListener; QScopedPointer preferencesService; ctkServiceRegistration prefServiceReg; QScopedPointer defaultRegistry; ctkServiceRegistration registryServiceReg; QScopedPointer userRegistryKey; QScopedPointer masterRegistryKey; }; typedef org_blueberry_core_runtime_Activator CTKPluginActivator; } #endif // BERRYCTKPLUGINACTIVATOR_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp index b98281bf9a..7d35c5c3f0 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp @@ -1,272 +1,272 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryRegistryStrategy.h" #include "berryCoreException.h" #include "berryCTKPluginListener.h" #include "berryExtensionRegistry.h" #include "berryExtensionType.h" #include "berryRegistryConstants.h" #include "berryRegistryContributor.h" #include "berryRegistryMessages.h" #include "berryRegistrySupport.h" #include "berryStatus.h" #include "berryLog.h" #include "berryCTKPluginActivator.h" #include "berryCTKPluginUtils.h" #include #include #include #include #include #include namespace berry { RegistryStrategy::RegistryStrategy(const QList& storageDirs, const QList& cacheReadOnly, QObject* key) : storageDirs(storageDirs), cacheReadOnly(cacheReadOnly), token(key), trackTimestamp(false) { // Only do timestamp calculations if osgi.checkConfiguration is set to "true" (typically, // this implies -dev mode) ctkPluginContext* context = org_blueberry_core_runtime_Activator::getPluginContext(); if (context) { trackTimestamp = context->getProperty(RegistryConstants::PROP_CHECK_CONFIG).toString().compare("true", Qt::CaseInsensitive) == 0; } } RegistryStrategy::~RegistryStrategy() { } int RegistryStrategy::GetLocationsLength() const { return storageDirs.size(); } QString RegistryStrategy::GetStorage(int index) const { return storageDirs[index]; } bool RegistryStrategy::IsCacheReadOnly(int index) const { if (!cacheReadOnly.empty()) return cacheReadOnly[index]; return true; } void RegistryStrategy::Log(const SmartPointer& status) { RegistrySupport::Log(status, QString()); } QString RegistryStrategy::Translate(const QString& key, QTranslator* resources) { return RegistrySupport::Translate(key, resources); } void RegistryStrategy::OnStart(IExtensionRegistry* reg, bool loadedFromCache) { ExtensionRegistry* registry = dynamic_cast(reg); if (registry == NULL) return; // register a listener to catch new plugin installations/resolutions. pluginListener.reset(new CTKPluginListener(registry, token, this)); org_blueberry_core_runtime_Activator::getPluginContext()->connectPluginListener( pluginListener.data(), SLOT(PluginChanged(ctkPluginEvent)), Qt::DirectConnection); // populate the registry with all the currently installed plugins. // There is a small window here while ProcessPlugins is being // called where the pluginListener may receive a ctkPluginEvent // to add/remove a plugin from the registry. This is ok since // the registry is a synchronized object and will not add the // same bundle twice. if (!loadedFromCache) pluginListener->ProcessPlugins(org_blueberry_core_runtime_Activator::getPluginContext()->getPlugins()); } void RegistryStrategy::OnStop(IExtensionRegistry* /*registry*/) { if (!pluginListener.isNull()) { org_blueberry_core_runtime_Activator::getPluginContext()->disconnectPluginListener(pluginListener.data()); } } QObject* RegistryStrategy::CreateExecutableExtension(const SmartPointer& contributor, const QString& className, const QString& /*overridenContributorName*/) { QObject* result = NULL; QSharedPointer plugin = CTKPluginUtils::GetDefault()->GetPlugin(contributor->GetName()); if (!plugin.isNull()) { // immediately start the plugin but do not change the plugins autostart setting plugin->start(ctkPlugin::START_TRANSIENT); } else { QString message = QString("Unable to find plugin \"%1\" for contributor \"%2\".") .arg(contributor->GetName()).arg(contributor->GetActualName()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } QString typeName = contributor->GetActualName() + "_" + className; - int extensionTypeId = ExtensionType::type(typeName.toAscii().data()); + int extensionTypeId = ExtensionType::type(typeName.toLatin1().data()); if (extensionTypeId == 0) { QString message = QString("Unable to find class \"%1\" from contributor \"%2\"." " The class was either not registered via " "BERRY_REGISTER_EXTENSION_CLASS(type, pluginContext) " "or you forgot to run Qt's moc on the header file.") .arg(className).arg(contributor->GetActualName()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } else { try { result = ExtensionType::construct(extensionTypeId); } catch (const ctkException& e) { QString message = QString("Contributor \"%1\" was unable to instantiate class \"%2\".") .arg(contributor->GetActualName()).arg(className); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, e, BERRY_STATUS_LOC)); throw CoreException(status); } catch (const std::exception& e) { QString message = QString("Contributor \"%1\" was unable to instantiate class \"%2\". Error: \"%3\"") .arg(contributor->GetActualName()).arg(className).arg(QString(e.what())); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } } return result; } //void RegistryStrategy::ScheduleChangeEvent(const QList& listeners, // const QHash& deltas, // IExtensionRegistry* registry) //{ // if (ExtensionRegistry* extRegistry = dynamic_cast(registry)) // extRegistry->ScheduleChangeEvent(listeners, deltas); //} //SmartPointer RegistryStrategy::ProcessChangeEvent(const QList& listeners, // const QHash& deltas, // IExtensionRegistry* registry) //{ // if (ExtensionRegistry* extRegistry = dynamic_cast(registry)) // return extRegistry->ProcessChangeEvent(listeners, deltas); // return IStatus::Pointer(); //} bool RegistryStrategy::Debug() const { return false; } bool RegistryStrategy::DebugRegistryEvents() const { return false; } bool RegistryStrategy::CacheUse() const { return true; } bool RegistryStrategy::CacheLazyLoading() const { return true; } long RegistryStrategy::GetContainerTimestamp() const { return 0; } long RegistryStrategy::GetContributionsTimestamp() const { return 0; } bool RegistryStrategy::CheckContributionsTimestamp() const { return trackTimestamp; } long RegistryStrategy::GetExtendedTimestamp(const QSharedPointer& plugin, const QString& pluginManifest) const { if (pluginManifest.isEmpty()) return 0; // The plugin manifest does not have a timestamp as it is embedded into // the plugin itself. Try to get the timestamp of the plugin instead. QFileInfo pluginInfo(QUrl(plugin->getLocation()).toLocalFile()); if (pluginInfo.exists()) { return ctk::msecsTo(QDateTime::fromTime_t(0), pluginInfo.lastModified()) + plugin->getPluginId(); //return pluginManifest.openConnection().getLastModified() + bundle.getBundleId(); } else { if (Debug()) { BERRY_DEBUG << "Unable to obtain timestamp for the plugin " << plugin->getSymbolicName(); } return 0; } } QXmlReader* RegistryStrategy::GetXMLParser() const { if (theXMLParser.isNull()) { theXMLParser.reset(new QXmlSimpleReader()); } return theXMLParser.data(); } QList RegistryStrategy::Translate(const QList& nonTranslated, const SmartPointer& /*contributor*/, const QLocale& /*locale*/) { return nonTranslated; } QLocale RegistryStrategy::GetLocale() const { return QLocale(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp index 23e76d1407..48b5f29083 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,735 +1,749 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryCommandContributionItem.h" #include "berryIMenuService.h" #include "berryICommandService.h" #include "berryICommandImageService.h" #include "berryIContributionManager.h" #include "berryIElementReference.h" #include "berryIElementUpdater.h" #include "berryUIElement.h" #include #include #include #include #include #include #include #include "../berryDisplay.h" #include "../berryAsyncRunnable.h" #include "../handlers/berryIHandlerService.h" #include "../services/berryIServiceLocator.h" #include "../internal/berryCommandContributionItemParameter.h" #include "../internal/berryWorkbenchPlugin.h" #include #include #include #include +#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0)) +#include +#endif + namespace berry { ContributionItem::Modes CommandContributionItem::modes = ContributionItem::MODE_FORCE_TEXT; //class CommandUIElementListener : public IUIElementListener //{ //private: // CommandContributionItem* item; // public: // CommandUIElementListener(CommandContributionItem* item); // void UIElementDisposed(UIElement* item); //void UIElementSelected(SmartPointer item); //}; CommandContributionItem::CommandContributionItem( const SmartPointer& contributionParameters) : ContributionItem(contributionParameters->id) , action(0) , checkedState(false) { this->icon = contributionParameters->icon; this->label = contributionParameters->label; this->mnemonic = contributionParameters->mnemonic; this->tooltip = contributionParameters->tooltip; this->style = contributionParameters->style; this->helpContextId = contributionParameters->helpContextId; this->visibleEnabled = contributionParameters->visibleEnabled; this->mode = contributionParameters->mode; menuService = contributionParameters->serviceLocator->GetService(); commandService = contributionParameters->serviceLocator->GetService(); handlerService = contributionParameters->serviceLocator->GetService(); // bindingService = (IBindingService) contributionParameters.serviceLocator // .getService(IBindingService.class); this->CreateCommand(contributionParameters->commandId, contributionParameters->parameters); if (command) { try { class CommandUIElement : public UIElement { private: CommandContributionItem* item; public: CommandUIElement(CommandContributionItem* item, IServiceLocator* serviceLocator) : UIElement(serviceLocator), item(item) {} void SetText(const QString& text) { item->SetText(text); } void SetToolTip(const QString& text) { item->SetToolTip(text); } void SetIcon(const QIcon& icon) { item->SetIcon(icon); } void SetChecked(bool checked) { item->SetChecked(checked); } void SetDropDownId(const QString& id) { item->dropDownMenuOverride = id; } }; UIElement::Pointer callback(new CommandUIElement(this, contributionParameters->serviceLocator)); elementRef = commandService->RegisterElementForCommand(command, callback); command->GetCommand()->AddCommandListener(this->GetCommandListener()); this->SetImages(contributionParameters->serviceLocator, contributionParameters->iconStyle); if (contributionParameters->helpContextId.isEmpty()) { try { this->helpContextId = commandService->GetHelpContextId( contributionParameters->commandId); } catch (const NotDefinedException& /*e*/) { // it's OK to not have a helpContextId } } // IWorkbenchLocationService::Pointer wls = contributionParameters.serviceLocator // ->GetService(IWorkbenchLocationService::GetManifestName()).Cast(); // const IWorkbench* workbench = wls->GetWorkbench();; // if (workbench != 0 && !helpContextId.empty()) { // this->workbenchHelpSystem = workbench->GetHelpSystem(); // } } catch (const NotDefinedException& /*e*/) { WorkbenchPlugin::Log(QString("Unable to register menu item \"") + this->GetId() + "\", command \"" + contributionParameters->commandId + "\" not defined"); } } } QAction* CommandContributionItem::Fill(QMenu* parent, QAction* before) { if (!command) { return 0; } if (action || parent == 0) { return 0; } // Menus don't support the pulldown style Style tmpStyle = style; if (tmpStyle == STYLE_PULLDOWN) tmpStyle = STYLE_PUSH; QAction* item = 0; if (before) { item = new QAction(icon, label, parent); parent->insertAction(before, item); } else { item = parent->addAction(icon, label); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(item, helpContextId); // } connect(item, SIGNAL(triggered()), this, SLOT(HandleWidgetSelection())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); return item; } QAction *CommandContributionItem::Fill(QToolBar *parent, QAction *before) { if (!command) { return 0; } if (action || parent == 0) { return 0; } QAction* item = 0; if (before) { item = parent->addAction(icon, label); } else { item = new QAction(icon, label, parent); parent->insertAction(before, item); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); //item->AddListener(this->GetItemListener()); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); return item; } void CommandContributionItem::Update() { this->Update(QString()); } void CommandContributionItem::Update(const QString& /*id*/) { if (action) { QWidget* parent = action->parentWidget(); if(qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateToolItem(); } } } void CommandContributionItem::UpdateMenuItem() { QString text = label; if (text.isEmpty()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } text = UpdateMnemonic(text); // String keyBindingText = null; // if (command != null) // { // TriggerSequence binding = bindingService // .getBestActiveBindingFor(command); // if (binding != null) // { // keyBindingText = binding.format(); // } // } // if (text != null) // { // if (keyBindingText == null) // { // item.setText(text); // } // else // { // item.setText(text + '\t' + keyBindingText); // } // } if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } void CommandContributionItem::UpdateToolItem() { QString text = label; QString tooltip = label; if (text.isNull()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); tooltip = command->GetCommand()->GetDescription(); if (tooltip.trimmed().isEmpty()) { tooltip = text; } } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } if ((icon.isNull() || (mode & MODE_FORCE_TEXT) == MODE_FORCE_TEXT) && !text.isNull()) { action->setText(text); } QString toolTipText = GetToolTipText(tooltip); action->setToolTip(toolTipText); if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } CommandContributionItem::~CommandContributionItem() { if (elementRef) { commandService->UnregisterElement(elementRef); } if (commandListener) { command->GetCommand()->RemoveCommandListener(commandListener.data()); } } bool CommandContributionItem::IsEnabled() const { if (command) { command->GetCommand()->SetEnabled(menuService->GetCurrentState()); return command->GetCommand()->IsEnabled(); } return false; } bool CommandContributionItem::IsVisible() const { if (visibleEnabled) { return ContributionItem::IsVisible() && this->IsEnabled(); } return ContributionItem::IsVisible(); } void CommandContributionItem::SetImages(IServiceLocator* locator, const QString& iconStyle) { if (icon.isNull()) { ICommandImageService* service = locator->GetService(); if (service) { icon = service->GetImage(command->GetId(), iconStyle); } } } ICommandListener* CommandContributionItem::GetCommandListener() { if (!commandListener) { class MyCommandListener : public ICommandListener { private: CommandContributionItem* item; public: MyCommandListener(CommandContributionItem* item) : item(item) {} void CommandChanged(const SmartPointer& commandEvent) { if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged() || commandEvent->IsDefinedChanged()) { item->UpdateCommandProperties(commandEvent); } } }; commandListener.reset(new MyCommandListener(this)); } return commandListener.data(); } void CommandContributionItem::UpdateCommandProperties(const SmartPointer< const CommandEvent> commandEvent) { if (commandEvent->IsHandledChanged()) { dropDownMenuOverride = ""; } if (!action) { return; } Display* display = Display::GetDefault(); typedef AsyncRunnable, CommandContributionItem > UpdateRunnable; Poco::Runnable* update = new UpdateRunnable(this, &CommandContributionItem::UpdateCommandPropertiesInUI, commandEvent); if (display->InDisplayThread()) { update->run(); } else { display->AsyncExec(update); } } void CommandContributionItem::UpdateCommandPropertiesInUI(const SmartPointer< const CommandEvent>& commandEvent) { if (commandEvent->GetCommand()->IsDefined()) { this->Update(); } if (commandEvent->IsEnabledChanged() || commandEvent->IsHandledChanged()) { if (visibleEnabled) { IContributionManager* parent = this->GetParent(); if (parent) { parent->Update(true); } } } } bool CommandContributionItem::ShouldRestoreAppearance(const SmartPointer& handler) { // if no handler or handler doesn't implement IElementUpdater, // restore the contributed elements if (handler.IsNull()) return true; if (!(handler.Cast())) return true; // special case, if its HandlerProxy, then check the actual handler // if (handler instanceof HandlerProxy) { // HandlerProxy handlerProxy = (HandlerProxy) handler; // IHandler actualHandler = handlerProxy.getHandler(); // return shouldRestoreAppearance(actualHandler); // } return false; } SmartPointer CommandContributionItem::GetCommand() const { return command; } void CommandContributionItem::CreateCommand(const QString &commandId, const QHash ¶meters) { if (commandId.isEmpty()) { // StatusManager.getManager().handle(StatusUtil.newStatus(IStatus.ERROR, // "Unable to create menu item \"" + getId() // + "\", no command id", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", no command id"; return; } Command::Pointer cmd = commandService->GetCommand(commandId); if (!cmd->IsDefined()) { // StatusManager.getManager().handle(StatusUtil.newStatus( // IStatus.ERROR, "Unable to create menu item \"" + getId() // + "\", command \"" + commandId + "\" not defined", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", command \"" << commandId.toStdString() << "\" not defined"; return; } command = ParameterizedCommand::GenerateCommand(cmd, parameters); } QString CommandContributionItem::GetToolTipText(const QString& text) const { QString tooltipText = tooltip; if (tooltip.isNull()) { if (!text.isNull()) { tooltipText = text; } else { tooltipText = ""; } } // TriggerSequence activeBinding = bindingService // .getBestActiveBindingFor(command); // if (activeBinding != null && !activeBinding.isEmpty()) // { // String acceleratorText = activeBinding.format(); // if (acceleratorText != null // && acceleratorText.length() != 0) // { // tooltipText = NLS.bind(CommandMessages.Tooltip_Accelerator, // tooltipText, acceleratorText); // } // } return tooltipText; } QString CommandContributionItem::UpdateMnemonic(const QString &s) { if (mnemonic.isNull() || s.isEmpty()) { return s; } int idx = s.indexOf(mnemonic); if (idx == -1) { return s; } return s.left(idx) + '&' + s.mid(idx); } //SmartPointer CommandContributionItem::GetItemListener() //{ // if (!itemListener) // { // itemListener = new CommandUIElementListener(this); // } // return itemListener; //} void CommandContributionItem::HandleWidgetSelection() { // // Special check for ToolBar dropdowns... // if (this->OpenDropDownMenu(event)) // //return; if ((style & STYLE_CHECK) != 0) { checkedState = action->isChecked(); } try { handlerService->ExecuteCommand(command, UIElement::Pointer(0)); } catch (const ExecutionException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotDefinedException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotEnabledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotHandledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } } +#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) void CommandContributionItem::connectNotify(const char *signal) { qDebug() << "Connected to:" << signal; } - void CommandContributionItem::disconnectNotify(const char *signal) { qDebug() << "Disconnected from:" << signal; } +#else +void CommandContributionItem::connectNotify(const QMetaMethod& signal) +{ + qDebug() << "Connected to:" << signal.name(); +} +void CommandContributionItem::disconnectNotify(const QMetaMethod& signal) +{ + qDebug() << "Disconnected from:" << signal.name(); +} +#endif //TODO Tool item drop down menu contributions //bool CommandContributionItem::OpenDropDownMenu(SmartPointer event) //{ //Widget item = event.widget; //if (item != null) //{ // int style = item.getStyle(); // if ((style & SWT.DROP_DOWN) != 0) // { // if (event.detail == 4) // { // on drop-down button // ToolItem ti = (ToolItem) item; // // final MenuManager menuManager = new MenuManager(); // Menu menu = menuManager.createContextMenu(ti.getParent()); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(menu, helpContextId); // } // menuManager.addMenuListener(new IMenuListener() // { // public void menuAboutToShow(IMenuManager manager) // { // String id = getId(); // if (dropDownMenuOverride != null) // { // id = dropDownMenuOverride; // } // menuService.populateContributionManager( // menuManager, "menu:" + id); //$NON-NLS-1$ // } // }); // // // position the menu below the drop down item // Point point = ti.getParent().toDisplay( // new Point(event.x, event.y)); // menu.setLocation(point.x, point.y); // waiting for SWT // // 0.42 // menu.setVisible(true); // return true; // we don't fire the action // } // } //} // //return false; //} void CommandContributionItem::SetIcon(const QIcon &icon) { this->icon = icon; this->UpdateIcons(); } void CommandContributionItem::UpdateIcons() { action->setIcon(icon); } void CommandContributionItem::SetText(const QString &text) { label = text; this->Update(); } void CommandContributionItem::SetChecked(bool checked) { if (checkedState == checked) { return; } checkedState = checked; action->setChecked(checkedState); } void CommandContributionItem::SetToolTip(const QString &text) { tooltip = text; action->setToolTip(text); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h index 8da3b853be..f8028c05ba 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h @@ -1,214 +1,218 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYCOMMANDCONTRIBUTIONITEM_H_ #define BERRYCOMMANDCONTRIBUTIONITEM_H_ #include "berryContributionItem.h" #include namespace berry { struct IMenuService; struct ICommandService; struct ICommandListener; struct IHandlerService; struct IHandler; struct IElementReference; struct IServiceLocator; class CommandEvent; class ParameterizedCommand; class CommandContributionItemParameter; class UIElement; /** * A contribution item which delegates to a command. It can be used in {@link * AbstractContributionFactory#CreateContributionItems(IServiceLocator, * IContributionRoot)}. *

* It currently supports placement in menus and toolbars. *

*

* This class may be instantiated; it is not intended to be subclassed. *

*/ class BERRY_UI_QT CommandContributionItem : public QObject, public ContributionItem { Q_OBJECT public: /** * Mode bit: Show text on tool items or buttons, even if an image is * present. If this mode bit is not set, text is only shown on tool items if * there is no image present. */ static Modes modes; private: //LocalResourceManager localResourceManager; //Listener menuItemListener; QAction* action; IMenuService* menuService; ICommandService* commandService; IHandlerService* handlerService; //IBindingService bindingService; SmartPointer command; QIcon icon; QString label; QString tooltip; QChar mnemonic; SmartPointer elementRef; bool checkedState; Style style; QScopedPointer commandListener; QString dropDownMenuOverride; //IWorkbenchHelpSystem workbenchHelpSystem; QString helpContextId; Modes mode; /** * This is true when the menu contribution's visibleWhen * checkEnabled attribute is true. */ bool visibleEnabled; // items contributed QString contributedLabel; QIcon contributedIcon; SmartPointer serviceLocator; public: /** * Create a CommandContributionItem to place in a ContributionManager. * * @param contributionParameters * parameters necessary to render this contribution item. */ CommandContributionItem( const SmartPointer& contributionParameters); ~CommandContributionItem(); using ContributionItem::Fill; QAction* Fill(QMenu* parent, QAction* before); QAction* Fill(QToolBar* parent, QAction* before); void Update(); void Update(const QString& id); bool IsEnabled() const; bool IsVisible() const; void UpdateCommandPropertiesInUI(const SmartPointer& commandEvent); private: void SetImages(IServiceLocator* locator, const QString &iconStyle); ICommandListener *GetCommandListener(); void UpdateMenuItem(); void UpdateToolItem(); void UpdateCommandProperties(const SmartPointer commandEvent); bool ShouldRestoreAppearance(const SmartPointer& handler); SmartPointer GetCommand() const; void CreateCommand(const QString& commandId, const QHash& parameters); QString GetToolTipText(const QString& text) const; QString UpdateMnemonic(const QString& s); // void disposeOldImages() { // if (localResourceManager != null) { // localResourceManager.dispose(); // localResourceManager = null; // } // } //SmartPointer GetItemListener(); +#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) void connectNotify(const char *signal); void disconnectNotify(const char *signal); - +#else + void connectNotify(const QMetaMethod& signal); + void disconnectNotify(const QMetaMethod& signal); +#endif /** * Determines if the selection was on the dropdown affordance and, if so, * opens the drop down menu (populated using the same id as this item... * * @param event * The SWT.Selection event to be tested * * @return true iff a drop down menu was opened */ //TODO Tool item drop down menu contributions //bool OpenDropDownMenu(SmartPointer event); void SetIcon(const QIcon& icon); void UpdateIcons(); void SetText(const QString& text); void SetChecked(bool checked); void SetToolTip(const QString& text); private slots: void HandleWidgetSelection(); }; } #endif /* BERRYCOMMANDCONTRIBUTIONITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp index 33911dd535..72b34854b3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp @@ -1,1060 +1,1071 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchMenuService.h" #include #include #include #include #include #include #include #include #include #include #include #include "berryAbstractMenuAdditionCacheEntry.h" #include "berryAlwaysEnabledExpression.h" #include "berryContributionItem.h" #include "berryContributionRoot.h" #include "berryMenuManager.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchWindow.h" +#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0)) +#include +#endif + namespace berry { const QString WorkbenchMenuService::INDEX_AFTER_ADDITIONS_QK = "after"; const QString WorkbenchMenuService::INDEX_AFTER_ADDITIONS_QV = "additions"; const QString WorkbenchMenuService::PROP_VISIBLE = "visible"; /** * A combined property and activity listener that updates the visibility of * contribution items in the new menu system. */ class ContributionItemUpdater : public IPropertyChangeListener //, public IIdentifierListener { private: const IContributionItem::Pointer item; //IIdentifier identifier; bool lastExpressionResult; WorkbenchMenuService* wms; void UpdateVisibility() { //bool visible = identifier.IsNotNull() ? (identifier->IsEnabled() && lastExpressionResult) // : lastExpressionResult; bool visible = lastExpressionResult; item->SetVisible(visible); IContributionManager* parent = 0; if (ContributionItem::Pointer ci = item.Cast()) { parent = ci->GetParent(); } else if (MenuManager::Pointer mm = item.Cast()) { parent = mm->GetParent(); } if (parent != 0) { parent->MarkDirty(); wms->managersAwaitingUpdates.insert(parent); } } public: ContributionItemUpdater(WorkbenchMenuService* wms, const IContributionItem::Pointer& item) //, IIdentifier identifier) : item(item), lastExpressionResult(true), wms(wms) { // if (identifier.IsNotNull()) // { // this->identifier = identifier; // this->identifier->AddIdentifierListener(this); // UpdateVisibility(); // force initial visibility to fall in line // // with activity enablement // } } /** * Dispose of this updater */ ~ContributionItemUpdater() { // if (identifier.IsNotNull()) // identifier->RemoveIdentifierListener(this); } using IPropertyChangeListener::PropertyChange; /* * @see IPropertyChangeListener#PropertyChange(PropertyChangeEvent) */ void PropertyChange(const PropertyChangeEvent::Pointer& event) { if (event->GetProperty() == WorkbenchMenuService::PROP_VISIBLE) { if (event->GetNewValue().IsNotNull()) { lastExpressionResult = event->GetNewValue(); } else { lastExpressionResult = false; } UpdateVisibility(); } } /* * @see IIdentifierListener#IdentifierChanged(IdentifierEvent) */ // void identifierChanged(IdentifierEvent identifierEvent) // { // UpdateVisibility(); // } }; WorkbenchMenuService::ManagerPopulationRecord::ManagerPopulationRecord() : wms(0), serviceLocatorToUse(0), recurse(false) { } WorkbenchMenuService::ManagerPopulationRecord:: ManagerPopulationRecord(WorkbenchMenuService* wms, IServiceLocator* serviceLocatorToUse, const QSet >& restriction, const QString& uri, bool recurse) : wms(wms), serviceLocatorToUse(serviceLocatorToUse), restriction(restriction), uri(uri), recurse(recurse) { } void WorkbenchMenuService::ManagerPopulationRecord:: AddFactoryContribution(const SmartPointer& factory, const SmartPointer& ciList) { // Remove any existing cache info for this factory RemoveFactoryContribution(factory); // save the new info factoryToItems.insert(factory, ciList); } void WorkbenchMenuService::ManagerPopulationRecord:: RemoveFactoryContribution(const SmartPointer& factory) { ContributionRoot::Pointer items = factoryToItems.take(factory); if (items.IsNotNull()) { wms->ReleaseContributions(items.GetPointer()); } } SmartPointer WorkbenchMenuService::ManagerPopulationRecord:: GetContributions(const SmartPointer& factory) const { if (factoryToItems.contains(factory)) return factoryToItems[factory]; return ContributionRoot::Pointer(0); } void WorkbenchMenuService::ManagerPopulationRecord:: ReleaseContributions() { foreach (ContributionRoot::Pointer items, factoryToItems.values()) { wms->ReleaseContributions(items.GetPointer()); } factoryToItems.clear(); } WorkbenchMenuService::WorkbenchMenuService(IServiceLocator* serviceLocator) : evaluationService(0), serviceLocator(serviceLocator) { //this.menuPersistence = new MenuPersistence(this); evaluationService = serviceLocator->GetService(); evaluationService->AddServiceListener(GetServiceListener()); // IWorkbenchLocationService wls = (IWorkbenchLocationService) serviceLocator // .getService(IWorkbenchLocationService.class); // wls.getWorkbench() // .getActivitySupport().getActivityManager() // .addActivityManagerListener(getActivityManagerListener()); // final IExtensionRegistry registry = Platform.getExtensionRegistry(); // registryChangeListener = new IRegistryChangeListener() { // public void registryChanged(final IRegistryChangeEvent event) { // final Display display = PlatformUI.getWorkbench().getDisplay(); // if (display.isDisposed()) { // return; // } // display.syncExec(new Runnable() { // public void run() { // handleRegistryChanges(event); // } // }); // } // }; // registry.addRegistryChangeListener(registryChangeListener); } WorkbenchMenuService::~WorkbenchMenuService() { this->Dispose(); } void WorkbenchMenuService::Dispose() { //menuPersistence.dispose(); // if (registryChangeListener != null) // { // final IExtensionRegistry registry = Platform.getExtensionRegistry(); // registry.removeRegistryChangeListener(registryChangeListener); // registryChangeListener = null; // } foreach (IEvaluationReference::Pointer ref, evaluationsByItem.values()) { evaluationService->RemoveEvaluationListener(ref); } evaluationsByItem.clear(); managersAwaitingUpdates.clear(); evaluationService->RemoveServiceListener(GetServiceListener()); // if (activityManagerListener != null) // { // IWorkbenchLocationService wls = (IWorkbenchLocationService) serviceLocator // .getService(IWorkbenchLocationService.class); // IWorkbench workbench = wls.getWorkbench(); // if (workbench != null) // { // workbench.getActivitySupport().getActivityManager() // .removeActivityManagerListener(activityManagerListener); // } // } } void WorkbenchMenuService::AddSourceProvider(const SmartPointer& /*provider*/) { // no-op } void WorkbenchMenuService::ReadRegistry() { //menuPersistence.read(); } void WorkbenchMenuService::RemoveSourceProvider(const SmartPointer& /*provider*/) { // no-op } void WorkbenchMenuService::UpdateManagers() { QList managers = managersAwaitingUpdates.toList(); managersAwaitingUpdates.clear(); foreach (IContributionManager* mgr, managers) { mgr->Update(true); // if (ToolBarManager* tbMgr = dynamic_cast(mgr)) // { // if (!UpdateToolBar(tbMgr)) // { // //UpdateTrim((ToolBarManager) mgr); // } // } // else if (MenuManager* mMgr = dynamic_cast(mgr)) { IContributionManager* parent = mMgr->GetParent(); if (parent != 0) { parent->Update(true); } } } } WorkbenchMenuService::FactoryListType WorkbenchMenuService::GetAdditionsForURI(const QUrl& uri) { if (uri.isEmpty()) return FactoryListType(); return uriToFactories[GetIdFromURI(uri)]; } void WorkbenchMenuService::AddContributionFactory(const SmartPointer& factory) { if (factory.IsNull() || factory->GetLocation().isNull()) return; QUrl uri(factory->GetLocation()); QString factoryId = GetIdFromURI(uri); FactoryListType& factories = uriToFactories[factoryId]; { // MenuAdditionCacheEntry::Pointer mace = factory.Cast(); // if (mace && mace->HasAdditions()) // { // factories.push_front(factory); // } // else { factories.push_back(factory); } } // OK, now update any managers that use this uri FactoryListType factoryList; factoryList.push_back(factory); foreach (IContributionManager* mgr, GetManagersFor(factoryId)) { const ManagerPopulationRecord& mpr = populatedManagers[mgr]; AddContributionsToManager(mpr.serviceLocatorToUse, mpr.restriction, dynamic_cast(mgr), mpr.uri, mpr.recurse, factoryList); mgr->Update(true); } } void WorkbenchMenuService::RemoveContributionFactory(const SmartPointer& factory) { if (factory.IsNull() || factory->GetLocation().isNull()) return; QUrl uri(factory->GetLocation()); QString factoryId = GetIdFromURI(uri); if (uriToFactories.contains(factoryId)) { FactoryListType& factories = uriToFactories[factoryId]; // // Before we remove the top-level cache we recursively // // remove any sub-caches created by this one // if (MenuAdditionCacheEntry::Pointer mace = factory.Cast()) // { // QList subCaches = mace->GetSubCaches(); // foreach (AbstractMenuAdditionCacheEntry::Pointer amace, subCaches) // { // RemoveContributionFactory(amace); // } // } factories.removeAll(factory); } // OK, now update any managers that use this uri FactoryListType factoryList; factoryList.push_back(factory); foreach (IContributionManager* mgr, GetManagersFor(factoryId)) { RemoveContributionsForFactory(mgr, factory); mgr->Update(true); } } void WorkbenchMenuService::PopulateContributionManager(ContributionManager* mgr, const QString& uri) { PopulateContributionManager(serviceLocator, QSet >(), mgr, uri, true); } void WorkbenchMenuService::PopulateContributionManager(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const QString& uri, bool recurse) { // Track this attempt to populate the menu, remembering all the parameters if (!populatedManagers.contains(mgr)) { populatedManagers.insert(mgr, ManagerPopulationRecord(this, serviceLocatorToUse, restriction, uri, recurse)); } QUrl contributionLocation(uri); FactoryListType factories = GetAdditionsForURI(contributionLocation); AddContributionsToManager(serviceLocatorToUse, restriction, mgr, uri, recurse, factories); } void WorkbenchMenuService::AddContributionsToManager(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const QString& uri, bool recurse, const QList >& factories) { QUrl contributionLocation(uri); QList retryList; QSet itemsAdded; foreach (AbstractContributionFactory::Pointer cache, factories) { if (!ProcessAdditions(serviceLocatorToUse, restriction, mgr, cache, itemsAdded)) { retryList.push_back(cache); } } // OK, iteratively loop through entries whose URI's could not // be resolved until we either run out of entries or the list // doesn't change size (indicating that the remaining entries // can never be resolved). bool done = retryList.isEmpty(); while (!done) { // Clone the retry list and clear it QList curRetry = retryList; int retryCount = retryList.size(); retryList.clear(); // Walk the current list seeing if any entries can now be resolved foreach (AbstractContributionFactory::Pointer cache, curRetry) { if (!ProcessAdditions(serviceLocatorToUse, restriction, mgr, cache, itemsAdded)) { retryList.push_back(cache); } } // We're done if the retryList is now empty (everything done) or // if the list hasn't changed at all (no hope) done = retryList.isEmpty() || (retryList.size() == retryCount); } // Now, recurse through any sub-menus foreach (IContributionItem::Pointer curItem, mgr->GetItems()) { if (ContributionManager::Pointer cm = curItem.Cast()) { QString id = curItem->GetId(); if (!id.isEmpty() && (recurse || itemsAdded.contains(id))) { PopulateContributionManager(serviceLocatorToUse, restriction, cm.GetPointer(), contributionLocation.scheme() + ":" + id, true); } } // else if (IToolBarContributionItem::Pointer tbci = curItem.Cast()) // { // if (!(tbci->GetId().isEmpty()) && (recurse || itemsAdded.contains(tbci->GetId()))) // { // PopulateContributionManager(serviceLocatorToUse, // restriction, dynamic_cast(tbci->GetToolBarManager()), // contributionLocation.scheme() + ":" + tbci->GetId(), true); // } // } } } SmartPointer WorkbenchMenuService::GetCurrentState() const { return evaluationService->GetCurrentState(); } void WorkbenchMenuService::RegisterVisibleWhen(const SmartPointer& item, const SmartPointer& visibleWhen, QSet >& /*restriction*/, const QString& /*identifierID*/) { if (item.IsNull()) { throw std::invalid_argument("item cannot be null"); } if (visibleWhen.IsNull()) { throw std::invalid_argument("visibleWhen expression cannot be null"); } if (evaluationsByItem.contains(item)) { QString id = item->GetId(); WorkbenchPlugin::Log(QString("item is already registered: ") + (id.isEmpty() ? QString("no id") : id)); return; } // TODO activity support // IIdentifier identifier = null; // if (identifierID != null) { // identifier = PlatformUI.getWorkbench().getActivitySupport() // .getActivityManager().getIdentifier(identifierID); // } // ContributionItemUpdater* listener = // new ContributionItemUpdater(item, identifier); // if (visibleWhen != AlwaysEnabledExpression::INSTANCE) // { // IEvaluationReference::Pointer ref = evaluationService->AddEvaluationListener( // visibleWhen, listener, PROP_VISIBLE); // restriction.insert(ref); // evaluationsByItem.insert(item, ref); // } // activityListenersByItem.put(item, listener); } void WorkbenchMenuService::UnregisterVisibleWhen(const SmartPointer& item, QSet >& restriction) { // TODO activity support // ContributionItemUpdater identifierListener = (ContributionItemUpdater) activityListenersByItem // .remove(item); // if (identifierListener != null) { // identifierListener.dispose(); // } IEvaluationReference::Pointer ref = evaluationsByItem.take(item); if (ref.IsNull()) { return; } evaluationService->RemoveEvaluationListener(ref); restriction.remove(ref); } void WorkbenchMenuService::ReleaseContributions(ContributionManager* mgr) { if (mgr == 0) return; // Recursively remove any contributions from sub-menus foreach (IContributionItem::Pointer item, mgr->GetItems()) { if (ContributionManager::Pointer cm = item.Cast()) { ReleaseContributions(cm.GetPointer()); } // else if (IToolBarContributionItem::Pointer tbci = item.Cast()) // { // ReleaseContributions(tbci->GetToolBarManager()); // } } // Now remove any cached information if (populatedManagers.contains(mgr)) { populatedManagers[mgr].ReleaseContributions(); populatedManagers.remove(mgr); } managersAwaitingUpdates.remove(mgr); } //void WorkbenchMenuService::HandleDynamicAdditions(const QList >& menuAdditions) //{ // for (Iterator additionsIter = menuAdditions.iterator(); additionsIter.hasNext();) { // AbstractContributionFactory newFactory = null; // final IConfigurationElement menuAddition = (IConfigurationElement) additionsIter.next(); // if (isProgramaticContribution(menuAddition)) // newFactory = new ProxyMenuAdditionCacheEntry( // menuAddition // .getAttribute(IWorkbenchRegistryConstants.TAG_LOCATION_URI), // menuAddition.getNamespaceIdentifier(), menuAddition); // else // newFactory = new MenuAdditionCacheEntry( // this, // menuAddition, // menuAddition // .getAttribute(IWorkbenchRegistryConstants.TAG_LOCATION_URI), // menuAddition.getNamespaceIdentifier()); // if (newFactory != null) // addContributionFactory(newFactory); // } //} //void WorkbenchMenuService::HandleDynamicRemovals(const QList >& menuRemovals) //{ // for (Iterator additionsIter = menuRemovals.iterator(); additionsIter.hasNext();) { // IConfigurationElement ceToRemove = (IConfigurationElement) additionsIter.next(); // AbstractMenuAdditionCacheEntry factoryToRemove = findFactory(ceToRemove); // removeContributionFactory(factoryToRemove); // } //} //void WorkbenchMenuService::HandleRegistryChanges(const SmartPointer& event) //{ // // HACK!! determine if this is an addition or deletion from the first delta // IExtensionDelta[] deltas = event.getExtensionDeltas(); // if (deltas.length == 0) // return; // boolean isAddition = deltas[0].getKind() == IExtensionDelta.ADDED; // // access all the necessary service persistence handlers // HandlerService handlerSvc = (HandlerService) serviceLocator.getService(IHandlerService.class); // HandlerPersistence handlerPersistence = handlerSvc.getHandlerPersistence(); // CommandService cmdSvc = (CommandService) serviceLocator.getService(ICommandService.class); // CommandPersistence cmdPersistence = cmdSvc.getCommandPersistence(); // BindingService bindingSvc = (BindingService) serviceLocator.getService(IBindingService.class); // BindingPersistence bindingPersistence = bindingSvc.getBindingPersistence(); // boolean needsUpdate = false; // // determine order from the type of delta // if (isAddition) { // // additions order: Commands, Handlers, Bindings, Menus // if (cmdPersistence.commandsNeedUpdating(event)) { // cmdPersistence.reRead(); // needsUpdate = true; // } // if (handlerPersistence.handlersNeedUpdating(event)) { // handlerPersistence.reRead(); // needsUpdate = true; // } // if (bindingPersistence.bindingsNeedUpdating(event)) { // bindingPersistence.reRead(); // needsUpdate = true; // } // if (menuPersistence.menusNeedUpdating(event)) { // handleMenuChanges(event); // needsUpdate = true; // } // } // else { // // Removal order: Menus, Bindings, Handlers, Commands // if (menuPersistence.menusNeedUpdating(event)) { // handleMenuChanges(event); // needsUpdate = true; // } // if (bindingPersistence.bindingsNeedUpdating(event)) { // bindingPersistence.reRead(); // needsUpdate = true; // } // if (handlerPersistence.handlersNeedUpdating(event)) { // final IExtensionDelta[] handlerDeltas = event.getExtensionDeltas( // PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_HANDLERS); // for (int i = 0; i < handlerDeltas.length; i++) { // IConfigurationElement[] ices = handlerDeltas[i].getExtension().getConfigurationElements(); // HandlerProxy.updateStaleCEs(ices); // } // handlerPersistence.reRead(); // needsUpdate = true; // } // if (cmdPersistence.commandsNeedUpdating(event)) { // cmdPersistence.reRead(); // needsUpdate = true; // } // } // if (needsUpdate) { // ContributionManager[] managers = (ContributionManager[]) populatedManagers // .keySet().toArray( // new ContributionManager[populatedManagers.keySet() // .size()]); // for (int i = 0; i < managers.length; i++) { // ContributionManager mgr = managers[i]; // mgr.update(false); // } // } //} //MenuPersistence* WorkbenchMenuService::GetMenuPersistence() //{ // return menuPersistence; //} void WorkbenchMenuService::PopulateContributionManager(ContributionManager* mgr, const QString& uri, bool recurse) { PopulateContributionManager(serviceLocator, QSet(), mgr, uri, recurse); } void WorkbenchMenuService::RemoveContributionsForFactory(IContributionManager* manager, const SmartPointer& factory) { populatedManagers[manager].RemoveFactoryContribution(factory); // automatically cleans its caches } void WorkbenchMenuService::ReleaseContributions(ContributionRoot* items) { ContributionManager* mgr = items->GetManager(); foreach(IContributionItem::Pointer item, items->GetItems()) { ReleaseItem(item, items->restriction); mgr->Remove(item); } ReleaseCache(items); } void WorkbenchMenuService::PropertyChange(const PropertyChangeEvent::Pointer& event) { if (event->GetProperty() == IEvaluationService::PROP_NOTIFYING) { if (!(event->GetNewValue().Cast()->GetValue())) { // if it's false, the evaluation service has // finished with its latest round of updates this->UpdateManagers(); } } } //SmartPointer WorkbenchMenuService::GetActivityManagerListener() //{ // if (activityManagerListener == null) { // activityManagerListener = new IActivityManagerListener() { // public void activityManagerChanged( // ActivityManagerEvent activityManagerEvent) { // if (activityManagerEvent.haveEnabledActivityIdsChanged()) { // updateManagers(); // called after all identifiers have // // been update - now update the // // managers // } // } // }; // } // return activityManagerListener; //} IPropertyChangeListener* WorkbenchMenuService::GetServiceListener() { return this; } //void WorkbenchMenuService::UpdateTrim(ToolBarManager* mgr) //{ // Control control = mgr.getControl(); // if (control == null || control.isDisposed()) { // return; // } // LayoutUtil.resize(control); //} bool WorkbenchMenuService::UpdateToolBar(ToolBarManager* /*mgr*/) { // QList windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); // QList::iterator wend = windows.end(); // for (QList::iterator i = windows.begin(); i != wend; ++i) // { // WorkbenchWindow::Pointer window = i->Cast(); // IToolBarManager* tb = window->GetToolBarManager(); // if (tb != 0) // { // foreach (IContributionItem::Pointer item, tb->GetItems()) // { // if (ToolBarContributionItem::Pointer tbci = item.Cast()) // { // IToolBarManager* tbm = tbci->GetToolBarManager(); // if (mgr == tbm) // { // tb->Update(true); // return true; // } // } // } // } // } return false; } QString WorkbenchMenuService::GetIdFromURI(const QUrl& uri) { return uri.scheme() + ":" + uri.path(); } QList WorkbenchMenuService::GetManagersFor(const QString& factoryId) { QList mgrs; QHashIterator mgrIter(populatedManagers); while(mgrIter.hasNext()) { if (factoryId == mgrIter.value().uri) { mgrs.push_back(mgrIter.key()); } } return mgrs; } bool WorkbenchMenuService::ProcessAdditions(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const AbstractContributionFactory::Pointer& cache, QSet& itemsAdded) { if (!ProcessFactory(mgr, cache)) return true; const int idx = GetInsertionIndex(mgr, cache->GetLocation()); if (idx == -1) return false; // can't process (yet) struct _SafeRunnable : public ISafeRunnable { WorkbenchMenuService* wms; int insertionIndex; IServiceLocator* serviceLocatorToUse; QSet > restriction; ContributionManager* mgr; AbstractContributionFactory::Pointer cache; QSet& itemsAdded; _SafeRunnable(WorkbenchMenuService* wms, int idx, IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, AbstractContributionFactory::Pointer cache, QSet& itemsAdded) : wms(wms), insertionIndex(idx), serviceLocatorToUse(serviceLocatorToUse), restriction(restriction), mgr(mgr), cache(cache), itemsAdded(itemsAdded) {} void HandleException(const std::exception&) {} void Run() { // Get the additions ContributionRoot::Pointer ciList(new ContributionRoot(wms, restriction, mgr, cache.GetPointer())); cache->CreateContributionItems(serviceLocatorToUse, ciList); // If we have any then add them at the correct location if (!ciList->GetItems().isEmpty()) { // Cache the items for future cleanup ManagerPopulationRecord& mpr = wms->populatedManagers[mgr]; ContributionRoot::Pointer contributions = mpr.GetContributions(cache); if (contributions.IsNotNull()) { // Existing contributions in the mgr will be released. // Adjust the insertionIndex foreach (IContributionItem::Pointer item, contributions->GetItems()) { if (item == mgr->Find(item->GetId())) insertionIndex--; } } mpr.AddFactoryContribution(cache, ciList); foreach (IContributionItem::Pointer ici, ciList->GetItems()) { if ((ici.Cast() || //ici.Cast || ici.Cast()) && !(ici->GetId().isEmpty())) { IContributionItem::Pointer foundIci = mgr->Find(ici->GetId()); // really, this is a very specific scenario that // allows merging but, if it is a contribution manager that also // contains items, then we would be throwing stuff away. if (ContributionManager::Pointer cm = foundIci.Cast()) { if (cm->GetSize() > 0) { // IStatus status = new Status( // IStatus.WARNING, // WorkbenchPlugin.PI_WORKBENCH, // "Menu contribution id collision: " // + ici.getId()); // StatusManager.getManager().handle(status); BERRY_WARN << "Menu contribution id collision: " << ici->GetId().toStdString(); } continue; } // else if (IToolBarContributionItem::Pointer tbci = foundIci.Cast()) // { // IToolBarManager* toolBarManager = tbci->GetToolBarManager(); // if (ContributionManager::Pointer tbcm = dynamic_cast(toolBarManager) // && tbcm->GetSize() > 0) // { //// IStatus status = new Status( //// IStatus.WARNING, //// WorkbenchPlugin.PI_WORKBENCH, //// "Toolbar contribution id collision: " //$NON-NLS-1$ //// + ici.getId()); //// StatusManager.getManager().handle(status); // BERRY_WARN << "Toolbar contribution id collision: " << ici->GetId().toStdString(); // } // continue; // } else if (foundIci.Cast()) { continue; } } const int oldSize = mgr->GetSize(); mgr->Insert(insertionIndex, ici); if (!ici->GetId().isEmpty()) { itemsAdded.insert(ici->GetId()); } if (mgr->GetSize() > oldSize) insertionIndex++; } } } }; ISafeRunnable::Pointer run (new _SafeRunnable(this, idx, serviceLocatorToUse, restriction, mgr, cache, itemsAdded)); SafeRunner::Run(run); return true; } bool WorkbenchMenuService::ProcessFactory(ContributionManager* mgr, const AbstractContributionFactory::Pointer& factory) { QUrl uri(factory->GetLocation()); if (MenuUtil::ANY_POPUP == (uri.scheme() + ':' + uri.path())) { // its any popup. check whether manager has additions if (mgr->IndexOf(WorkbenchActionConstants::MB_ADDITIONS) == -1) { // // menu has no additions. Add only if allPopups = true // if (MenuAdditionCacheEntry::Pointer menuEntry = factory.Cast()) // { // return menuEntry->ContributeToAllPopups(); // } } } return true; } void WorkbenchMenuService::ReleaseCache(ContributionRoot* items) { items->Release(); } int WorkbenchMenuService::GetInsertionIndex(ContributionManager* mgr, const QString& location) { QUrl uri(location); +#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) QList > queryParts = uri.queryItems(); + bool indexAfterAdditions = uri.queryItemValue(INDEX_AFTER_ADDITIONS_QK) == INDEX_AFTER_ADDITIONS_QV; +#else + QUrlQuery query(uri); + QList > queryParts = query.queryItems(); + bool indexAfterAdditions = query.queryItemValue(INDEX_AFTER_ADDITIONS_QK) == INDEX_AFTER_ADDITIONS_QV; +#endif int additionsIndex = -1; // No Query means 'after=additions' (if there) or // the end of the menu - if (queryParts.isEmpty() || uri.queryItemValue(INDEX_AFTER_ADDITIONS_QK) == INDEX_AFTER_ADDITIONS_QV) + if (queryParts.isEmpty() || indexAfterAdditions) { additionsIndex = mgr->IndexOf(WorkbenchActionConstants::MB_ADDITIONS); if (additionsIndex == -1) additionsIndex = mgr->GetItems().size(); else ++additionsIndex; } else { // Should be in the form "[before|after|endof]=id" if (queryParts.size() > 0 && !(queryParts[0].second.isEmpty())) { QString modifier = queryParts[0].first; QString id = queryParts[0].second; additionsIndex = mgr->IndexOf(id); if (additionsIndex != -1) { if (MenuUtil::QUERY_BEFORE == modifier) { // this is OK, the additionsIndex will either be correct // or -1 (which is a no-op) } else if (MenuUtil::QUERY_AFTER == modifier) { additionsIndex++; } else if (MenuUtil::QUERY_ENDOF == modifier) { // OK, this one is exciting QList items = mgr->GetItems(); for (additionsIndex++; additionsIndex < items.size(); additionsIndex++) { if (items[additionsIndex]->IsGroupMarker()) { break; } } } } } } return additionsIndex; } void WorkbenchMenuService::ReleaseItem(const SmartPointer& item, QSet >& restriction) { UnregisterVisibleWhen(item, restriction); if (ContributionManager::Pointer cm = item.Cast()) { ReleaseContributions(cm.GetPointer()); } // else if (IToolBarContributionItem::Pointer tbci = item.Cast()) // { // ReleaseContributions(dynamic_cast(tbci->GetToolBarManager())); // } } bool WorkbenchMenuService::IsProgramaticContribution(const SmartPointer& menuAddition) const { return !menuAddition->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isEmpty(); } SmartPointer WorkbenchMenuService::FindFactory(const SmartPointer& ceToRemove) { QUrl uri = ceToRemove->GetAttribute(WorkbenchRegistryConstants::TAG_LOCATION_URI); FactoryListType factories = GetAdditionsForURI(uri); foreach (AbstractContributionFactory::Pointer factory, GetAdditionsForURI(uri)) { if (AbstractMenuAdditionCacheEntry::Pointer mace = factory.Cast()) { if (mace->GetConfigElement() == ceToRemove) return mace; } } return AbstractMenuAdditionCacheEntry::Pointer(0); } //void WorkbenchMenuService::HandleMenuChanges(const SmartPointer& event) //{ // final IExtensionDelta[] menuDeltas = event.getExtensionDeltas( // PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_MENUS); // final List menuAdditions = new ArrayList(); // final List menuRemovals = new ArrayList(); // for (int i = 0; i < menuDeltas.length; i++) { // IConfigurationElement[] ices = menuDeltas[i].getExtension().getConfigurationElements(); // for (int j = 0; j < ices.length; j++) { // if (IWorkbenchRegistryConstants.PL_MENU_CONTRIBUTION.equals(ices[j].getName())) { // if (menuDeltas[i].getKind() == IExtensionDelta.ADDED) // menuAdditions.add(ices[j]); // else // menuRemovals.add(ices[j]); // } // } // } // // Handle additions // if (menuAdditions.size() > 0) { // handleDynamicAdditions(menuAdditions); // } // // Handle Removals // if (menuRemovals.size() > 0) { // handleDynamicRemovals(menuRemovals); // } //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp index a9c8571aae..576ba5785b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp @@ -1,391 +1,393 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbench.h" #include "berryPlatform.h" #include "intro/berryEditorIntroAdapterPart.h" #include "defaultpresentation/berryQtWorkbenchPresentationFactory.h" #include "berryQtStyleManager.h" #include "berryQtWorkbenchTweaklet.h" #include "berryQtWorkbenchPageTweaklet.h" #include "berryQtWidgetsTweaklet.h" #include "berryQtStylePreferencePage.h" #include "berryStatusUtil.h" #include "berryHandlerServiceFactory.h" #include "berryMenuServiceFactory.h" #include "berryCommandServiceFactory.h" #include "berryWorkbenchSourceProvider.h" #include "berryObjectString.h" #include "berryObjects.h" #include "berryShowViewHandler.h" #include "berryIQtStyleManager.h" #include "berryIContributor.h" #include "berryILog.h" #include "berryIExtension.h" #include namespace berry { bool WorkbenchPlugin::DEBUG = false; char WorkbenchPlugin::PREFERENCE_PAGE_CATEGORY_SEPARATOR = '/'; WorkbenchPlugin* WorkbenchPlugin::inst = 0; WorkbenchPlugin::WorkbenchPlugin() : AbstractUICTKPlugin() { inst = this; presentationFactory = 0; editorRegistry = 0; viewRegistry = 0; perspRegistry = 0; introRegistry = 0; } WorkbenchPlugin::~WorkbenchPlugin() { delete presentationFactory; delete editorRegistry; delete viewRegistry; delete perspRegistry; delete introRegistry; inst = 0; } bool WorkbenchPlugin::HasExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { if (!element->GetAttribute(extensionName).isNull()) return true; QString elementText = element->GetValue(); if (!elementText.isEmpty()) return true; QList children(element->GetChildren(extensionName)); if (children.size() == 1) { if (!(children[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isNull())) return true; } return false; } bool WorkbenchPlugin::IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { QSharedPointer plugin = WorkbenchPlugin::GetBundleForExecutableExtension(element, extensionName); if (plugin.isNull()) return true; return plugin->getState() == ctkPlugin::ACTIVE; } QSharedPointer WorkbenchPlugin::GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { // this code is derived heavily from // ConfigurationElement.createExecutableExtension. QString prop; QString executable; QString contributorName; int i = 0; if (!extensionName.isNull()) prop = element->GetAttribute(extensionName); else { // property not specified, try as element value prop = element->GetValue(); if (!prop.isNull()) { prop = prop.trimmed(); if (prop.isEmpty()) prop = QString(); } } if (prop.isNull()) { // property not defined, try as a child element QList exec(element->GetChildren(extensionName)); if (!exec.isEmpty()) contributorName = exec[0]->GetAttribute("plugin"); } else { // simple property or element value, parse it into its components i = prop.indexOf(':'); if (i != -1) executable = prop.left(i).trimmed(); else executable = prop; i = executable.indexOf('/'); if (i != -1) contributorName = executable.left(i).trimmed(); } if (contributorName.isNull()) contributorName = element->GetContributor()->GetName(); return Platform::GetPlugin(contributorName); } WorkbenchPlugin* WorkbenchPlugin::GetDefault() { return inst; } std::size_t WorkbenchPlugin::GetBundleCount() { // TODO BundleContext GetBundles //return bundleContext->GetBundles().size(); return 0; } // ImageRegistry createImageRegistry() { // return WorkbenchImages.getImageRegistry(); // } IPerspectiveRegistry* WorkbenchPlugin::GetPerspectiveRegistry() { if (perspRegistry == 0) { perspRegistry = new PerspectiveRegistry(); // the load methods can touch on WorkbenchImages if an image is // missing so we need to wrap the call in // a startup block for the case where a custom descriptor exists on // startup that does not have an image // associated with it. See bug 196352. //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { perspRegistry->Load(); // } //}); } return perspRegistry; } // PreferenceManager getPreferenceManager() { // if (preferenceManager == null) { // preferenceManager = new WorkbenchPreferenceManager( // PREFERENCE_PAGE_CATEGORY_SEPARATOR); // // //Get the pages from the registry // PreferencePageRegistryReader registryReader = new PreferencePageRegistryReader( // getWorkbench()); // registryReader // .loadFromRegistry(Platform.getExtensionRegistry()); // preferenceManager.addPages(registryReader.getTopLevelNodes()); // // } // return preferenceManager; // } // ISharedImages getSharedImages() { // if (sharedImages == null) { // sharedImages = new SharedImages(); // } // return sharedImages; // } IIntroRegistry* WorkbenchPlugin::GetIntroRegistry() { if (introRegistry == 0) { introRegistry = new IntroRegistry(); } return introRegistry; } IViewRegistry* WorkbenchPlugin::GetViewRegistry() { if (!viewRegistry) viewRegistry = new ViewRegistry(); return viewRegistry; } IEditorRegistry* WorkbenchPlugin::GetEditorRegistry() { if (!editorRegistry) editorRegistry = new EditorRegistry(); return editorRegistry; } IPresentationFactory* WorkbenchPlugin::GetPresentationFactory() { if (presentationFactory != 0) return presentationFactory; QString targetID = Workbench::GetInstance()->GetPresentationId(); presentationFactory = this->CreateExtension( WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES, "factory", targetID); if (presentationFactory == 0) WorkbenchPlugin::Log("Error creating presentation factory: " + targetID + " -- class is not an IPresentationFactory"); return presentationFactory; } void WorkbenchPlugin::Log(const QString& message) { BERRY_INFO << "LOG: " << message << std::endl; //inst->GetLog().log(message); } void WorkbenchPlugin::Log(const ctkException &exc) { QString str; QDebug dbg(&str); dbg << exc.printStackTrace(); BERRY_INFO << "LOG: " << str << std::endl; //inst->GetLog().log(exc); } void WorkbenchPlugin::Log(const QString& message, const ctkException &t) { PlatformException exc(message, t); WorkbenchPlugin::Log(exc); } void WorkbenchPlugin::Log(const QString& clazz, const QString& methodName, const ctkException &t) { QString msg = QString("Exception in ") + clazz + "." + methodName + ": " + t.what(); WorkbenchPlugin::Log(msg, t); } void WorkbenchPlugin::Log(const QString& message, const SmartPointer& status) { //1FTUHE0: ITPCORE:ALL - API - Status & logging - loss of semantic info if (!message.isEmpty()) { GetDefault()->GetLog()->Log(StatusUtil::NewStatus(IStatus::ERROR_TYPE, message, BERRY_STATUS_LOC)); } GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::Log(const SmartPointer& status) { GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::start(ctkPluginContext* context) { //context.addBundleListener(getBundleListener()); AbstractUICTKPlugin::start(context); bundleContext = context; BERRY_REGISTER_EXTENSION_CLASS(EditorIntroAdapterPart, context) BERRY_REGISTER_EXTENSION_CLASS(QtWidgetsTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPageTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPresentationFactory, context) BERRY_REGISTER_EXTENSION_CLASS(QtStylePreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(HandlerServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(MenuServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(CommandServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(WorkbenchSourceProvider, context) BERRY_REGISTER_EXTENSION_CLASS(ShowViewHandler, context) styleManager.reset(new QtStyleManager()); context->registerService(styleManager.data()); // The UI plugin needs to be initialized so that it can install the callback in PrefUtil, // which needs to be done as early as possible, before the workbench // accesses any API preferences. // Bundle uiBundle = Platform.getBundle(PlatformUI.PLUGIN_ID); // try // { // // Attempt to load the activator of the ui bundle. This will force lazy start // // of the ui bundle. Using the bundle activator class here because it is a // // class that needs to be loaded anyway so it should not cause extra classes // // to be loaded. // if(uiBundle != null) // uiBundle.loadClass(UI_BUNDLE_ACTIVATOR); // } // catch (ClassNotFoundException e) // { // WorkbenchPlugin.log("Unable to load UI activator", e); //$NON-NLS-1$ // } /* * DO NOT RUN ANY OTHER CODE AFTER THIS LINE. If you do, then you are * likely to cause a deadlock in class loader code. Please see Bug 86450 * for more information. */ } //const QList WorkbenchPlugin::GetBundles() //{ // return bundleContext.IsNull() ? QList() : bundleContext->GetBundles(); //} ctkPluginContext* WorkbenchPlugin::GetPluginContext() { return bundleContext; } void WorkbenchPlugin::stop(ctkPluginContext* context) { AbstractUICTKPlugin::stop(context); styleManager.reset(); delete perspRegistry; // avoid possible crash, see bug #18399 perspRegistry = 0; } QString WorkbenchPlugin::GetDataLocation() const { QFileInfo fileInfo = bundleContext->getDataFile(""); if (!fileInfo.isWritable()) return QString(); return fileInfo.absoluteFilePath(); } } -Q_EXPORT_PLUGIN2(org_blueberry_ui_qt, berry::WorkbenchPlugin) +#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) + Q_EXPORT_PLUGIN2(org_blueberry_ui_qt, berry::WorkbenchPlugin) +#endif diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h index f0e5af7d13..b66951df5e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h @@ -1,498 +1,498 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHPLUGIN_H_ #define BERRYWORKBENCHPLUGIN_H_ #include #include #include #include #include #include "berryAbstractUICTKPlugin.h" #include "berryPlatformUI.h" #include "presentations/berryIPresentationFactory.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryPerspectiveRegistry.h" #include "intro/berryIntroRegistry.h" namespace berry { class QtStyleManager; /** * \ingroup org_blueberry_ui_internal * * This class represents the TOP of the workbench UI world * A plugin class is effectively an application wrapper * for a plugin & its classes. This class should be thought * of as the workbench UI's application class. * * This class is responsible for tracking various registries * font, preference, graphics, dialog store. * * This class is explicitly referenced by the * workbench plugin's "plugin.xml" and places it * into the UI start extension point of the main * overall application harness * * When is this class started? * When the Application * calls createExecutableExtension to create an executable * instance of our workbench class. */ class WorkbenchPlugin : public AbstractUICTKPlugin { Q_OBJECT -#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - Q_PLUGIN_METADATA(IID "org_blueberry_ui") +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + Q_PLUGIN_METADATA(IID "org_blueberry_ui_qt") #endif Q_INTERFACES(ctkPluginActivator) private: //static const QString UI_BUNDLE_ACTIVATOR = "org.blueberry.ui.internal.UIPlugin"; //$NON-NLS-1$ // Default instance of the receiver static WorkbenchPlugin* inst; // The presentation factory IPresentationFactory* presentationFactory; // Manager that maps resources to descriptors of editors to use EditorRegistry* editorRegistry; // The context within which this plugin was started. ctkPluginContext* bundleContext; // Other data. //WorkbenchPreferenceManager preferenceManager; ViewRegistry* viewRegistry; PerspectiveRegistry* perspRegistry; IntroRegistry* introRegistry; //SharedImages sharedImages; QScopedPointer styleManager; public: /** * Global workbench ui plugin flag. Only workbench implementation is allowed to use this flag * All other plugins, examples, or test cases must *not* use this flag. */ static bool DEBUG; /** * The character used to separate preference page category ids */ static char PREFERENCE_PAGE_CATEGORY_SEPARATOR; /** * Create an instance of the WorkbenchPlugin. The workbench plugin is * effectively the "application" for the workbench UI. The entire UI * operates as a good plugin citizen. */ WorkbenchPlugin(); ~WorkbenchPlugin(); /** * Creates an extension. If the extension plugin has not * been loaded a busy cursor will be activated during the duration of * the load. * * @param element the config element defining the extension * @param classAttribute the name of the attribute carrying the class * @return the extension object * @throws CoreException if the extension cannot be created */ // template // static E* CreateExtension(IConfigurationElement::ConstPointer element, // const QString& classAttribute) { // try { // // If plugin has been loaded create extension. // // Otherwise, show busy cursor then create extension. // if (BundleUtility.isActivated(element.getDeclaringExtension() // .getNamespace())) { // return element.createExecutableExtension(classAttribute); // } // final Object[] ret = new Object[1]; // final CoreException[] exc = new CoreException[1]; // BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { // ret[0] = element // .createExecutableExtension(classAttribute); // } catch (CoreException e) { // exc[0] = e; // } // } // }); // if (exc[0] != null) { // throw exc[0]; // } // return ret[0]; // // } catch (CoreException core) { // throw core; // } catch (Exception e) { // throw new CoreException(new Status(IStatus.ERR, PI_WORKBENCH, // IStatus.ERR, WorkbenchMessages.WorkbenchPlugin_extension,e)); // } // } /** * Answers whether the provided element either has an attribute with the * given name or a child element with the given name with an attribute * called class. * * @param element * the element to test * @param extensionName * the name of the extension to test for * @return whether or not the extension is declared */ static bool HasExecutableExtension(const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Checks to see if the provided element has the syntax for an executable * extension with a given name that resides in a bundle that is already * active. Determining the bundle happens in one of two ways:
*
    *
  • The element has an attribute with the specified name or element text * in the form bundle.id/class.name[:optional attributes]
  • *
  • The element has a child element with the specified name that has a * plugin attribute
  • *
* * @param element * the element to test * @param extensionName * the name of the extension to test for * @return whether or not the bundle expressed by the above criteria is * active. If the bundle cannot be determined then the state of the * bundle that declared the element is returned. */ static bool IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Returns the bundle that contains the class referenced by an executable * extension. Determining the bundle happens in one of two ways:
*
    *
  • The element has an attribute with the specified name or element text * in the form bundle.id/class.name[:optional attributes]
  • *
  • The element has a child element with the specified name that has a * plugin attribute
  • *
* * @param element * the element to test * @param extensionName * the name of the extension to test for * @return the bundle referenced by the extension. If that bundle cannot be * determined the bundle that declared the element is returned. Note * that this may be null. */ static QSharedPointer GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Return the default instance of the receiver. This represents the runtime plugin. * @return WorkbenchPlugin * @see AbstractUICTKPlugin for the typical implementation pattern for plugin classes. */ static WorkbenchPlugin* GetDefault(); std::size_t GetBundleCount(); /** * Answer the manager that maps resource types to a the * description of the editor to use * @return IEditorRegistry the editor registry used * by this plug-in. */ IEditorRegistry* GetEditorRegistry(); /** * Returns the presentation factory with the given id, or null if not found. * @param targetID The id of the presentation factory to use. * @return IPresentationFactory or null * if not factory matches that id. */ IPresentationFactory* GetPresentationFactory(); protected: /* * Returns the image registry for this plugin. * * Where are the images? The images (typically gifs) are found in the same * plugins directory. * * @see ImageRegistry * * Note: The workbench uses the standard JFace ImageRegistry to track its * images. In addition the class WorkbenchGraphicResources provides * convenience access to the graphics resources and fast field access for * some of the commonly used graphical images. */ //ImageRegistry createImageRegistry(); private: /** * Looks up the configuration element with the given id on the given extension point * and instantiates the class specified by the class attributes. * * @param extensionPointId the extension point id (simple id) * @param elementName the name of the configuration element, or null * to match any element * @param targetID the target id * @return the instantiated extension object, or null if not found */ template C* CreateExtension(const QString& extensionPointId, const QString& elementName, const QString& targetID) { IExtensionPoint::Pointer extensionPoint = Platform::GetExtensionRegistry() ->GetExtensionPoint(PlatformUI::PLUGIN_ID() + "." + extensionPointId); if (extensionPoint == 0) { WorkbenchPlugin::Log("Unable to find extension. Extension point: " + extensionPointId + " not found"); return 0; } // Loop through the config elements. IConfigurationElement::Pointer targetElement(0); QList elements( Platform::GetExtensionRegistry()->GetConfigurationElementsFor(PlatformUI::PLUGIN_ID() + "." + extensionPointId)); for (int j = 0; j < elements.size(); j++) { if (elementName == "" || elementName == elements[j]->GetName()) { QString strID = elements[j]->GetAttribute("id"); if (targetID == strID) { targetElement = elements[j]; break; } } } if (targetElement.IsNull()) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to find extension: " + targetID + " in extension point: " + extensionPointId); return 0; } // Create the extension. try { return targetElement->CreateExecutableExtension("class"); } catch (const CoreException& /*e*/) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to create extension: " + targetID + " in extension point: " + extensionPointId); } return 0; } public: /** * Return the perspective registry. * @return IPerspectiveRegistry. The registry for the receiver. */ IPerspectiveRegistry* GetPerspectiveRegistry(); /** * Returns the introduction registry. * * @return the introduction registry. */ IIntroRegistry* GetIntroRegistry(); /* * Get the preference manager. * @return PreferenceManager the preference manager for * the receiver. */ //PreferenceManager getPreferenceManager(); /* * Returns the shared images for the workbench. * * @return the shared image manager */ //ISharedImages getSharedImages(); /** * Answer the view registry. * @return IViewRegistry the view registry for the * receiver. */ IViewRegistry* GetViewRegistry(); /** * Logs the given message to the platform log. * * If you have an exception in hand, call log(String, Throwable) instead. * * If you have a status object in hand call log(String, IStatus) instead. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. */ static void Log(const QString &message); /** * Log the throwable. * @param t */ static void Log(const ctkException& exc); /** * Logs the given message and throwable to the platform log. * * If you have a status object in hand call log(String, IStatus) instead. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. * @param t * The throwable from where the problem actually occurred. */ static void Log(const QString &message, const ctkException& t); /** * Logs the given throwable to the platform log, indicating the class and * method from where it is being logged (this is not necessarily where it * occurred). * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param clazz * The calling class. * @param methodName * The calling method name. * @param t * The throwable from where the problem actually occurred. */ static void Log(const QString &clazz, const QString &methodName, const ctkException& t); /** * Logs the given message and status to the platform log. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. * May be null. * @param status * The status describing the problem. Must not be null. */ static void Log(const QString& message, const SmartPointer& status); /** * Log the status to the default log. * @param status */ static void Log(const SmartPointer& status); /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ void start(ctkPluginContext* context); /* * Return an array of all bundles contained in this workbench. * * @return an array of bundles in the workbench or an empty array if none */ //const QList GetBundles(); /** * Returns the bundle context associated with the workbench plug-in. * * @return the bundle context */ ctkPluginContext* GetPluginContext(); /* (non-Javadoc) * @see org.blueberry.ui.plugin.AbstractUICTKPlugin#stop(org.osgi.framework.BundleContext) */ void stop(ctkPluginContext* context); /** * FOR INTERNAL WORKBENCH USE ONLY. * * Returns the path to a location in the file system that can be used * to persist/restore state between workbench invocations. * If the location did not exist prior to this call it will be created. * Returns null if no such location is available. * * @return path to a location in the file system where this plug-in can * persist data between sessions, or null if no such * location is available. */ QString GetDataLocation() const; }; } #endif /*BERRYWORKBENCHPLUGIN_H_*/ diff --git a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp index a2c44b27e7..202fc37e34 100755 --- a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp +++ b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp @@ -1,83 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCoreExtActivator.h" #include "mitkCoreExtConstants.h" #include "mitkLogMacros.h" -#include "mitkInputDeviceRegistry.h" #include #include #include #include #include namespace mitk { void CoreExtActivator::start(ctkPluginContext* context) { Q_UNUSED(context) this->StartInputDeviceModules(context); } void CoreExtActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } void CoreExtActivator::StartInputDeviceModules(ctkPluginContext* context) { m_InputDeviceRegistry.reset(new InputDeviceRegistry()); context->registerService(m_InputDeviceRegistry.data()); // Gets the last setting of the preferences; if a device was selected, // it will still be activated after a restart ctkServiceReference prefServiceRef = context->getServiceReference(); if (!prefServiceRef) { MITK_WARN << "Preferences service not available"; return; } berry::IPreferencesService* prefService = context->getService(prefServiceRef); berry::IPreferences::Pointer extPreferencesNode = prefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES); // Initializes the modules QList descriptors(m_InputDeviceRegistry->GetInputDevices()); for (QList::const_iterator it = descriptors.begin(); it != descriptors.end(); ++it) { if (extPreferencesNode->GetBool((*it)->GetID(), false)) { IInputDevice::Pointer temp = (*it)->CreateInputDevice(); temp->RegisterInputDevice(); } } } CoreExtActivator::~CoreExtActivator() { } } // end namespace mitk #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_core_ext, mitk::CoreExtActivator) #endif diff --git a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h index d53eb07456..b346c383cf 100755 --- a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h +++ b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h @@ -1,70 +1,70 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCOREEXTACTIVATOR_H_ #define MITKCOREEXTACTIVATOR_H_ #include +#include "mitkInputDeviceRegistry.h" + namespace mitk { -class InputDeviceRegistry; - /** * @brief The activator class for the org.mitk.core.ext plug-in. * @ingroup org_mitk_core_ext_internal * * When the plug-in is started by the framework, it calls a global function to initialize * the mitkCoreExt module. * */ class CoreExtActivator : public QObject, public ctkPluginActivator { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_core_ext") #endif Q_INTERFACES(ctkPluginActivator) public: ~CoreExtActivator(); /** * Starts this plug-in and registers object factories. * * @param context * The context for the plug-in. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: /** * Activates the input device modules. */ void StartInputDeviceModules(ctkPluginContext *context); QScopedPointer m_InputDeviceRegistry; }; // end class CoreExtActivator } //end namespace mitk #endif /* MITKCOREEXTACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp index e04072db6c..6caaae4406 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp @@ -1,1119 +1,1119 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "QmitkQBallReconstructionView.h" // qt includes #include // itk includes #include "itkTimeProbe.h" // mitk includes #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "itkDiffusionQballReconstructionImageFilter.h" #include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" #include "itkDiffusionMultiShellQballReconstructionImageFilter.h" #include "itkVectorContainer.h" #include "itkB0ImageExtractionImageFilter.h" #include #include "mitkQBallImage.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include #include "mitkDiffusionImagingConfigure.h" #include "berryIStructuredSelection.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" #include const std::string QmitkQBallReconstructionView::VIEW_ID = "org.mitk.views.qballreconstruction"; typedef float TTensorPixelType; const int QmitkQBallReconstructionView::nrconvkernels = 252; struct QbrShellSelection { typedef mitk::DiffusionPropertyHelper::GradientDirectionType GradientDirectionType; typedef mitk::DiffusionPropertyHelper::GradientDirectionsContainerType GradientDirectionContainerType; typedef mitk::DiffusionPropertyHelper::BValueMapType BValueMapType; typedef itk::VectorImage< DiffusionPixelType, 3 > ITKDiffusionImageType; QmitkQBallReconstructionView* m_View; mitk::DataNode * m_Node; std::string m_NodeName; std::vector m_CheckBoxes; QLabel * m_Label; mitk::Image * m_Image; QbrShellSelection(QmitkQBallReconstructionView* view, mitk::DataNode * node) : m_View(view), m_Node(node), m_NodeName(node->GetName()) { m_Image = dynamic_cast (node->GetData()); if(!m_Image) { MITK_ERROR << "QmitkQBallReconstructionView::QbrShellSelection : no image selected"; return; } bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(m_Node->GetData())) ); if( !isDiffusionImage ) { MITK_ERROR << "QmitkQBallReconstructionView::QbrShellSelection : selected image contains no diffusion information"; return; } GenerateCheckboxes(); } void GenerateCheckboxes() { BValueMapType origMap = static_cast(m_Image->GetProperty(mitk::DiffusionPropertyHelper::BVALUEMAPPROPERTYNAME.c_str()).GetPointer() )->GetBValueMap(); BValueMapType::iterator itStart = origMap.begin(); itStart++; BValueMapType::iterator itEnd = origMap.end(); m_Label = new QLabel(m_NodeName.c_str()); m_Label->setVisible(true); m_View->m_Controls->m_QBallSelectionBox->layout()->addWidget(m_Label); for(BValueMapType::iterator it = itStart ; it!= itEnd; it++) { QCheckBox * box = new QCheckBox(QString::number(it->first)); m_View->m_Controls->m_QBallSelectionBox->layout()->addWidget(box); box->setChecked(true); box->setCheckable(true); // box->setVisible(true); m_CheckBoxes.push_back(box); } } void SetVisible(bool vis) { foreach(QCheckBox * box, m_CheckBoxes) { box->setVisible(vis); } } BValueMapType GetBValueSelctionMap() { BValueMapType inputMap = static_cast(m_Image->GetProperty(mitk::DiffusionPropertyHelper::BVALUEMAPPROPERTYNAME.c_str()).GetPointer() )->GetBValueMap(); BValueMapType outputMap; unsigned int val = 0; if(inputMap.find(0) == inputMap.end()){ MITK_INFO << "QbrShellSelection: return empty BValueMap from GUI Selection"; return outputMap; }else{ outputMap[val] = inputMap[val]; MITK_INFO << val; } foreach(QCheckBox * box, m_CheckBoxes) { if(box->isChecked()){ val = box->text().toDouble(); outputMap[val] = inputMap[val]; MITK_INFO << val; } } return outputMap; } ~QbrShellSelection() { m_View->m_Controls->m_QBallSelectionBox->layout()->removeWidget(m_Label); delete m_Label; for(std::vector::iterator it = m_CheckBoxes.begin() ; it!= m_CheckBoxes.end(); it++) { m_View->m_Controls->m_QBallSelectionBox->layout()->removeWidget((*it)); delete (*it); } m_CheckBoxes.clear(); } }; using namespace berry; struct QbrSelListener : ISelectionListener { QbrSelListener(QmitkQBallReconstructionView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { bool foundDwiVolume = false; m_View->m_Controls->m_DiffusionImageLabel->setText("mandatory"); m_View->m_Controls->m_InputData->setTitle("Please Select Input Data"); QString selected_images = ""; mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); mitk::Image* diffusionImage = dynamic_cast(node->GetData()); // only look at interesting types if(diffusionImage && isDiffusionImage) { foundDwiVolume = true; selected_images += QString(node->GetName().c_str()); if(i + 1 != m_View->m_CurrentSelection->End()) selected_images += "\n"; set->InsertElement(at++, node); } } } m_View->GenerateShellSelectionUI(set); m_View->m_Controls->m_DiffusionImageLabel->setText(selected_images); m_View->m_Controls->m_ButtonStandard->setEnabled(foundDwiVolume); if (foundDwiVolume) m_View->m_Controls->m_InputData->setTitle("Input Data"); else m_View->m_Controls->m_DiffusionImageLabel->setText("mandatory"); } } void SelectionChanged(const IWorkbenchPart::Pointer& part, - const ISelection::ConstPointer& selection) override + const ISelection::ConstPointer& selection) { // check, if selection comes from datamanager if (part) { QString partname = part->GetPartName(); if(partname == "Data Manager") { // apply selection DoSelectionChanged(selection); } } } QmitkQBallReconstructionView* m_View; }; // --------------- QmitkQBallReconstructionView----------------- // QmitkQBallReconstructionView::QmitkQBallReconstructionView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { } QmitkQBallReconstructionView::~QmitkQBallReconstructionView() { this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); } void QmitkQBallReconstructionView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkQBallReconstructionViewControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_DiffusionImageLabel->setText("mandatory"); QStringList items; items << "2" << "4" << "6" << "8" << "10" << "12"; m_Controls->m_QBallReconstructionMaxLLevelComboBox->addItems(items); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setCurrentIndex(1); MethodChoosen(m_Controls->m_QBallReconstructionMethodComboBox->currentIndex()); #ifndef DIFFUSION_IMAGING_EXTENDED m_Controls->m_QBallReconstructionMethodComboBox->removeItem(3); #endif AdvancedCheckboxClicked(); } m_SelListener.reset(new QbrSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); static_cast(m_SelListener.data())->DoSelectionChanged(sel); } void QmitkQBallReconstructionView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkQBallReconstructionView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkQBallReconstructionView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ButtonStandard), SIGNAL(clicked()), this, SLOT(ReconstructStandard()) ); connect( (QObject*)(m_Controls->m_AdvancedCheckbox), SIGNAL(clicked()), this, SLOT(AdvancedCheckboxClicked()) ); connect( (QObject*)(m_Controls->m_QBallReconstructionMethodComboBox), SIGNAL(currentIndexChanged(int)), this, SLOT(MethodChoosen(int)) ); connect( (QObject*)(m_Controls->m_QBallReconstructionThreasholdEdit), SIGNAL(valueChanged(int)), this, SLOT(PreviewThreshold(int)) ); } } void QmitkQBallReconstructionView::OnSelectionChanged( std::vector ) { } void QmitkQBallReconstructionView::Activated() { QmitkFunctionality::Activated(); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); static_cast(m_SelListener.data())->DoSelectionChanged(sel); } void QmitkQBallReconstructionView::Deactivated() { mitk::DataStorage::SetOfObjects::ConstPointer objects = this->GetDefaultDataStorage()->GetAll(); mitk::DataStorage::SetOfObjects::const_iterator itemiter( objects->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( objects->end() ); while ( itemiter != itemiterend ) // for all items { mitk::DataNode::Pointer node = *itemiter; if (node.IsNull()) continue; // only look at interesting types bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); if( isDiffusionImage ) { if (this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter)) { node = this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter); this->GetDefaultDataStorage()->Remove(node); } } itemiter++; } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Deactivated(); } void QmitkQBallReconstructionView::ReconstructStandard() { int index = m_Controls->m_QBallReconstructionMethodComboBox->currentIndex(); #ifndef DIFFUSION_IMAGING_EXTENDED if(index>=3) { index = index + 1; } #endif switch(index) { case 0: { // Numerical Reconstruct(0,0); break; } case 1: { // Standard Reconstruct(1,0); break; } case 2: { // Solid Angle Reconstruct(1,6); break; } case 3: { // Constrained Solid Angle Reconstruct(1,7); break; } case 4: { // ADC Reconstruct(1,4); break; } case 5: { // Raw Signal Reconstruct(1,5); break; } case 6: { // Q-Ball reconstruction Reconstruct(2,0); break; } } } void QmitkQBallReconstructionView::MethodChoosen(int method) { #ifndef DIFFUSION_IMAGING_EXTENDED if(method>=3) { method = method + 1; } #endif m_Controls->m_QBallSelectionBox->setHidden(true); m_Controls->m_OutputCoeffsImage->setHidden(true); if (method==0) m_Controls->m_ShFrame->setVisible(false); else m_Controls->m_ShFrame->setVisible(true); switch(method) { case 0: m_Controls->m_Description->setText("Numerical recon. (Tuch 2004)"); break; case 1: m_Controls->m_Description->setText("Spherical harmonics recon. (Descoteaux 2007)"); m_Controls->m_OutputCoeffsImage->setHidden(false); break; case 2: m_Controls->m_Description->setText("SH recon. with solid angle consideration (Aganj 2009)"); m_Controls->m_OutputCoeffsImage->setHidden(false); break; case 3: m_Controls->m_Description->setText("SH solid angle with non-neg. constraint (Goh 2009)"); break; case 4: m_Controls->m_Description->setText("SH recon. of the plain ADC-profiles"); break; case 5: m_Controls->m_Description->setText("SH recon. of the raw diffusion signal"); break; case 6: m_Controls->m_Description->setText("SH recon. of the multi shell diffusion signal (Aganj 2010)"); m_Controls->m_QBallSelectionBox->setHidden(false); m_Controls->m_OutputCoeffsImage->setHidden(false); break; } } void QmitkQBallReconstructionView::AdvancedCheckboxClicked() { bool check = m_Controls->m_AdvancedCheckbox->isChecked(); m_Controls->m_QBallReconstructionMaxLLevelTextLabel_2->setVisible(check); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setVisible(check); m_Controls->m_QBallReconstructionLambdaTextLabel_2->setVisible(check); m_Controls->m_QBallReconstructionLambdaLineEdit->setVisible(check); m_Controls->m_QBallReconstructionThresholdLabel_2->setVisible(check); m_Controls->m_QBallReconstructionThreasholdEdit->setVisible(check); m_Controls->label_2->setVisible(check); m_Controls->frame_2->setVisible(check); } void QmitkQBallReconstructionView::Reconstruct(int method, int normalization) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); if ( isDiffusionImage ) { set->InsertElement(at++, node); } } } if(method == 0) { NumericalQBallReconstruction(set, normalization); } else { #if BOOST_VERSION / 100000 > 0 #if BOOST_VERSION / 100 % 1000 > 34 if(method == 1) { AnalyticalQBallReconstruction(set, normalization); } if(method == 2) { MultiQBallReconstruction(set); } #else std::cout << "ERROR: Boost 1.35 minimum required" << std::endl; QMessageBox::warning(NULL,"ERROR","Boost 1.35 minimum required"); #endif #else std::cout << "ERROR: Boost 1.35 minimum required" << std::endl; QMessageBox::warning(NULL,"ERROR","Boost 1.35 minimum required"); #endif } } } void QmitkQBallReconstructionView::NumericalQBallReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // QBALL RECONSTRUCTION clock.Start(); MITK_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str()).toLatin1()); typedef itk::DiffusionQballReconstructionImageFilter QballReconstructionImageFilterType; ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetGradientImage( static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(), itkVectorImagePointer ); filter->SetBValue( static_cast(vols->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->value() ); std::string nodePostfix; switch(normalization) { case 0: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); nodePostfix = "_Numerical_Qball"; break; } case 1: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO_B_VALUE); nodePostfix = "_Numerical_ZeroBvalueNormalization_Qball"; break; } case 2: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO); nodePostfix = "_NumericalQball_ZeroNormalization_Qball"; break; } case 3: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_NONE); nodePostfix = "_NumericalQball_NoNormalization_Qball"; break; } default: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); nodePostfix = "_NumericalQball_Qball"; } } filter->Update(); clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s." ; // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename+nodePostfix); mitk::ProgressBar::GetInstance()->Progress(); GetDefaultDataStorage()->Add(node, *itemiter); ++itemiter; } mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return ; } } void QmitkQBallReconstructionView::AnalyticalQBallReconstruction( mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->value(); lambdas.push_back(minLambda); int nLambdas = lambdas.size(); QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles*nLambdas); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector* nodes = new std::vector(); while ( itemiter != itemiterend ) // for all items { // QBALL RECONSTRUCTION clock.Start(); MITK_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("QBall reconstruction for %s", (*itemiter)->GetName().c_str()).toLatin1()); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentIndex()) { case 0: { TemplatedAnalyticalQBallReconstruction<2>(*itemiter, currentLambda, normalization); break; } case 1: { TemplatedAnalyticalQBallReconstruction<4>(*itemiter, currentLambda, normalization); break; } case 2: { TemplatedAnalyticalQBallReconstruction<6>(*itemiter, currentLambda, normalization); break; } case 3: { TemplatedAnalyticalQBallReconstruction<8>(*itemiter, currentLambda, normalization); break; } case 4: { TemplatedAnalyticalQBallReconstruction<10>(*itemiter, currentLambda, normalization); break; } case 5: { TemplatedAnalyticalQBallReconstruction<12>(*itemiter, currentLambda, normalization); break; } } clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s." ; mitk::ProgressBar::GetInstance()->Progress(); itemiter++; } } std::vector::iterator nodeIt; for(nodeIt = nodes->begin(); nodeIt != nodes->end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); m_MultiWidget->RequestUpdate(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return; } } template void QmitkQBallReconstructionView::TemplatedAnalyticalQBallReconstruction(mitk::DataNode* dataNodePointer, float lambda, int normalization) { typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); mitk::Image* vols = dynamic_cast(dataNodePointer->GetData()); ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); filter->SetGradientImage( static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(), itkVectorImagePointer ); filter->SetBValue( static_cast(vols->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->value() ); filter->SetLambda(lambda); std::string nodePostfix; switch(normalization) { case 0: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); nodePostfix = "_SphericalHarmonics_Qball"; break; } case 1: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO_B_VALUE); nodePostfix = "_SphericalHarmonics_1_Qball"; break; } case 2: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO); nodePostfix = "_SphericalHarmonics_2_Qball"; break; } case 3: { filter->SetNormalizationMethod(FilterType::QBAR_NONE); nodePostfix = "_SphericalHarmonics_3_Qball"; break; } case 4: { filter->SetNormalizationMethod(FilterType::QBAR_ADC_ONLY); nodePostfix = "_AdcProfile"; break; } case 5: { filter->SetNormalizationMethod(FilterType::QBAR_RAW_SIGNAL); nodePostfix = "_RawSignal"; break; } case 6: { filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); nodePostfix = "_SphericalHarmonics_CSA_Qball"; break; } case 7: { filter->SetNormalizationMethod(FilterType::QBAR_NONNEG_SOLID_ANGLE); nodePostfix = "_SphericalHarmonics_NonNegCSA_Qball"; break; } default: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); } } filter->Update(); // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, dataNodePointer->GetName()+nodePostfix); GetDefaultDataStorage()->Add(node, dataNodePointer); if(m_Controls->m_OutputCoeffsImage->isChecked()) { mitk::Image::Pointer coeffsImage = mitk::Image::New(); coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); mitk::DataNode::Pointer coeffsNode=mitk::DataNode::New(); coeffsNode->SetData( coeffsImage ); coeffsNode->SetProperty( "name", mitk::StringProperty::New(dataNodePointer->GetName()+"_SH-Coeffs") ); coeffsNode->SetVisibility(false); GetDefaultDataStorage()->Add(coeffsNode, node); } } void QmitkQBallReconstructionView::MultiQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->value(); lambdas.push_back(minLambda); int nLambdas = lambdas.size(); QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles*nLambdas); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::DataNode* nodePointer = (*itemiter).GetPointer(); std::string nodename; (*itemiter)->GetStringProperty("name",nodename); itemiter++; // QBALL RECONSTRUCTION clock.Start(); MITK_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("QBall reconstruction for %s", nodename.c_str()).toLatin1()); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentIndex()) { case 0: { TemplatedMultiQBallReconstruction<2>(currentLambda, nodePointer); break; } case 1: { TemplatedMultiQBallReconstruction<4>(currentLambda, nodePointer); break; } case 2: { TemplatedMultiQBallReconstruction<6>(currentLambda, nodePointer); break; } case 3: { TemplatedMultiQBallReconstruction<8>(currentLambda, nodePointer); break; } case 4: { TemplatedMultiQBallReconstruction<10>(currentLambda, nodePointer); break; } case 5: { TemplatedMultiQBallReconstruction<12>(currentLambda, nodePointer); break; } } clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s." ; mitk::ProgressBar::GetInstance()->Progress(); } } m_MultiWidget->RequestUpdate(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return ; } } template void QmitkQBallReconstructionView::TemplatedMultiQBallReconstruction(float lambda, mitk::DataNode* dataNodePointer) { typedef itk::DiffusionMultiShellQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); std::string nodename; dataNodePointer->GetStringProperty("name",nodename); mitk::Image* dwi = dynamic_cast(dataNodePointer->GetData()); BValueMapType currSelectionMap = m_ShellSelectorMap[dataNodePointer]->GetBValueSelctionMap(); if(currSelectionMap.size() != 4 && currSelectionMap.find(0) != currSelectionMap.end()) { QMessageBox::information(0, "Reconstruction not possible:" ,QString("Only three shells in a equidistant configuration is supported. (ImageName: " + QString(nodename.c_str()) + ")")); return; } BValueMapType::reverse_iterator it1 = currSelectionMap.rbegin(); BValueMapType::reverse_iterator it2 = currSelectionMap.rbegin(); ++it2; // Get average distance int avdistance = 0; for(; it2 != currSelectionMap.rend(); ++it1,++it2) avdistance += (int)it1->first - (int)it2->first; avdistance /= currSelectionMap.size()-1; // Check if all shells are using the same averae distance it1 = currSelectionMap.rbegin(); it2 = currSelectionMap.rbegin(); ++it2; for(; it2 != currSelectionMap.rend(); ++it1,++it2) if(avdistance != (int)it1->first - (int)it2->first) { QMessageBox::information(0, "Reconstruction not possible:" ,QString("Selected Shells are not in a equidistant configuration. (ImageName: " + QString(nodename.c_str()) + ")")); return; } ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(dwi, itkVectorImagePointer); filter->SetBValueMap(m_ShellSelectorMap[dataNodePointer]->GetBValueSelctionMap()); filter->SetGradientImage( static_cast( dwi->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(), itkVectorImagePointer, static_cast(dwi->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->value() ); filter->SetLambda(lambda); filter->Update(); // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename+"_SphericalHarmonics_MultiShell_Qball"); GetDefaultDataStorage()->Add(node, dataNodePointer); if(m_Controls->m_OutputCoeffsImage->isChecked()) { mitk::Image::Pointer coeffsImage = mitk::Image::New(); coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); mitk::DataNode::Pointer coeffsNode=mitk::DataNode::New(); coeffsNode->SetData( coeffsImage ); coeffsNode->SetProperty( "name", mitk::StringProperty::New( QString(nodename.c_str()).append("_SH-Coefficients").toStdString()) ); coeffsNode->SetVisibility(false); GetDefaultDataStorage()->Add(coeffsNode, node); } } void QmitkQBallReconstructionView::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 500 ) ); node->SetProperty( "Scaling", mitk::FloatProperty::New( 1.0 ) ); node->SetProperty( "Normalization", mitk::OdfNormalizationMethodProperty::New()); node->SetProperty( "ScaleBy", mitk::OdfScaleByProperty::New()); node->SetProperty( "IndexParam1", mitk::FloatProperty::New(2)); node->SetProperty( "IndexParam2", mitk::FloatProperty::New(1)); node->SetProperty( "visible", mitk::BoolProperty::New( true ) ); node->SetProperty( "VisibleOdfs", mitk::BoolProperty::New( false ) ); node->SetProperty ("layer", mitk::IntProperty::New(100)); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); node->SetProperty( "name", mitk::StringProperty::New(name) ); } void QmitkQBallReconstructionView::GenerateShellSelectionUI(mitk::DataStorage::SetOfObjects::Pointer set) { m_DiffusionImages = set; std::map tempMap; const mitk::DataStorage::SetOfObjects::iterator setEnd( set->end() ); mitk::DataStorage::SetOfObjects::iterator NodeIt( set->begin() ); while(NodeIt != setEnd) { if(m_ShellSelectorMap.find( (*NodeIt).GetPointer() ) != m_ShellSelectorMap.end()) { tempMap[(*NodeIt).GetPointer()] = m_ShellSelectorMap[(*NodeIt).GetPointer()]; m_ShellSelectorMap.erase((*NodeIt).GetPointer()); }else { tempMap[(*NodeIt).GetPointer()] = new QbrShellSelection(this, (*NodeIt) ); tempMap[(*NodeIt).GetPointer()]->SetVisible(true); } NodeIt++; } for(std::map::iterator it = m_ShellSelectorMap.begin(); it != m_ShellSelectorMap.end();it ++) { delete it->second; } m_ShellSelectorMap.clear(); m_ShellSelectorMap = tempMap; } void QmitkQBallReconstructionView::PreviewThreshold(int threshold) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_DiffusionImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_DiffusionImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast( (*itemiter)->GetData()); // Extract b0 image ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); typedef itk::B0ImageExtractionImageFilter FilterType; FilterType::Pointer filterB0 = FilterType::New(); filterB0->SetInput( itkVectorImagePointer ); filterB0->SetDirections( static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer() ); filterB0->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); typedef itk::Image ImageType; typedef itk::Image SegmentationType; typedef itk::BinaryThresholdImageFilter ThresholdFilterType; // apply threshold ThresholdFilterType::Pointer filterThreshold = ThresholdFilterType::New(); filterThreshold->SetInput(filterB0->GetOutput()); filterThreshold->SetLowerThreshold(threshold); filterThreshold->SetInsideValue(0); filterThreshold->SetOutsideValue(1); // mark cut off values red filterThreshold->Update(); mitkImage->InitializeByItk( filterThreshold->GetOutput() ); mitkImage->SetVolume( filterThreshold->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node; if (this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter)) { node = this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter); } else { // create a new node, to show thresholded values node = mitk::DataNode::New(); GetDefaultDataStorage()->Add( node, *itemiter ); node->SetProperty( "name", mitk::StringProperty::New("ThresholdOverlay")); node->SetBoolProperty("helper object", true); } node->SetData( mitkImage ); itemiter++; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp index c08648b13a..eaad1a609c 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp @@ -1,1327 +1,1327 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkPointBasedRegistrationView.h" #include "ui_QmitkPointBasedRegistrationViewControls.h" #include "QmitkPointListWidget.h" #include #include #include #include "vtkPolyData.h" #include #include #include "qradiobutton.h" #include "qapplication.h" #include #include #include #include #include "qmessagebox.h" #include "mitkLandmarkWarping.h" #include #include #include "mitkOperationEvent.h" #include "mitkUndoController.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateNot.h" #include #include #include #include "mitkDataNodeObject.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkPointBasedRegistrationView::VIEW_ID = "org.mitk.views.pointbasedregistration"; using namespace berry; struct SelListenerPointBasedRegistration : ISelectionListener { berryObjectMacro(SelListenerPointBasedRegistration); SelListenerPointBasedRegistration(QmitkPointBasedRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // if(!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.line2->hide(); m_View->m_Controls.m_FixedPointListWidget->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.line1->hide(); m_View->m_Controls.m_MovingPointListWidget->hide(); m_View->m_Controls.m_OpacityLabel->hide(); m_View->m_Controls.m_OpacitySlider->hide(); m_View->m_Controls.label->hide(); m_View->m_Controls.label_2->hide(); m_View->m_Controls.m_SwitchImages->hide(); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::TNodePredicateDataType::Pointer isBaseData(mitk::TNodePredicateDataType::New()); mitk::TNodePredicateDataType::Pointer isPointSet(mitk::TNodePredicateDataType::New()); mitk::NodePredicateNot::Pointer notPointSet = mitk::NodePredicateNot::New(isPointSet); mitk::TNodePredicateDataType::Pointer isPlaneGeometryData(mitk::TNodePredicateDataType::New()); mitk::NodePredicateNot::Pointer notPlaneGeometryData = mitk::NodePredicateNot::New(isPlaneGeometryData); mitk::NodePredicateAnd::Pointer notPointSetAndNotPlaneGeometryData = mitk::NodePredicateAnd::New( notPointSet, notPlaneGeometryData ); mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New( isBaseData, notPointSetAndNotPlaneGeometryData ); mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = m_View->GetDataStorage()->GetSubset(predicate); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if(nodeIt->Value().GetPointer() == node.GetPointer()) { // was - compare() // use contain to allow other Image types to be selected, i.e. a diffusion image if (QString( node->GetData()->GetNameOfClass() ).contains("Image") ) { // verify that the node selected by name is really an image or derived class mitk::Image* _image = dynamic_cast(node->GetData()); if (_image != NULL) { if( _image->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "PointBasedRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { // method deleted for more information see bug-18492 // m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.line2->show(); m_View->m_Controls.m_FixedPointListWidget->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.line1->show(); m_View->m_Controls.m_MovingPointListWidget->show(); m_View->m_Controls.m_OpacityLabel->show(); m_View->m_Controls.m_OpacitySlider->show(); m_View->m_Controls.label->show(); m_View->m_Controls.label_2->show(); m_View->m_Controls.m_SwitchImages->show(); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } void SelectionChanged(const IWorkbenchPart::Pointer& part, - const ISelection::ConstPointer& selection) override + const ISelection::ConstPointer& selection) { // check, if selection comes from datamanager if (part) { QString partname = part->GetPartName(); if(partname == "Data Manager") { // apply selection DoSelectionChanged(selection); } } } QmitkPointBasedRegistrationView* m_View; }; QmitkPointBasedRegistrationView::QmitkPointBasedRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality(), m_MultiWidget(NULL), m_FixedLandmarks(NULL), m_MovingLandmarks(NULL), m_MovingNode(NULL), m_FixedNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Transformation(0), m_HideFixedImage(false), m_HideMovingImage(false), m_OldFixedLabel(""), m_OldMovingLabel(""), m_Deactivated (false), m_CurrentFixedLandmarksObserverID(0), m_CurrentMovingLandmarksObserverID(0) { m_FixedLandmarksChangedCommand = itk::SimpleMemberCommand::New(); m_FixedLandmarksChangedCommand->SetCallbackFunction(this, &QmitkPointBasedRegistrationView::updateFixedLandmarksList); m_MovingLandmarksChangedCommand = itk::SimpleMemberCommand::New(); m_MovingLandmarksChangedCommand->SetCallbackFunction(this, &QmitkPointBasedRegistrationView::updateMovingLandmarksList); this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkPointBasedRegistrationView::DataNodeHasBeenRemoved )); } QmitkPointBasedRegistrationView::~QmitkPointBasedRegistrationView() { if(m_SelListener) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener.data()); } if (m_FixedPointSetNode.IsNotNull()) { m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); } if (m_MovingPointSetNode.IsNotNull()) { m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); } m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); } void QmitkPointBasedRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Parent->setEnabled(false); m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_ShowRedGreenValues->setEnabled(false); this->CreateConnections(); // let the point set widget know about the multi widget (cross hair updates) m_Controls.m_FixedPointListWidget->SetMultiWidget( m_MultiWidget ); m_Controls.m_MovingPointListWidget->SetMultiWidget( m_MultiWidget ); } void QmitkPointBasedRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); m_Controls.m_FixedPointListWidget->SetMultiWidget( m_MultiWidget ); m_Controls.m_MovingPointListWidget->SetMultiWidget( m_MultiWidget ); } void QmitkPointBasedRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; m_Controls.m_FixedPointListWidget->SetMultiWidget( NULL ); m_Controls.m_MovingPointListWidget->SetMultiWidget( NULL ); } void QmitkPointBasedRegistrationView::CreateConnections() { connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(EditPointSets(bool)), (QObject*)(m_Controls.m_MovingPointListWidget), SLOT(DeactivateInteractor(bool))); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(EditPointSets(bool)), (QObject*)(m_Controls.m_FixedPointListWidget), SLOT(DeactivateInteractor(bool))); connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(EditPointSets(bool)), this, SLOT(HideMovingImage(bool))); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(EditPointSets(bool)), this, SLOT(HideFixedImage(bool))); connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(PointListChanged()), this, SLOT(updateFixedLandmarksList())); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(PointListChanged()), this, SLOT(updateMovingLandmarksList())); connect((QObject*)(m_Controls.m_Calculate),SIGNAL(clicked()),this,SLOT(calculate())); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect((QObject*)(m_Controls.m_UndoTransformation),SIGNAL(clicked()),this,SLOT(UndoTransformation())); connect((QObject*)(m_Controls.m_RedoTransformation),SIGNAL(clicked()),this,SLOT(RedoTransformation())); connect((QObject*)(m_Controls.m_ShowRedGreenValues),SIGNAL(toggled(bool)),this,SLOT(showRedGreen(bool))); connect((QObject*)(m_Controls.m_OpacitySlider),SIGNAL(valueChanged(int)),this,SLOT(OpacityUpdate(int))); connect((QObject*)(m_Controls.m_SelectedTransformationClass),SIGNAL(activated(int)), this,SLOT(transformationChanged(int))); connect((QObject*)(m_Controls.m_UseICP),SIGNAL(toggled(bool)), this,SLOT(checkCalculateEnabled())); connect((QObject*)(m_Controls.m_UseICP),SIGNAL(toggled(bool)), this,SLOT(checkLandmarkError())); } void QmitkPointBasedRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); this->clearTransformationLists(); if (m_SelListener.isNull()) { m_SelListener.reset(new SelListenerPointBasedRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); static_cast(m_SelListener.data())->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->showRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); } void QmitkPointBasedRegistrationView::Visible() { } void QmitkPointBasedRegistrationView::Deactivated() { m_Deactivated = true; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); this->setImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } this->clearTransformationLists(); if (m_FixedPointSetNode.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_FixedLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_FixedPointSetNode); } if (m_MovingPointSetNode.IsNotNull() && m_MovingLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_MovingPointSetNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FixedNode = NULL; m_MovingNode = NULL; if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); m_FixedLandmarks = NULL; if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); m_MovingLandmarks = NULL; m_FixedPointSetNode = NULL; m_MovingPointSetNode = NULL; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener.data()); m_SelListener.reset(); } void QmitkPointBasedRegistrationView::Hidden() { /* m_Deactivated = true; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); this->setImageColor(false); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } this->clearTransformationLists(); if (m_FixedPointSetNode.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_FixedLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_FixedPointSetNode); } if (m_MovingPointSetNode.IsNotNull() && m_MovingLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_MovingPointSetNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FixedNode = NULL; m_MovingNode = NULL; if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); m_FixedLandmarks = NULL; if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); m_MovingLandmarks = NULL; m_FixedPointSetNode = NULL; m_MovingPointSetNode = NULL; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated();*/ } void QmitkPointBasedRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_ShowRedGreenValues->setEnabled(false); } } void QmitkPointBasedRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); if (fixedImage.IsNotNull()) { if (m_FixedNode != fixedImage) { // remove changes on previous selected node if (m_FixedNode.IsNotNull()) { this->setImageColor(false); m_FixedNode->SetOpacity(1.0); if (m_FixedPointSetNode.IsNotNull()) { m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); } } // get selected node m_FixedNode = fixedImage; m_FixedNode->SetOpacity(0.5); m_FixedNode->SetVisibility(true); m_Controls.m_FixedLabel->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.m_SwitchImages->show(); m_Controls.TextLabelFixed->show(); m_Controls.line2->show(); m_Controls.m_FixedPointListWidget->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->setImageColor(m_ShowRedGreen); bool hasPointSetNode = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_FixedNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::StringProperty::Pointer nameProp = dynamic_cast(children->GetElement(i)->GetProperty("name")); if(nameProp.IsNotNull() && nameProp->GetValueAsString()=="PointBasedRegistrationNode") { m_FixedPointSetNode=children->GetElement(i); m_FixedLandmarks = dynamic_cast (m_FixedPointSetNode->GetData()); this->GetDataStorage()->Remove(m_FixedPointSetNode); hasPointSetNode = true; break; } } if (!hasPointSetNode) { m_FixedLandmarks = mitk::PointSet::New(); m_FixedPointSetNode = mitk::DataNode::New(); m_FixedPointSetNode->SetData(m_FixedLandmarks); m_FixedPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); } m_FixedPointSetNode->GetStringProperty("label", m_OldFixedLabel); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New("F ")); m_FixedPointSetNode->SetProperty("color", mitk::ColorProperty::New(0.0f, 1.0f, 1.0f)); m_FixedPointSetNode->SetVisibility(true); m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); this->GetDataStorage()->Add(m_FixedPointSetNode, m_FixedNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if (m_FixedPointSetNode.IsNull()) { m_FixedLandmarks = mitk::PointSet::New(); m_FixedPointSetNode = mitk::DataNode::New(); m_FixedPointSetNode->SetData(m_FixedLandmarks); m_FixedPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); m_FixedPointSetNode->GetStringProperty("label", m_OldFixedLabel); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New("F ")); m_FixedPointSetNode->SetProperty("color", mitk::ColorProperty::New(0.0f, 1.0f, 1.0f)); m_FixedPointSetNode->SetVisibility(true); m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); this->GetDataStorage()->Add(m_FixedPointSetNode, m_FixedNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_FixedNode = NULL; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_FixedPointSetNode = NULL; m_FixedLandmarks = NULL; m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_SwitchImages->hide(); } if(m_FixedLandmarks.IsNotNull()) m_CurrentFixedLandmarksObserverID = m_FixedLandmarks->AddObserver(itk::ModifiedEvent(), m_FixedLandmarksChangedCommand); } void QmitkPointBasedRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); if (movingImage.IsNotNull()) { if (m_MovingNode != movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->setImageColor(false); if (m_MovingNode != m_FixedNode) { m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); } else { m_OldFixedLabel = m_OldMovingLabel; } } if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_MovingNode = movingImage; m_MovingNode->SetVisibility(true); m_Controls.m_MovingLabel->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); m_Controls.line1->show(); m_Controls.m_MovingPointListWidget->show(); m_Controls.m_OpacityLabel->show(); m_Controls.m_OpacitySlider->show(); m_Controls.label->show(); m_Controls.label_2->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->setImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); bool hasPointSetNode = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::StringProperty::Pointer nameProp = dynamic_cast(children->GetElement(i)->GetProperty("name")); if(nameProp.IsNotNull() && nameProp->GetValueAsString()=="PointBasedRegistrationNode") { m_MovingPointSetNode=children->GetElement(i); m_MovingLandmarks = dynamic_cast (m_MovingPointSetNode->GetData()); this->GetDataStorage()->Remove(m_MovingPointSetNode); hasPointSetNode = true; break; } } if (!hasPointSetNode) { m_MovingLandmarks = mitk::PointSet::New(); m_MovingPointSetNode = mitk::DataNode::New(); m_MovingPointSetNode->SetData(m_MovingLandmarks); m_MovingPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); } this->GetDataStorage()->Add(m_MovingPointSetNode, m_MovingNode); m_MovingPointSetNode->GetStringProperty("label", m_OldMovingLabel); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New("M ")); m_MovingPointSetNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f)); m_MovingPointSetNode->SetVisibility(true); m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->clearTransformationLists(); this->OpacityUpdate(m_Opacity); } if (m_MovingPointSetNode.IsNull()) { m_MovingLandmarks = mitk::PointSet::New(); m_MovingPointSetNode = mitk::DataNode::New(); m_MovingPointSetNode->SetData(m_MovingLandmarks); m_MovingPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); m_MovingPointSetNode->GetStringProperty("label", m_OldMovingLabel); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New("M ")); m_MovingPointSetNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f)); m_MovingPointSetNode->SetVisibility(true); m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); this->GetDataStorage()->Add(m_MovingPointSetNode, m_MovingNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_MovingNode = NULL; if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_MovingPointSetNode = NULL; m_MovingLandmarks = NULL; m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); } if(m_MovingLandmarks.IsNotNull()) m_CurrentMovingLandmarksObserverID = m_MovingLandmarks->AddObserver(itk::ModifiedEvent(), m_MovingLandmarksChangedCommand); } void QmitkPointBasedRegistrationView::updateMovingLandmarksList() { // mitk::PointSet* ps = mitk::PointSet::New(); // ps = dynamic_cast(m_MovingPointSetNode->GetData()); // mitk::DataNode::Pointer tmpPtr = m_MovingPointSetNode; // m_MovingLandmarks = 0; // m_MovingLandmarks = (ps); m_MovingLandmarks = dynamic_cast(m_MovingPointSetNode->GetData()); // m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); //Workaround: m_MovingPointListWidget->m_PointListView->m_PointListModel loses the pointer on the pointsetnode this->checkLandmarkError(); this->CheckCalculate(); } void QmitkPointBasedRegistrationView::updateFixedLandmarksList() { m_FixedLandmarks = dynamic_cast(m_FixedPointSetNode->GetData()); this->checkLandmarkError(); this->CheckCalculate(); } void QmitkPointBasedRegistrationView::HideFixedImage(bool hide) { m_HideFixedImage = hide; if(m_FixedNode.IsNotNull()) { m_FixedNode->SetVisibility(!hide); } if (hide) { //this->reinitMovingClicked(); } if (!m_HideMovingImage && !m_HideFixedImage) { //this->globalReinitClicked(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::HideMovingImage(bool hide) { m_HideMovingImage = hide; if(m_MovingNode.IsNotNull()) { m_MovingNode->SetVisibility(!hide); } if (hide) { //this->reinitFixedClicked(); } if (!m_HideMovingImage && !m_HideFixedImage) { //this->globalReinitClicked(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } bool QmitkPointBasedRegistrationView::CheckCalculate() { if((m_MovingPointSetNode.IsNull())||(m_FixedPointSetNode.IsNull()||m_FixedLandmarks.IsNull()||m_MovingLandmarks.IsNull())) return false; if(m_MovingNode==m_FixedNode) return false; return this->checkCalculateEnabled(); } void QmitkPointBasedRegistrationView::UndoTransformation() { if(!m_UndoPointsGeometryList.empty()) { mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_RedoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); m_MovingLandmarks->SetGeometry(m_UndoPointsGeometryList.back()); m_UndoPointsGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingPointSetNode->SetMapper(1, NULL); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0)->Clone(); m_RedoGeometryList.push_back(movingGeometry.GetPointer()); movingData->SetGeometry(m_UndoGeometryList.back()); m_UndoGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeGeometry()->Update(); m_MovingLandmarks->GetTimeGeometry()->Update(); m_Controls.m_RedoTransformation->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } if(!m_UndoPointsGeometryList.empty()) { m_Controls.m_UndoTransformation->setEnabled(true); } else { m_Controls.m_UndoTransformation->setEnabled(false); } } void QmitkPointBasedRegistrationView::RedoTransformation() { if(!m_RedoPointsGeometryList.empty()) { mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); m_MovingLandmarks->SetGeometry(m_RedoPointsGeometryList.back()); m_RedoPointsGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingPointSetNode->SetMapper(1, NULL); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(movingGeometry.GetPointer()); movingData->SetGeometry(m_RedoGeometryList.back()); m_RedoGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeGeometry()->Update(); m_MovingLandmarks->GetTimeGeometry()->Update(); m_Controls.m_UndoTransformation->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } if(!m_RedoPointsGeometryList.empty()) { m_Controls.m_RedoTransformation->setEnabled(true); } else { m_Controls.m_RedoTransformation->setEnabled(false); } } void QmitkPointBasedRegistrationView::showRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->setImageColor(m_ShowRedGreen); } void QmitkPointBasedRegistrationView::setImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::OpacityUpdate(float opacity) { if (opacity > 1) { opacity = opacity/100.0f; } m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkPointBasedRegistrationView::clearTransformationLists() { m_Controls.m_UndoTransformation->setEnabled(false); m_Controls.m_RedoTransformation->setEnabled(false); m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); m_UndoGeometryList.clear(); m_UndoPointsGeometryList.clear(); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); } void QmitkPointBasedRegistrationView::checkLandmarkError() { double totalDist = 0, dist = 0, dist2 = 0; mitk::Point3D point1, point2, point3; double p1[3], p2[3]; if(m_Transformation < 3) { if (m_Controls.m_UseICP->isChecked()) { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull()&& m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(0); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; dist = vtkMath::Distance2BetweenPoints(p1, p2); for(int pointId2 = 1; pointId2 < m_FixedLandmarks->GetSize(); ++pointId2) { point2 = m_FixedLandmarks->GetPoint(pointId2); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = p1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = p2[2]; dist2 = vtkMath::Distance2BetweenPoints(p1, p2); if (dist2 < dist) { dist = dist2; } } totalDist += dist; } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } else { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0 && m_MovingLandmarks->GetSize() == m_FixedLandmarks->GetSize()) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(pointId); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; totalDist += vtkMath::Distance2BetweenPoints(p1, p2); } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } } else { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0 && m_MovingLandmarks->GetSize() == m_FixedLandmarks->GetSize()) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(pointId); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; totalDist += vtkMath::Distance2BetweenPoints(p1, p2); } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } } void QmitkPointBasedRegistrationView::transformationChanged(int transform) { m_Transformation = transform; this->checkCalculateEnabled(); this->checkLandmarkError(); } // ICP with vtkLandmarkTransformation void QmitkPointBasedRegistrationView::calculateLandmarkbasedWithICP() { if(CheckCalculate()) { mitk::BaseGeometry::Pointer pointsGeometry = m_MovingLandmarks->GetGeometry(0); mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); mitk::BaseData::Pointer originalData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer originalDataGeometry = originalData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(originalDataGeometry.GetPointer()); vtkIdType pointId; vtkPoints* vPointsSource=vtkPoints::New(); vtkCellArray* vCellsSource=vtkCellArray::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D pointSource=m_MovingLandmarks->GetPoint(pointId); vPointsSource->InsertNextPoint(pointSource[0],pointSource[1],pointSource[2]); vCellsSource->InsertNextCell(1, &pointId); } vtkPoints* vPointsTarget=vtkPoints::New(); vtkCellArray* vCellsTarget = vtkCellArray::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D pointTarget=m_FixedLandmarks->GetPoint(pointId); vPointsTarget->InsertNextPoint(pointTarget[0],pointTarget[1],pointTarget[2]); vCellsTarget->InsertNextCell(1, &pointId); } vtkPolyData* vPointSetSource=vtkPolyData::New(); vtkPolyData* vPointSetTarget=vtkPolyData::New(); vPointSetTarget->SetPoints(vPointsTarget); vPointSetTarget->SetVerts(vCellsTarget); vPointSetSource->SetPoints(vPointsSource); vPointSetSource->SetVerts(vCellsSource); vtkIterativeClosestPointTransform * icp=vtkIterativeClosestPointTransform::New(); icp->SetCheckMeanDistance(1); icp->SetSource(vPointSetSource); icp->SetTarget(vPointSetTarget); icp->SetMaximumNumberOfIterations(50); icp->StartByMatchingCentroidsOn(); vtkLandmarkTransform * transform=icp->GetLandmarkTransform(); if(m_Transformation==0) { transform->SetModeToRigidBody(); } if(m_Transformation==1) { transform->SetModeToSimilarity(); } if(m_Transformation==2) { transform->SetModeToAffine(); } vtkMatrix4x4 * matrix=icp->GetMatrix(); double determinant = fabs(matrix->Determinant()); if((determinant < mitk::eps) || (determinant > 100) || (determinant < 0.01) || (determinant==itk::NumericTraits::infinity()) || (determinant==itk::NumericTraits::quiet_NaN()) || (determinant==itk::NumericTraits::signaling_NaN()) || (determinant==-itk::NumericTraits::infinity()) || (determinant==-itk::NumericTraits::quiet_NaN()) || (determinant==-itk::NumericTraits::signaling_NaN()) || (!(determinant <= 0) && !(determinant > 0))) { QMessageBox msgBox; msgBox.setText("Suspicious determinant of matrix calculated by ICP.\n" "Please select more points or other points!" ); msgBox.exec(); return; } pointsGeometry->Compose(matrix); m_MovingLandmarks->GetTimeGeometry()->Update(); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0); movingGeometry->Compose(matrix); movingData->GetTimeGeometry()->Update(); m_Controls.m_UndoTransformation->setEnabled(true); m_Controls.m_RedoTransformation->setEnabled(false); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } } // only vtkLandmarkTransformation void QmitkPointBasedRegistrationView::calculateLandmarkbased() { if(CheckCalculate()) { mitk::BaseGeometry::Pointer pointsGeometry = m_MovingLandmarks->GetGeometry(0); mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); mitk::BaseData::Pointer originalData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer originalDataGeometry = originalData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(originalDataGeometry.GetPointer()); vtkIdType pointId; vtkPoints* vPointsSource=vtkPoints::New(); for(pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { mitk::Point3D sourcePoint = m_MovingLandmarks->GetPoint(pointId); vPointsSource->InsertNextPoint(sourcePoint[0],sourcePoint[1],sourcePoint[2]); } vtkPoints* vPointsTarget=vtkPoints::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D targetPoint=m_FixedLandmarks->GetPoint(pointId); vPointsTarget->InsertNextPoint(targetPoint[0],targetPoint[1],targetPoint[2]); } vtkLandmarkTransform * transform= vtkLandmarkTransform::New(); transform->SetSourceLandmarks(vPointsSource); transform->SetTargetLandmarks(vPointsTarget); if(m_Transformation==0) { transform->SetModeToRigidBody(); } if(m_Transformation==1) { transform->SetModeToSimilarity(); } if(m_Transformation==2) { transform->SetModeToAffine(); } vtkMatrix4x4 * matrix=transform->GetMatrix(); double determinant = fabs(matrix->Determinant()); if((determinant < mitk::eps) || (determinant > 100) || (determinant < 0.01) || (determinant==itk::NumericTraits::infinity()) || (determinant==itk::NumericTraits::quiet_NaN()) || (determinant==itk::NumericTraits::signaling_NaN()) || (determinant==-itk::NumericTraits::infinity()) || (determinant==-itk::NumericTraits::quiet_NaN()) || (determinant==-itk::NumericTraits::signaling_NaN()) || (!(determinant <= 0) && !(determinant > 0))) { QMessageBox msgBox; msgBox.setText("Suspicious determinant of matrix calculated.\n" "Please select more points or other points!" ); msgBox.exec(); return; } pointsGeometry->Compose(matrix); m_MovingLandmarks->GetTimeGeometry()->Update(); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0); movingGeometry->Compose(matrix); movingData->GetTimeGeometry()->Update(); m_Controls.m_UndoTransformation->setEnabled(true); m_Controls.m_RedoTransformation->setEnabled(false); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } } void QmitkPointBasedRegistrationView::calculateLandmarkWarping() { mitk::LandmarkWarping* registration = new mitk::LandmarkWarping(); mitk::LandmarkWarping::FixedImageType::Pointer fixedImage = mitk::LandmarkWarping::FixedImageType::New(); mitk::Image::Pointer fimage = dynamic_cast(m_FixedNode->GetData()); mitk::LandmarkWarping::MovingImageType::Pointer movingImage = mitk::LandmarkWarping::MovingImageType::New(); mitk::Image::Pointer mimage = dynamic_cast(m_MovingNode->GetData()); if (fimage.IsNotNull() && /*fimage->GetDimension() == 2 || */ fimage->GetDimension() == 3 && mimage.IsNotNull() && mimage->GetDimension() == 3) { mitk::CastToItkImage(fimage, fixedImage); mitk::CastToItkImage(mimage, movingImage); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImage); unsigned int pointId; mitk::Point3D sourcePoint, targetPoint; mitk::LandmarkWarping::LandmarkContainerType::Pointer fixedLandmarks = mitk::LandmarkWarping::LandmarkContainerType::New(); mitk::LandmarkWarping::LandmarkPointType point; for(pointId = 0; pointId < (unsigned int)m_FixedLandmarks->GetSize(); ++pointId) { fimage->GetGeometry(0)->WorldToItkPhysicalPoint(m_FixedLandmarks->GetPoint(pointId), point); fixedLandmarks->InsertElement( pointId, point); } mitk::LandmarkWarping::LandmarkContainerType::Pointer movingLandmarks = mitk::LandmarkWarping::LandmarkContainerType::New(); for(pointId = 0; pointId < (unsigned int)m_MovingLandmarks->GetSize(); ++pointId) { mitk::BaseData::Pointer fixedData = m_FixedNode->GetData(); mitk::BaseGeometry::Pointer fixedGeometry = fixedData->GetGeometry(0); fixedGeometry->WorldToItkPhysicalPoint(m_MovingLandmarks->GetPoint(pointId), point); movingLandmarks->InsertElement( pointId, point); } registration->SetLandmarks(fixedLandmarks.GetPointer(), movingLandmarks.GetPointer()); mitk::LandmarkWarping::MovingImageType::Pointer output = registration->Register(); if (output.IsNotNull()) { mitk::Image::Pointer image = mitk::Image::New(); mitk::CastToMitkImage(output, image); m_MovingNode->SetData(image); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( image ); levWinProp->SetLevelWindow(levelWindow); m_MovingNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); movingLandmarks = registration->GetTransformedTargetLandmarks(); mitk::PointSet::PointDataIterator it; it = m_MovingLandmarks->GetPointSet()->GetPointData()->Begin(); //increase the eventId to encapsulate the coming operations mitk::OperationEvent::IncCurrObjectEventId(); mitk::OperationEvent::ExecuteIncrement(); for(pointId=0; pointIdSize();++pointId, ++it) { int position = it->Index(); mitk::PointSet::PointType pt = m_MovingLandmarks->GetPoint(position); mitk::Point3D undoPoint = ( pt ); point = movingLandmarks->GetElement(pointId); fimage->GetGeometry(0)->ItkPhysicalPointToWorld(point, pt); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVE, pt, position); //undo operation mitk::PointOperation* undoOp = new mitk::PointOperation(mitk::OpMOVE, undoPoint, position); mitk::OperationEvent* operationEvent = new mitk::OperationEvent(m_MovingLandmarks, doOp, undoOp, "Move point"); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent(operationEvent); //execute the Operation m_MovingLandmarks->ExecuteOperation(doOp); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->clearTransformationLists(); this->checkLandmarkError(); } } } bool QmitkPointBasedRegistrationView::checkCalculateEnabled() { if (m_FixedLandmarks.IsNotNull() && m_MovingLandmarks.IsNotNull()) { int fixedPoints = m_FixedLandmarks->GetSize(); int movingPoints = m_MovingLandmarks->GetSize(); if (m_Transformation == 0 || m_Transformation == 1 || m_Transformation == 2) { if (m_Controls.m_UseICP->isChecked()) { if((movingPoints > 0 && fixedPoints > 0)) { m_Controls.m_Calculate->setEnabled(true); return true; } else { m_Controls.m_Calculate->setEnabled(false); return false; } } else { if ((movingPoints == fixedPoints) && movingPoints > 0) { m_Controls.m_Calculate->setEnabled(true); return true; } else { m_Controls.m_Calculate->setEnabled(false); return false; } } } else { m_Controls.m_Calculate->setEnabled(true); return true; } } else { return false; } } void QmitkPointBasedRegistrationView::calculate() { if (m_Transformation == 0 || m_Transformation == 1 || m_Transformation == 2) { if (m_Controls.m_UseICP->isChecked()) { if (m_MovingLandmarks->GetSize() == 1 && m_FixedLandmarks->GetSize() == 1) { this->calculateLandmarkbased(); } else { this->calculateLandmarkbasedWithICP(); } } else { this->calculateLandmarkbased(); } } else { this->calculateLandmarkWarping(); } } void QmitkPointBasedRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp index c7dad79144..a80e7ad21f 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp @@ -1,1465 +1,1465 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk includes #include "QmitkRigidRegistrationView.h" #include "QmitkStdMultiWidget.h" // MITK includes #include "mitkDataNodeObject.h" #include #include "mitkManualSegmentationToSurfaceFilter.h" #include #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateProperty.h" // QT includes #include "qinputdialog.h" #include "qmessagebox.h" #include "qcursor.h" #include "qapplication.h" #include "qradiobutton.h" #include "qslider.h" #include "qtooltip.h" // VTK includes #include // ITK includes #include // BlueBerry includes #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkRigidRegistrationView::VIEW_ID = "org.mitk.views.rigidregistration"; using namespace berry; struct SelListenerRigidRegistration : ISelectionListener { berryObjectMacro(SelListenerRigidRegistration); SelListenerRigidRegistration(QmitkRigidRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.m_UseMaskingCB->hide(); m_View->m_Controls.m_OpacityLabel->setEnabled(false); m_View->m_Controls.m_OpacitySlider->setEnabled(false); m_View->m_Controls.label->setEnabled(false); m_View->m_Controls.label_2->setEnabled(false); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); m_View->m_Controls.m_SwitchImages->hide(); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { if (dynamic_cast(node->GetData())->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "RigidRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { // m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.m_UseMaskingCB->show(); m_View->m_Controls.m_OpacityLabel->setEnabled(true); m_View->m_Controls.m_OpacitySlider->setEnabled(true); m_View->m_Controls.label->setEnabled(true); m_View->m_Controls.label_2->setEnabled(true); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } void SelectionChanged(const IWorkbenchPart::Pointer& part, - const ISelection::ConstPointer& selection) override + const ISelection::ConstPointer& selection) { // check, if selection comes from datamanager if (part) { QString partname = part->GetPartName(); if(partname == "Data Manager") { // apply selection DoSelectionChanged(selection); } } } QmitkRigidRegistrationView* m_View; }; QmitkRigidRegistrationView::QmitkRigidRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality(), m_MultiWidget(NULL), m_MovingNode(NULL), m_MovingMaskNode(NULL), m_FixedNode(NULL), m_FixedMaskNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Deactivated(false),m_FixedDimension(0), m_MovingDimension(0) { m_TranslateSliderPos[0] = 0; m_TranslateSliderPos[1] = 0; m_TranslateSliderPos[2] = 0; m_RotateSliderPos[0] = 0; m_RotateSliderPos[1] = 0; m_RotateSliderPos[2] = 0; m_ScaleSliderPos[0] = 0; m_ScaleSliderPos[1] = 0; m_ScaleSliderPos[2] = 0; translationParams = new int[3]; rotationParams = new int[3]; scalingParams = new int[3]; m_TimeStepperAdapter = NULL; this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkRigidRegistrationView::DataNodeHasBeenRemoved )); } QmitkRigidRegistrationView::~QmitkRigidRegistrationView() { if(m_SelListener) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener.data()); } this->GetDataStorage()->RemoveNodeEvent.RemoveListener(mitk::MessageDelegate1 ( this, &QmitkRigidRegistrationView::DataNodeHasBeenRemoved )); } void QmitkRigidRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Controls.m_ManualFrame->hide(); m_Controls.timeSlider->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); //m_Controls.m_UseFixedImageMask->hide(); //m_Controls.m_UseMovingImageMask->hide(); m_Controls.m_UseMaskingCB->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_SwitchImages->hide(); if (m_Controls.m_RigidTransform->currentIndex() == 1) { m_Controls.frame->show(); } else { m_Controls.frame->hide(); } m_Controls.m_ManualFrame->setEnabled(false); m_Parent->setEnabled(false); mitk::NodePredicateAnd::Pointer andPred = // we want binary images in the selectors mitk::NodePredicateAnd::New(mitk::NodePredicateDataType::New("Image"), mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true))); m_Controls.m_FixedImageCB->SetPredicate(andPred); m_Controls.m_FixedImageCB->SetDataStorage(this->GetDataStorage()); m_Controls.m_FixedImageCB->hide(); m_Controls.m_FixedMaskLB->hide(); m_Controls.m_MovingImageCB->SetPredicate(andPred); m_Controls.m_MovingImageCB->SetDataStorage(this->GetDataStorage()); m_Controls.m_MovingImageCB->hide(); m_Controls.m_MovingMaskLB->hide(); this->CreateConnections(); this->CheckCalculateEnabled(); } void QmitkRigidRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); } void QmitkRigidRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; } void QmitkRigidRegistrationView::CreateConnections() { connect( m_Controls.m_ManualRegistrationCheckbox, SIGNAL(toggled(bool)), this, SLOT(ShowManualRegistrationFrame(bool))); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect(m_Controls.m_ShowRedGreenValues, SIGNAL(toggled(bool)), this, SLOT(ShowRedGreen(bool))); connect(m_Controls.m_ShowContour, SIGNAL(toggled(bool)), this, SLOT(EnableContour(bool))); //connect(m_Controls.m_UseFixedImageMask, SIGNAL(toggled(bool)), this, SLOT(UseFixedMaskImageChecked(bool))); //connect(m_Controls.m_UseMovingImageMask, SIGNAL(toggled(bool)), this, SLOT(UseMovingMaskImageChecked(bool))); connect(m_Controls.m_RigidTransform, SIGNAL(currentChanged(int)), this, SLOT(TabChanged(int))); connect(m_Controls.m_OpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityUpdate(int))); connect(m_Controls.m_ContourSlider, SIGNAL(sliderReleased()), this, SLOT(ShowContour())); connect(m_Controls.m_CalculateTransformation, SIGNAL(clicked()), this, SLOT(Calculate())); connect(m_Controls.m_UndoTransformation,SIGNAL(clicked()),this,SLOT(UndoTransformation())); connect(m_Controls.m_RedoTransformation,SIGNAL(clicked()),this,SLOT(RedoTransformation())); connect(m_Controls.m_AutomaticTranslation,SIGNAL(clicked()),this,SLOT(AlignCenters())); connect(m_Controls.m_StopOptimization,SIGNAL(clicked()), this , SLOT(StopOptimizationClicked())); connect(m_Controls.m_XTransSlider, SIGNAL(valueChanged(int)), this, SLOT(xTrans_valueChanged(int))); connect(m_Controls.m_YTransSlider, SIGNAL(valueChanged(int)), this, SLOT(yTrans_valueChanged(int))); connect(m_Controls.m_ZTransSlider, SIGNAL(valueChanged(int)), this, SLOT(zTrans_valueChanged(int))); connect(m_Controls.m_XRotSlider, SIGNAL(valueChanged(int)), this, SLOT(xRot_valueChanged(int))); connect(m_Controls.m_YRotSlider, SIGNAL(valueChanged(int)), this, SLOT(yRot_valueChanged(int))); connect(m_Controls.m_ZRotSlider, SIGNAL(valueChanged(int)), this, SLOT(zRot_valueChanged(int))); connect(m_Controls.m_XScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(xScale_valueChanged(int))); connect(m_Controls.m_YScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(yScale_valueChanged(int))); connect(m_Controls.m_ZScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(zScale_valueChanged(int))); connect(m_Controls.m_LoadRigidRegistrationParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(LoadRigidRegistrationParameter())); connect(m_Controls.m_SaveRigidRegistrationParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(SaveRigidRegistrationParameter())); connect(m_Controls.m_LoadRigidRegistrationTestParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(LoadRigidRegistrationTestParameter())); connect(m_Controls.m_SaveRigidRegistrationTestParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(SaveRigidRegistrationTestParameter())); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(OptimizerChanged(double)),this,SLOT(SetOptimizerValue( double ))); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(TransformChanged()),this,SLOT(CheckCalculateEnabled())); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(AddNewTransformationToUndoList()),this,SLOT(AddNewTransformationToUndoList())); connect(m_Controls.m_UseMaskingCB, SIGNAL(stateChanged(int)),this,SLOT(OnUseMaskingChanged(int))); connect(m_Controls.m_FixedImageCB, SIGNAL(OnSelectionChanged(const mitk::DataNode*)),this,SLOT(OnFixedMaskImageChanged(const mitk::DataNode*))); connect(m_Controls.m_MovingImageCB, SIGNAL(OnSelectionChanged(const mitk::DataNode*)),this,SLOT(OnMovingMaskImageChanged(const mitk::DataNode*))); } void QmitkRigidRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.isNull()) { m_SelListener.reset(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); static_cast(m_SelListener.data())->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled(); /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/ *"org.mitk.views.datamanager",* / m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled();*/ } void QmitkRigidRegistrationView::Visible() { /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener("org.mitk.views.datamanager", m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled();*/ } void QmitkRigidRegistrationView::Deactivated() { m_Deactivated = true; this->SetImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener.data()); m_SelListener.reset(); /* m_Deactivated = true; this->SetImageColor(false); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Deactivated();*/ } void QmitkRigidRegistrationView::Hidden() { /*m_Deactivated = true; this->SetImageColor(false); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated();*/ } void QmitkRigidRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_SwitchImages->hide(); } else if(node == m_ContourHelperNode) { // can this cause a memory leak? m_ContourHelperNode = NULL; } } void QmitkRigidRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if (m_FixedNode.IsNotNull()) { this->SetImageColor(false); m_FixedNode->SetOpacity(1.0); } m_FixedNode = fixedImage; if (m_FixedNode.IsNotNull()) { m_FixedNode->SetOpacity(0.5); m_FixedNode->SetVisibility(true); m_Controls.TextLabelFixed->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.TextLabelFixed->show(); m_Controls.m_SwitchImages->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if (dynamic_cast(m_FixedNode->GetData())) { m_FixedDimension = dynamic_cast(m_FixedNode->GetData())->GetDimension(); m_Controls.qmitkRigidRegistrationSelector1->SetFixedDimension(m_FixedDimension); m_Controls.qmitkRigidRegistrationSelector1->SetFixedNode(m_FixedNode); } // what's about masking? m_Controls.m_UseMaskingCB->show(); // Modify slider range mitk::Image::Pointer image = dynamic_cast(m_FixedNode->GetData()); int min = (int)image->GetStatistics()->GetScalarValueMin(); int max = (int)image->GetStatistics()->GetScalarValueMax(); m_Controls.m_ContourSlider->setRange(min, max); // Set slider to a default value int avg = (min+max) / 2; m_Controls.m_ContourSlider->setSliderPosition(avg); m_Controls.m_ThresholdLabel->setText(QString::number(avg)); } else { m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); } this->CheckCalculateEnabled(); if(this->GetActiveStdMultiWidget()) { m_TimeStepperAdapter = new QmitkStepperAdapter((QObject*) m_Controls.timeSlider, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromRigidRegistration"); connect( m_TimeStepperAdapter, SIGNAL( Refetch() ), this, SLOT( UpdateTimestep() ) ); } } void QmitkRigidRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->SetImageColor(false); } // selection did not change - do onot reset if( m_MovingNode.IsNotNull() && m_MovingNode == movingImage) { } else { m_MovingNode = movingImage; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetVisibility(true); m_Controls.TextLabelMoving->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); // what's about masking? m_Controls.m_UseMaskingCB->show(); } else { m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_UseMaskingCB->hide(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->MovingImageChanged(); this->CheckCalculateEnabled(); } } bool QmitkRigidRegistrationView::CheckCalculate() { if(m_MovingNode==m_FixedNode) return false; return true; } void QmitkRigidRegistrationView::AddNewTransformationToUndoList() { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_UndoGeometryList.push_back(static_cast(movingData->GetGeometry()->Clone().GetPointer())); GeometryMapType childGeometries = GeometryMapType(); if(m_MovingMaskNode.IsNotNull()) { childGeometries.insert(std::pair(m_MovingMaskNode, static_cast(m_MovingMaskNode->GetData()->GetGeometry()->Clone().GetPointer()))); } mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); if(children.IsNotNull() && children->Size() != 0) { unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { childGeometries.insert(std::pair(children->GetElement(i), static_cast(children->GetElement(i)->GetData()->GetGeometry()->Clone().GetPointer()))); } } m_UndoChildGeometryList.push_back(childGeometries); m_RedoGeometryList.clear(); m_RedoChildGeometryList.clear(); this->SetUndoEnabled(true); this->SetRedoEnabled(false); } void QmitkRigidRegistrationView::UndoTransformation() { if(!m_UndoGeometryList.empty()) { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_RedoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size = 0; GeometryMapType childGeometries = GeometryMapType(); if(m_MovingMaskNode.IsNotNull()) { ++size; } mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size += children->Size(); for (unsigned long i = 0; i < size; ++i) { if(i==0) { childGeometries.insert(std::pair(m_MovingMaskNode, static_cast(m_MovingMaskNode->GetData()->GetGeometry()->Clone().GetPointer()))); } else { childGeometries.insert(std::pair(children->GetElement(i), static_cast(children->GetElement(i)->GetData()->GetGeometry()->Clone().GetPointer()))); } } m_RedoChildGeometryList.push_back(childGeometries); movingData->SetGeometry(m_UndoGeometryList.back()); m_UndoGeometryList.pop_back(); GeometryMapType oldChildGeometries; oldChildGeometries = m_UndoChildGeometryList.back(); m_UndoChildGeometryList.pop_back(); GeometryMapType::iterator iter; for (unsigned long j = 0; j < size; ++j) { if(j == 0) // we have put the geometry for the moving mask at position one { iter = oldChildGeometries.find(m_MovingMaskNode); mitk::Geometry3D* geo = static_cast((*iter).second); m_MovingMaskNode->GetData()->SetGeometry(geo); m_MovingMaskNode->GetData()->GetTimeGeometry()->Update(); } else { iter = oldChildGeometries.find(children->GetElement(j)); children->GetElement(j)->GetData()->SetGeometry((*iter).second); } } //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper //m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->SetRedoEnabled(true); } if(!m_UndoGeometryList.empty()) { this->SetUndoEnabled(true); } else { this->SetUndoEnabled(false); } this->CheckCalculateEnabled(); } void QmitkRigidRegistrationView::RedoTransformation() { if(!m_RedoGeometryList.empty()) { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_UndoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size = 0; GeometryMapType childGeometries = GeometryMapType(); if(m_MovingMaskNode.IsNotNull()) { ++size; } mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size += children->Size(); for (unsigned long i = 0; i < size; ++i) { if(i == 0) { childGeometries.insert(std::pair(m_MovingMaskNode, static_cast(m_MovingMaskNode->GetData()->GetGeometry()->Clone().GetPointer()))); } else { childGeometries.insert(std::pair(children->GetElement(i), static_cast(children->GetElement(i)->GetData()->GetGeometry()->Clone().GetPointer()))); } } m_UndoChildGeometryList.push_back(childGeometries); movingData->SetGeometry(m_RedoGeometryList.back()); m_RedoGeometryList.pop_back(); GeometryMapType oldChildGeometries; oldChildGeometries = m_RedoChildGeometryList.back(); m_RedoChildGeometryList.pop_back(); GeometryMapType::iterator iter; for (unsigned long j = 0; j < size; ++j) { if(j == 0) { iter = oldChildGeometries.find(m_MovingMaskNode); m_MovingMaskNode->GetData()->SetGeometry((*iter).second); } else { iter = oldChildGeometries.find(children->GetElement(j)); children->GetElement(j)->GetData()->SetGeometry((*iter).second); } } movingData->GetTimeGeometry()->Update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->SetUndoEnabled(true); } if(!m_RedoGeometryList.empty()) { this->SetRedoEnabled(true); } else { this->SetRedoEnabled(false); } } void QmitkRigidRegistrationView::ShowRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->SetImageColor(m_ShowRedGreen); } void QmitkRigidRegistrationView::EnableContour(bool show) { if(show) ShowContour(); // Can happen when the m_ContourHelperNode was deleted before and now the show contour checkbox is turned off if(m_ContourHelperNode.IsNull()) return; m_Controls.m_ContourSlider->setEnabled(show); m_ContourHelperNode->SetProperty("visible", mitk::BoolProperty::New(show)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkRigidRegistrationView::ShowContour() { int threshold = m_Controls.m_ContourSlider->value(); bool show = m_Controls.m_ShowContour->isChecked(); if(m_FixedNode.IsNull() || !show) return; // Update the label next to the slider m_Controls.m_ThresholdLabel->setText(QString::number(threshold)); mitk::Image::Pointer image = dynamic_cast(m_FixedNode->GetData()); typedef itk::Image FloatImageType; typedef itk::Image ShortImageType; // Create a binary image using the given treshold typedef itk::BinaryThresholdImageFilter ThresholdFilterType; FloatImageType::Pointer floatImage = FloatImageType::New(); mitk::CastToItkImage(image, floatImage); ThresholdFilterType::Pointer thresholdFilter = ThresholdFilterType::New(); thresholdFilter->SetInput(floatImage); thresholdFilter->SetLowerThreshold(threshold); thresholdFilter->SetUpperThreshold((int)image->GetStatistics()->GetScalarValueMax()); thresholdFilter->SetInsideValue(1); thresholdFilter->SetOutsideValue(0); thresholdFilter->Update(); ShortImageType::Pointer binaryImage = thresholdFilter->GetOutput(); mitk::Image::Pointer mitkBinaryImage = mitk::Image::New(); mitk::CastToMitkImage(binaryImage, mitkBinaryImage); // Create a contour from the binary image mitk::ManualSegmentationToSurfaceFilter::Pointer surfaceFilter = mitk::ManualSegmentationToSurfaceFilter::New(); surfaceFilter->SetInput( mitkBinaryImage ); surfaceFilter->SetThreshold( 1 ); //expects binary image with zeros and ones surfaceFilter->SetUseGaussianImageSmooth(false); // apply gaussian to thresholded image ? surfaceFilter->SetMedianFilter3D(false); // apply median to segmentation before marching cubes ? surfaceFilter->SetDecimate( mitk::ImageToSurfaceFilter::NoDecimation ); surfaceFilter->UpdateLargestPossibleRegion(); // calculate normals for nicer display mitk::Surface::Pointer surface = surfaceFilter->GetOutput(); if(m_ContourHelperNode.IsNull()) { m_ContourHelperNode = mitk::DataNode::New(); m_ContourHelperNode->SetData(surface); m_ContourHelperNode->SetProperty("opacity", mitk::FloatProperty::New(1.0) ); m_ContourHelperNode->SetProperty("line width", mitk::IntProperty::New(2) ); m_ContourHelperNode->SetProperty("scalar visibility", mitk::BoolProperty::New(false) ); m_ContourHelperNode->SetProperty( "name", mitk::StringProperty::New("surface") ); m_ContourHelperNode->SetProperty("color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); m_ContourHelperNode->SetBoolProperty("helper object", true); this->GetDataStorage()->Add(m_ContourHelperNode); } else { m_ContourHelperNode->SetData(surface); } mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkRigidRegistrationView::SetImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::OpacityUpdate(float opacity) { m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkRigidRegistrationView::ClearTransformationLists() { this->SetUndoEnabled(false); this->SetRedoEnabled(false); m_UndoGeometryList.clear(); m_UndoChildGeometryList.clear(); m_RedoGeometryList.clear(); m_RedoChildGeometryList.clear(); } void QmitkRigidRegistrationView::Translate(int* translateVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D translateVec; mitk::ScalarType sliderSensitivity = 0.1; translateVec[0] = sliderSensitivity * (translateVector[0] - m_TranslateSliderPos[0]); translateVec[1] = sliderSensitivity * (translateVector[1] - m_TranslateSliderPos[1]); translateVec[2] = sliderSensitivity * (translateVector[2] - m_TranslateSliderPos[2]); m_TranslateSliderPos[0] = translateVector[0]; m_TranslateSliderPos[1] = translateVector[1]; m_TranslateSliderPos[2] = translateVector[2]; vtkMatrix4x4* translationMatrix = vtkMatrix4x4::New(); translationMatrix->Identity(); double (*transMatrix)[4] = translationMatrix->Element; transMatrix[0][3] = -translateVec[0]; transMatrix[1][3] = -translateVec[1]; transMatrix[2][3] = -translateVec[2]; translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); m_MovingNode->GetData()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::Rotate(int* rotateVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D rotateVec; rotateVec[0] = rotateVector[0] - m_RotateSliderPos[0]; rotateVec[1] = rotateVector[1] - m_RotateSliderPos[1]; rotateVec[2] = rotateVector[2] - m_RotateSliderPos[2]; m_RotateSliderPos[0] = rotateVector[0]; m_RotateSliderPos[1] = rotateVector[1]; m_RotateSliderPos[2] = rotateVector[2]; vtkMatrix4x4* rotationMatrix = vtkMatrix4x4::New(); vtkMatrix4x4* translationMatrix = vtkMatrix4x4::New(); rotationMatrix->Identity(); translationMatrix->Identity(); double (*rotMatrix)[4] = rotationMatrix->Element; double (*transMatrix)[4] = translationMatrix->Element; mitk::Point3D centerBB = m_MovingNode->GetData()->GetGeometry()->GetCenter(); transMatrix[0][3] = centerBB[0]; transMatrix[1][3] = centerBB[1]; transMatrix[2][3] = centerBB[2]; translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } double radianX = rotateVec[0] * vnl_math::pi / 180; double radianY = rotateVec[1] * vnl_math::pi / 180; double radianZ = rotateVec[2] * vnl_math::pi / 180; if ( rotateVec[0] != 0 ) { rotMatrix[1][1] = cos( radianX ); rotMatrix[1][2] = -sin( radianX ); rotMatrix[2][1] = sin( radianX ); rotMatrix[2][2] = cos( radianX ); } else if ( rotateVec[1] != 0 ) { rotMatrix[0][0] = cos( radianY ); rotMatrix[0][2] = sin( radianY ); rotMatrix[2][0] = -sin( radianY ); rotMatrix[2][2] = cos( radianY ); } else if ( rotateVec[2] != 0 ) { rotMatrix[0][0] = cos( radianZ ); rotMatrix[0][1] = -sin( radianZ ); rotMatrix[1][0] = sin( radianZ ); rotMatrix[1][1] = cos( radianZ ); } m_MovingNode->GetData()->GetGeometry()->Compose( rotationMatrix ); for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( rotationMatrix ); childNode->GetData()->Modified(); } translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } m_MovingNode->GetData()->Modified(); m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::Scale(int* scaleVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D scaleVec; scaleVec[0] = scaleVector[0] - m_ScaleSliderPos[0]; scaleVec[1] = scaleVector[1] - m_ScaleSliderPos[1]; scaleVec[2] = scaleVector[2] - m_ScaleSliderPos[2]; m_ScaleSliderPos[0] = scaleVector[0]; m_ScaleSliderPos[1] = scaleVector[1]; m_ScaleSliderPos[2] = scaleVector[2]; vtkMatrix4x4* scalingMatrix = vtkMatrix4x4::New(); scalingMatrix->Identity(); double (*scaleMatrix)[4] = scalingMatrix->Element; if (scaleVec[0] >= 0) { for(int i = 0; i= 0) { for(int i = 0; i= 0) { for(int i = 0; iInvert(); m_MovingNode->GetData()->GetGeometry()->Compose( scalingMatrix ); m_MovingNode->GetData()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( scalingMatrix ); childNode->GetData()->Modified(); } m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::AlignCenters() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { mitk::Point3D fixedPoint = m_FixedNode->GetData()->GetGeometry()->GetCenter(); mitk::Point3D movingPoint = m_MovingNode->GetData()->GetGeometry()->GetCenter(); mitk::Vector3D translateVec; translateVec = fixedPoint - movingPoint; m_Controls.m_XTransSlider->setValue((int)m_Controls.m_XTransSlider->value() + (int)translateVec[0]); m_Controls.m_YTransSlider->setValue((int)m_Controls.m_YTransSlider->value() + (int)translateVec[1]); m_Controls.m_ZTransSlider->setValue((int)m_Controls.m_ZTransSlider->value() + (int)translateVec[2]); } } void QmitkRigidRegistrationView::SetUndoEnabled( bool enable ) { m_Controls.m_UndoTransformation->setEnabled(enable); } void QmitkRigidRegistrationView::SetRedoEnabled( bool enable ) { m_Controls.m_RedoTransformation->setEnabled(enable); } void QmitkRigidRegistrationView::CheckCalculateEnabled() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { m_Controls.m_ManualFrame->setEnabled(true); m_Controls.m_CalculateTransformation->setEnabled(true); if ( (m_FixedDimension != m_MovingDimension && std::max(m_FixedDimension, m_MovingDimension) != 4) || m_FixedDimension < 2 /*|| m_FixedDimension > 3*/) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if (m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() < 5 && (m_FixedDimension < 2) /*|| m_FixedDimension > 3)*/) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if ((m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() > 4 && m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() < 13) && !(m_FixedDimension > 2)) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if (m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() > 12 && m_FixedDimension != 2) { m_Controls.m_CalculateTransformation->setEnabled(false); } } else { m_Controls.m_CalculateTransformation->setEnabled(false); m_Controls.m_ManualFrame->setEnabled(false); } } void QmitkRigidRegistrationView::xTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=v; translationParams[1]=m_Controls.m_YTransSlider->value(); translationParams[2]=m_Controls.m_ZTransSlider->value(); Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=m_Controls.m_XTransSlider->value(); translationParams[1]=v; translationParams[2]=m_Controls.m_ZTransSlider->value(); Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=m_Controls.m_XTransSlider->value(); translationParams[1]=m_Controls.m_YTransSlider->value(); translationParams[2]=v; Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::xRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=v; rotationParams[1]=m_Controls.m_YRotSlider->value(); rotationParams[2]=m_Controls.m_ZRotSlider->value(); Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=m_Controls.m_XRotSlider->value(); rotationParams[1]=v; rotationParams[2]=m_Controls.m_ZRotSlider->value(); Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=m_Controls.m_XRotSlider->value(); rotationParams[1]=m_Controls.m_YRotSlider->value(); rotationParams[2]=v; Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::xScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=v; scalingParams[1]=m_Controls.m_YScaleSlider->value(); scalingParams[2]=m_Controls.m_ZScaleSlider->value(); Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=m_Controls.m_XScaleSlider->value(); scalingParams[1]=v; scalingParams[2]=m_Controls.m_ZScaleSlider->value(); Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=m_Controls.m_XScaleSlider->value(); scalingParams[1]=m_Controls.m_YScaleSlider->value(); scalingParams[2]=v; Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::MovingImageChanged() { if (dynamic_cast(m_MovingNode->GetData())) { m_Controls.m_XTransSlider->setValue(0); m_Controls.m_YTransSlider->setValue(0); m_Controls.m_ZTransSlider->setValue(0); translationParams[0]=0; translationParams[1]=0; translationParams[2]=0; m_Controls.m_XRotSlider->setValue(0); m_Controls.m_YRotSlider->setValue(0); m_Controls.m_ZRotSlider->setValue(0); rotationParams[0]=0; rotationParams[1]=0; rotationParams[2]=0; m_Controls.m_XScaleSlider->setValue(0); m_Controls.m_YScaleSlider->setValue(0); m_Controls.m_ZScaleSlider->setValue(0); scalingParams[0]=0; scalingParams[1]=0; scalingParams[2]=0; m_MovingDimension = dynamic_cast(m_MovingNode->GetData())->GetDimension(); m_Controls.qmitkRigidRegistrationSelector1->SetMovingDimension(m_MovingDimension); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNode(m_MovingNode); this->CheckCalculateEnabled(); } } void QmitkRigidRegistrationView::Calculate() { m_Controls.qmitkRigidRegistrationSelector1->SetFixedNode(m_FixedNode); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNode(m_MovingNode); if (m_FixedMaskNode.IsNotNull() && m_Controls.m_UseMaskingCB->isChecked()) { m_Controls.qmitkRigidRegistrationSelector1->SetFixedMaskNode(m_FixedMaskNode); } else { m_Controls.qmitkRigidRegistrationSelector1->SetFixedMaskNode(NULL); } if (m_MovingMaskNode.IsNotNull() && m_Controls.m_UseMaskingCB->isChecked()) { m_Controls.qmitkRigidRegistrationSelector1->SetMovingMaskNode(m_MovingMaskNode); } else { m_Controls.qmitkRigidRegistrationSelector1->SetMovingMaskNode(NULL); } m_Controls.frame_2->setEnabled(false); m_Controls.frame_3->setEnabled(false); m_Controls.m_CalculateTransformation->setEnabled(false); m_Controls.m_StopOptimization->setEnabled(true); m_Controls.qmitkRigidRegistrationSelector1->CalculateTransformation(((QmitkSliderNavigatorWidget*)m_Controls.timeSlider)->GetPos()); m_Controls.m_StopOptimization->setEnabled(false); m_Controls.frame_2->setEnabled(true); m_Controls.frame_3->setEnabled(true); m_Controls.m_CalculateTransformation->setEnabled(true); m_Controls.qmitkRigidRegistrationSelector1->StopOptimization(false); } void QmitkRigidRegistrationView::SetOptimizerValue( double value ) { m_Controls.m_OptimizerValueLCD->display(value); } void QmitkRigidRegistrationView::StopOptimizationClicked() { m_Controls.qmitkRigidRegistrationSelector1->StopOptimization(true); } void QmitkRigidRegistrationView::UpdateTimestep() { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::ShowManualRegistrationFrame(bool show) { if (show) { m_Controls.m_ManualFrame->show(); } else { m_Controls.m_ManualFrame->hide(); } } void QmitkRigidRegistrationView::SetImagesVisible(berry::ISelection::ConstPointer /*selection*/) { if (this->m_CurrentSelection->Size() == 0) { // show all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(true); } } } else { // hide all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(false); } } } } void QmitkRigidRegistrationView::TabChanged(int index) { if (index == 0) { m_Controls.frame->hide(); } else { m_Controls.frame->show(); } } void QmitkRigidRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); if(m_ContourHelperNode.IsNotNull()) { // Update the contour ShowContour(); } if(m_Controls.m_UseMaskingCB->isChecked()) { mitk::DataNode::Pointer tempMovingMask = NULL; mitk::DataNode::Pointer tempFixedMask = NULL; if(m_FixedMaskNode.IsNotNull()) // it is initialized { tempFixedMask = m_Controls.m_FixedImageCB->GetSelectedNode(); } if(m_MovingMaskNode.IsNotNull()) // it is initialized { tempMovingMask = m_Controls.m_MovingImageCB->GetSelectedNode(); } m_Controls.m_FixedImageCB->SetSelectedNode(tempMovingMask); m_Controls.m_MovingImageCB->SetSelectedNode(tempFixedMask); } } void QmitkRigidRegistrationView::OnUseMaskingChanged( int state ) { if(state == Qt::Checked) { m_Controls.m_FixedImageCB->show(); m_Controls.m_MovingImageCB->show(); m_Controls.m_MovingMaskLB->show(); m_Controls.m_FixedMaskLB->show(); } else { m_Controls.m_FixedImageCB->hide(); m_Controls.m_MovingImageCB->hide(); m_Controls.m_MovingMaskLB->hide(); m_Controls.m_FixedMaskLB->hide(); m_FixedMaskNode = NULL; m_MovingMaskNode = NULL; } } void QmitkRigidRegistrationView::OnFixedMaskImageChanged( const mitk::DataNode* node ) { if(m_Controls.m_UseMaskingCB->isChecked()) m_FixedMaskNode = const_cast(node); else m_FixedMaskNode = NULL; } void QmitkRigidRegistrationView::OnMovingMaskImageChanged( const mitk::DataNode* node ) { if(m_Controls.m_UseMaskingCB->isChecked()) m_MovingMaskNode = const_cast(node); else m_MovingMaskNode = NULL; }