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_ */