diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp index 1f7eabc4db..99777fef44 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp @@ -1,161 +1,161 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkIsoSurface.h" // MITK headers #include #include #include #include // Qt-GUI headers #include #include #include QmitkIsoSurface::QmitkIsoSurface(QObject * /*parent*/, const char * /*name*/) : m_Controls(nullptr), m_MitkImage(nullptr), m_SurfaceCounter(0) { } void QmitkIsoSurface::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkIsoSurfaceControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_ImageSelector->SetDataStorage(this->GetDataStorage()); m_Controls->m_ImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); auto* prefs = this->GetPreferences(); if (prefs != nullptr) m_Controls->thresholdLineEdit->setText(QString::fromStdString(prefs->Get("defaultThreshold", "0"))); } } void QmitkIsoSurface::SetFocus() { m_Controls->m_ImageSelector->setFocus(); } void QmitkIsoSurface::CreateConnections() { if (m_Controls) { connect(m_Controls->m_ImageSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode *)), this, SLOT(ImageSelected(const mitk::DataNode *))); connect(m_Controls->createSurfacePushButton, SIGNAL(clicked()), this, SLOT(CreateSurface())); } } void QmitkIsoSurface::ImageSelected(const mitk::DataNode *item) { // nothing selected (nullptr selection) if (item == nullptr || item->GetData() == nullptr) return; m_MitkImage = dynamic_cast(item->GetData()); } void QmitkIsoSurface::CreateSurface() { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); if (m_MitkImage != nullptr) { // Value Gauss // float gsDev = 1.5; // Value for DecimatePro float targetReduction = 0.05; // ImageToSurface Instance mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode(); mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout << "nullptr Pointer for ManualSegmentationToSurfaceFilter" << std::endl; return; } filter->SetInput(m_MitkImage); filter->SetGaussianStandardDeviation(0.5); filter->SetUseGaussianImageSmooth(true); filter->SetThreshold(getThreshold()); // if( Gauss ) --> TH manipulated for vtkMarchingCube filter->SetTargetReduction(targetReduction); int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys(); if (numOfPolys > 2000000) { QApplication::restoreOverrideCursor(); if (QMessageBox::question(nullptr, "CAUTION!!!", "The number of polygons is greater than 2 000 000. If you continue, the program might " "crash. How do you want to go on?", "Proceed anyway!", "Cancel immediately! (maybe you want to insert an other threshold)!", - QString::null, + QString(), 0, 1) == 1) { return; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); } mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetData(filter->GetOutput()); int layer = 0; ++m_SurfaceCounter; std::ostringstream buffer; buffer << m_SurfaceCounter; std::string surfaceNodeName = "Surface " + buffer.str(); node->GetIntProperty("layer", layer); surfaceNode->SetIntProperty("layer", layer + 1); surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true)); surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName)); this->GetDataStorage()->Add(surfaceNode, node); // to show surfaceContur surfaceNode->SetColor(m_RainbowColor.GetNextColor()); surfaceNode->SetVisibility(true); mitk::IRenderWindowPart *renderPart = this->GetRenderWindowPart(); if (renderPart) { renderPart->RequestUpdate(); } } QApplication::restoreOverrideCursor(); } float QmitkIsoSurface::getThreshold() { return m_Controls->thresholdLineEdit->text().toFloat(); } QmitkIsoSurface::~QmitkIsoSurface() { auto* prefs = this->GetPreferences(); if (prefs != nullptr) prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text().toStdString()); } diff --git a/Modules/QtWidgetsExt/include/QmitkHistogram.h b/Modules/QtWidgetsExt/include/QmitkHistogram.h index 77128944ce..b2baf5861d 100644 --- a/Modules/QtWidgetsExt/include/QmitkHistogram.h +++ b/Modules/QtWidgetsExt/include/QmitkHistogram.h @@ -1,58 +1,58 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkHistogram_h #define QmitkHistogram_h #include #include #include #include #include /** \brief Used to create a histogram that can be shown in a Qwt Plot. See QmitkHistogramWidget for an example of its usage. */ class QmitkHistogram : public QwtPlotItem { public: - explicit QmitkHistogram(const QString &title = QString::null); + explicit QmitkHistogram(const QString &title = QString()); explicit QmitkHistogram(const QwtText &title); ~QmitkHistogram() override; void setData(const QwtIntervalSeriesData &data); const QwtIntervalSeriesData &data() const; void setColor(const QColor &); QColor color() const; QRectF boundingRect() const override; void draw(QPainter *, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &) const override; void setBaseline(double reference); double baseline() const; protected: virtual void drawBar(QPainter *, Qt::Orientation o, const QRect &) const; private: void init(); class HistogramData; HistogramData *m_Data; }; #endif diff --git a/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp b/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp index 17bb2e4466..679126aa90 100644 --- a/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp +++ b/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp @@ -1,138 +1,135 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkNumberPropertyView.h" #include #define DT_SHORT 1 #define DT_INT 2 #define DT_FLOAT 3 #define DT_DOUBLE 4 QmitkNumberPropertyView::QmitkNumberPropertyView(const mitk::IntProperty *property, QWidget *parent) : QLabel(parent), PropertyView(property), m_IntProperty(property), m_DataType(DT_INT) { initialize(); } QmitkNumberPropertyView::QmitkNumberPropertyView(const mitk::FloatProperty *property, QWidget *parent) : QLabel(parent), PropertyView(property), m_FloatProperty(property), m_DataType(DT_FLOAT) { initialize(); } QmitkNumberPropertyView::QmitkNumberPropertyView(const mitk::DoubleProperty *property, QWidget *parent) : QLabel(parent), PropertyView(property), m_DoubleProperty(property), m_DataType(DT_DOUBLE) { initialize(); } QmitkNumberPropertyView::~QmitkNumberPropertyView() { } void QmitkNumberPropertyView::initialize() { // only to be called from constructors m_Suffix = ""; m_DisplayFactor = 1.0; setDecimalPlaces(2); } short QmitkNumberPropertyView::decimalPlaces() const { return m_DecimalPlaces; } void QmitkNumberPropertyView::setDecimalPlaces(short places) { m_DecimalPlaces = places; DisplayNumber(); } QString QmitkNumberPropertyView::suffix() const { - if (m_Suffix == "") - return QString::null; - else - return m_Suffix; + return m_Suffix; } void QmitkNumberPropertyView::setSuffix(const QString &suffix) { m_Suffix = suffix; DisplayNumber(); } bool QmitkNumberPropertyView::showPercent() const { return m_DisplayFactor == 100.0; } void QmitkNumberPropertyView::setShowPercent(bool show) { if (show) { m_DisplayFactor = 100.0; setSuffix("%"); } else { m_DisplayFactor = 1.0; setSuffix(""); } } void QmitkNumberPropertyView::PropertyChanged() { if (m_Property) DisplayNumber(); } void QmitkNumberPropertyView::PropertyRemoved() { m_Property = nullptr; setText("n/a"); } void QmitkNumberPropertyView::DisplayNumber() { QString displayedText; QTextStream stream(&displayedText); stream.setRealNumberPrecision(m_DecimalPlaces); switch (m_DataType) { case DT_INT: { int i = m_IntProperty->GetValue(); stream << (i * m_DisplayFactor); break; } case DT_FLOAT: { float f = m_FloatProperty->GetValue(); stream << (f * m_DisplayFactor); break; } case DT_DOUBLE: { double d = m_DoubleProperty->GetValue(); stream << (d * m_DisplayFactor); break; } default: break; } setText(displayedText); } diff --git a/Plugins/org.blueberry.core.commands/src/berryCommand.cpp b/Plugins/org.blueberry.core.commands/src/berryCommand.cpp index a1da140043..722a2e26b1 100644 --- a/Plugins/org.blueberry.core.commands/src/berryCommand.cpp +++ b/Plugins/org.blueberry.core.commands/src/berryCommand.cpp @@ -1,555 +1,555 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryCommand.h" #include "berryIParameter.h" #include "berryITypedParameter.h" #include "berryIHandler.h" #include "berryIHandlerListener.h" #include "berryIParameterValueConverter.h" #include "berryHandlerEvent.h" #include "berryCommandEvent.h" #include "berryExecutionEvent.h" #include "berryCommandCategory.h" #include "berryState.h" #include "util/berryCommandTracing.h" #include "internal/berryCommandUtils.h" #include namespace berry { bool Command::DEBUG_COMMAND_EXECUTION = false; bool Command::DEBUG_HANDLERS = false; -QString Command::DEBUG_HANDLERS_COMMAND_ID = QString::null; +QString Command::DEBUG_HANDLERS_COMMAND_ID = QString(); Command::Command(const QString& id) : NamedHandleObjectWithState(id) { } void Command::AddCommandListener(ICommandListener* commandListener) { if (!commandListener) { throw ctkInvalidArgumentException("Cannot add a null command listener"); } commandEvents.AddListener(commandListener); } void Command::AddExecutionListener(IExecutionListener* executionListener) { if (!executionListener) { throw ctkInvalidArgumentException("Cannot add a null execution listener"); } executionEvents.AddListener(executionListener); } void Command::AddState(const QString& id, const State::Pointer& state) { NamedHandleObjectWithState::AddState(id, state); state->SetId(id); if (IObjectWithState::Pointer stateHandler = handler.Cast()) { stateHandler->AddState(id, state); } } bool Command::operator<(const Object* object) const { const Command* castedObject = dynamic_cast(object); int compareTo = CommandUtils::CompareObj(category, castedObject->category); if (compareTo == 0) { compareTo = CommandUtils::Compare(defined, castedObject->defined); if (compareTo == 0) { compareTo = CommandUtils::Compare(description, castedObject->description); if (compareTo == 0) { compareTo = CommandUtils::CompareObj(handler, castedObject->handler); if (compareTo == 0) { compareTo = CommandUtils::Compare(id, castedObject->id); if (compareTo == 0) { compareTo = CommandUtils::Compare(name, castedObject->name); if (compareTo == 0) { compareTo = CommandUtils::Compare(parameters, castedObject->parameters); } } } } } } return compareTo < 0; } void Command::Define(const QString& name, const QString& description, const CommandCategory::Pointer category, const QList& parameters, const ParameterType::Pointer& returnType, const QString& helpContextId) { if (name == "") { throw ctkInvalidArgumentException("The name of a command cannot be empty"); } if (!category) { throw ctkInvalidArgumentException("The category of a command cannot be null"); } const bool definedChanged = !this->defined; this->defined = true; const bool nameChanged = this->name != name; this->name = name; const bool descriptionChanged = this->description != description; this->description = description; const bool categoryChanged = this->category != category; this->category = category; const bool parametersChanged = !CommandUtils::Equals(this->parameters, parameters); this->parameters = parameters; const bool returnTypeChanged = this->returnType != returnType; this->returnType = returnType; const bool helpContextIdChanged = this->helpContextId != helpContextId; this->helpContextId = helpContextId; CommandEvent::Pointer event(new CommandEvent(Command::Pointer(this), categoryChanged, definedChanged, descriptionChanged, false, nameChanged, parametersChanged, returnTypeChanged, helpContextIdChanged)); this->FireCommandChanged(event); } Object::Pointer Command::ExecuteWithChecks(const ExecutionEvent::ConstPointer event) { this->FirePreExecute(event); const IHandler::Pointer handler(this->handler); if (!this->IsDefined()) { const NotDefinedException exception( "Trying to execute a command that is not defined. " + this->GetId()); this->FireNotDefined(&exception); throw exception; } // Perform the execution, if there is a handler. if (handler && handler->IsHandled()) { this->SetEnabled(event->GetApplicationContext()); if (!this->IsEnabled()) { const NotEnabledException exception( "Trying to execute the disabled command " + this->GetId()); this->FireNotEnabled(&exception); throw exception; } try { const Object::Pointer returnValue(handler->Execute(event)); this->FirePostExecuteSuccess(returnValue); return returnValue; } catch (const ExecutionException* e) { this->FirePostExecuteFailure(e); throw e; } } const NotHandledException e( "There is no handler to execute for command " + this->GetId()); this->FireNotHandled(&e); throw e; } void Command::FireCommandChanged(const CommandEvent::ConstPointer commandEvent) { if (!commandEvent) { throw ctkInvalidArgumentException("Cannot fire a null event"); } try { commandEvents.commandChanged(commandEvent); } catch (...) { //TODO log exceptions? } } void Command::FireNotDefined(const NotDefinedException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "not defined: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.notDefined(this->GetId(), e); } void Command::FireNotEnabled(const NotEnabledException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "not enabled: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.notEnabled(this->GetId(), e); } void Command::FireNotHandled(const NotHandledException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "not handled: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.notHandled(this->GetId(), e); } void Command::FirePostExecuteFailure(const ExecutionException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "failure: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.postExecuteFailure(this->GetId(), e); } void Command::FirePostExecuteSuccess(const Object::Pointer returnValue) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "success: id=" + this->GetId() + "; returnValue=" + (returnValue.IsNull() ? QString("nullptr") : returnValue->ToString())); } executionEvents.postExecuteSuccess(this->GetId(), returnValue); } void Command::FirePreExecute(const ExecutionEvent::ConstPointer event) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "starting: id=" + this->GetId() + "; event=" + event->ToString()); } executionEvents.preExecute(this->GetId(), event); } IHandler::Pointer Command::GetHandler() const { return handler; } QString Command::GetHelpContextId() const { return helpContextId; } IParameter::Pointer Command::GetParameter(const QString& parameterId) const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot get a parameter from an undefined command. " + id); } for (int i = 0; i < parameters.size(); i++) { IParameter::Pointer parameter(parameters[i]); if (parameter->GetId() == parameterId) { return parameter; } } return IParameter::Pointer(nullptr); } QList > Command::GetParameters() const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot get the parameters from an undefined command. " + id); } return parameters; } ParameterType::Pointer Command::GetParameterType(const QString& parameterId) const { const IParameter::Pointer parameter(this->GetParameter(parameterId)); if (ITypedParameter::Pointer parameterWithType = parameter.Cast()) { return parameterWithType->GetParameterType(); } return ParameterType::Pointer(nullptr); } ParameterType::Pointer Command::GetReturnType() const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot get the return type of an undefined command. " + id); } return returnType; } bool Command::IsEnabled() const { if (!handler) { return false; } return handler->IsEnabled(); } void Command::SetEnabled(const Object::Pointer& evaluationContext) { if (handler) { handler->SetEnabled(evaluationContext); } } bool Command::IsHandled() const { if (!handler) { return false; } return handler->IsHandled(); } void Command::RemoveCommandListener(ICommandListener *commandListener) { if (!commandListener) { throw ctkInvalidArgumentException( "Cannot remove a null command listener"); } commandEvents.RemoveListener(commandListener); } /** * Removes a listener from this command. * * @param executionListener * The listener to be removed; must not be null. * */ void Command::RemoveExecutionListener(IExecutionListener* executionListener) { if (!executionListener) { throw Poco::NullPointerException( "Cannot remove a null execution listener"); } executionEvents.RemoveListener(executionListener); } void Command::RemoveState(const QString& stateId) { if (IObjectWithState::Pointer stateHandler = handler.Cast()) { stateHandler->RemoveState(stateId); } NamedHandleObjectWithState::RemoveState(stateId); } bool Command::SetHandler(const IHandler::Pointer handler) { if (handler == this->handler) { return false; } // Swap the state around. const QList stateIds(this->GetStateIds()); for (int i = 0; i < stateIds.size(); ++i) { const QString stateId = stateIds[i]; if (IObjectWithState::Pointer stateHandler = this->handler.Cast()) { stateHandler->RemoveState(stateId); } if (IObjectWithState::Pointer stateHandler = handler.Cast()) { const State::Pointer stateToAdd(this->GetState(stateId)); stateHandler->AddState(stateId, stateToAdd); } } bool enabled = this->IsEnabled(); if (this->handler) { this->handler->RemoveHandlerListener(this->GetHandlerListener()); } // Update the handler, and flush the string representation. this->handler = handler; if (this->handler) { this->handler->AddHandlerListener(this->GetHandlerListener()); } this->str = ""; // Debugging output if ((DEBUG_HANDLERS) && ((DEBUG_HANDLERS_COMMAND_ID.isEmpty()) || (DEBUG_HANDLERS_COMMAND_ID == id))) { QString buffer("Command('"); buffer += id + "') has changed to "; if (!handler) { buffer += "no handler"; } else { buffer += "\'" + handler->ToString() + "' as its handler"; } CommandTracing::PrintTrace("HANDLERS", buffer); } // Send notification CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), false, false, false, true, false, false, false, false, enabled != this->IsEnabled())); this->FireCommandChanged(cmdEvent); return true; } IHandlerListener* Command::GetHandlerListener() { return this; } void Command::HandlerChanged(const SmartPointer& handlerEvent) { bool enabledChanged = handlerEvent->IsEnabledChanged(); bool handledChanged = handlerEvent->IsHandledChanged(); CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), false, false, false, handledChanged, false, false, false, false, enabledChanged)); this->FireCommandChanged(cmdEvent); } QString Command::ToString() const { if (str.isEmpty()) { QTextStream buffer(&str); buffer << "Command(" << id << ',' << name << ",\n\t\t"; buffer << description << ",\n\t\t" << (category ? category->ToString() : QString("")); buffer << ",\n\t\t" << (handler ? handler->ToString() : ""); buffer << ",\n\t\t" << "["; for (int i = 0; i < parameters.size(); ++i) { buffer << parameters[i]->GetId(); } buffer << "]," << (returnType ? returnType->ToString() : ""); buffer << "," << defined << ")"; } return str; } void Command::Undefine() { bool enabledChanged = this->IsEnabled(); str = ""; const bool definedChanged = defined; defined = false; const bool nameChanged = !name.isEmpty(); name = ""; const bool descriptionChanged = !description.isEmpty(); description = ""; const bool categoryChanged = category; category = nullptr; const bool parametersChanged = !parameters.empty(); parameters.clear(); const bool returnTypeChanged = returnType; returnType = nullptr; const QList stateIds(this->GetStateIds()); if (IObjectWithState::Pointer handlerWithState = handler.Cast()) { for (int i = 0; i < stateIds.size(); i++) { const QString stateId(stateIds[i]); handlerWithState->RemoveState(stateId); const State::Pointer state(this->GetState(stateId)); this->RemoveState(stateId); //state.dispose(); } } else { for (int i = 0; i < stateIds.size(); ++i) { const QString stateId(stateIds[i]); const State::Pointer state(this->GetState(stateId)); this->RemoveState(stateId); //state.dispose(); } } CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), categoryChanged, definedChanged, descriptionChanged, false, nameChanged, parametersChanged, returnTypeChanged, false, enabledChanged)); this->FireCommandChanged(cmdEvent); } } diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp index 629c2b1da7..2bfa5131d4 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp @@ -1,92 +1,92 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryProductExtensionBranding.h" #include #include #include #include "berryCTKPluginActivator.h" namespace berry { const QString ProductExtensionBranding::ATTR_DESCRIPTION = "description"; const QString ProductExtensionBranding::ATTR_NAME = "name"; const QString ProductExtensionBranding::ATTR_APPLICATION = "application"; const QString ProductExtensionBranding::ATTR_VALUE = "value"; ProductExtensionBranding::ProductExtensionBranding(const QString& id, const SmartPointer& element) : id(id) { if (element.IsNull()) return; application = element->GetAttribute(ATTR_APPLICATION); name = element->GetAttribute(ATTR_NAME); description = element->GetAttribute(ATTR_DESCRIPTION); LoadProperties(element); } QSharedPointer ProductExtensionBranding::GetDefiningPlugin() const { return definingPlugin; } QString ProductExtensionBranding::GetApplication() const { return application; } QString ProductExtensionBranding::GetName() const { return name; } QString ProductExtensionBranding::GetDescription() const { return description; } QString ProductExtensionBranding::GetId() const { return id; } QString ProductExtensionBranding::GetProperty(const QString& key) const { auto iter = properties.find(key); - return iter != properties.end() ? iter.value() : QString::null; + return iter != properties.end() ? iter.value() : QString(); } SmartPointer ProductExtensionBranding::GetProduct() const { return IProduct::Pointer(); } void ProductExtensionBranding::LoadProperties(const SmartPointer& element) { QList children = element->GetChildren(); properties.clear(); for (const auto &child : qAsConst(children)) { QString key = child->GetAttribute(ATTR_NAME); QString value = child->GetAttribute(ATTR_VALUE); if (!key.isEmpty() && !value.isEmpty()) { properties.insert(key, value); } } definingPlugin = org_blueberry_core_runtime_Activator::GetPlugin(element->GetContributor()); } } diff --git a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp index 2b1d6a2d19..5fc1652d1f 100644 --- a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,726 +1,726 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "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 #include "../berryDisplay.h" #include "../berryAsyncRunnable.h" #include "../handlers/berryIHandlerService.h" #include "../services/berryIServiceLocator.h" #include "../berryWorkbenchPlugin.h" #include #include #include #include #include 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(nullptr) , checkedState(false) { this->icon = contributionParameters->icon; this->label = contributionParameters->label; this->mnemonic = contributionParameters->mnemonic; this->shortcut = contributionParameters->shortcut; 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) override { item->SetText(text); } void SetToolTip(const QString& text) override { item->SetToolTip(text); } void SetIcon(const QIcon& icon) override { item->SetIcon(icon); } void SetChecked(bool checked) override { item->SetChecked(checked); } void SetDropDownId(const QString& id) override { 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"); } } } void CommandContributionItem::Fill(QMenu* parent, QAction* before) { if (!command || action || parent == nullptr) { return; } // Menus don't support the pulldown style Style tmpStyle = style; if (tmpStyle == STYLE_PULLDOWN) tmpStyle = STYLE_PUSH; QAction* item = nullptr; if (before) { item = new QAction(icon, label, parent); parent->insertAction(before, item); } else { item = parent->addAction(icon, label); } // Remove this when key binding support is fully implemented if (!shortcut.isEmpty()) { item->setShortcut(shortcut); } 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()), SLOT(HandleWidgetSelection())); connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); } void CommandContributionItem::Fill(QToolBar *parent, QAction *before) { if (!command || action || parent == nullptr) { return; } QAction* item = nullptr; 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))); connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection())); connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); } void CommandContributionItem::Update() { - this->Update(QString::null); + 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) override { 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); } } } } void CommandContributionItem::HandleActionDestroyed() { this->action = nullptr; } 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(nullptr)); } 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); } } //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/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp index e259834687..50ea7619d6 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp @@ -1,211 +1,211 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryEditorHistoryItem.h" #include "berryIEditorInput.h" #include "berryIEditorDescriptor.h" #include "berryIElementFactory.h" #include "berryIMemento.h" #include "berryIPersistableElement.h" #include "berryStatus.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" namespace berry { EditorHistoryItem::EditorHistoryItem(const SmartPointer& input, const SmartPointer& descriptor) : input(input) , descriptor(descriptor) { } EditorHistoryItem::EditorHistoryItem(const SmartPointer& memento) : memento(memento) { } SmartPointer EditorHistoryItem::GetDescriptor() const { return descriptor; } SmartPointer EditorHistoryItem::GetInput() const { return input; } bool EditorHistoryItem::IsRestored() const { return memento.IsNull(); } QString EditorHistoryItem::GetName() const { QString result; if (IsRestored() && GetInput().IsNotNull()) { result = GetInput()->GetName(); } else if (memento.IsNotNull()) { memento->GetString(WorkbenchConstants::TAG_NAME, result); } return result; } QString EditorHistoryItem::GetToolTipText() const { QString result; if (IsRestored() && GetInput().IsNotNull()) { result = GetInput()->GetToolTipText(); } else if (memento.IsNotNull()) { memento->GetString(WorkbenchConstants::TAG_TOOLTIP, result); } return result; } bool EditorHistoryItem::Matches(const SmartPointer& input) const { if (IsRestored()) { return input == GetInput(); } // if not restored, compare name, tool tip text and factory id, // avoiding as much work as possible if (GetName() != input->GetName()) { return false; } if (GetToolTipText() != input->GetToolTipText()) { return false; } const IPersistableElement* persistable = input->GetPersistable(); - QString inputId = persistable ? persistable->GetFactoryId() : QString::null; + QString inputId = persistable ? persistable->GetFactoryId() : QString(); QString myId = GetFactoryId(); return myId.isEmpty() ? inputId.isEmpty() : myId == inputId; } QString EditorHistoryItem::GetFactoryId() const { QString result; if (IsRestored()) { if (input.IsNotNull()) { const IPersistableElement* persistable = input->GetPersistable(); if (persistable != nullptr) { result = persistable->GetFactoryId(); } } } else if (memento.IsNotNull()) { memento->GetString(WorkbenchConstants::TAG_FACTORY_ID, result); } return result; } SmartPointer EditorHistoryItem::RestoreState() { Q_ASSERT_X(!IsRestored(), "RestoreState", "already restored"); IStatus::ConstPointer result = Status::OK_STATUS(BERRY_STATUS_LOC); IMemento::Pointer memento = this->memento; this->memento = nullptr; QString factoryId; memento->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryId); if (factoryId.isEmpty()) { WorkbenchPlugin::Log("Unable to restore mru list - no input factory ID."); return result; } QScopedPointer factory( PlatformUI::GetWorkbench()->GetElementFactory(factoryId)); if (!factory) { return result; } IMemento::Pointer persistableMemento = memento->GetChild(WorkbenchConstants::TAG_PERSISTABLE); if (persistableMemento.IsNull()) { WorkbenchPlugin::Log("Unable to restore mru list - no input element state: " + factoryId); return result; } QScopedPointer adaptable(factory->CreateElement(persistableMemento)); if (adaptable == nullptr || dynamic_cast(adaptable.data()) == nullptr) { return result; } input = dynamic_cast(adaptable.data()); // Get the editor descriptor. QString editorId; memento->GetString(WorkbenchConstants::TAG_ID, editorId); if (!editorId.isEmpty()) { IEditorRegistry* registry = WorkbenchPlugin::GetDefault()->GetEditorRegistry(); descriptor = registry->FindEditor(editorId); } return result; } bool EditorHistoryItem::CanSave() const { return !IsRestored() || (GetInput().IsNotNull() && GetInput()->GetPersistable() != nullptr); } SmartPointer EditorHistoryItem::SaveState(const SmartPointer& memento) { if (!IsRestored()) { memento->PutMemento(this->memento); } else if (input.IsNotNull()) { const IPersistableElement* persistable = input->GetPersistable(); if (persistable != nullptr) { /* * Store IPersistable of the IEditorInput in a separate section * since it could potentially use a tag already used in the parent * memento and thus overwrite data. */ IMemento::Pointer persistableMemento = memento->CreateChild(WorkbenchConstants::TAG_PERSISTABLE); persistable->SaveState(persistableMemento); memento->PutString(WorkbenchConstants::TAG_FACTORY_ID, persistable->GetFactoryId()); if (descriptor.IsNotNull() && !descriptor->GetId().isEmpty()) { memento->PutString(WorkbenchConstants::TAG_ID, descriptor->GetId()); } // save the name and tooltip separately so they can be restored // without having to instantiate the input, which can activate plugins memento->PutString(WorkbenchConstants::TAG_NAME, input->GetName()); memento->PutString(WorkbenchConstants::TAG_TOOLTIP, input->GetToolTipText()); } } return Status::OK_STATUS(BERRY_STATUS_LOC); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp index bea2f397df..c18a6cccea 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp @@ -1,88 +1,88 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryKeywordRegistry.h" #include "berryIConfigurationElement.h" #include "berryIExtension.h" #include "berryIExtensionPoint.h" #include "berryIExtensionPointFilter.h" #include "berryIExtensionRegistry.h" #include "berryExtensionTracker.h" #include "berryObjectString.h" #include "berryPlatform.h" #include "berryPlatformUI.h" #include "berryWorkbenchRegistryConstants.h" namespace berry { const QString KeywordRegistry::ATT_ID = "id"; const QString KeywordRegistry::ATT_LABEL = "label"; const QString KeywordRegistry::TAG_KEYWORD = "keyword"; KeywordRegistry::KeywordRegistry() { IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker(); tracker->RegisterHandler(this, ExtensionTracker::CreateExtensionPointFilter(GetExtensionPointFilter())); QList extensions = GetExtensionPointFilter()->GetExtensions(); for (auto& extension : extensions) { AddExtension(tracker, extension); } } SmartPointer KeywordRegistry::GetExtensionPointFilter() const { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_KEYWORDS); } KeywordRegistry*KeywordRegistry::GetInstance() { static KeywordRegistry instance; return &instance; } void KeywordRegistry::AddExtension(IExtensionTracker* tracker, const SmartPointer& extension) { for (const auto &element : extension->GetConfigurationElements()) { if (element->GetName() == TAG_KEYWORD) { QString name = element->GetAttribute(ATT_LABEL); QString id = element->GetAttribute(ATT_ID); internalKeywordMap.insert(id, name); Object::Pointer trackedObject(new ObjectString(id)); tracker->RegisterObject(extension, trackedObject, IExtensionTracker::REF_STRONG); } } } QString KeywordRegistry::GetKeywordLabel(const QString& id) { auto it = internalKeywordMap.find(id); - return it == internalKeywordMap.end() ? QString::null : *it; + return it == internalKeywordMap.end() ? QString() : *it; } void KeywordRegistry::RemoveExtension(const SmartPointer& /*extension*/, const QList >& objects) { for (const auto &object : objects) { if (ObjectString::Pointer objString = object.Cast()) { internalKeywordMap.remove(*objString); } } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp index fd0371a370..1920232ef7 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp @@ -1,624 +1,624 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryPerspectiveRegistry.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" #include "berryPreferenceConstants.h" #include "berryPerspective.h" #include "berryPerspectiveRegistryReader.h" #include "berryPlatformUI.h" #include "handlers/berryClosePerspectiveHandler.h" #include "berryIExtension.h" #include "berryIExtensionTracker.h" #include namespace berry { const QString PerspectiveRegistry::EXT = "_persp.xml"; const QString PerspectiveRegistry::ID_DEF_PERSP = "PerspectiveRegistry.DEFAULT_PERSP"; const QString PerspectiveRegistry::PERSP = "_persp"; const char PerspectiveRegistry::SPACE_DELIMITER = ' '; class PerspectiveRegistry::PreferenceChangeListener { PerspectiveRegistry* m_Registry; public: PreferenceChangeListener(PerspectiveRegistry* registry) : m_Registry(registry) {} void PropertyChange(const mitk::IPreferences::ChangeEvent& event) { /* * To ensure that no custom perspective definitions are * deleted when preferences are imported, merge old and new * values */ if (QString::fromStdString(event.GetProperty()).endsWith(PERSP)) { /* A Perspective is being changed, merge */ this->MergePerspectives(event); } else if (event.GetProperty() == PreferenceConstants::PERSPECTIVES) { /* The list of perspectives is being changed, merge */ UpdatePreferenceList(event.GetSource()); } } void MergePerspectives(const mitk::IPreferences::ChangeEvent& event) { auto* store = event.GetSource(); if (event.GetNewValue().empty()) { /* * Perspective is being removed; if the user has deleted or * reverted a custom perspective, let the change pass * through. Otherwise, restore the custom perspective entry */ // Find the matching descriptor in the registry QList perspectiveList = m_Registry->GetPerspectives(); for (int i = 0; i < perspectiveList.size(); i++) { QString id = perspectiveList[i]->GetId(); const auto property = QString::fromStdString(event.GetProperty()); if (property == id + PERSP) { // found // descriptor // see if the perspective has been flagged for // reverting or deleting if (!m_Registry->perspToRemove.contains(id)) { // restore store->Put((id + PERSP).toStdString(), event.GetOldValue()); } else { // remove element from the list m_Registry->perspToRemove.removeAll(id); } } } } else if (event.GetOldValue().empty()) { /* * New perspective is being added, update the * perspectiveRegistry to contain the new custom perspective */ auto property = QString::fromStdString(event.GetProperty()); QString id = property.left(property.lastIndexOf(PERSP)); if (m_Registry->FindPerspectiveWithId(id).IsNull()) { // perspective does not already exist in registry, add // it PerspectiveDescriptor::Pointer desc(new PerspectiveDescriptor( - QString::null, QString::null, PerspectiveDescriptor::Pointer())); + QString(), QString(), PerspectiveDescriptor::Pointer())); std::stringstream reader; std::string xmlStr = event.GetNewValue(); reader.str(xmlStr); try { XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(reader); desc->RestoreState(memento); m_Registry->AddPerspective(desc); } catch (const WorkbenchException& e) { //m_Registry->UnableToLoadPerspective(e.getStatus()); m_Registry->UnableToLoadPerspective(e.what()); } } } /* If necessary, add to the list of perspectives */ this->UpdatePreferenceList(store); } void UpdatePreferenceList(mitk::IPreferences* store) { QList perspectiveList = m_Registry->GetPerspectives(); QStringList perspBuffer; for (int i = 0; i < perspectiveList.size(); i++) { PerspectiveDescriptor::Pointer desc = perspectiveList[i].Cast(); if (m_Registry->HasCustomDefinition(desc)) { perspBuffer.push_back(desc->GetId()); } } store->Put(PreferenceConstants::PERSPECTIVES, perspBuffer.join(QString(SPACE_DELIMITER)).toStdString()); } }; PerspectiveRegistry::PerspectiveRegistry() : preferenceListener(new PreferenceChangeListener(this)) { IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker(); tracker->RegisterHandler(this, QString("org.blueberry.ui.perspectives")); mitk::IPreferences* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); prefs->OnPropertyChanged += mitk::MessageDelegate1( preferenceListener.data(), &PreferenceChangeListener::PropertyChange); } void PerspectiveRegistry::AddPerspective(PerspectiveDescriptor::Pointer desc) { if (desc == 0) { return; } this->Add(desc); } void PerspectiveRegistry::RevertPerspectives( const QList& perspToRevert) { // indicate that the user is removing these perspectives for (QList::const_iterator iter = perspToRevert.begin(); iter != perspToRevert.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } } void PerspectiveRegistry::DeletePerspectives( const QList& perspToDelete) { for (QList::const_iterator iter = perspToDelete.begin(); iter != perspToDelete.end(); ++iter) { this->DeletePerspective(*iter); } } void PerspectiveRegistry::DeletePerspective(IPerspectiveDescriptor::Pointer in) { PerspectiveDescriptor::Pointer desc = in.Cast(); // Don't delete predefined perspectives if (!desc->IsPredefined()) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } } void PerspectiveRegistry::Load() { // Load the registries. this->LoadPredefined(); this->LoadCustom(); // Get default perspective. // Get it from the R1.0 dialog settings first. Fixes bug 17039 // IDialogSettings dialogSettings = // WorkbenchPlugin.getDefault() .getDialogSettings(); // QString str = dialogSettings.get(ID_DEF_PERSP); // if (str != null && str.length() > 0) // { // this->SetDefaultPerspective(str); // dialogSettings.put(ID_DEF_PERSP, ""); //$NON-NLS-1$ // } this->VerifyDefaultPerspective(); } void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc, XMLMemento* memento) { auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); // Save it to the preference store. std::stringstream ss; memento->Save(ss); prefs->Put((desc->GetId() + PERSP).toStdString(), ss.str()); } IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& id) { std::stringstream ss; auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); const auto xmlString = prefs->Get((id + PERSP).toStdString(), ""); if (!xmlString.empty()) { // defined in store ss.str(xmlString); } XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); return memento; } bool PerspectiveRegistry::ValidateLabel(const QString& label) { return !label.trimmed().isEmpty(); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithId(const QString& id) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetId() == id) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return null; // } return desc; } } return IPerspectiveDescriptor::Pointer(nullptr); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithLabel( const QString& label) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetLabel() == label) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return 0; // } return desc; } } return IPerspectiveDescriptor::Pointer(nullptr); } QString PerspectiveRegistry::GetDefaultPerspective() { return defaultPerspID; } QList PerspectiveRegistry::GetPerspectives() { // Collection descs = WorkbenchActivityHelper.restrictCollection(perspectives, // new ArrayList()); // return (IPerspectiveDescriptor[]) descs.toArray( // new IPerspectiveDescriptor[descs.size()]); QList result; for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { result.push_back(iter->Cast()); } return result; } void PerspectiveRegistry::SetDefaultPerspective(const QString& id) { IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { defaultPerspID = id; //TODO Preferences // PrefUtil.getAPIPreferenceStore().setValue( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id); } } IPerspectiveDescriptor::Pointer PerspectiveRegistry::CreatePerspective(const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Sanity check to avoid invalid or duplicate labels. if (!this->ValidateLabel(label)) { return IPerspectiveDescriptor::Pointer(nullptr); } if (this->FindPerspectiveWithLabel(label) != 0) { return IPerspectiveDescriptor::Pointer(nullptr); } // Calculate ID. QString id(label); id = id.replace(' ', '_').trimmed(); // Create descriptor. PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, label, originalDescriptor.Cast())); this->Add(desc); return IPerspectiveDescriptor::Pointer(static_cast(desc.GetPointer())); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Check for invalid labels if (label == "" || label.trimmed().isEmpty()) { throw Poco::InvalidArgumentException(); } // Check for duplicates IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { throw Poco::InvalidArgumentException(); } // Create descriptor. desc = new PerspectiveDescriptor(id, label, originalDescriptor.Cast()); this->Add(desc.Cast()); return desc; } void PerspectiveRegistry::RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) { PerspectiveDescriptor::Pointer desc = perspToRevert.Cast(); perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } PerspectiveRegistry::~PerspectiveRegistry() { // PlatformUI::GetWorkbench()->GetExtensionTracker()->UnregisterHandler(this); // WorkbenchPlugin::GetDefault()->GetPreferences()->RemovePropertyChangeListener(preferenceListener); } void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc) { // remove the entry from the preference store. auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); prefs->Remove((desc->GetId() + PERSP).toStdString()); } bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const { auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); const auto keys = prefs->Keys(); return std::find(keys.begin(), keys.end(), (desc->GetId() + PERSP).toStdString()) != keys.end(); } void PerspectiveRegistry::Add(PerspectiveDescriptor::Pointer desc) { perspectives.push_back(desc); IConfigurationElement::Pointer element = desc->GetConfigElement(); if (element.IsNotNull()) { PlatformUI::GetWorkbench()->GetExtensionTracker()->RegisterObject( element->GetDeclaringExtension(), desc, IExtensionTracker::REF_WEAK); } } void PerspectiveRegistry::InternalDeletePerspective(PerspectiveDescriptor::Pointer desc) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } void PerspectiveRegistry::LoadCustom() { QScopedPointer reader; /* Get the entries from the Preference store */ auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); /* Get the space-delimited list of custom perspective ids */ QString customPerspectives = QString::fromStdString(prefs->Get(PreferenceConstants::PERSPECTIVES, "")); QStringList perspectivesList = customPerspectives.split(' ', Qt::SkipEmptyParts); for (int i = 0; i < perspectivesList.size(); i++) { try { const auto xmlString = prefs->Get((perspectivesList[i] + PERSP).toStdString(), ""); if (!xmlString.empty()) { reader.reset(new std::stringstream(xmlString)); //reader->exceptions(std::ios_base::failbit); } else { throw WorkbenchException(QString("Description of '%1' perspective could not be found.").arg(perspectivesList[i])); } // Restore the layout state. XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(*reader); PerspectiveDescriptor::Pointer newPersp(new PerspectiveDescriptor( - QString::null, QString::null, + QString(), QString(), PerspectiveDescriptor::Pointer(nullptr))); newPersp->RestoreState(memento); QString id = newPersp->GetId(); IPerspectiveDescriptor::Pointer oldPersp = FindPerspectiveWithId(id); if (oldPersp.IsNull()) { Add(newPersp); } } catch (const std::ios_base::failure&) { - UnableToLoadPerspective(QString::null); + UnableToLoadPerspective(QString()); } catch (const WorkbenchException& e) { UnableToLoadPerspective(e.message()); } } // // Get the entries from files, if any // // if -data @noDefault specified the state location may not be // // initialized // IPath path = WorkbenchPlugin.getDefault().getDataLocation(); // if (path == null) // { // return; // } // File folder = path.toFile(); // if (folder.isDirectory()) // { // File[] fileList = folder.listFiles(); // int nSize = fileList.length; // for (int nX = 0; nX < nSize; nX++) // { // File file = fileList[nX]; // if (file.getName().endsWith(EXT)) // { // // get the memento // InputStream stream = null; // try // { // stream = new FileInputStream(file); // reader = new BufferedReader(new InputStreamReader(stream, "utf-8")); //$NON-NLS-1$ // // Restore the layout state. // XMLMemento memento = XMLMemento.createReadRoot(reader); // PerspectiveDescriptor newPersp = // new PerspectiveDescriptor(null, null, null); // newPersp.restoreState(memento); // IPerspectiveDescriptor oldPersp = findPerspectiveWithId( // newPersp .getId()); // if (oldPersp == null) // { // add(newPersp); // } // // save to the preference store // saveCustomPersp(newPersp, memento); // // delete the file // file.delete(); // reader.close(); // stream.close(); // } catch (IOException e) // { // unableToLoadPerspective(null); // } catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // } // } } void PerspectiveRegistry::UnableToLoadPerspective(const QString& status) { QString msg = "Unable to load perspective"; if (status == "") { WorkbenchPlugin::Log(msg); //IStatus errStatus = // new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } else { WorkbenchPlugin::Log(status + ": " + msg); //IStatus errStatus = StatusUtil.newStatus(status, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } } void PerspectiveRegistry::LoadPredefined() { PerspectiveRegistryReader reader(this); reader.ReadPerspectives(Platform::GetExtensionRegistry()); } void PerspectiveRegistry::VerifyDefaultPerspective() { // Step 1: Try current defPerspId value. IPerspectiveDescriptor::Pointer desc; if (defaultPerspID != "") { desc = this->FindPerspectiveWithId(defaultPerspID); } if (desc != 0) { return; } // Step 2. Read default value. //TODO Preferences // QString str = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID); // if (str != null && str.length() > 0) // { // desc = this->FindPerspectiveWithId(str); // } // if (desc != 0) // { // defaultPerspID = str; // return; // } // Step 3. Use application-specific default defaultPerspID = Workbench::GetInstance()->GetDefaultPerspectiveId(); } void PerspectiveRegistry::RemoveExtension(const IExtension::Pointer& /*source*/, const QList& objects) { for (int i = 0; i < objects.size(); i++) { if (PerspectiveDescriptor::Pointer desc = objects[i].Cast()) { // close the perspective in all windows QList windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (int w = 0; w < windows.size(); ++w) { IWorkbenchWindow::Pointer window = windows[w]; QList pages = window->GetPages(); for (int p = 0; p < pages.size(); ++p) { WorkbenchPage::Pointer page = pages[p].Cast(); ClosePerspectiveHandler::ClosePerspective(page, page->FindPerspective(desc)); } } // ((Workbench)PlatformUI.getWorkbench()).getPerspectiveHistory().removeItem(desc); this->InternalDeletePerspective(desc); } } } void PerspectiveRegistry::AddExtension(IExtensionTracker* /*tracker*/, const IExtension::Pointer& addedExtension) { QList addedElements = addedExtension->GetConfigurationElements(); for (int i = 0; i < addedElements.size(); i++) { PerspectiveRegistryReader reader(this); reader.ReadElement(addedElements[i]); } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp index c783409106..f7714bbcb5 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp @@ -1,63 +1,63 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtShowPerspectiveDialog.h" #include "ui_berryQtShowPerspectiveDialog.h" #include #include namespace berry { QtShowPerspectiveDialog::QtShowPerspectiveDialog(IPerspectiveRegistry* perspReg, QWidget *parent) : QDialog(parent) , ui(new Ui::QtShowPerspectiveDialog) { ui->setupUi(this); QAbstractItemModel* model = new PerspectiveListModel(*perspReg, true, this); auto proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->sort(0); ui->m_ListView->setModel(proxyModel); ui->m_ListView->setSelectionMode(QAbstractItemView::SingleSelection); ui->m_ListView->selectionModel()->select(model->index(0, 0), QItemSelectionModel::ClearAndSelect); ui->m_ListView->setIconSize(QSize(16, 16)); connect(ui->m_ListView, SIGNAL(clicked(QModelIndex)), this, SLOT(setDescription(QModelIndex))); connect(ui->m_ListView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); connect(ui->m_ListView, SIGNAL(activated(QModelIndex)), this, SLOT(accept())); } QtShowPerspectiveDialog::~QtShowPerspectiveDialog() { delete ui; } QString QtShowPerspectiveDialog::GetSelection() const { const QItemSelection selection = ui->m_ListView->selectionModel()->selection(); - if (selection.isEmpty()) return QString::null; + if (selection.isEmpty()) return QString(); return selection.indexes().front().data(PerspectiveListModel::Id).toString(); } void QtShowPerspectiveDialog::setDescription(const QModelIndex& index) { ui->m_Description->setText(ui->m_ListView->model()->data(index, PerspectiveListModel::Description).toString()); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp index 155db01074..e66d27ec25 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp @@ -1,275 +1,275 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryShowViewMenu.h" #include #include #include #include #include #include #include #include #include #include "berryCommandContributionItemParameter.h" #include "berryWorkbenchPlugin.h" #include "berryViewDescriptor.h" #include "intro/berryIntroConstants.h" #include #include #include namespace berry { const QString ShowViewMenu::NO_TARGETS_MSG = ""; struct ActionComparator { bool operator()(const CommandContributionItemParameter::Pointer& p1, const CommandContributionItemParameter::Pointer& p2) const { return p1->label < p2->label; } }; ShowViewMenu::ShowViewMenu(IWorkbenchWindow *window, const QString& id) : ContributionItem(id), dirty(true), window(window) { CommandContributionItemParameter::Pointer showDlgItemParms( new CommandContributionItemParameter( - window, QString::null, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, + window, QString(), IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); showDlgItemParms->label = "&Other..."; showDlgItem = new CommandContributionItem(showDlgItemParms); // window.getWorkbench().getHelpSystem().setHelp(showDlgAction, // IWorkbenchHelpContextIds.SHOW_VIEW_OTHER_ACTION); // // indicate that a show views submenu has been created // if (window instanceof WorkbenchWindow) { // ((WorkbenchWindow) window) // .addSubmenu(WorkbenchWindow.SHOW_VIEW_SUBMENU); // } } bool ShowViewMenu::IsDirty() const { return dirty; } /** * Overridden to always return true and force dynamic menu building. */ bool ShowViewMenu::IsDynamic() const { return true; } void ShowViewMenu::Fill(QMenu* menu, QAction* before) { if (MenuManager* mm = dynamic_cast(GetParent())) { this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); } if (!dirty) { return; } MenuManager::Pointer manager(new MenuManager()); FillMenu(manager.GetPointer()); QList items = manager->GetItems(); if (items.isEmpty()) { auto action = new QAction(NO_TARGETS_MSG, menu); action->setEnabled(false); menu->insertAction(before, action); } else { foreach (IContributionItem::Pointer item, items) { item->Fill(menu, before); } } dirty = false; } void ShowViewMenu::FillMenu(IMenuManager* innerMgr) { // Remove all. innerMgr->RemoveAll(); // If no page disable all. IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } // If no active perspective disable all if (page->GetPerspective().IsNull()) { return; } typedef QPair ViewIdPair; // Get visible actions. QSet viewIds = GetShortcuts(page.GetPointer()); // add all open views viewIds = AddOpenedViews(page.GetPointer(), viewIds); QList actions; foreach (ViewIdPair id, viewIds) { if (id.first == IntroConstants::INTRO_VIEW_ID) { continue; } CommandContributionItemParameter::Pointer item = GetItem(id.first, id.second); if (item) { actions.append(item); } } qSort(actions.begin(), actions.end(), ActionComparator()); foreach (CommandContributionItemParameter::Pointer ccip, actions) { // if (WorkbenchActivityHelper.filterItem(ccip)) { // continue; // } CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); innerMgr->Add(item); } // We only want to add the separator if there are show view shortcuts, // otherwise, there will be a separator and then the 'Other...' entry // and that looks weird as the separator is separating nothing if (!innerMgr->IsEmpty()) { IContributionItem::Pointer separator(new Separator()); innerMgr->Add(separator); } // Add Other... innerMgr->Add(showDlgItem); } QSet > ShowViewMenu::GetShortcuts(IWorkbenchPage* page) const { QSet > list; QList shortcuts(page->GetShowViewShortcuts()); for (int i = 0; i < shortcuts.size(); ++i) { list.insert(qMakePair(shortcuts[i], QString())); } return list; } void ShowViewMenu::AboutToShow(IMenuManager* manager) { manager->MarkDirty(); this->dirty = true; } CommandContributionItemParameter::Pointer ShowViewMenu::GetItem(const QString& viewId, const QString& secondaryId) const { IViewRegistry* reg = WorkbenchPlugin::GetDefault()->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(viewId); if (desc.IsNull()) { return CommandContributionItemParameter::Pointer(nullptr); } QString label = desc->GetLabel(); class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution { QString localId; QString pluginId; public: typedef PluginCCIP Self; static const char* GetStaticClassName() { return "PluginCCIP"; } berryObjectTypeInfo(CommandContributionItemParameter, IPluginContribution) PluginCCIP(const IViewDescriptor::Pointer& v, IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) : CommandContributionItemParameter(serviceLocator, id, commandId, style) { ViewDescriptor::Pointer vd = v.Cast(); localId = vd->GetLocalId(); pluginId = vd->GetPluginId(); } QString GetLocalId() const override { return localId; } QString GetPluginId() const override { return pluginId; } }; CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, window, viewId, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); parms->label = label; parms->icon = desc->GetImageDescriptor(); Object::Pointer strViewId(new ObjectString(viewId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID, strViewId); // if (makeFast) // { // parms.parameters.put( // IWorkbenchCommandConstants.VIEWS_SHOW_VIEW_PARM_FASTVIEW, // "true"); //$NON-NLS-1$ // } if (!secondaryId.isEmpty()) { Object::Pointer strSecondaryId(new ObjectString(secondaryId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID, strSecondaryId); } return parms; } QSet > ShowViewMenu::AddOpenedViews(IWorkbenchPage* page, QSet >& actions) const { QSet > views = GetParts(page); return views.unite(actions); } QSet > ShowViewMenu::GetParts(IWorkbenchPage* page) const { QSet > parts; QList refs = page->GetViewReferences(); for (int i = 0; i < refs.size(); ++i) { parts.insert(qMakePair(refs[i]->GetId(), refs[i]->GetSecondaryId())); } return parts; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp index 18425006a8..88de2a2fa0 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp @@ -1,155 +1,155 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berrySwitchToWindowMenu.h" #include #include #include #include #include #include #include #include namespace berry { void SwitchToWindowMenu::AboutToShow(IMenuManager* manager) { manager->MarkDirty(); dirty = true; } void SwitchToWindowMenu::MenuItemTriggered(int index) { if (index < 0 || index >= windows.size()) return; IWorkbenchWindow* window = windows[index]; Shell::Pointer windowShell = window->GetShell(); if (windowShell->GetMinimized()) { windowShell->SetMinimized(false); } windowShell->SetActive(); windowShell->GetControl()->raise(); } QString SwitchToWindowMenu::CalcText(int number, IWorkbenchWindow* window) { QString suffix = window->GetShell()->GetText(); if (suffix.isEmpty()) { - return QString::null; + return QString(); } QString sb; if (number < 10) { sb.append('&'); } sb.append(QString::number(number)); sb.append(' '); if (suffix.size() <= MAX_TEXT_LENGTH) { sb.append(suffix); } else { sb.append(suffix.leftRef(MAX_TEXT_LENGTH)); sb.append("..."); } return sb; } SwitchToWindowMenu::SwitchToWindowMenu(IWorkbenchWindow* window, const QString& id, bool showSeparator) : ContributionItem(id) , workbenchWindow(window) , showSeparator(showSeparator) , dirty(true) { } void SwitchToWindowMenu::Fill(QMenu* menu, QAction* before) { // Get workbench windows. IWorkbench* workbench = workbenchWindow->GetWorkbench(); windows.clear(); for (const auto &window : workbench->GetWorkbenchWindows()) { windows.push_back(window.GetPointer()); } // avoid showing the separator and list for 0 or 1 items if (windows.size() < 2) { return; } if (MenuManager* mm = dynamic_cast(GetParent())) { this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); } if (!dirty) { return; } // Add separator. if (showSeparator) { menu->insertSeparator(before); } // Add one item for each window. auto actionGroup = new QActionGroup(menu); actionGroup->setExclusive(true); auto signalMapper = new QSignalMapper(menu); connect(signalMapper, SIGNAL(mapped(int)), SLOT(MenuItemTriggered(int))); int count = 0; for (auto window : qAsConst(windows)) { // can encounter disposed shells if this update is in response to a shell closing //if (!window->GetShell()->IsDisposed()) //{ QString name = CalcText(count, window); if (!name.isEmpty()) { auto mi = new QAction(name, menu); mi->setCheckable(true); mi->setChecked(window == workbenchWindow); actionGroup->addAction(mi); menu->insertAction(before, mi); signalMapper->setMapping(mi, count); connect(mi, SIGNAL(triggered()), signalMapper, SLOT(map())); } ++count; } //} dirty = false; } bool SwitchToWindowMenu::IsDirty() const { return dirty; } bool SwitchToWindowMenu::IsDynamic() const { return true; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp index bee11dae60..42d5dd5812 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp @@ -1,112 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryShowViewHandler.h" #include "berryIWorkbenchCommandConstants.h" #include "berryHandlerUtil.h" #include "berryUIException.h" #include "berryIWorkbenchPage.h" #include "berryIViewDescriptor.h" #include "berryPlatformUI.h" #include "berryWorkbenchPlugin.h" #include "internal/berryQtShowViewDialog.h" #include #include namespace berry { ShowViewHandler::ShowViewHandler() { } Object::Pointer ShowViewHandler::Execute(const ExecutionEvent::ConstPointer& event) { IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); // Get the view identifier, if any. const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); ExecutionEvent::ParameterMap::const_iterator result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID); - QString viewId = result != parameters.end() ? result.value() : QString::null; + QString viewId = result != parameters.end() ? result.value() : QString(); result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID); - QString secondary = result != parameters.end() ? result.value() : QString::null; + QString secondary = result != parameters.end() ? result.value() : QString(); if (viewId.isEmpty()) { this->OpenOther(window); } else { try { this->OpenView(viewId, secondary, window); } catch (const PartInitException& e) { throw ExecutionException("Part could not be initialized", e); } } return Object::Pointer(nullptr); } void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window) { const IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } QtShowViewDialog dialog(window.GetPointer(), WorkbenchPlugin::GetDefault()->GetViewRegistry()); int returnCode = dialog.exec(); if (returnCode == QDialog::Rejected) { return; } const QList descriptors = dialog.GetSelection(); for (const QString &id : descriptors) { try { this->OpenView(id, QString(), window); } catch (const PartInitException& e) { BERRY_WARN << e.what(); // StatusUtil.handleStatus(e.getStatus(), // WorkbenchMessages.ShowView_errorTitle // + ": " + e.getMessage(), //$NON-NLS-1$ // StatusManager.SHOW); } } } void ShowViewHandler::OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::Pointer activeWorkbenchWindow) { const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); if (activePage.IsNull()) { return; } activePage->ShowView(viewId, secondaryId, IWorkbenchPage::VIEW_ACTIVATE); } } diff --git a/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp b/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp index a86ff3d902..40b52eba43 100644 --- a/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp +++ b/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp @@ -1,138 +1,138 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryPerspectiveListModel.h" #include #include #include namespace berry { struct PerspectiveListModel::Impl { IPerspectiveRegistry& m_PerspReg; QList m_Perspectives; const bool m_MarkDefault; Impl(IPerspectiveRegistry& perspReg, bool markDefault) : m_PerspReg(perspReg) // TODO use activity filter for correct perspective list , m_Perspectives(perspReg.GetPerspectives()) , m_MarkDefault(markDefault) { } }; PerspectiveListModel::PerspectiveListModel(IPerspectiveRegistry& perspReg, bool markDefault, QObject* parent) : QAbstractListModel(parent) , d(new Impl(perspReg, markDefault)) { } PerspectiveListModel::~PerspectiveListModel() { } int PerspectiveListModel::rowCount(const QModelIndex& /*parent*/) const { return d->m_Perspectives.size(); } QVariant PerspectiveListModel::data(const QModelIndex& index, int role) const { if (index.row() < 0 || index.row() >= d->m_Perspectives.size() || index.column() > 0) { return QVariant(); } if (role == Qt::DisplayRole) { const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); QString label = desc->GetLabel(); if (d->m_MarkDefault) { QString def = d->m_PerspReg.GetDefaultPerspective(); if (desc->GetId() == def) { label += " (default)"; } } return label; } else if (role == Qt::DecorationRole) { const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); return desc->GetImageDescriptor(); } else if (role == Id) { const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); return desc->GetId(); } else if (role == Description) { const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); return desc->GetDescription(); } return QVariant(); } QVariant PerspectiveListModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const { if (role == Qt::DisplayRole) { if (section == 0) { return QString("Perspective"); } } return QVariant(); } QString PerspectiveListModel::perspectiveName(const QModelIndex& index) const { - if (!index.isValid()) return QString::null; + if (!index.isValid()) return QString(); return d->m_Perspectives.at(index.row())->GetLabel(); } IPerspectiveDescriptor::Pointer PerspectiveListModel::perspectiveDescriptor(const QModelIndex& index) const { return d->m_Perspectives.at(index.row()); } QModelIndex PerspectiveListModel::index(const QString& perspId) const { int index = -1; for(int i = 0; i < d->m_Perspectives.size(); ++i) { if (d->m_Perspectives.at(i)->GetId() == perspId) { index = i; break; } } if (index > -1) { return this->createIndex(index, 0); } return QModelIndex(); } }