diff --git a/Modules/AppUtil/src/mitkProvisioningInfo.cpp b/Modules/AppUtil/src/mitkProvisioningInfo.cpp index 7b5990b3e7..696fe1a621 100644 --- a/Modules/AppUtil/src/mitkProvisioningInfo.cpp +++ b/Modules/AppUtil/src/mitkProvisioningInfo.cpp @@ -1,207 +1,207 @@ /*============================================================================ 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 "mitkProvisioningInfo.h" #include #include #include #include #include #include namespace mitk { #ifdef CMAKE_INTDIR const QString ProvisioningInfo::intermediateOutDir = QString(CMAKE_INTDIR); #else const QString ProvisioningInfo::intermediateOutDir = QString(); #endif ProvisioningInfo::ProvisioningInfo(const QString &file) { this->readProvisioningFile(file); } - QStringList ProvisioningInfo::getPluginDirs() const { return pluginDirs.toList(); } + QStringList ProvisioningInfo::getPluginDirs() const { return pluginDirs.values(); } QList ProvisioningInfo::getPluginsToInstall() const { return pluginsToInstall; } QList ProvisioningInfo::getPluginsToStart() const { return pluginsToStart; } void ProvisioningInfo::readProvisioningFile(const QString &filePath) { QFile file(filePath); file.open(QFile::ReadOnly); QTextStream fileStream(&file); QRegularExpression sep("\\s+"); QString line; int count = 1; do { line = fileStream.readLine().trimmed(); if (!line.isEmpty() && !line.startsWith('#')) { QString keyword = line.section(sep, 0, 0); QString value = line.mid(keyword.size()).trimmed(); value = substituteKeywords(value); if (keyword.isEmpty()) { MITK_WARN << "Keyword missing in line " << count << " of provisioning file " << filePath.toStdString(); continue; } Keyword key = UNKNOWN; if (keyword.compare("READ", Qt::CaseInsensitive) == 0) { key = READ; } else if (keyword.compare("INSTALL", Qt::CaseInsensitive) == 0) { key = INSTALL; } else if (keyword.compare("START", Qt::CaseInsensitive) == 0) { key = START; } else if (keyword.compare("STOP", Qt::CaseInsensitive) == 0) { key = STOP; } if (key == UNKNOWN) { MITK_WARN << "Keyword " << keyword.toStdString() << " in line " << count << " of provisioning file " << filePath.toStdString() << " unknown"; continue; } if (value.isEmpty()) { MITK_WARN << "Value after keyword " << keyword.toStdString() << " missing in line " << count << " of provisioning file " << filePath.toStdString(); continue; } switch (key) { case READ: { QUrl readFileUrl(value); if (!readFileUrl.isValid()) { MITK_WARN << "The READ URL " << value.toStdString() << "is invalid: " << readFileUrl.errorString().toStdString(); break; } this->readProvisioningFile(readFileUrl.toLocalFile()); break; } case INSTALL: { this->addPluginToInstall(value); break; } case START: { this->addPluginToStart(value); break; } case STOP: { break; } case UNKNOWN: { break; // error handled above } } } ++count; } while (!line.isNull()); } QUrl ProvisioningInfo::addPluginToInstall(const QString &file) { QUrl pluginUrl(file); if (!pluginUrl.isValid()) { MITK_WARN << "The plugin URL " << file.toStdString() << " is invalid:" << pluginUrl.errorString().toStdString(); return QUrl(); } QFileInfo fileInfo(pluginUrl.toLocalFile()); if (!fileInfo.exists()) { QString fileName = fileInfo.fileName(); QString filePath = fileInfo.absolutePath(); if (!intermediateOutDir.isEmpty()) { // search in the intermediate output dir QString filePath2 = filePath + "/" + intermediateOutDir; fileInfo = QFileInfo(filePath2 + "/" + fileName); if (!fileInfo.exists()) { MITK_WARN << "The plugin " << fileName.toStdString() << " was not found in " << filePath.toStdString() << " or " << filePath2.toStdString(); return QUrl(); } pluginUrl = QUrl::fromLocalFile(fileInfo.canonicalFilePath()); pluginDirs.insert(fileInfo.canonicalPath()); } else { MITK_WARN << "The plugin " << fileName.toStdString() << " was not found in " << filePath.toStdString(); return QUrl(); } } else { pluginDirs.insert(fileInfo.canonicalPath()); } pluginsToInstall.append(pluginUrl); return pluginUrl; } void ProvisioningInfo::addPluginToStart(const QString &file) { QUrl pluginUrl = this->addPluginToInstall(file); if (!pluginUrl.isEmpty()) { pluginsToStart.append(pluginUrl); } } QString ProvisioningInfo::substituteKeywords(const QString &value) const { QString appPath = QCoreApplication::applicationDirPath(); if (appPath.endsWith('/')) { appPath.chop(1); } #ifdef CMAKE_INTDIR // Strip the intermediate dir from the application path QString intDir(CMAKE_INTDIR); if (appPath.endsWith(intDir)) { appPath.chop(intDir.size() + 1); } #endif #ifdef _WIN32 if (value.contains("@EXECUTABLE_DIR") && value.contains("blueberry_osgi")) { // special case for org_blueberry_osgi in install trees for Windows return QString(value).replace("@EXECUTABLE_DIR", appPath, Qt::CaseInsensitive).replace("plugins/", ""); } #endif return QString(value).replace("@EXECUTABLE_DIR", appPath, Qt::CaseInsensitive); } } diff --git a/Modules/Chart/src/mitkChartExampleTestHelper.cpp b/Modules/Chart/src/mitkChartExampleTestHelper.cpp index 06bebf4bb2..50e8fed921 100644 --- a/Modules/Chart/src/mitkChartExampleTestHelper.cpp +++ b/Modules/Chart/src/mitkChartExampleTestHelper.cpp @@ -1,353 +1,353 @@ /*============================================================================ 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 "mitkChartExampleTestHelper.h" // std includes #include std::unique_ptr mitk::ChartExampleTestHelper::GetDataOne() { auto myDataOne = std::make_unique(); std::vector< std::pair > data; for (int i = 0; i < 10; i++) { data.emplace_back(i, i); } myDataOne->SetData(data); myDataOne->SetLabel("DataOne"); myDataOne->SetChartType("bar"); myDataOne->SetColor("red"); myDataOne->SetLineStyle("solid"); return myDataOne; } std::unique_ptr mitk::ChartExampleTestHelper::GetDataTwo() { auto myDataTwo = std::make_unique(); std::vector< std::pair > data; for (int i = 10; i < 20; i++) { data.emplace_back(i, i); } myDataTwo->SetData(data); myDataTwo->SetLabel("DataTwo"); myDataTwo->SetChartType("bar"); myDataTwo->SetColor("green"); myDataTwo->SetLineStyle("solid"); return myDataTwo; } std::unique_ptr mitk::ChartExampleTestHelper::GetDataThree() { auto myDataThree = std::make_unique(); std::vector< std::pair > data; for (int i = 20; i < 30; i++) { data.emplace_back(i, i); } myDataThree->SetData(data); myDataThree->SetLabel("DataThree"); myDataThree->SetChartType("bar"); myDataThree->SetColor("blue"); myDataThree->SetLineStyle("solid"); return myDataThree; } std::unique_ptr mitk::ChartExampleTestHelper::GetDataFour() { auto myDataFour = std::make_unique(); std::vector< std::pair > data; for (int i = 30; i < 40; i++) { data.emplace_back(i, i); } myDataFour->SetData(data); myDataFour->SetLabel("DataFour"); myDataFour->SetChartType("bar"); myDataFour->SetColor("yellow"); myDataFour->SetLineStyle("solid"); return myDataFour; } std::unique_ptr mitk::ChartExampleTestHelper::GetDataFive() { auto myDataFive = std::make_unique(); std::vector< std::pair > data; for (int i = 40; i < 50; i++) { data.emplace_back(i, i); } myDataFive->SetData(data); myDataFive->SetLabel("DataFive"); myDataFive->SetChartType("bar"); myDataFive->SetColor("black"); myDataFive->SetLineStyle("solid"); return myDataFive; } QmitkChartWidget::ChartType mitk::ChartExampleTestHelper::ReturnChartTypeByString(std::string chartTypeString) { if (chartTypeString == "bar") { return QmitkChartWidget::ChartType::bar; } if (chartTypeString == "line") { return QmitkChartWidget::ChartType::line; } if (chartTypeString == "spline") { return QmitkChartWidget::ChartType::spline; } if (chartTypeString == "pie") { return QmitkChartWidget::ChartType::pie; } if (chartTypeString == "area") { return QmitkChartWidget::ChartType::area; } if (chartTypeString == "area_spline") { return QmitkChartWidget::ChartType::area_spline; } if (chartTypeString == "scatter") { return QmitkChartWidget::ChartType::scatter; } return QmitkChartWidget::ChartType::bar; } QmitkChartWidget::ChartColor mitk::ChartExampleTestHelper::ReturnChartColorByString(std::string chartColorString) { if (chartColorString == "red") { return QmitkChartWidget::ChartColor::red; } if (chartColorString == "orange") { return QmitkChartWidget::ChartColor::orange; } if (chartColorString == "yellow") { return QmitkChartWidget::ChartColor::yellow; } if (chartColorString == "green") { return QmitkChartWidget::ChartColor::green; } if (chartColorString == "blue") { return QmitkChartWidget::ChartColor::blue; } if (chartColorString == "purple") { return QmitkChartWidget::ChartColor::purple; } if (chartColorString == "brown") { return QmitkChartWidget::ChartColor::brown; } if (chartColorString == "magenta") { return QmitkChartWidget::ChartColor::magenta; } if (chartColorString == "tan") { return QmitkChartWidget::ChartColor::tan; } if (chartColorString == "cyan") { return QmitkChartWidget::ChartColor::cyan; } if (chartColorString == "olive") { return QmitkChartWidget::ChartColor::olive; } if (chartColorString == "maroon") { return QmitkChartWidget::ChartColor::maroon; } if (chartColorString == "navy") { return QmitkChartWidget::ChartColor::navy; } if (chartColorString == "aquamarine") { return QmitkChartWidget::ChartColor::aquamarine; } if (chartColorString == "turqouise") { return QmitkChartWidget::ChartColor::turqouise; } if (chartColorString == "silver") { return QmitkChartWidget::ChartColor::silver; } if (chartColorString == "lime") { return QmitkChartWidget::ChartColor::lime; } if (chartColorString == "teal") { return QmitkChartWidget::ChartColor::teal; } if (chartColorString == "indigo") { return QmitkChartWidget::ChartColor::indigo; } if (chartColorString == "violet") { return QmitkChartWidget::ChartColor::violet; } if (chartColorString == "pink") { return QmitkChartWidget::ChartColor::pink; } if (chartColorString == "black") { return QmitkChartWidget::ChartColor::black; } if (chartColorString == "white") { return QmitkChartWidget::ChartColor::white; } if (chartColorString == "grey") { return QmitkChartWidget::ChartColor::grey; } return QmitkChartWidget::ChartColor::red; } QmitkChartWidget::LineStyle mitk::ChartExampleTestHelper::ReturnChartStyleByString(std::string chartStyleString) { if (chartStyleString == "solid") { return QmitkChartWidget::LineStyle::solid; } if (chartStyleString == "dashed") { return QmitkChartWidget::LineStyle::dashed; } return QmitkChartWidget::LineStyle::solid; } void mitk::ChartExampleTestHelper::Add(int dataSet) { std::unique_ptr myData; if (dataSet == 1) { myData = mitk::ChartExampleTestHelper::GetDataOne(); } if (dataSet == 2) { myData = mitk::ChartExampleTestHelper::GetDataTwo(); } if (dataSet == 3) { myData = mitk::ChartExampleTestHelper::GetDataThree(); } if (dataSet == 4) { myData = mitk::ChartExampleTestHelper::GetDataFour(); } if (dataSet == 5) { myData = mitk::ChartExampleTestHelper::GetDataFive(); } std::vector< std::pair > data = mitk::ChartExampleTestHelper::ToStdPairList(myData->GetXData(), myData->GetYData()); auto label = myData->GetLabel().toString().toStdString(); auto type = myData->GetChartType().toString().toStdString(); auto color = myData->GetColor().toString().toStdString(); auto style = myData->GetLineStyle().toString().toStdString(); qmitkChartWidget.AddChartExampleData(data, label, type, color, style); } std::vector< std::pair > mitk::ChartExampleTestHelper::ToStdPairList(QVariantList xData, QVariantList yData) { - auto xDataConverted = xData.toVector().toStdVector(); - auto yDataConverted = yData.toVector().toStdVector(); + std::vector xDataConverted(xData.begin(), xData.end()); + std::vector yDataConverted(yData.begin(), yData.end()); std::vector< std::pair > data; for (size_t i = 0; i < xDataConverted.size(); i++) { data.emplace_back(xDataConverted[i].toDouble(), yDataConverted[i].toDouble()); } return data; } void mitk::ChartExampleTestHelper::ClearMemory() { // Clear the vector qmitkChartWidget.Clear(); } diff --git a/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp b/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp index 2b48e0e411..4481fcc6b8 100644 --- a/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp +++ b/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp @@ -1,69 +1,70 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include // mitk qt widgets module #include "QmitkMimeTypes.h" // qt #include #include #include #include QmitkDnDDataNodeWidget::QmitkDnDDataNodeWidget(QWidget* parent /*= nullptr*/) : QFrame(parent) { this->setAcceptDrops(true); } QmitkDnDDataNodeWidget::~QmitkDnDDataNodeWidget() { // nothing here } void QmitkDnDDataNodeWidget::dragEnterEvent(QDragEnterEvent* event) { if (this != event->source()) { event->acceptProposedAction(); } else { event->ignore(); } } void QmitkDnDDataNodeWidget::dragMoveEvent(QDragMoveEvent* event) { if (event->mimeData()->hasFormat(QmitkMimeTypes::DataNodePtrs)) { event->acceptProposedAction(); } else { event->ignore(); } } void QmitkDnDDataNodeWidget::dropEvent(QDropEvent* event) { QList dataNodeList = QmitkMimeTypes::ToDataNodePtrList(event->mimeData()); if (!dataNodeList.empty()) { - emit NodesDropped(dataNodeList.toVector().toStdVector()); + std::vector nodes(dataNodeList.begin(), dataNodeList.end()); + emit NodesDropped(nodes); } event->acceptProposedAction(); } diff --git a/Modules/QtWidgets/src/QmitkRenderWindow.cpp b/Modules/QtWidgets/src/QmitkRenderWindow.cpp index ddb449d628..a478536dc4 100644 --- a/Modules/QtWidgets/src/QmitkRenderWindow.cpp +++ b/Modules/QtWidgets/src/QmitkRenderWindow.cpp @@ -1,515 +1,516 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRenderWindow.h" #include "mitkInteractionKeyEvent.h" #include "mitkInternalEvent.h" #include "mitkMouseDoubleClickEvent.h" #include "mitkMouseMoveEvent.h" #include "mitkMousePressEvent.h" #include "mitkMouseReleaseEvent.h" #include "mitkMouseWheelEvent.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include QmitkRenderWindow::QmitkRenderWindow(QWidget *parent, const QString &name, mitk::VtkPropRenderer *) : QVTKOpenGLNativeWidget(parent) , m_ResendQtEvents(true) , m_MenuWidget(nullptr) , m_MenuWidgetActivated(false) , m_LayoutIndex(QmitkRenderWindowMenu::LayoutIndex::Axial) , m_GeometryViolationWarningOverlay(nullptr) { m_InternalRenderWindow = vtkSmartPointer::New(); m_InternalRenderWindow->SetMultiSamples(0); m_InternalRenderWindow->SetAlphaBitPlanes(0); setRenderWindow(m_InternalRenderWindow); Initialize(name.toStdString().c_str()); setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setSizePolicy(sizePolicy); // setup overlay widget to show a warning message with a button m_GeometryViolationWarningOverlay = new QmitkButtonOverlayWidget(this); m_GeometryViolationWarningOverlay->setVisible(false); m_GeometryViolationWarningOverlay->SetOverlayText( QStringLiteral("

Interaction is not possible because the " "render window geometry
does not match the interaction reference geometry.

")); m_GeometryViolationWarningOverlay->SetButtonText("Reset geometry"); m_GeometryViolationWarningOverlay->SetButtonIcon(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/reset.svg"))); connect(m_GeometryViolationWarningOverlay, &QmitkButtonOverlayWidget::Clicked, this, &QmitkRenderWindow::ResetGeometry); } QmitkRenderWindow::~QmitkRenderWindow() { Destroy(); // Destroy mitkRenderWindowBase } void QmitkRenderWindow::SetResendQtEvents(bool resend) { m_ResendQtEvents = resend; } void QmitkRenderWindow::SetLayoutIndex(QmitkRenderWindowMenu::LayoutIndex layoutIndex) { m_LayoutIndex = layoutIndex; if (nullptr != m_MenuWidget) { m_MenuWidget->SetLayoutIndex(layoutIndex); } } QmitkRenderWindowMenu::LayoutIndex QmitkRenderWindow::GetLayoutIndex() { if (nullptr != m_MenuWidget) { return m_MenuWidget->GetLayoutIndex(); } else { return QmitkRenderWindowMenu::LayoutIndex::Axial; } } void QmitkRenderWindow::UpdateLayoutDesignList(QmitkRenderWindowMenu::LayoutDesign layoutDesign) { if (nullptr != m_MenuWidget) { m_MenuWidget->UpdateLayoutDesignList(layoutDesign); } } void QmitkRenderWindow::UpdateCrosshairVisibility(bool visible) { m_MenuWidget->UpdateCrosshairVisibility(visible); } void QmitkRenderWindow::UpdateCrosshairRotationMode(int mode) { m_MenuWidget->UpdateCrosshairRotationMode(mode); } void QmitkRenderWindow::ActivateMenuWidget(bool state) { if (nullptr == m_MenuWidget) { m_MenuWidget = new QmitkRenderWindowMenu(this, {}, m_Renderer); m_MenuWidget->SetLayoutIndex(m_LayoutIndex); } if (m_MenuWidgetActivated == state) { // no new state; nothing to do return; } m_MenuWidgetActivated = state; if (m_MenuWidgetActivated) { connect(m_MenuWidget, &QmitkRenderWindowMenu::LayoutDesignChanged, this, &QmitkRenderWindow::LayoutDesignChanged); connect(m_MenuWidget, &QmitkRenderWindowMenu::ResetView, this, &QmitkRenderWindow::ResetView); connect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairVisibilityChanged, this, &QmitkRenderWindow::CrosshairVisibilityChanged); connect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairRotationModeChanged, this, &QmitkRenderWindow::CrosshairRotationModeChanged); } else { disconnect(m_MenuWidget, &QmitkRenderWindowMenu::LayoutDesignChanged, this, &QmitkRenderWindow::LayoutDesignChanged); disconnect(m_MenuWidget, &QmitkRenderWindowMenu::ResetView, this, &QmitkRenderWindow::ResetView); disconnect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairVisibilityChanged, this, &QmitkRenderWindow::CrosshairVisibilityChanged); disconnect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairRotationModeChanged, this, &QmitkRenderWindow::CrosshairRotationModeChanged); m_MenuWidget->hide(); } } void QmitkRenderWindow::ShowOverlayMessage(bool show) { m_GeometryViolationWarningOverlay->setVisible(show); } void QmitkRenderWindow::moveEvent(QMoveEvent *event) { QVTKOpenGLNativeWidget::moveEvent(event); // after a move the overlays need to be positioned emit moved(); } void QmitkRenderWindow::showEvent(QShowEvent *event) { QVTKOpenGLNativeWidget::showEvent(event); // this singleshot is necessary to have the overlays positioned correctly after initial show // simple call of moved() is no use here!! QTimer::singleShot(0, this, SIGNAL(moved())); } bool QmitkRenderWindow::event(QEvent* e) { mitk::InteractionEvent::Pointer mitkEvent = nullptr; mitk::Point2D mousePosition; bool updateStatusBar = false; switch (e->type()) { case QEvent::MouseMove: { auto me = static_cast(e); mousePosition = this->GetMousePosition(me); mitkEvent = mitk::MouseMoveEvent::New(m_Renderer, mousePosition, GetButtonState(me), GetModifiers(me)); updateStatusBar = true; break; } case QEvent::MouseButtonPress: { auto me = static_cast(e); mitkEvent = mitk::MousePressEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); break; } case QEvent::MouseButtonRelease: { auto me = static_cast(e); mitkEvent = mitk::MouseReleaseEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); break; } case QEvent::MouseButtonDblClick: { auto me = static_cast(e); mitkEvent = mitk::MouseDoubleClickEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); break; } case QEvent::Wheel: { auto we = static_cast(e); mousePosition = this->GetMousePosition(we); mitkEvent = mitk::MouseWheelEvent::New(m_Renderer, mousePosition, GetButtonState(we), GetModifiers(we), GetDelta(we)); updateStatusBar = true; break; } case QEvent::KeyPress: { auto ke = static_cast(e); mitkEvent = mitk::InteractionKeyEvent::New(m_Renderer, GetKeyLetter(ke), GetModifiers(ke)); break; } case QEvent::Resize: { if (nullptr != m_MenuWidget) m_MenuWidget->MoveWidgetToCorrectPos(); } default: { break; } } if (mitkEvent != nullptr) { if (this->HandleEvent(mitkEvent.GetPointer())) { return m_ResendQtEvents ? false : true; } } if (updateStatusBar) { this->UpdateStatusBar(mousePosition); } return QVTKOpenGLNativeWidget::event(e); } void QmitkRenderWindow::enterEvent(QEvent *e) { auto* baseRenderer = mitk::BaseRenderer::GetInstance(this->GetVtkRenderWindow()); this->ShowOverlayMessage(!baseRenderer->GetReferenceGeometryAligned()); if (nullptr != m_MenuWidget) m_MenuWidget->ShowMenu(); QVTKOpenGLNativeWidget::enterEvent(e); } void QmitkRenderWindow::leaveEvent(QEvent *e) { auto statusBar = mitk::StatusBar::GetInstance(); statusBar->DisplayGreyValueText(""); this->ShowOverlayMessage(false); if (nullptr != m_MenuWidget) m_MenuWidget->HideMenu(); QVTKOpenGLNativeWidget::leaveEvent(e); } void QmitkRenderWindow::resizeGL(int w, int h) { QVTKOpenGLNativeWidget::resizeGL(w, h); mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(renderWindow()); } void QmitkRenderWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("application/x-mitk-datanodes")) { event->accept(); } } void QmitkRenderWindow::dropEvent(QDropEvent *event) { QList dataNodeList = QmitkMimeTypes::ToDataNodePtrList(event->mimeData()); if (!dataNodeList.empty()) { - emit NodesDropped(this, dataNodeList.toVector().toStdVector()); + std::vector dataNodes(dataNodeList.begin(), dataNodeList.end()); + emit NodesDropped(this, dataNodes); } } void QmitkRenderWindow::DeferredHideMenu() { MITK_DEBUG << "QmitkRenderWindow::DeferredHideMenu"; if (nullptr != m_MenuWidget) { m_MenuWidget->HideMenu(); } } mitk::Point2D QmitkRenderWindow::GetMousePosition(QMouseEvent *me) const { mitk::Point2D point; const auto scale = this->devicePixelRatioF(); point[0] = me->x()*scale; // We need to convert the y component, as the display and vtk have other definitions for the y direction point[1] = m_Renderer->GetSizeY() - me->y()*scale; return point; } mitk::Point2D QmitkRenderWindow::GetMousePosition(QWheelEvent *we) const { mitk::Point2D point; const auto scale = this->devicePixelRatioF(); point[0] = we->x()*scale; // We need to convert the y component, as the display and vtk have other definitions for the y direction point[1] = m_Renderer->GetSizeY() - we->y()*scale; return point; } mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetEventButton(QMouseEvent *me) const { mitk::InteractionEvent::MouseButtons eventButton; switch (me->button()) { case Qt::LeftButton: eventButton = mitk::InteractionEvent::LeftMouseButton; break; case Qt::RightButton: eventButton = mitk::InteractionEvent::RightMouseButton; break; case Qt::MidButton: eventButton = mitk::InteractionEvent::MiddleMouseButton; break; default: eventButton = mitk::InteractionEvent::NoButton; break; } return eventButton; } mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QMouseEvent *me) const { mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton; if (me->buttons() & Qt::LeftButton) { buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton; } if (me->buttons() & Qt::RightButton) { buttonState = buttonState | mitk::InteractionEvent::RightMouseButton; } if (me->buttons() & Qt::MidButton) { buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton; } return buttonState; } mitk::InteractionEvent::ModifierKeys QmitkRenderWindow::GetModifiers(QInputEvent *me) const { mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::NoKey; if (me->modifiers() & Qt::ALT) { modifiers = modifiers | mitk::InteractionEvent::AltKey; } if (me->modifiers() & Qt::CTRL) { modifiers = modifiers | mitk::InteractionEvent::ControlKey; } if (me->modifiers() & Qt::SHIFT) { modifiers = modifiers | mitk::InteractionEvent::ShiftKey; } return modifiers; } mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QWheelEvent *we) const { mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton; if (we->buttons() & Qt::LeftButton) { buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton; } if (we->buttons() & Qt::RightButton) { buttonState = buttonState | mitk::InteractionEvent::RightMouseButton; } if (we->buttons() & Qt::MidButton) { buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton; } return buttonState; } std::string QmitkRenderWindow::GetKeyLetter(QKeyEvent *ke) const { // Converting Qt Key Event to string element. std::string key = ""; int tkey = ke->key(); if (tkey < 128) { // standard ascii letter key = (char)toupper(tkey); } else { // special keys switch (tkey) { case Qt::Key_Return: key = mitk::InteractionEvent::KeyReturn; break; case Qt::Key_Enter: key = mitk::InteractionEvent::KeyEnter; break; case Qt::Key_Escape: key = mitk::InteractionEvent::KeyEsc; break; case Qt::Key_Delete: key = mitk::InteractionEvent::KeyDelete; break; case Qt::Key_Up: key = mitk::InteractionEvent::KeyArrowUp; break; case Qt::Key_Down: key = mitk::InteractionEvent::KeyArrowDown; break; case Qt::Key_Left: key = mitk::InteractionEvent::KeyArrowLeft; break; case Qt::Key_Right: key = mitk::InteractionEvent::KeyArrowRight; break; case Qt::Key_F1: key = mitk::InteractionEvent::KeyF1; break; case Qt::Key_F2: key = mitk::InteractionEvent::KeyF2; break; case Qt::Key_F3: key = mitk::InteractionEvent::KeyF3; break; case Qt::Key_F4: key = mitk::InteractionEvent::KeyF4; break; case Qt::Key_F5: key = mitk::InteractionEvent::KeyF5; break; case Qt::Key_F6: key = mitk::InteractionEvent::KeyF6; break; case Qt::Key_F7: key = mitk::InteractionEvent::KeyF7; break; case Qt::Key_F8: key = mitk::InteractionEvent::KeyF8; break; case Qt::Key_F9: key = mitk::InteractionEvent::KeyF9; break; case Qt::Key_F10: key = mitk::InteractionEvent::KeyF10; break; case Qt::Key_F11: key = mitk::InteractionEvent::KeyF11; break; case Qt::Key_F12: key = mitk::InteractionEvent::KeyF12; break; case Qt::Key_End: key = mitk::InteractionEvent::KeyEnd; break; case Qt::Key_Home: key = mitk::InteractionEvent::KeyPos1; break; case Qt::Key_Insert: key = mitk::InteractionEvent::KeyInsert; break; case Qt::Key_PageDown: key = mitk::InteractionEvent::KeyPageDown; break; case Qt::Key_PageUp: key = mitk::InteractionEvent::KeyPageUp; break; case Qt::Key_Space: key = mitk::InteractionEvent::KeySpace; break; } } return key; } int QmitkRenderWindow::GetDelta(QWheelEvent *we) const { return we->delta(); } void QmitkRenderWindow::UpdateStatusBar(mitk::Point2D pointerPositionOnScreen) { mitk::Point3D worldPosition; m_Renderer->ForceImmediateUpdate(); m_Renderer->DisplayToWorld(pointerPositionOnScreen, worldPosition); auto statusBar = mitk::StatusBar::GetInstance(); statusBar->DisplayRendererInfo(worldPosition, m_Renderer->GetTime()); } diff --git a/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp b/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp index 516f9f51e7..ffae990899 100644 --- a/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp +++ b/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp @@ -1,330 +1,330 @@ /*============================================================================ 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 "berryExtensionTracker.h" #include #include #include #include #include #include #include #include #include "internal/berrySimpleExtensionPointFilter.h" #include #include #include #include namespace berry { struct ExtensionTracker::Impl { struct HandlerWrapper; ExtensionTracker* const q; QHash > extensionToStrongObjects; QHash > extensionToWeakObjects; //ListenerList handlers; QHash handlerToWrapper; QMutex mutex; bool closed; IExtensionRegistry* registry; // the registry that this tacker works with Impl(ExtensionTracker* q, IExtensionRegistry* theRegistry) : q(q) , closed(false) , registry(theRegistry) {} }; struct ExtensionTracker::Impl::HandlerWrapper : public IRegistryEventListener { ExtensionTracker* const q; IExtensionChangeHandler* const handler; HandlerWrapper(ExtensionTracker* q, IExtensionChangeHandler* handler) : q(q) , handler(handler) {} bool operator==(const HandlerWrapper& target) const { return handler == target.handler; } void Added(const QList& extensions) override { for (int i = 0; i < extensions.size(); ++i) { q->ApplyAdd(handler, extensions[i]); } } void Removed(const QList& extensions) override { QList > removedObjects; { QMutexLocker lock(&q->d->mutex); for (int i = 0; i < extensions.size(); ++i) { QSet associatedObjects = q->d->extensionToStrongObjects.take(extensions[i]); foreach(const Object::WeakPtr& ptr, q->d->extensionToWeakObjects.take(extensions[i])) { if (!ptr.Expired()) { associatedObjects.insert(ptr.Lock()); } } - removedObjects.push_back(associatedObjects.toList()); + removedObjects.push_back(associatedObjects.values()); } } for (int i = 0; i < extensions.size(); ++i) { q->ApplyRemove(handler, extensions[i], removedObjects[i]); } } void Added(const QList& /*extensionPoints*/) override { // do nothing } void Removed(const QList& /*extensionPoints*/) override { // do nothing } }; ExtensionTracker::ExtensionTracker() { this->Init(Platform::GetExtensionRegistry()); } ExtensionTracker::~ExtensionTracker() { } ExtensionTracker::ExtensionTracker(IExtensionRegistry* theRegistry) : d() { this->Init(theRegistry); } void ExtensionTracker::Init(IExtensionRegistry* registry) { d.reset(new Impl(this, registry)); if (registry == nullptr) { //RuntimeLog.log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_no_default, null)); BERRY_ERROR << "Extension tracker was unable to obtain BlueBerry extension registry."; d->closed = true; } } void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter) { QMutexLocker lock(&d->mutex); if (d->closed) return; auto iter = d->handlerToWrapper.insert(handler, new Impl::HandlerWrapper(this, handler)); d->registry->AddListener(iter.value(), filter); } void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const QString& extensionPointId) { this->RegisterHandler(handler, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr) : IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId))); } void ExtensionTracker::UnregisterHandler(IExtensionChangeHandler* handler) { QMutexLocker lock(&d->mutex); if (d->closed) return; IRegistryEventListener* listener = d->handlerToWrapper.take(handler); d->registry->RemoveListener(listener); delete listener; } void ExtensionTracker::RegisterObject(const SmartPointer& element, const SmartPointer& object, IExtensionTracker::ReferenceType referenceType) { if (element.IsNull() || object.IsNull()) return; QMutexLocker lock(&d->mutex); if (d->closed) return; if (referenceType == REF_STRONG) { d->extensionToStrongObjects[element].insert(object); } else if (referenceType == REF_WEAK) { d->extensionToWeakObjects[element].insert(Object::WeakPtr(object)); } } QList > ExtensionTracker::GetObjects(const IExtension::Pointer& element) const { QSet objectSet; QMutexLocker lock(&d->mutex); - if (d->closed) return objectSet.toList(); + if (d->closed) return objectSet.values(); auto iter = d->extensionToStrongObjects.find(element); if (iter != d->extensionToStrongObjects.end()) { objectSet.unite(iter.value()); } auto iter2 = d->extensionToWeakObjects.find(element); if (iter2 != d->extensionToWeakObjects.end()) { foreach(const Object::WeakPtr& ptr, iter2.value()) { if (!ptr.Expired()) objectSet.insert(ptr.Lock()); } } - return objectSet.toList(); + return objectSet.values(); } void ExtensionTracker::Close() { QMutexLocker lock(&d->mutex); if (d->closed) return; foreach(Impl::HandlerWrapper* wrapper, d->handlerToWrapper.values()) { d->registry->RemoveListener(wrapper); delete wrapper; } d->extensionToStrongObjects.clear(); d->extensionToWeakObjects.clear(); d->handlerToWrapper.clear(); d->closed = true; } void ExtensionTracker::UnregisterObject(const SmartPointer& extension, const SmartPointer& object) { QMutexLocker lock(&d->mutex); if (d->closed) return; auto iter = d->extensionToStrongObjects.find(extension); if (iter != d->extensionToStrongObjects.end()) { iter.value().remove(object); } auto iter2 = d->extensionToWeakObjects.find(extension); if (iter2 != d->extensionToWeakObjects.end()) { iter2.value().remove(Object::WeakPtr(object)); } } QList > ExtensionTracker::UnregisterObject(const SmartPointer& extension) { QSet objectSet; QMutexLocker lock(&d->mutex); - if (d->closed) return objectSet.toList(); + if (d->closed) return objectSet.values(); auto iter = d->extensionToStrongObjects.find(extension); if (iter != d->extensionToStrongObjects.end()) { objectSet.unite(iter.value()); d->extensionToStrongObjects.erase(iter); } auto iter2 = d->extensionToWeakObjects.find(extension); if (iter2 != d->extensionToWeakObjects.end()) { foreach(const Object::WeakPtr& ptr, iter2.value()) { if (!ptr.Expired()) objectSet.insert(ptr.Lock()); } d->extensionToWeakObjects.erase(iter2); } - return objectSet.toList(); + return objectSet.values(); } IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const SmartPointer& xpt) { struct F : IExtensionPointFilter::Concept { const IExtensionPoint::Pointer m_Xpt; F(const IExtensionPoint::Pointer& xp) : m_Xpt(xp) {} bool Matches(const IExtensionPoint* target) const override { return m_Xpt == target; } }; return IExtensionPointFilter(new F(xpt)); } IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const QList >& xpts) { struct F : IExtensionPointFilter::Concept { const QList m_Xpts; F(const QList& xps) : m_Xpts(xps) {} bool Matches(const IExtensionPoint* target) const override { for (int i = 0; i < m_Xpts.size(); i++) { if (m_Xpts[i] == target) { return true; } } return false; } }; return IExtensionPointFilter(new F(xpts)); } IExtensionPointFilter ExtensionTracker::CreateNamespaceFilter(const QString& id) { struct F : IExtensionPointFilter::Concept { const QString m_Id; F(const QString& id) : m_Id(id) {} bool Matches(const IExtensionPoint* target) const override { return m_Id == target->GetNamespaceIdentifier(); } }; return IExtensionPointFilter(new F(id)); } void ExtensionTracker::ApplyAdd(IExtensionChangeHandler* handler, const SmartPointer& extension) { handler->AddExtension(this, extension); } void ExtensionTracker::ApplyRemove(IExtensionChangeHandler* handler, const SmartPointer& removedExtension, const QList& removedObjects) { handler->RemoveExtension(removedExtension, removedObjects); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp index 889118ab0a..b23926e210 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp @@ -1,313 +1,313 @@ /*============================================================================ 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 "berryCommandService.h" #include #include #include #include #include #include "berryPersistentState.h" #include "berryWorkbenchPlugin.h" #include "berryElementReference.h" #include #include #include #include #include #include #include namespace berry { const std::string CommandService::PREFERENCE_KEY_PREFIX = "org.blueberry.ui.commands/state"; std::string CommandService::CreatePreferenceKey(const SmartPointer& command, const QString& stateId) { return PREFERENCE_KEY_PREFIX + '/' + command->GetId().toStdString() + '/' + stateId.toStdString(); } CommandService::CommandService( CommandManager* commandManager) : commandManager(commandManager) , commandPersistence(this) { if (commandManager == nullptr) { throw std::invalid_argument("Cannot create a command service with a null manager"); } } CommandService::~CommandService() { this->Dispose(); } void CommandService::AddExecutionListener(IExecutionListener* listener) { commandManager->AddExecutionListener(listener); } void CommandService::DefineUncategorizedCategory(const QString& name, const QString& description) { commandManager->DefineUncategorizedCategory(name, description); } SmartPointer CommandService::Deserialize(const QString& serializedParameterizedCommand) const { return commandManager->Deserialize(serializedParameterizedCommand); } void CommandService::Dispose() { /* * All state on all commands needs to be disposed. This is so that the * state has a chance to persist any changes. */ const QList commands = commandManager->GetAllCommands(); foreach (const Command::Pointer& command, commands) { const QList stateIds = command->GetStateIds(); foreach(const QString& stateId, stateIds) { const State::Pointer state = command->GetState(stateId); if (PersistentState::Pointer persistentState = state.Cast()) { if (persistentState->ShouldPersist()) { persistentState->Save(WorkbenchPlugin::GetDefault()->GetPreferences(), CreatePreferenceKey(command, stateId)); } } } } commandCallbacks.clear(); } SmartPointer CommandService::GetCategory(const QString& categoryId) const { return commandManager->GetCategory(categoryId); } SmartPointer CommandService::GetCommand(const QString& commandId) const { return commandManager->GetCommand(commandId); } QList > CommandService::GetDefinedCategories() const { return commandManager->GetDefinedCategories(); } QStringList CommandService::GetDefinedCategoryIds() const { - return commandManager->GetDefinedCategoryIds().toList(); + return commandManager->GetDefinedCategoryIds().values(); } QStringList CommandService::GetDefinedCommandIds() const { - return commandManager->GetDefinedCommandIds().toList(); + return commandManager->GetDefinedCommandIds().values(); } QList > CommandService::GetDefinedCommands() const { return commandManager->GetDefinedCommands(); } QStringList CommandService::GetDefinedParameterTypeIds() const { - return commandManager->GetDefinedParameterTypeIds().toList(); + return commandManager->GetDefinedParameterTypeIds().values(); } QList > CommandService::GetDefinedParameterTypes() const { return commandManager->GetDefinedParameterTypes(); } QString CommandService::GetHelpContextId(const SmartPointer& command) const { return commandManager->GetHelpContextId(command); } QString CommandService::GetHelpContextId(const QString& commandId) const { Command::Pointer command = GetCommand(commandId); return commandManager->GetHelpContextId(command); } SmartPointer CommandService::GetParameterType(const QString& parameterTypeId) const { return commandManager->GetParameterType(parameterTypeId); } void CommandService::ReadRegistry() { commandPersistence.Read(); } void CommandService::RemoveExecutionListener(IExecutionListener* listener) { commandManager->RemoveExecutionListener(listener); } void CommandService::SetHelpContextId(const SmartPointer& handler, const QString& helpContextId) { commandManager->SetHelpContextId(handler, helpContextId); } void CommandService::RefreshElements(const QString& commandId, const QHash& filter) { Command::Pointer cmd = GetCommand(commandId); if (!cmd->IsDefined() || !(cmd->GetHandler().Cast())) { return; } IElementUpdater::Pointer updater = cmd->GetHandler().Cast(); if (commandCallbacks.isEmpty()) { return; } if(!commandCallbacks.contains(commandId)) { return; } foreach (IElementReference::Pointer callbackRef, commandCallbacks[commandId]) { struct _SafeRunnable : public ISafeRunnable { IElementUpdater* updater; IElementReference* callbackRef; _SafeRunnable(IElementUpdater* updater, IElementReference* callbackRef) : updater(updater), callbackRef(callbackRef) {} void HandleException(const ctkException& exc) override { WorkbenchPlugin::Log(QString("Failed to update callback: ") + callbackRef->GetCommandId() + exc.what()); } void Run() override { updater->UpdateElement(callbackRef->GetElement().GetPointer(), callbackRef->GetParameters()); } }; QHash parms = callbackRef->GetParameters(); ISafeRunnable::Pointer run(new _SafeRunnable(updater.GetPointer(), callbackRef.GetPointer())); if (filter.isEmpty()) { SafeRunner::Run(run); } else { bool match = true; QHashIterator i(filter); while (i.hasNext()) { i.next(); Object::Pointer value = parms[i.key()]; if (i.value() != value) { match = false; break; } } if (match) { SafeRunner::Run(run); } } } } SmartPointer CommandService::RegisterElementForCommand( const SmartPointer& command, const SmartPointer& element) { if (!command->GetCommand()->IsDefined()) { throw NotDefinedException( "Cannot define a callback for undefined command " + command->GetCommand()->GetId()); } if (element.IsNull()) { throw NotDefinedException("No callback defined for command " + command->GetCommand()->GetId()); } QHash paramMap = command->GetParameterMap(); QHash parms; for (QHash::const_iterator i = paramMap.begin(); i != paramMap.end(); ++i) { Object::Pointer value(new ObjectString(i.value())); parms.insert(i.key(), value); } IElementReference::Pointer ref(new ElementReference(command->GetId(), element, parms)); RegisterElement(ref); return ref; } void CommandService::RegisterElement(const SmartPointer& elementReference) { QList& parameterizedCommands = commandCallbacks[elementReference->GetCommandId()]; parameterizedCommands.push_back(elementReference); // If the active handler wants to update the callback, it can do // so now Command::Pointer command = GetCommand(elementReference->GetCommandId()); if (command->IsDefined()) { if (IElementUpdater::Pointer updater = command->GetHandler().Cast()) { updater->UpdateElement(elementReference->GetElement().GetPointer(), elementReference->GetParameters()); } } } void CommandService::UnregisterElement(const SmartPointer& elementReference) { if (commandCallbacks.contains(elementReference->GetCommandId())) { QList& parameterizedCommands = commandCallbacks[elementReference->GetCommandId()]; parameterizedCommands.removeAll(elementReference); if (parameterizedCommands.isEmpty()) { commandCallbacks.remove(elementReference->GetCommandId()); } } } const CommandPersistence* CommandService::GetCommandPersistence() const { return &commandPersistence; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp index c4c35cbdda..920abd7639 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp @@ -1,1295 +1,1295 @@ /*============================================================================ 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 "berryEditorRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryEditorRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" namespace berry { const QString EditorRegistry::EMPTY_EDITOR_ID = "org.blueberry.ui.internal.emptyEditorTab"; QHash EditorRegistry::EditorMap::defaultMap; QHash EditorRegistry::EditorMap::map; EditorRegistry::RelatedRegistry::RelatedRegistry(EditorRegistry* reg) : editorRegistry(reg) { } QList EditorRegistry::RelatedRegistry::GetRelatedObjects( const QString& fileName) { IFileEditorMapping::Pointer mapping = editorRegistry->GetMappingFor(fileName); if (mapping.IsNull()) { return QList(); } return mapping->GetEditors(); } EditorRegistry::EditorRegistry() : relatedRegistry(this) { this->InitialIdToEditorMap(mapIDtoEditor); this->InitializeFromStorage(); //IExtensionTracker tracker = PlatformUI.getWorkbench().getExtensionTracker(); //tracker.registerHandler(this, // ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter())); } void EditorRegistry::AddEditorFromPlugin(EditorDescriptor::Pointer editor, const QList& extensions, const QList& filenames, const QList& /*contentTypeVector*/, bool bDefault) { //PlatformUI.getWorkbench().getExtensionTracker().registerObject(editor.getConfigurationElement().getDeclaringExtension(), editor, IExtensionTracker.REF_WEAK); // record it in our quick reference list sortedEditorsFromPlugins.push_back(editor); // add it to the table of mappings for (QList::const_iterator itr = extensions.begin(); itr != extensions.end(); ++itr) { QString fileExtension = *itr; if (!fileExtension.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor("*." + fileExtension); if (mapping.IsNull()) { // no mapping for that extension mapping = new FileEditorMapping(fileExtension); typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping); } mapping->AddEditor(editor); if (bDefault) { mapping->SetDefaultEditor(editor); } } } // add it to the table of mappings for (QList::const_iterator itr = filenames.begin(); itr != filenames.end(); ++itr) { QString filename = *itr; if (!filename.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor(filename); if (mapping.IsNull()) { // no mapping for that extension QString name; QString extension; int index = filename.indexOf('.'); if (index == -1) { name = filename; extension = ""; } else { name = filename.left(index); extension = filename.mid(index + 1); } mapping = new FileEditorMapping(name, extension); typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping); } mapping->AddEditor(editor); if (bDefault) { mapping->SetDefaultEditor(editor); } } } // for (QList::const_iterator itr = contentTypeVector.begin(); // itr != contentTypeVector.end(); ++itr) // { // QString contentTypeId = *itr; // if (!contentTypeId.empty()) // { // IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeId); // if (contentType != null) // { // IEditorDescriptor [] editorArray = (IEditorDescriptor[]) contentTypeToEditorMappings.get(contentType); // if (editorArray == null) // { // editorArray = new IEditorDescriptor[] // { editor}; // contentTypeToEditorMappings.put(contentType, editorArray); // } // else // { // IEditorDescriptor [] newArray = new IEditorDescriptor[editorArray.length + 1]; // if (bDefault) // { // default editors go to the front of the line // newArray[0] = editor; // System.arraycopy(editorArray, 0, newArray, 1, editorArray.length); // } // else // { // newArray[editorArray.length] = editor; // System.arraycopy(editorArray, 0, newArray, 0, editorArray.length); // } // contentTypeToEditorMappings.put(contentType, newArray); // } // } // } // } // Update editor map. mapIDtoEditor[editor->GetId()] = editor; } void EditorRegistry::AddExternalEditorsToEditorMap() { // Add registered editors (may include external editors). QList maps = typeEditorMappings.AllMappings(); for (int i = 0; i < maps.size(); ++i) { FileEditorMapping::Pointer map = maps[i]; QList descArray = map->GetEditors(); for (QList::iterator itr = descArray.begin(); itr != descArray.end(); ++itr) { mapIDtoEditor[(*itr)->GetId()] = itr->Cast (); } } } IEditorDescriptor::Pointer EditorRegistry::FindEditor(const QString& id) { return mapIDtoEditor[id]; } IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor() { // the default editor will always be the system external editor // this should never return null return this->FindEditor(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor( const QString& fileName) { //return this->GetDefaultEditor(filename, guessAtContentType(filename)); return this->GetEditorForContentType(fileName /*, contentType*/); } IEditorDescriptor::Pointer EditorRegistry::GetEditorForContentType( const QString& filename /*IContentType contentType*/) { IEditorDescriptor::Pointer desc; ; QList contentTypeResults = this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry); if (contentTypeResults.size() > 0) { desc = contentTypeResults.front(); } return desc; } QList EditorRegistry::FindRelatedObjects( /*IContentType type,*/const QString& fileName, RelatedRegistry& /*registry*/) { QList allRelated; QList nonDefaultFileEditors; QList related; if (!fileName.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor(fileName); if (!mapping.IsNull()) { // backwards compatibility - add editors flagged as "default" related = mapping->GetDeclaredDefaultEditors(); for (QList::iterator itr = related.begin(); itr != related.end(); ++itr) { // we don't want to return duplicates if (std::find(allRelated.begin(), allRelated.end(), *itr) == allRelated.end()) { allRelated.push_back(*itr); } } // add all filename editors to the nonDefaultList // we'll later try to add them all after content types are resolved // duplicates (ie: default editors) will be ignored QList tmpList = mapping->GetEditors(); nonDefaultFileEditors.append(tmpList); } int index = fileName.indexOf('.'); if (index != -1) { QString extension = "*" + fileName.mid(index); mapping = this->GetMappingFor(extension); if (!mapping.IsNull()) { related = mapping->GetDeclaredDefaultEditors(); for (QList::iterator itr = related.begin(); itr != related.end(); ++itr) { // we don't want to return duplicates if (std::find(allRelated.begin(), allRelated.end(), *itr) == allRelated.end()) { allRelated.push_back(*itr); } } QList tmpList = mapping->GetEditors(); nonDefaultFileEditors.append(tmpList); } } } // if (type != null) { // // now add any objects directly related to the content type // related = registry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // // } // if (type != null) { // // now add any indirectly related objects, walking up the content type hierarchy // while ((type = type.getBaseType()) != null) { // related = registry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // } // } // add all non-default editors to the list for (QList::iterator i = nonDefaultFileEditors.begin(); i != nonDefaultFileEditors.end(); ++i) { IEditorDescriptor::Pointer editor = *i; if (std::find(allRelated.begin(), allRelated.end(), editor) == allRelated.end()) { allRelated.push_back(editor); } } return allRelated; } QList EditorRegistry::GetEditors( const QString& filename) { //return getEditors(filename, guessAtContentType(filename)); return this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry); } QList EditorRegistry::GetFileEditorMappings() { QList array(typeEditorMappings.AllMappings()); std::sort(array.begin(), array.end(), CmpFileEditorMapping()); QList result; for (QList::iterator itr = array.begin(); itr != array.end(); ++itr) { result.push_back(itr->Cast ()); } return result; } FileEditorMapping::Pointer EditorRegistry::GetMappingFor(const QString& ext) { QString key = this->MappingKeyFor(ext); return typeEditorMappings.Get(key); } QList EditorRegistry::GetMappingForFilename( const QString& filename) { QList mapping; // Lookup on entire filename mapping[0] = this->GetMappingFor(filename); // Lookup on filename's extension int index = filename.indexOf('.'); if (index != -1) { QString extension = filename.mid(index); mapping[1] = this->GetMappingFor("*" + extension); } return mapping; } // QList EditorRegistry::GetSortedEditorsFromOS() // { // List externalEditors = new ArrayList(); // Program[] programs = Program.getPrograms(); // // for (int i = 0; i < programs.length; i++) // { // //1FPLRL2: ITPUI:WINNT - NOTEPAD editor cannot be launched // //Some entries start with %SystemRoot% // //For such cases just use the file name as they are generally // //in directories which are on the path // /* // * if (fileName.charAt(0) == '%') { fileName = name + ".exe"; } // */ // // EditorDescriptor editor = new EditorDescriptor(); // editor.setOpenMode(EditorDescriptor.OPEN_EXTERNAL); // editor.setProgram(programs[i]); // // // determine the program icon this editor would need (do not let it // // be cached in the workbench registry) // ImageDescriptor desc = new ExternalProgramImageDescriptor( // programs[i]); // editor.setImageDescriptor(desc); // externalEditors.add(editor); // } // // Object[] tempArray = sortEditors(externalEditors); // IEditorDescriptor[] array = new IEditorDescriptor[externalEditors // .size()]; // for (int i = 0; i < tempArray.length; i++) // { // array[i] = (IEditorDescriptor) tempArray[i]; // } // return array; // } QList EditorRegistry::GetSortedEditorsFromPlugins() { QList result; for (QList::iterator itr = sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr) { result.push_back((*itr).Cast ()); } return result; } void EditorRegistry::InitialIdToEditorMap( QHash& map) { this->AddSystemEditors(map); } void EditorRegistry::AddSystemEditors( QHash& map) { // there will always be a system external editor descriptor EditorDescriptor::Pointer editor(new EditorDescriptor()); editor->SetID(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); editor->SetName("System Editor"); editor->SetOpenMode(EditorDescriptor::OPEN_EXTERNAL); // @issue we need a real icon for this editor? map[IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID] = editor; // there may be a system in-place editor if supported by platform // if (ComponentSupport.inPlaceEditorSupported()) // { // editor = new EditorDescriptor(); // editor.setID(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); // editor.setName(WorkbenchMessages.SystemInPlaceDescription_name); // editor.setOpenMode(EditorDescriptor.OPEN_INPLACE); // // @issue we need a real icon for this editor? // map.put(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID, editor); // } EditorDescriptor::Pointer emptyEditorDescriptor(new EditorDescriptor()); emptyEditorDescriptor->SetID(EMPTY_EDITOR_ID); emptyEditorDescriptor->SetName("(Empty)"); //$NON-NLS-1$ //emptyEditorDescriptor.setImageDescriptor(WorkbenchImages //.getImageDescriptor(IWorkbenchGraphicConstants.IMG_OBJ_ELEMENT)); map[EMPTY_EDITOR_ID] = emptyEditorDescriptor; } void EditorRegistry::InitializeFromStorage() { //Get editors from the registry EditorRegistryReader registryReader; registryReader.AddEditors(this); this->SortInternalEditors(); this->RebuildInternalEditorMap(); // IPreferenceStore store = PlatformUI.getPreferenceStore(); // String defaultEditors = store // .getString(IPreferenceConstants.DEFAULT_EDITORS); // String chachedDefaultEditors = store // .getString(IPreferenceConstants.DEFAULT_EDITORS_CACHE); //If defaults has changed load it afterwards so it overrides the users // associations. //if (defaultEditors == null // || defaultEditors.equals(chachedDefaultEditors)) //{ this->SetProductDefaults("");//defaultEditors); this->LoadAssociations(); //get saved earlier state // } // else // { // loadAssociations(); //get saved earlier state // setProductDefaults(defaultEditors); // store.putValue(IPreferenceConstants.DEFAULT_EDITORS_CACHE, // defaultEditors); // } this->AddExternalEditorsToEditorMap(); } void EditorRegistry::SetProductDefaults(const QString& defaultEditors) { if (defaultEditors.isEmpty()) { return; } // Poco::StringTokenizer extEditors(defaultEditors, // IPreferenceConstants::SEPARATOR, Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); // while (extEditors.hasMoreTokens()) // { // String extEditor = extEditors.nextToken().trim(); // int index = extEditor.indexOf(':'); // if (extEditor.length() < 3 || index <= 0 || index // >= (extEditor.length() - 1)) // { // //Extension and id must have at least one char. // WorkbenchPlugin // .log("Error setting default editor. Could not parse '" + extEditor // + "'. Default editors should be specified as '*.ext1:editorId1;*.ext2:editorId2'"); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } // String ext = extEditor.substring(0, index).trim(); // String editorId = extEditor.substring(index + 1).trim(); // FileEditorMapping mapping = getMappingFor(ext); // if (mapping == null) // { // WorkbenchPlugin // .log("Error setting default editor. Could not find mapping for '" // + ext + "'."); //$NON-NLS-1$ //$NON-NLS-2$ // continue; // } // EditorDescriptor editor = (EditorDescriptor) findEditor(editorId); // if (editor == null) // { // WorkbenchPlugin // .log("Error setting default editor. Could not find editor: '" // + editorId + "'."); //$NON-NLS-1$ //$NON-NLS-2$ // continue; // } // mapping.setDefaultEditor(editor); // } } bool EditorRegistry::ReadEditors( QHash& /*editorTable*/) { //Get the workbench plugin's working directory QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (workbenchStatePath.isNull()) { return false; } // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // Reader reader = null; // try // { // // Get the editors defined in the preferences store // String xmlString = store.getString(IPreferenceConstants.EDITORS); // if (xmlString == null || xmlString.length() == 0) // { // FileInputStream stream = new FileInputStream(workbenchStatePath // .append(IWorkbenchConstants.EDITOR_FILE_NAME) // .toOSString()); // reader = new BufferedReader(new InputStreamReader(stream, // "utf-8")); //$NON-NLS-1$ // } // else // { // reader = new StringReader(xmlString); // } // XMLMemento memento = XMLMemento.createReadRoot(reader); // EditorDescriptor editor; // IMemento[] edMementos = memento // .getChildren(IWorkbenchConstants.TAG_DESCRIPTOR); // // Get the editors and validate each one // for (int i = 0; i < edMementos.length; i++) // { // editor = new EditorDescriptor(); // boolean valid = editor.loadValues(edMementos[i]); // if (!valid) // { // continue; // } // if (editor.getPluginID() != null) // { // //If the editor is from a plugin we use its ID to look it // // up in the mapping of editors we // //have obtained from plugins. This allows us to verify that // // the editor is still valid // //and allows us to get the editor description from the // // mapping table which has // //a valid config element field. // EditorDescriptor validEditorDescritor = (EditorDescriptor) mapIDtoEditor // .get(editor.getId()); // if (validEditorDescritor != null) // { // editorTable.put(validEditorDescritor.getId(), // validEditorDescritor); // } // } // else // { //This is either from a program or a user defined // // editor // ImageDescriptor descriptor; // if (editor.getProgram() == null) // { // descriptor = new ProgramImageDescriptor(editor // .getFileName(), 0); // } // else // { // descriptor = new ExternalProgramImageDescriptor(editor // .getProgram()); // } // editor.setImageDescriptor(descriptor); // editorTable.put(editor.getId(), editor); // } // } // } // catch (IOException e) // { // try // { // if (reader != null) // { // reader.close(); // } // } // catch (IOException ex) // { // e.printStackTrace(); // } // //Ignore this as the workbench may not yet have saved any state // return false; // } // catch (WorkbenchException e) // { // ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage, // e.getStatus()); // return false; // } return true; } void EditorRegistry::ReadResources( QHash& /*editorTable*/, std::ostream& /*reader*/) { // XMLMemento memento = XMLMemento.createReadRoot(reader); // String versionString = memento.getString(IWorkbenchConstants.TAG_VERSION); // boolean versionIs31 = "3.1".equals(versionString); //$NON-NLS-1$ // // IMemento[] extMementos = memento // .getChildren(IWorkbenchConstants.TAG_INFO); // for (int i = 0; i < extMementos.length; i++) // { // String name = extMementos[i] // .getString(IWorkbenchConstants.TAG_NAME); // if (name == null) // { // name = "*"; //$NON-NLS-1$ // } // String extension = extMementos[i] // .getString(IWorkbenchConstants.TAG_EXTENSION); // IMemento[] idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_EDITOR); // String[] editorIDs = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // editorIDs[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_DELETED_EDITOR); // String[] deletedEditorIDs = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // deletedEditorIDs[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // FileEditorMapping mapping = getMappingFor(name + "." + extension); //$NON-NLS-1$ // if (mapping == null) // { // mapping = new FileEditorMapping(name, extension); // } // List editors = new ArrayList(); // for (int j = 0; j < editorIDs.length; j++) // { // if (editorIDs[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(editorIDs[j]); // if (editor != null) // { // editors.add(editor); // } // } // } // List deletedEditors = new ArrayList(); // for (int j = 0; j < deletedEditorIDs.length; j++) // { // if (deletedEditorIDs[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(deletedEditorIDs[j]); // if (editor != null) // { // deletedEditors.add(editor); // } // } // } // // List defaultEditors = new ArrayList(); // // if (versionIs31) // { // parse the new format // idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_DEFAULT_EDITOR); // String[] defaultEditorIds = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // defaultEditorIds[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // for (int j = 0; j < defaultEditorIds.length; j++) // { // if (defaultEditorIds[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(defaultEditorIds[j]); // if (editor != null) // { // defaultEditors.add(editor); // } // } // } // } // else // { // guess at pre 3.1 format defaults // if (!editors.isEmpty()) // { // EditorDescriptor editor = (EditorDescriptor) editors.get(0); // if (editor != null) // { // defaultEditors.add(editor); // } // } // defaultEditors.addAll(Arrays.asList(mapping.getDeclaredDefaultEditors())); // } // // // Add any new editors that have already been read from the registry // // which were not deleted. // IEditorDescriptor[] editorsArray = mapping.getEditors(); // for (int j = 0; j < editorsArray.length; j++) // { // if (!contains(editors, editorsArray[j]) // && !deletedEditors.contains(editorsArray[j])) // { // editors.add(editorsArray[j]); // } // } // // Map the editor(s) to the file type // mapping.setEditorsList(editors); // mapping.setDeletedEditorsList(deletedEditors); // mapping.setDefaultEditors(defaultEditors); // typeEditorMappings.put(mappingKeyFor(mapping), mapping); // } } bool EditorRegistry::Contains( const QList& editorsArray, IEditorDescriptor::Pointer editorDescriptor) { IEditorDescriptor::Pointer currentEditorDescriptor; for (QList::const_iterator i = editorsArray.begin(); i != editorsArray.end(); ++i) { currentEditorDescriptor = *i; if (currentEditorDescriptor->GetId() == editorDescriptor->GetId()) { return true; } } return false; } bool EditorRegistry::ReadResources( QHash& /*editorTable*/) { //Get the workbench plugin's working directory QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation(); // XXX: nobody cares about this return value if (workbenchStatePath.isNull()) { return false; } // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // Reader reader = null; // try // { // // Get the resource types // String xmlString = store.getString(IPreferenceConstants.RESOURCES); // if (xmlString == null || xmlString.length() == 0) // { // FileInputStream stream = new FileInputStream(workbenchStatePath // .append(IWorkbenchConstants.RESOURCE_TYPE_FILE_NAME) // .toOSString()); // reader = new BufferedReader(new InputStreamReader(stream, // "utf-8")); //$NON-NLS-1$ // } // else // { // reader = new StringReader(xmlString); // } // // Read the defined resources into the table // readResources(editorTable, reader); // } // catch (IOException e) // { // try // { // if (reader != null) // { // reader.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage); // return false; // } // catch (WorkbenchException e) // { // ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage, // e.getStatus()); // return false; // } return true; } bool EditorRegistry::LoadAssociations() { QHash editorTable; if (!this->ReadEditors(editorTable)) { return false; } return this->ReadResources(editorTable); } QString EditorRegistry::MappingKeyFor(const QString& type) { // keep everything lower case for case-sensitive platforms return type.toLower(); } QString EditorRegistry::MappingKeyFor(FileEditorMapping::Pointer mapping) { return this->MappingKeyFor(mapping->GetName() + (mapping->GetExtension().size() == 0 ? "" : "." + mapping->GetExtension())); //$NON-NLS-1$ //$NON-NLS-2$ } void EditorRegistry::RebuildEditorMap() { this->RebuildInternalEditorMap(); this->AddExternalEditorsToEditorMap(); } void EditorRegistry::RebuildInternalEditorMap() { EditorDescriptor::Pointer desc; // Allocate a new map. mapIDtoEditor.clear(); this->InitialIdToEditorMap(mapIDtoEditor); // Add plugin editors. for (QList::iterator itr = sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr) { desc = *itr; mapIDtoEditor[desc->GetId()] = desc; } } void EditorRegistry::SaveAssociations() { //Save the resource type descriptions // List editors = new ArrayList(); // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // // XMLMemento memento = XMLMemento // .createWriteRoot(IWorkbenchConstants.TAG_EDITORS); // memento.putString(IWorkbenchConstants.TAG_VERSION, "3.1"); //$NON-NLS-1$ // FileEditorMapping maps[] = typeEditorMappings.userMappings(); // for (int mapsIndex = 0; mapsIndex < maps.length; mapsIndex++) // { // FileEditorMapping type = maps[mapsIndex]; // IMemento editorMemento = memento // .createChild(IWorkbenchConstants.TAG_INFO); // editorMemento.putString(IWorkbenchConstants.TAG_NAME, type // .getName()); // editorMemento.putString(IWorkbenchConstants.TAG_EXTENSION, type // .getExtension()); // IEditorDescriptor[] editorArray = type.getEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // editorArray = type.getDeletedEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_DELETED_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // editorArray = type.getDeclaredDefaultEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_DEFAULT_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // } // Writer writer = null; // try // { // writer = new StringWriter(); // memento.save(writer); // writer.close(); // store.setValue(IPreferenceConstants.RESOURCES, writer.toString()); // } // catch (IOException e) // { // try // { // if (writer != null) // { // writer.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, "Saving Problems", //$NON-NLS-1$ // "Unable to save resource associations."); //$NON-NLS-1$ // return; // } // // memento = XMLMemento.createWriteRoot(IWorkbenchConstants.TAG_EDITORS); // Iterator itr = editors.iterator(); // while (itr.hasNext()) // { // EditorDescriptor editor = (EditorDescriptor) itr.next(); // IMemento editorMemento = memento // .createChild(IWorkbenchConstants.TAG_DESCRIPTOR); // editor.saveValues(editorMemento); // } // writer = null; // try // { // writer = new StringWriter(); // memento.save(writer); // writer.close(); // store.setValue(IPreferenceConstants.EDITORS, writer.toString()); // } // catch (IOException e) // { // try // { // if (writer != null) // { // writer.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, // "Error", "Unable to save resource associations."); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } } void EditorRegistry::SetFileEditorMappings( const QList& newResourceTypes) { typeEditorMappings.Clear(); for (int i = 0; i < newResourceTypes.size(); i++) { FileEditorMapping::Pointer mapping = newResourceTypes[i]; typeEditorMappings.Put(this->MappingKeyFor(mapping), mapping); } //extensionImages = new HashMap(); this->RebuildEditorMap(); //firePropertyChange(PROP_CONTENTS); } void EditorRegistry::SetDefaultEditor(const QString& fileName, const QString& editorId) { EditorDescriptor::Pointer desc = this->FindEditor(editorId).Cast< EditorDescriptor> (); QList mapping = this->GetMappingForFilename( fileName); if (!mapping[0].IsNull()) { mapping[0]->SetDefaultEditor(desc); } if (!mapping[1].IsNull()) { mapping[1]->SetDefaultEditor(desc); } } QList EditorRegistry::SortEditors( const QList& unsortedList) { QList result(unsortedList); std::sort(result.begin(), result.end(), CmpIEditorDescriptor()); return result; } void EditorRegistry::SortInternalEditors() { qSort(sortedEditorsFromPlugins.begin(), sortedEditorsFromPlugins.end(), CmpEditorDescriptor()); } void EditorRegistry::EditorMap::PutDefault(const QString& key, FileEditorMapping::Pointer value) { defaultMap[key] = value; } void EditorRegistry::EditorMap::Put(const QString& key, FileEditorMapping::Pointer value) { QHash::iterator result = defaultMap.find(key); if (result != defaultMap.end()) { map[key] = value; } } FileEditorMapping::Pointer EditorRegistry::EditorMap::Get( const QString& key) { QHash::const_iterator result = map.find(key); if (result == map.end()) { return defaultMap[key]; } return result.value(); } void EditorRegistry::EditorMap::Clear() { defaultMap.clear(); map.clear(); } QList EditorRegistry::EditorMap::AllMappings() { QSet resultSet; QHash::const_iterator iter; for (iter = defaultMap.begin(); iter != defaultMap.end(); ++iter) { resultSet.insert(iter.value()); } for (iter = map.begin(); iter != map.end(); ++iter) { resultSet.insert(iter.value()); } - return resultSet.toList(); + return resultSet.values(); } QList EditorRegistry::EditorMap::UserMappings() { return map.values(); } bool EditorRegistry::IsSystemInPlaceEditorAvailable(const QString& /*filename*/) { //return ComponentSupport.inPlaceEditorAvailable(filename); return false; } bool EditorRegistry::IsSystemExternalEditorAvailable( const QString& /*filename*/) { // QString::size_type nDot = filename.find_last_of('.'); // if (nDot != QString::npos) // { // QString strName = filename.substr(nDot); // return Program.findProgram(strName) != null; // } return false; } void EditorRegistry::RemoveEditorFromMapping( QHash& map, IEditorDescriptor::Pointer desc) { FileEditorMapping::Pointer mapping; for (QHash::iterator iter = map.begin(); iter != map.end(); ++iter) { mapping = iter.value(); QList editors(mapping->GetEditors()); QList::iterator result = std::find( editors.begin(), editors.end(), desc); if (result != editors.end()) { mapping->RemoveEditor(result->Cast ()); editors.erase(result); } if (editors.empty()) { map.erase(iter); break; } } } IExtensionPoint::Pointer EditorRegistry::GetExtensionPointFilter() { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_EDITOR); } QList EditorRegistry::GetUnifiedMappings() { QList standardMappings( dynamic_cast (PlatformUI::GetWorkbench() ->GetEditorRegistry())->GetFileEditorMappings()); QList allMappings(standardMappings); // mock-up content type extensions into IFileEditorMappings // IContentType [] contentTypes = Platform.getContentTypeManager().getAllContentTypes(); // for (int i = 0; i < contentTypes.length; i++) // { // IContentType type = contentTypes[i]; // String [] extensions = type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC); // for (int j = 0; j < extensions.length; j++) // { // String extension = extensions[j]; // boolean found = false; // for (Iterator k = allMappings.iterator(); k.hasNext();) // { // IFileEditorMapping mapping = (IFileEditorMapping) k.next(); // if ("*".equals(mapping.getName()) // && extension.equals(mapping.getExtension())) // { //$NON-NLS-1$ // found = true; // break; // } // } // if (!found) // { // MockMapping mockMapping = new MockMapping(type, "*", extension); //$NON-NLS-1$ // allMappings.add(mockMapping); // } // } // // String [] filenames = type.getFileSpecs(IContentType.FILE_NAME_SPEC); // for (int j = 0; j < filenames.length; j++) // { // String wholename = filenames[j]; // int idx = wholename.indexOf('.'); // String name = idx == -1 ? wholename : wholename.substring(0, idx); // String extension = idx == -1 ? "" : wholename.substring(idx + 1); //$NON-NLS-1$ // // boolean found = false; // for (Iterator k = allMappings.iterator(); k.hasNext();) // { // IFileEditorMapping mapping = (IFileEditorMapping) k.next(); // if (name.equals(mapping.getName()) // && extension.equals(mapping.getExtension())) // { // found = true; // break; // } // } // if (!found) // { // MockMapping mockMapping = new MockMapping(type, name, extension); // allMappings.add(mockMapping); // } // } // } return allMappings; } MockMapping::MockMapping(/*IContentType type,*/const QString& name, const QString& ext) : extension(ext), filename(name) { //this.contentType = type; } IEditorDescriptor::Pointer MockMapping::GetDefaultEditor() { // QList candidates = PlatformUI::GetWorkbench()->GetEditorRegistry() // ->GetEditorsForContentType(contentType); // if (candidates.empty()) // { // return IEditorDescriptor::Pointer(); // } // return candidates[0]; return IEditorDescriptor::Pointer(); } QList MockMapping::GetEditors() const { // QList editorsForContentType = (dynamic_cast(PlatformUI // ::GetWorkbench()->GetEditorRegistry()) // ->GetEditorsForContentType(contentType); // return editorsForContentType; return QList(); } QList MockMapping::GetDeletedEditors() const { return QList(); } QString MockMapping::GetExtension() const { return extension; } QString MockMapping::GetLabel() const { return filename + '.' + extension; } QString MockMapping::GetName() const { return filename; } bool MockMapping::operator==(const Object* obj) const { if (const MockMapping* other = dynamic_cast(obj)) { if (this == other) { return true; } //MockMapping mapping = (MockMapping) obj; if (!(this->filename == other->filename)) { return false; } if (!(this->extension == other->extension)) { return false; } if (!(this->GetEditors() == other->GetEditors())) { return false; } return this->GetDeletedEditors() == other->GetDeletedEditors(); } return false; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp index ee9098c4cd..5a700c2801 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp @@ -1,244 +1,244 @@ /*============================================================================ 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 "berryEvaluationAuthority.h" #include "berryCommandTracing.h" #include "berryExpressionInfo.h" #include "berryExpression.h" #include "berryEvaluationReference.h" #include "berryPolicy.h" #include "berryWorkbenchPlugin.h" #include #include #include #include #include namespace berry { const QString EvaluationAuthority::COMPONENT = "EVALUATION"; QStringList EvaluationAuthority::GetNames(const SmartPointer& ref) const { ExpressionInfo info; ref->GetExpression()->CollectExpressionInfo(&info); QSet allNames = info.GetAccessedVariableNames(); if (info.HasDefaultVariableAccess()) { allNames << ISources::ACTIVE_CURRENT_SELECTION_NAME(); } allNames.unite(info.GetAccessedPropertyNames()); - return allNames.toList(); + return allNames.values(); } void EvaluationAuthority::RefsWithSameExpression(const QList >& refs) { int k = 0; while (k < refs.size() && !refs[k]->IsPostingChanges()) { k++; } if (k >= refs.size()) { return; } EvaluationReference::Pointer ref = refs[k]; bool oldValue = Evaluate(ref); ref->ClearResult(); const bool newValue = Evaluate(ref); if (oldValue != newValue) { FirePropertyChange(ref, ValueOf(oldValue), ValueOf(newValue)); } for (k++; k < refs.size(); k++) { ref = refs[k]; // this is not as expensive as it looks if (ref->IsPostingChanges()) { oldValue = Evaluate(ref); if (oldValue != newValue) { ref->SetResult(newValue); FirePropertyChange(ref, ValueOf(oldValue), ValueOf(newValue)); } } } } void EvaluationAuthority::StartSourceChange(const QStringList& sourceNames) { if (Policy::DEBUG_SOURCES()) { CommandTracing::PrintTrace(COMPONENT, "start source changed: " + sourceNames.join(", ")); } notifying++; if (notifying == 1) { FireServiceChange(IEvaluationService::PROP_NOTIFYING, ValueOf(false), ValueOf(true)); } } void EvaluationAuthority::EndSourceChange(const QStringList& sourceNames) { if (Policy::DEBUG_SOURCES()) { CommandTracing::PrintTrace(COMPONENT, "end source changed: " + sourceNames.join(", ")); } if (notifying == 1) { FireServiceChange(IEvaluationService::PROP_NOTIFYING, ValueOf(true), ValueOf(false)); } notifying--; } void EvaluationAuthority::FirePropertyChange(const SmartPointer& ref, Object::Pointer oldValue, Object::Pointer newValue) { PropertyChangeEvent::Pointer event(new PropertyChangeEvent(ref, ref->GetProperty(), oldValue, newValue)); ref->GetListener()->PropertyChange(event); } void EvaluationAuthority::FireServiceChange(const QString& property, Object::Pointer oldValue, Object::Pointer newValue) { PropertyChangeEvent::Pointer event( new PropertyChangeEvent(Object::Pointer(this), property, oldValue, newValue)); serviceListeners.propertyChange(event); } void EvaluationAuthority::ServiceChangeException(const std::exception &exc) { WorkbenchPlugin::Log(exc.what()); } Object::Pointer EvaluationAuthority::ValueOf(bool result) { return ObjectBool::Pointer(new ObjectBool(result)); } void EvaluationAuthority::SourceChanged(int /*sourcePriority*/) { // no-op, we want the other one } void EvaluationAuthority::SourceChanged(const QStringList& sourceNames) { struct SourceChangeScope { EvaluationAuthority* const ea; const QStringList& sourceNames; SourceChangeScope(EvaluationAuthority* ea, const QStringList& sourceNames) : ea(ea), sourceNames(sourceNames) { ea->StartSourceChange(sourceNames); } ~SourceChangeScope() { ea->EndSourceChange(sourceNames); } }; SourceChangeScope(this, sourceNames); // evaluations to recompute for (int i = 0; i < sourceNames.size(); i++) { if (cachesBySourceName.contains(sourceNames[i])) { const ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]]; QList > expressionCaches = cachesByExpression.values(); for (int j = 0; j < expressionCaches.size(); j++) { if (!(expressionCaches[j].isEmpty())) { - QList refs = expressionCaches[j].toList(); + QList refs = expressionCaches[j].values(); RefsWithSameExpression(refs); } } } } } EvaluationAuthority::EvaluationAuthority() : serviceExceptionHandler(this, &EvaluationAuthority::ServiceChangeException), notifying(0) { serviceListeners.propertyChange.SetExceptionHandler(serviceExceptionHandler); } SmartPointer EvaluationAuthority::GetActiveShell() const { return GetVariable(ISources::ACTIVE_SHELL_NAME()).Cast(); } void EvaluationAuthority::AddEvaluationListener(const SmartPointer& ref) { // we update the source priority bucket sort of activations. QStringList sourceNames = GetNames(ref); for (int i = 0; i < sourceNames.size(); i++) { ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]]; const Expression::Pointer expression = ref->GetExpression(); cachesByExpression[expression].insert(ref.Cast()); } bool result = Evaluate(ref); FirePropertyChange(ref, Object::Pointer(nullptr), ValueOf(result)); } void EvaluationAuthority::RemoveEvaluationListener(const SmartPointer& ref) { // Next we update the source priority bucket sort of activations. QStringList sourceNames = GetNames(ref); for (int i = 0; i < sourceNames.size(); i++) { if (cachesBySourceName.contains(sourceNames[i])) { ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]]; if (cachesByExpression.contains(ref->GetExpression())) { QSet& caches = cachesByExpression[ref->GetExpression()]; caches.remove(ref.Cast()); if (caches.isEmpty()) { cachesByExpression.remove(ref->GetExpression()); } } if (cachesByExpression.isEmpty()) { cachesBySourceName.remove(sourceNames[i]); } } } bool result = Evaluate(ref); FirePropertyChange(ref, ValueOf(result), Object::Pointer(nullptr)); } void EvaluationAuthority::AddServiceListener(IPropertyChangeListener* listener) { serviceListeners.AddListener(listener); } void EvaluationAuthority::RemoveServiceListener(IPropertyChangeListener* listener) { serviceListeners.RemoveListener(listener); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp index 00d07f3fc2..fcfad52895 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp @@ -1,81 +1,81 @@ /*============================================================================ 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 "berryNestableHandlerService.h" #include "berryExpression.h" #include "berryIHandlerActivation.h" #include "berryISourceProvider.h" namespace berry { NestableHandlerService::NestableHandlerService(IHandlerService* parentHandlerService, const SmartPointer& defaultExpression) : SlaveHandlerService(parentHandlerService, defaultExpression) , active(false) { } void NestableHandlerService::Activate() { if (active) { return; } QList localActivations = localActivationsToParentActivations.keys(); for (int i = 0; i < localActivations.size(); i++) { // Ignore activations that have been cleared since the copy // was made. if (localActivationsToParentActivations.contains(localActivations[i])) { SlaveHandlerService::DoActivation(localActivations[i]); } } active = true; } void NestableHandlerService::Deactivate() { if (!active) { return; } - DeactivateHandlers(parentActivations.toList()); + DeactivateHandlers(parentActivations.values()); parentActivations.clear(); QList localActivations = localActivationsToParentActivations.keys(); for (int i = 0; i < localActivations.size(); i++) { if (localActivationsToParentActivations.contains(localActivations[i])) { localActivationsToParentActivations.insert(localActivations[i], nullptr); } } active = false; } SmartPointer NestableHandlerService::DoActivation( const SmartPointer& localActivation) { if (active) { return SlaveHandlerService::DoActivation(localActivation); } localActivationsToParentActivations.insert(localActivation, nullptr); return localActivation; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp index 9a7fda5765..9c5b90e430 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp @@ -1,628 +1,628 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berrySaveablesList.h" #include "berryWorkbenchPlugin.h" #include "berryDefaultSaveable.h" #include "berryWorkbenchPart.h" namespace berry { bool SaveablesList::AddModel(Object::Pointer source, Saveable::Pointer model) { if (model == 0) { this->LogWarning("Ignored attempt to add invalid saveable", source, model); //$NON-NLS-1$ return false; } bool result = false; Saveable::Set& modelsForSource = modelMap[source.GetPointer()]; if (modelsForSource.find(model) == modelsForSource.end()) { modelsForSource.insert(model); result = this->IncrementRefCount(modelRefCounts, model); } else { this->LogWarning("Ignored attempt to add saveable that was already registered", source, model); //$NON-NLS-1$ } return result; } bool SaveablesList::IncrementRefCount( QHash& referenceMap, Saveable::Pointer key) { bool result = false; int& refCount = referenceMap[key]; if (refCount == 0) { result = true; } refCount++; return result; } bool SaveablesList::DecrementRefCount( QHash& referenceMap, Saveable::Pointer key) { bool result = false; int& refCount = referenceMap[key]; poco_assert(refCount != 0); if (refCount == 1) { referenceMap.remove(key); result = true; } else { --refCount; } return result; } bool SaveablesList::RemoveModel(Object::Pointer source, Saveable::Pointer model) { bool result = false; QHash::iterator it = modelMap.find(source.GetPointer()); if (it == modelMap.end()) { this->LogWarning( "Ignored attempt to remove a saveable when no saveables were known", source, model); //$NON-NLS-1$ } else { Saveable::Set& modelsForSource = it.value(); if (modelsForSource.remove(model)) { result = this->DecrementRefCount(modelRefCounts, model); if (modelsForSource.empty()) { modelMap.remove(source.GetPointer()); } } else { this->LogWarning( "Ignored attempt to remove a saveable that was not registered", source, model); //$NON-NLS-1$ } } return result; } void SaveablesList::LogWarning(const QString& message, Object::Pointer source, Saveable::Pointer model) { // create a new exception QString text = message + "; " + "unknown saveable: " + model->GetName() + " from part: " + source->GetClassName(); // record the current stack trace to help with debugging //assertionFailedException.fillInStackTrace(); WorkbenchPlugin::Log(text); } void SaveablesList::UpdateNonPartSource(ISaveablesSource::Pointer source) { QList saveables = source->GetSaveables(); if (saveables.empty()) { nonPartSources.remove(source); } else { nonPartSources.insert(source); } } void SaveablesList::RemoveModels(Object::Pointer source, const QList& modelArray) { QList removed; for (int i = 0; i < modelArray.size(); i++) { Saveable::Pointer model = modelArray[i]; if (this->RemoveModel(source, model)) { removed.push_back(model); } } if (removed.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_OPEN, removed, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::AddModels(Object::Pointer source, const QList& modelArray) { QList added; for (int i = 0; i < modelArray.size(); i++) { Saveable::Pointer model = modelArray[i]; if (this->AddModel(source, model)) { added.push_back(model); } } if (added.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_OPEN, added, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::FireModelLifecycleEvent( SaveablesLifecycleEvent::Pointer event) { events.lifecycleChange(event); } bool SaveablesList::PromptForSavingIfNecessary( IWorkbenchWindow::Pointer /*window*/, const Saveable::Set& /*modelsClosing*/, const QHash& /*modelsDecrementing*/, bool /*canCancel*/) { // List modelsToOptionallySave = new ArrayList(); // for (Iterator it = modelsDecrementing.keySet().iterator(); it.hasNext();) // { // Saveable modelDecrementing = (Saveable) it.next(); // if (modelDecrementing.isDirty() && !modelsClosing.contains( // modelDecrementing)) // { // modelsToOptionallySave.add(modelDecrementing); // } // } // // boolean shouldCancel = // modelsToOptionallySave.isEmpty() ? false : promptForSaving( // modelsToOptionallySave, window, window, canCancel, true); // // if (shouldCancel) // { // return true; // } // // List modelsToSave = new ArrayList(); // for (Iterator it = modelsClosing.iterator(); it.hasNext();) // { // Saveable modelClosing = (Saveable) it.next(); // if (modelClosing.isDirty()) // { // modelsToSave.add(modelClosing); // } // } // return modelsToSave.isEmpty() ? false : promptForSaving(modelsToSave, window, // window, canCancel, false); return false; } void SaveablesList::FillModelsClosing(Saveable::Set& modelsClosing, const QHash& modelsDecrementing) { for (QHash::const_iterator it = modelsDecrementing.begin(); it != modelsDecrementing.end(); ++it) { Saveable::Pointer model = it.key(); if (it.value() == modelRefCounts[model]) { modelsClosing.insert(model); } } } QList SaveablesList::GetSaveables( IWorkbenchPart::Pointer part) { if (part.Cast () != 0) { ISaveablesSource::Pointer source = part.Cast(); return source->GetSaveables(); } else if (part.Cast () != 0) { QList result; Saveable::Pointer defaultSaveable(new DefaultSaveable(part)); result.push_back(defaultSaveable); return result; } else { return QList(); } } Saveable::Set SaveablesList::GetOpenModels() { Saveable::Set allDistinctModels; for (QHash::iterator it = modelMap.begin(); it != modelMap.end(); ++it) allDistinctModels.unite(it.value()); return allDistinctModels; } void SaveablesList::HandleLifecycleEvent(const SaveablesLifecycleEvent::Pointer& event) { if (event->GetSource().Cast () == 0) { // just update the set of non-part sources. No prompting necessary. // See bug 139004. this->UpdateNonPartSource(event->GetSource().Cast()); return; } QList modelArray = event->GetSaveables(); int eventType = event->GetEventType(); if (eventType == SaveablesLifecycleEvent::POST_OPEN) { this->AddModels(event->GetSource(), modelArray); } else if (eventType == SaveablesLifecycleEvent::PRE_CLOSE) { QList models = event->GetSaveables(); QHash modelsDecrementing; Saveable::Set modelsClosing; for (int i = 0; i < models.size(); i++) { this->IncrementRefCount(modelsDecrementing, models[i]); } this->FillModelsClosing(modelsClosing, modelsDecrementing); bool canceled = this->PromptForSavingIfNecessary( PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), modelsClosing, modelsDecrementing, !event->IsForce()); if (canceled) { event->SetVeto(true); } } else if (eventType == SaveablesLifecycleEvent::POST_CLOSE) { this->RemoveModels(event->GetSource(), modelArray); } else if (eventType == SaveablesLifecycleEvent::DIRTY_CHANGED) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer lifeCycleEvent( new SaveablesLifecycleEvent(source, event->GetEventType(), event->GetSaveables(), false)); this->FireModelLifecycleEvent(lifeCycleEvent); } } void SaveablesList::AddModelLifecycleListener(ISaveablesLifecycleListener* listener) { events.AddListener(listener); } void SaveablesList::RemoveModelLifecycleListener(ISaveablesLifecycleListener* listener) { events.RemoveListener(listener); } SaveablesList::PostCloseInfo::Pointer SaveablesList::PreCloseParts( const QList& partsToClose, bool save, IWorkbenchWindow::Pointer window) { // reference count (how many occurrences of a model will go away?) PostCloseInfo::Pointer postCloseInfo(new PostCloseInfo()); for (QList::const_iterator it = partsToClose.begin(); it != partsToClose.end(); ++it) { WorkbenchPart::Pointer part = it->Cast(); postCloseInfo->partsClosing.push_back(part); if (part.Cast () != 0) { ISaveablePart::Pointer saveablePart = part.Cast(); if (save && !saveablePart->IsSaveOnCloseNeeded()) { // pretend for now that this part is not closing continue; } } // if (save && part.Cast () != 0) // { // ISaveablePart2 saveablePart2 = (ISaveablePart2) part; // // TODO show saveablePart2 before prompting, see // // EditorManager.saveAll // int response = SaveableHelper.savePart(saveablePart2, window, true); // if (response == ISaveablePart2.CANCEL) // { // // user canceled // return 0; // } // else if (response != ISaveablePart2.DEFAULT) // { // // only include this part in the following logic if it returned // // DEFAULT // continue; // } // } QList modelsFromSource = this->GetSaveables(part); for (int i = 0; i < modelsFromSource.size(); i++) { this->IncrementRefCount(postCloseInfo->modelsDecrementing, modelsFromSource[i]); } } this->FillModelsClosing(postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing); if (save) { bool canceled = this->PromptForSavingIfNecessary(window, postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing, true); if (canceled) { return PostCloseInfo::Pointer(nullptr); } } return postCloseInfo; } bool SaveablesList::PromptForSaving( const QList& /*modelsToSave*/, /*final IShellProvider shellProvider, IRunnableContext runnableContext,*/ bool /*canCancel*/, bool /*stillOpenElsewhere*/) { // // Save parts, exit the method if cancel is pressed. // if (modelsToSave.size() > 0) { // boolean canceled = SaveableHelper.waitForBackgroundSaveJobs(modelsToSave); // if (canceled) { // return true; // } // // IPreferenceStore apiPreferenceStore = PrefUtil.getAPIPreferenceStore(); // boolean dontPrompt = stillOpenElsewhere && !apiPreferenceStore.getBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN); // // if (dontPrompt) { // modelsToSave.clear(); // return false; // } else if (modelsToSave.size() == 1) { // Saveable model = (Saveable) modelsToSave.get(0); // // Show a dialog. // QList buttons; // if(canCancel) { // buttons.push_back(IDialogConstants.YES_LABEL); // buttons.push_back(IDialogConstants.NO_LABEL); // buttons.push_back(IDialogConstants.CANCEL_LABEL); // } else { // buttons.push_back(IDialogConstants.YES_LABEL); // buttons.push_back(IDialogConstants.NO_LABEL); // } // // // don't save if we don't prompt // int choice = ISaveablePart2.NO; // // MessageDialog dialog; // if (stillOpenElsewhere) { // String message = NLS // .bind( // WorkbenchMessages.EditorManager_saveChangesOptionallyQuestion, // model.getName()); // MessageDialogWithToggle dialogWithToggle = new MessageDialogWithToggle(shellProvider.getShell(), // WorkbenchMessages.Save_Resource, 0, message, // MessageDialog.QUESTION, buttons, 0, WorkbenchMessages.EditorManager_closeWithoutPromptingOption, false) { // protected int getShellStyle() { // return (canCancel ? SWT.CLOSE : SWT.NONE) // | SWT.TITLE | SWT.BORDER // | SWT.APPLICATION_MODAL // | getDefaultOrientation(); // } // }; // dialog = dialogWithToggle; // } else { // String message = NLS // .bind( // WorkbenchMessages.EditorManager_saveChangesQuestion, // model.getName()); // dialog = new MessageDialog(shellProvider.getShell(), // WorkbenchMessages.Save_Resource, 0, message, // MessageDialog.QUESTION, buttons, 0) { // protected int getShellStyle() { // return (canCancel ? SWT.CLOSE : SWT.NONE) // | SWT.TITLE | SWT.BORDER // | SWT.APPLICATION_MODAL // | getDefaultOrientation(); // } // }; // } // // choice = SaveableHelper.testGetAutomatedResponse(); // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // choice = dialog.open(); // // if(stillOpenElsewhere) { // // map value of choice back to ISaveablePart2 values // switch (choice) { // case IDialogConstants.YES_ID: // choice = ISaveablePart2.YES; // break; // case IDialogConstants.NO_ID: // choice = ISaveablePart2.NO; // break; // case IDialogConstants.CANCEL_ID: // choice = ISaveablePart2.CANCEL; // break; // default: // break; // } // MessageDialogWithToggle dialogWithToggle = (MessageDialogWithToggle) dialog; // if (choice != ISaveablePart2.CANCEL && dialogWithToggle.getToggleState()) { // apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false); // } // } // } // // // Branch on the user choice. // // The choice id is based on the order of button labels // // above. // switch (choice) { // case ISaveablePart2.YES: // yes // break; // case ISaveablePart2.NO: // no // modelsToSave.clear(); // break; // default: // case ISaveablePart2.CANCEL: // cancel // return true; // } // } else { // MyListSelectionDialog dlg = new MyListSelectionDialog( // shellProvider.getShell(), // modelsToSave, // new ArrayContentProvider(), // new WorkbenchPartLabelProvider(), // stillOpenElsewhere ? WorkbenchMessages.EditorManager_saveResourcesOptionallyMessage // : WorkbenchMessages.EditorManager_saveResourcesMessage, // canCancel, stillOpenElsewhere); // dlg.setInitialSelections(modelsToSave.toArray()); // dlg.setTitle(EditorManager.SAVE_RESOURCES_TITLE); // // // this "if" statement aids in testing. // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // int result = dlg.open(); // // Just return 0 to prevent the operation continuing // if (result == IDialogConstants.CANCEL_ID) // return true; // // if (dlg.getDontPromptSelection()) { // apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false); // } // // modelsToSave = Arrays.asList(dlg.getResult()); // } // } // } // // Create save block. // return saveModels(modelsToSave, shellProvider, runnableContext); return true; } bool SaveablesList::SaveModels(const QList& /*finalModels*/ /*final IShellProvider shellProvider, IRunnableContext runnableContext*/) { // IRunnableWithProgress progressOp = new IRunnableWithProgress() { // public void run(IProgressMonitor monitor) { // IProgressMonitor monitorWrap = new EventLoopProgressMonitor( // monitor); // monitorWrap.beginTask("", finalModels.size()); //$NON-NLS-1$ // for (Iterator i = finalModels.iterator(); i.hasNext();) { // Saveable model = (Saveable) i.next(); // // handle case where this model got saved as a result of // // saving another // if (!model.isDirty()) { // monitor.worked(1); // continue; // } // SaveableHelper.doSaveModel(model, new SubProgressMonitor(monitorWrap, 1), shellProvider, true); // if (monitorWrap.isCanceled()) // break; // } // monitorWrap.done(); // } // }; // // // Do the save. // return !SaveableHelper.runProgressMonitorOperation( // WorkbenchMessages.Save_All, progressOp, runnableContext, // shellProvider); return true; } void SaveablesList::PostClose(PostCloseInfo::Pointer postCloseInfo) { QList removed; for (QList::const_iterator it = postCloseInfo->partsClosing.begin(); it != postCloseInfo->partsClosing.end(); ++it) { IWorkbenchPart::Pointer part = *it; QHash::iterator it2 = modelMap.find(part.GetPointer()); if (it2 != modelMap.end()) { // make a copy to avoid a ConcurrentModificationException - we // will remove from the original set as we iterate Saveable::Set saveables(it2.value()); for (Saveable::Set::const_iterator it3 = saveables.begin(); it3 != saveables.end(); ++it3) { if (RemoveModel(part, *it3)) { removed.push_back(*it3); } } } } if (!removed.empty()) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_CLOSE, removed, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::PostOpen(IWorkbenchPart::Pointer part) { this->AddModels(part, this->GetSaveables(part)); } void SaveablesList::DirtyChanged(IWorkbenchPart::Pointer part) { QList saveables = this->GetSaveables(part); if (saveables.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::DIRTY_CHANGED, saveables, false)); this->FireModelLifecycleEvent(event); } } QList SaveablesList::TestGetSourcesForModel( Saveable::Pointer /*model*/) { QList result; // for (Iterator it = modelMap.entrySet().iterator(); it.hasNext();) { // Map.Entry entry = (Map.Entry) it.next(); // Set values = (Set) entry.getValue(); // if (values.contains(model)) { // result.add(entry.getKey()); // } // } return result; } QList SaveablesList::GetNonPartSources() { - return nonPartSources.toList(); + return nonPartSources.values(); } QList SaveablesList::GetPartsForSaveable( Saveable::Pointer model) { QList result; for (QHash::iterator it = modelMap.begin(); it != modelMap.end(); ++it) { Saveable::Set& values = it.value(); IWorkbenchPart::Pointer part(dynamic_cast(it.key())); if (values.find(model) != values.end() && part) { result.push_back(part); } } return result; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp index 20177c4688..315bc51943 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp @@ -1,232 +1,232 @@ /*============================================================================ 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 "berrySlaveHandlerService.h" #include "berryIHandler.h" #include "berryIHandlerActivation.h" #include "berryISourceProvider.h" #include "berryAndExpression.h" #include "berryHandlerActivation.h" #include "berryExecutionEvent.h" namespace berry { SlaveHandlerService::SlaveHandlerService(IHandlerService* parentHandlerService, const SmartPointer& defaultExpression) : defaultExpression(defaultExpression) , parent(parentHandlerService) { if (parentHandlerService == nullptr) { throw ctkInvalidArgumentException("The parent handler service cannot be null"); } } SmartPointer SlaveHandlerService::ActivateHandler(const SmartPointer& childActivation) { const QString commandId = childActivation->GetCommandId(); const IHandler::Pointer handler = childActivation->GetHandler(); const Expression::Pointer childExpression = childActivation->GetExpression(); Expression::Pointer expression = defaultExpression; if (childExpression.IsNotNull() && defaultExpression.IsNotNull()) { const AndExpression::Pointer andExpression(new AndExpression()); andExpression->Add(childExpression); andExpression->Add(defaultExpression); expression = andExpression; } else if (childExpression.IsNotNull()) { expression = childExpression; } const int depth = childActivation->GetDepth() + 1; const IHandlerActivation::Pointer localActivation( new HandlerActivation(commandId, handler, expression, depth, this)); return DoActivation(localActivation); } SmartPointer SlaveHandlerService::ActivateHandler(const QString& commandId, const SmartPointer& handler) { const IHandlerActivation::Pointer localActivation( new HandlerActivation(commandId, handler, defaultExpression, IHandlerActivation::ROOT_DEPTH, this)); return DoActivation(localActivation); } SmartPointer SlaveHandlerService::ActivateHandler(const QString& commandId, const SmartPointer& handler, const SmartPointer& expression) { return ActivateHandler(commandId, handler, expression, false); } SmartPointer SlaveHandlerService::ActivateHandler(const QString& commandId, const SmartPointer& handler, const SmartPointer& expression, bool global) { if (global) { const IHandlerActivation::Pointer activation = parent->ActivateHandler( commandId, handler, expression, global); parentActivations.insert(activation); return activation; } Expression::Pointer aExpression = defaultExpression; if (expression.IsNotNull() && defaultExpression.IsNotNull()) { const AndExpression::Pointer andExpression(new AndExpression()); andExpression->Add(expression); andExpression->Add(defaultExpression); aExpression = andExpression; } else if (expression.IsNotNull()) { aExpression = expression; } const IHandlerActivation::Pointer localActivation( new HandlerActivation(commandId, handler, aExpression, IHandlerActivation::ROOT_DEPTH, this)); return DoActivation(localActivation); } void SlaveHandlerService::AddSourceProvider(const SmartPointer& provider) { if (!fSourceProviders.contains(provider)) { fSourceProviders.push_back(provider); } parent->AddSourceProvider(provider); } SmartPointer SlaveHandlerService::CreateExecutionEvent(const SmartPointer& command, const SmartPointer& event) { return parent->CreateExecutionEvent(command, event); } SmartPointer SlaveHandlerService::CreateExecutionEvent( const SmartPointer& command, const SmartPointer& event) { return parent->CreateExecutionEvent(command, event); } void SlaveHandlerService::DeactivateHandler(const SmartPointer& activation) { IHandlerActivation::Pointer parentActivation; if (localActivationsToParentActivations.contains(activation)) { parentActivation = localActivationsToParentActivations.take(activation); } else { parentActivation = activation; } if (parentActivation.IsNotNull()) { parent->DeactivateHandler(parentActivation); parentActivations.remove(parentActivation); } } void SlaveHandlerService::DeactivateHandlers(const QList >& activations) { for (int i = 0; i < activations.size(); i++) { DeactivateHandler(activations[i]); } } void SlaveHandlerService::Dispose() { - parent->DeactivateHandlers(parentActivations.toList()); + parent->DeactivateHandlers(parentActivations.values()); parentActivations.clear(); localActivationsToParentActivations.clear(); // Remove any "resource", like listeners, that were associated // with this service. if (!fSourceProviders.isEmpty()) { for (int i = 0; i < fSourceProviders.size(); i++) { RemoveSourceProvider(fSourceProviders[i]); } fSourceProviders.clear(); } } Object::Pointer SlaveHandlerService::ExecuteCommand(const SmartPointer& command, const SmartPointer& event) { return parent->ExecuteCommand(command, event); } Object::Pointer SlaveHandlerService::ExecuteCommand(const QString& commandId, const SmartPointer& event) { return parent->ExecuteCommand(commandId, event); } SmartPointer SlaveHandlerService::GetCurrentState() const { return parent->GetCurrentState(); } void SlaveHandlerService::ReadRegistry() { parent->ReadRegistry(); } void SlaveHandlerService::RemoveSourceProvider(const SmartPointer& provider) { fSourceProviders.removeAll(provider); parent->RemoveSourceProvider(provider); } void SlaveHandlerService::SetHelpContextId(const SmartPointer& handler, const QString& helpContextId) { parent->SetHelpContextId(handler, helpContextId); } SmartPointer SlaveHandlerService::GetDefaultExpression() const { return defaultExpression; } SmartPointer SlaveHandlerService::CreateContextSnapshot(bool includeSelection) { return parent->CreateContextSnapshot(includeSelection); } Object::Pointer SlaveHandlerService::ExecuteCommandInContext(const SmartPointer& command, const SmartPointer& event, const SmartPointer& context) { return parent->ExecuteCommandInContext(command, event, context); } SmartPointer SlaveHandlerService::DoActivation( const SmartPointer& localActivation) { const IHandlerActivation::Pointer parentActivation = parent->ActivateHandler(localActivation); parentActivations.insert(parentActivation); localActivationsToParentActivations.insert(localActivation, parentActivation.GetPointer()); return localActivation; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp index f0ce866065..4a80d065c4 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp @@ -1,81 +1,81 @@ /*============================================================================ 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 "berrySourceProviderService.h" #include "berryAbstractSourceProvider.h" #include "berryWorkbenchServiceRegistry.h" namespace berry { SourceProviderService::SourceProviderService(IServiceLocator *locator) : locator(locator) { } void SourceProviderService::Dispose() { sourceProvidersByName.clear(); } SmartPointer SourceProviderService::GetSourceProvider(const QString& sourceName) const { return sourceProvidersByName.value(sourceName); } QList > SourceProviderService::GetSourceProviders() const { - return sourceProviders.toList(); + return sourceProviders.values(); } void SourceProviderService::RegisterProvider(const SmartPointer& sourceProvider) { if (sourceProvider.IsNull()) { throw ctkInvalidArgumentException("The source provider cannot be null"); } const QList sourceNames = sourceProvider->GetProvidedSourceNames(); for (int i = 0; i < sourceNames.size(); i++) { const QString sourceName = sourceNames[i]; sourceProvidersByName.insert(sourceName, sourceProvider); } sourceProviders.insert(sourceProvider); } void SourceProviderService::UnregisterProvider(const SmartPointer& sourceProvider) { if (sourceProvider.IsNull()) { throw ctkInvalidArgumentException("The source provider cannot be null"); } const QList sourceNames = sourceProvider->GetProvidedSourceNames(); for (int i = 0; i < sourceNames.size(); i++) { sourceProvidersByName.remove(sourceNames[i]); } sourceProviders.remove(sourceProvider); } void SourceProviderService::ReadRegistry() { QList sp = WorkbenchServiceRegistry::GetRegistry()->GetSourceProviders(); for (int i = 0; i < sp.size(); i++) { sp[i]->Initialize(locator); RegisterProvider(sp[i]); } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp index 1e0de9ace4..f51891885b 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp @@ -1,291 +1,291 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryEditorSashContainer.h" #include "berryWorkbenchPlugin.h" #include "berryMenuManager.h" #include "berryQtDnDControlWidget.h" namespace berry { WorkbenchWindowConfigurer::WindowActionBarConfigurer::WindowActionBarConfigurer(WorkbenchWindow::WeakPtr wnd) : window(wnd) { } void WorkbenchWindowConfigurer::WindowActionBarConfigurer::SetProxy(IActionBarConfigurer::Pointer proxy) { this->proxy = proxy; } IWorkbenchWindowConfigurer::Pointer WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetWindowConfigurer() { return WorkbenchWindow::Pointer(window)->GetWindowConfigurer(); } IMenuManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetMenuManager() { if (proxy.IsNotNull()) { return proxy->GetMenuManager(); } return window.Lock()->GetMenuManager(); } IToolBarManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetToolBarManager() { if (proxy.IsNotNull()) { return proxy->GetToolBarManager(); } //return window.Lock()->GetToolBarManager(); return nullptr; } WorkbenchWindowConfigurer::WorkbenchWindowConfigurer(const WorkbenchWindow::Pointer& window) : shellStyle(nullptr) , showPerspectiveBar(false) , showStatusLine(true) , showToolBar(true) , showMenuBar(true) , showProgressIndicator(false) , dropTargetListener(nullptr) , initialSize(1632, 918) // 85% of 1920 x 1080 (FullHD, 1080p) { if (window.IsNull()) { throw Poco::InvalidArgumentException(); } this->window = window; windowTitle = "BlueBerry Application"; } IWorkbenchWindow::Pointer WorkbenchWindowConfigurer::GetWindow() { return IWorkbenchWindow::Pointer(window); } IWorkbenchConfigurer::Pointer WorkbenchWindowConfigurer::GetWorkbenchConfigurer() { return dynamic_cast(PlatformUI::GetWorkbench())->GetWorkbenchConfigurer(); } QString WorkbenchWindowConfigurer::BasicGetTitle() { return windowTitle; } QString WorkbenchWindowConfigurer::GetTitle() { Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { // update the cached title windowTitle = shell->GetText(); } return windowTitle; } void WorkbenchWindowConfigurer::SetTitle(const QString &title) { windowTitle = title; Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { shell->SetText(title); } } bool WorkbenchWindowConfigurer::GetShowMenuBar() const { return showMenuBar; } void WorkbenchWindowConfigurer::SetShowMenuBar(bool show) { showMenuBar = show; // WorkbenchWindow win = (WorkbenchWindow) getWindow(); // Shell shell = win.getShell(); // if (shell != null) // { // boolean showing = shell.getMenuBar() != null; // if (show != showing) // { // if (show) // { // shell.setMenuBar(win.getMenuBarManager().getMenu()); // } // else // { // shell.setMenuBar(null); // } // } // } } bool WorkbenchWindowConfigurer::GetShowToolBar() const { return showToolBar; } void WorkbenchWindowConfigurer::SetShowToolBar(bool show) { showToolBar = show; //window.setCoolBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowPerspectiveBar() const { return showPerspectiveBar; } void WorkbenchWindowConfigurer::SetShowPerspectiveBar(bool show) { showPerspectiveBar = show; //window.setPerspectiveBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowStatusLine() const { return showStatusLine; } void WorkbenchWindowConfigurer::SetShowStatusLine(bool show) { showStatusLine = show; // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowProgressIndicator() const { return showProgressIndicator; } void WorkbenchWindowConfigurer::SetShowProgressIndicator(bool show) { showProgressIndicator = show; // @issue need to be able to reconfigure after window's controls created } void WorkbenchWindowConfigurer::AddEditorAreaTransfer(const QStringList& transfers) { if (transfers.isEmpty()) return; int oldSize = transferTypes.size(); transferTypes.unite(QSet::fromList(transfers)); if (transferTypes.size() == oldSize) return; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); - dropTarget->SetTransferTypes(transferTypes.toList()); + dropTarget->SetTransferTypes(transferTypes.values()); } } void WorkbenchWindowConfigurer::ConfigureEditorAreaDropListener(IDropTargetListener* listener) { if (listener == nullptr) return; dropTargetListener = listener; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->AddDropListener(listener); } } QStringList WorkbenchWindowConfigurer::GetTransfers() const { - return transferTypes.toList(); + return transferTypes.values(); } IDropTargetListener* WorkbenchWindowConfigurer::GetDropTargetListener() const { return dropTargetListener; } IActionBarConfigurer::Pointer WorkbenchWindowConfigurer::GetActionBarConfigurer() { if (actionBarConfigurer.IsNull()) { // lazily initialize actionBarConfigurer = new WindowActionBarConfigurer(window); } return actionBarConfigurer; } Qt::WindowFlags WorkbenchWindowConfigurer::GetWindowFlags() const { return shellStyle; } void WorkbenchWindowConfigurer::SetWindowFlags(Qt::WindowFlags shellStyle) { this->shellStyle = shellStyle; } QPoint WorkbenchWindowConfigurer::GetInitialSize() const { return initialSize; } void WorkbenchWindowConfigurer::SetInitialSize(QPoint size) { initialSize = size; } void WorkbenchWindowConfigurer::CreateDefaultContents(Shell::Pointer shell) { WorkbenchWindow::Pointer(window)->CreateDefaultContents(shell); } QMenuBar* WorkbenchWindowConfigurer::CreateMenuBar() { return window.Lock()->GetMenuManager()->CreateMenuBar(window.Lock()->GetShell()->GetControl()); } QWidget* WorkbenchWindowConfigurer::CreateToolBar(QWidget* /*parent*/) { // IToolBarManager* toolBarManager = window->GetToolBarManager(); // if (toolBarManager) // { // return toolBarManager->CreateControl(parent); // } return nullptr; } QWidget *WorkbenchWindowConfigurer::CreatePageComposite(QWidget *parent) { return WorkbenchWindow::Pointer(window)->CreatePageComposite(parent); } bool WorkbenchWindowConfigurer::SaveState(IMemento::Pointer memento) { return WorkbenchWindow::Pointer(window)->SaveState(memento); } } diff --git a/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp b/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp index c4d49feb81..8fe1f286e6 100644 --- a/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp +++ b/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp @@ -1,460 +1,460 @@ /*============================================================================ 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 "berryViewTreeModel.h" #include "berryIViewRegistry.h" #include "berryIViewCategory.h" #include "berryIWorkbench.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "internal/intro/berryIntroConstants.h" #include "internal/berryKeywordRegistry.h" #include #include namespace berry { // --------------------------- Tree Item Classes --------------------------- struct ViewTreeItem; bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2); struct ViewTreeItem { ViewTreeItem(ViewTreeModel* model) : m_parent(nullptr) , m_model(model) {} virtual ~ViewTreeItem() { QList children = m_children; if (m_parent) m_parent->removeChild(this); qDeleteAll(children); } virtual QVariant data(int role) { if (role == ViewTreeModel::Keywords) { if (m_keywordCache.isEmpty()) { - m_keywordCache = QStringList(keywordLabels().toList()); + m_keywordCache = keywordLabels().values(); } return m_keywordCache; } return QVariant(); } virtual Qt::ItemFlags flags() const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } virtual QSet keywordLabels() const { return QSet(); } void appendChild(ViewTreeItem* child) { m_children.push_back(child); child->m_parent = this; qSort(m_children.begin(), m_children.end(), CompareViewTreeItem); } void removeChild(ViewTreeItem* child) { m_children.removeAll(child); } QList takeChildren() { QList children = m_children; m_children.clear(); return children; } ViewTreeItem* childItem(int row) const { if (row < 0 || row >= m_children.size()) return nullptr; return m_children.at(row); } ViewTreeItem* parentItem() const { return m_parent; } int childCount() const { return m_children.size(); } int row() const { if (m_parent) return m_parent->rowIndex(this); return 0; } int rowIndex(const ViewTreeItem* child) const { return m_children.indexOf(const_cast(child)); } QList m_children; ViewTreeItem* m_parent; ViewTreeModel* m_model; private: QStringList m_keywordCache; }; bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2) { return item1->data(Qt::DisplayRole).toString() < item2->data(Qt::DisplayRole).toString(); } struct RootTreeItem : ViewTreeItem { RootTreeItem(ViewTreeModel* model) : ViewTreeItem(model) {} QVariant data(int /*role*/) override { return QVariant(); } }; struct DescriptorTreeItem : ViewTreeItem { DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent = nullptr); QVariant data(int role) override; protected: QSet keywordLabels() const override; IViewDescriptor::Pointer m_descriptor; }; struct CategoryTreeItem : ViewTreeItem { CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent = nullptr); QVariant data(int role) override; Qt::ItemFlags flags() const override; protected: QSet keywordLabels() const override; /** * Removes the temporary intro view from the list so that it cannot be activated except through * the introduction command. */ void RemoveIntroView(QList& list); private: void CreateChildren(); IViewCategory::Pointer m_category; }; // --------------------------- Tree Model Classes --------------------------- struct ViewTreeModel::Impl { Impl(const IWorkbenchWindow* window) : window(window) , viewRegistry(*window->GetWorkbench()->GetViewRegistry()) { } const IWorkbenchWindow* window; IViewRegistry& viewRegistry; QScopedPointer rootItem; }; ViewTreeModel::ViewTreeModel(const IWorkbenchWindow* window, QObject* parent) : QAbstractItemModel(parent) , d(new Impl(window)) { d->rootItem.reset(new RootTreeItem(this)); QList categoryItems; QList categories = d->viewRegistry.GetCategories(); for (const auto &category : qAsConst(categories)) { if (category->GetViews().isEmpty()) continue; CategoryTreeItem* categoryItem = new CategoryTreeItem(this, category); if (categoryItem->childCount() == 0) { delete categoryItem; } else { categoryItems.push_back(categoryItem); } } // if there is only one category, return it's children directly if (categoryItems.size() == 1) { QList items = categoryItems.front()->takeChildren(); for (auto item : qAsConst(items)) { d->rootItem->appendChild(item); } qDeleteAll(categoryItems); } else { for (auto category : qAsConst(categoryItems)) { d->rootItem->appendChild(category); } } } ViewTreeModel::~ViewTreeModel() { } QVariant ViewTreeModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); return static_cast(index.internalPointer())->data(role); } Qt::ItemFlags ViewTreeModel::flags(const QModelIndex& index) const { if (!index.isValid()) return {}; return static_cast(index.internalPointer())->flags(); } QVariant ViewTreeModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const { if (role == Qt::DisplayRole && section == 0) { return "View"; } return QVariant(); } QModelIndex ViewTreeModel::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) { return QModelIndex(); } ViewTreeItem* parentItem = nullptr; if (!parent.isValid()) { parentItem = d->rootItem.data(); } else { parentItem = static_cast(parent.internalPointer()); } ViewTreeItem* childItem = parentItem->childItem(row); if (childItem) { return createIndex(row, column, childItem); } return QModelIndex(); } QModelIndex ViewTreeModel::parent(const QModelIndex& child) const { if (!child.isValid()) { return QModelIndex(); } ViewTreeItem* childItem = static_cast(child.internalPointer()); ViewTreeItem* parentItem = childItem->parentItem(); if (parentItem == d->rootItem.data()) { return QModelIndex(); } return createIndex(parentItem->row(), 0, parentItem); } int ViewTreeModel::rowCount(const QModelIndex& parent) const { ViewTreeItem* parentItem = nullptr; if (parent.column() > 0) return 0; if (!parent.isValid()) { parentItem = d->rootItem.data(); } else { parentItem = static_cast(parent.internalPointer()); } return parentItem->childCount(); } int ViewTreeModel::columnCount(const QModelIndex& /*parent*/) const { return 1; } const IWorkbenchWindow*ViewTreeModel::GetWorkbenchWindow() const { return d->window; } // --------------------------- DescriptorTreeItem --------------------------- DescriptorTreeItem::DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent) : ViewTreeItem(model) , m_descriptor(descriptor) { if (parent) parent->appendChild(this); } QVariant DescriptorTreeItem::data(int role) { if (role == Qt::DisplayRole) { return m_descriptor->GetLabel(); } else if (role == Qt::DecorationRole) { return m_descriptor->GetImageDescriptor(); } else if (role == Qt::ForegroundRole) { IWorkbenchPage::Pointer page = this->m_model->GetWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { if (page->FindViewReference(m_descriptor->GetId()).IsNotNull()) { return QBrush(QColor(Qt::gray)); } } } else if (role == ViewTreeModel::Description) { return m_descriptor->GetDescription(); } else if (role == ViewTreeModel::Id) { return m_descriptor->GetId(); } return ViewTreeItem::data(role); } QSet DescriptorTreeItem::keywordLabels() const { KeywordRegistry* registry = KeywordRegistry::GetInstance(); QStringList ids = m_descriptor->GetKeywordReferences(); QSet keywords; keywords.insert(m_descriptor->GetLabel()); for(const auto &id : qAsConst(ids)) { QString label = registry->GetKeywordLabel(id); for (const auto &keyword : label.split(' ', Qt::SkipEmptyParts)) { keywords.insert(keyword); } } return keywords; } // --------------------------- CategoryTreeItem --------------------------- CategoryTreeItem::CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent) : ViewTreeItem(model) , m_category(category) { if (parent) parent->appendChild(this); this->CreateChildren(); } QVariant CategoryTreeItem::data(int role) { if (role == Qt::DisplayRole) { return m_category->GetLabel(); } else if (role == Qt::DecorationRole) { return QIcon::fromTheme("folder"); } else if (role == ViewTreeModel::Id) { return m_category->GetId(); } return ViewTreeItem::data(role); } Qt::ItemFlags CategoryTreeItem::flags() const { return Qt::ItemIsEnabled; } QSet CategoryTreeItem::keywordLabels() const { QSet keywords; for(auto child : this->m_children) { for (const auto &keyword : child->data(ViewTreeModel::Keywords).toStringList()) { keywords.insert(keyword); } } return keywords; } void CategoryTreeItem::CreateChildren() { auto viewDescriptors = m_category->GetViews(); RemoveIntroView(viewDescriptors); for(const auto &viewDescriptor : qAsConst(viewDescriptors)) { new DescriptorTreeItem(this->m_model, viewDescriptor, this); } } void CategoryTreeItem::RemoveIntroView(QList& list) { for (auto view = list.begin(); view != list.end();) { if ((*view)->GetId() == IntroConstants::INTRO_VIEW_ID) { view = list.erase(view); } else ++view; } } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp index c706326752..f0e7398335 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp @@ -1,117 +1,118 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include "mitkIRenderWindowPart.h" // mitk gui common plugin #include // berry #include QList AbstractDataNodeAction::GetSelectedNodes(berry::IWorkbenchPartSite::Pointer workbenchPartSite) { QList selectedNodes; if (workbenchPartSite.IsNull()) { return selectedNodes; } berry::ISelection::ConstPointer selection = workbenchPartSite->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); if (currentSelection.IsNull() || currentSelection->IsEmpty()) { return selectedNodes; } - selectedNodes = QList::fromStdList(currentSelection->GetSelectedDataNodes()); + auto nodes = currentSelection->GetSelectedDataNodes(); + selectedNodes = QList(nodes.begin(), nodes.end()); return selectedNodes; } QmitkAbstractDataNodeAction::QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer workbenchPartSite) { m_WorkbenchPartSite = workbenchPartSite; } QmitkAbstractDataNodeAction::QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite* workbenchPartSite) { m_WorkbenchPartSite = berry::IWorkbenchPartSite::Pointer(workbenchPartSite); } void QmitkAbstractDataNodeAction::SetDataStorage(mitk::DataStorage* dataStorage) { if (m_DataStorage != dataStorage) { // set the new data storage m_DataStorage = dataStorage; } } void QmitkAbstractDataNodeAction::SetSelectedNodes(const QList& selectedNodes) { m_SelectedNodes = selectedNodes; // use the first selected node to initialize the data node actions InitializeWithDataNode(m_SelectedNodes.front()); } void QmitkAbstractDataNodeAction::SetBaseRenderer(mitk::BaseRenderer* baseRenderer) { if (m_BaseRenderer != baseRenderer) { // set the new base renderer m_BaseRenderer = baseRenderer; } } mitk::BaseRenderer::Pointer QmitkAbstractDataNodeAction::GetBaseRenderer() { return m_BaseRenderer.Lock(); } QList QmitkAbstractDataNodeAction::GetSelectedNodes() const { if (!m_SelectedNodes.isEmpty()) { return m_SelectedNodes; } auto workbenchPartSite = m_WorkbenchPartSite.Lock(); if (workbenchPartSite.IsNull()) { // return empty list of selected nodes return m_SelectedNodes; } // retrieve selection from the workbench selection service return AbstractDataNodeAction::GetSelectedNodes(workbenchPartSite); } mitk::DataNode::Pointer QmitkAbstractDataNodeAction::GetSelectedNode() const { QList selectedNodes = GetSelectedNodes(); if (selectedNodes.empty()) { return nullptr; } // no batch action; should only be called with a single node mitk::DataNode::Pointer dataNode = selectedNodes.front(); if (nullptr == dataNode) { return nullptr; } return dataNode; } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp index b7e0afe75d..33107498da 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp @@ -1,488 +1,489 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include #include #include #include #include #include #include QmitkDataNodeContextMenu::QmitkDataNodeContextMenu(berry::IWorkbenchPartSite::Pointer workbenchPartSite, QWidget* parent) : QMenu(parent), m_Parent(parent), m_WorkbenchPartSite(workbenchPartSite) { this->InitNodeDescriptors(); this->InitDefaultActions(); this->InitExtensionPointActions(); } QmitkDataNodeContextMenu::~QmitkDataNodeContextMenu() { for (auto& descriptorActionPair : m_DescriptorActionList) descriptorActionPair.first->RemoveAction(descriptorActionPair.second); } void QmitkDataNodeContextMenu::SetDataStorage(mitk::DataStorage* dataStorage) { m_DataStorage = dataStorage; for (auto& descriptorActionPair : m_DescriptorActionList) { auto dataNodeAction = dynamic_cast(descriptorActionPair.second); if (nullptr != dataNodeAction) dataNodeAction->SetDataStorage(dataStorage); } } void QmitkDataNodeContextMenu::SetBaseRenderer(mitk::BaseRenderer* baseRenderer) { m_BaseRenderer = baseRenderer; for (auto& descriptorActionPair : m_DescriptorActionList) { auto dataNodeAction = dynamic_cast(descriptorActionPair.second); if (nullptr != dataNodeAction) dataNodeAction->SetBaseRenderer(baseRenderer); } } void QmitkDataNodeContextMenu::SetSurfaceDecimation(bool surfaceDecimation) { m_SurfaceDecimation = surfaceDecimation; } void QmitkDataNodeContextMenu::SetSelectedNodes(const QList& selectedNodes) { m_SelectedNodes = selectedNodes; } void QmitkDataNodeContextMenu::InitNodeDescriptors() { auto nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance(); m_UnknownDataNodeDescriptor = nodeDescriptorManager->GetUnknownDataNodeDescriptor(); m_ImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("Image"); m_MultiComponentImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("MultiComponentImage"); m_DiffusionImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("DiffusionImage"); m_FiberBundleDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("FiberBundle"); m_PeakImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("PeakImage"); m_SegmentDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("Segment"); m_SurfaceDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("Surface"); m_PointSetNodeDescriptor = nodeDescriptorManager->GetDescriptor("PointSet"); m_PlanarLineNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarLine"); m_PlanarCircleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarCircle"); m_PlanarEllipseNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarEllipse"); m_PlanarAngleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarAngle"); m_PlanarFourPointAngleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarFourPointAngle"); m_PlanarRectangleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarRectangle"); m_PlanarPolygonNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarPolygon"); m_PlanarPathNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarPath"); m_PlanarDoubleEllipseNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarDoubleEllipse"); m_PlanarBezierCurveNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarBezierCurve"); m_PlanarSubdivisionPolygonNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarSubdivisionPolygon"); } void QmitkDataNodeContextMenu::InitDefaultActions() { auto workbenchPartSite = m_WorkbenchPartSite.Lock(); m_GlobalReinitAction = new QmitkDataNodeGlobalReinitAction(m_Parent, workbenchPartSite); m_GlobalReinitAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_GlobalReinitAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_GlobalReinitAction)); m_ReinitAction = new QmitkDataNodeReinitAction(m_Parent, workbenchPartSite); m_ReinitAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_ReinitAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ReinitAction)); m_ResetGeometryAction = new QmitkDataNodeResetGeometryAction(m_Parent, workbenchPartSite); m_ResetGeometryAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_ResetGeometryAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ResetGeometryAction)); QAction* saveAction = new QmitkFileSaveAction(QIcon(":/org.mitk.gui.qt.datamanager/Save_48.png"), workbenchPartSite->GetWorkbenchWindow()); m_UnknownDataNodeDescriptor->AddAction(saveAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, saveAction)); m_RemoveAction = new QmitkDataNodeRemoveAction(m_Parent, workbenchPartSite); m_RemoveAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Remove_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_RemoveAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_RemoveAction)); m_ShowSelectedNodesAction = new QmitkDataNodeShowSelectedNodesAction(m_Parent, workbenchPartSite); m_ShowSelectedNodesAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/ShowSelectedNode_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_ShowSelectedNodesAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ShowSelectedNodesAction)); m_ToggleVisibilityAction = new QmitkDataNodeToggleVisibilityAction(m_Parent, workbenchPartSite); m_ToggleVisibilityAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/InvertShowSelectedNode_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_ToggleVisibilityAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ToggleVisibilityAction)); m_ShowDetailsAction = new QmitkDataNodeShowDetailsAction(m_Parent, workbenchPartSite); m_ShowDetailsAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/ShowDataInfo_48.png")); m_UnknownDataNodeDescriptor->AddAction(m_ShowDetailsAction, true); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ShowDetailsAction)); m_OpacityAction = new QmitkDataNodeOpacityAction(m_Parent, workbenchPartSite); m_UnknownDataNodeDescriptor->AddAction(m_OpacityAction, false); m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_OpacityAction)); m_ColorAction = new QmitkDataNodeColorAction(m_Parent, workbenchPartSite); this->AddColorAction(m_ColorAction); m_ColormapAction = new QmitkDataNodeColorMapAction(m_Parent, workbenchPartSite); m_ImageDataNodeDescriptor->AddAction(m_ColormapAction); m_DescriptorActionList.push_back(std::make_pair(m_ImageDataNodeDescriptor, m_ColormapAction)); if (nullptr != m_DiffusionImageDataNodeDescriptor) { m_DiffusionImageDataNodeDescriptor->AddAction(m_ColormapAction, false); m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, m_ColormapAction)); } m_ComponentAction = new QmitkDataNodeComponentAction(m_Parent, workbenchPartSite); m_MultiComponentImageDataNodeDescriptor->AddAction(m_ComponentAction, false); m_DescriptorActionList.push_back(std::make_pair(m_MultiComponentImageDataNodeDescriptor, m_ComponentAction)); if (nullptr != m_DiffusionImageDataNodeDescriptor) { m_DiffusionImageDataNodeDescriptor->AddAction(m_ComponentAction, false); m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, m_ComponentAction)); } m_TextureInterpolationAction = new QmitkDataNodeTextureInterpolationAction(m_Parent, workbenchPartSite); m_ImageDataNodeDescriptor->AddAction(m_TextureInterpolationAction, false); m_DescriptorActionList.push_back(std::make_pair(m_ImageDataNodeDescriptor, m_TextureInterpolationAction)); if (nullptr != m_DiffusionImageDataNodeDescriptor) { m_DiffusionImageDataNodeDescriptor->AddAction(m_TextureInterpolationAction, false); m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, m_TextureInterpolationAction)); } if (nullptr != m_SegmentDataNodeDescriptor) { m_SegmentDataNodeDescriptor->AddAction(m_TextureInterpolationAction, false); m_DescriptorActionList.push_back(std::make_pair(m_SegmentDataNodeDescriptor, m_TextureInterpolationAction)); } m_SurfaceRepresentationAction = new QmitkDataNodeSurfaceRepresentationAction(m_Parent, workbenchPartSite); m_SurfaceDataNodeDescriptor->AddAction(m_SurfaceRepresentationAction, false); m_DescriptorActionList.push_back(std::make_pair(m_SurfaceDataNodeDescriptor, m_SurfaceRepresentationAction)); } void QmitkDataNodeContextMenu::InitExtensionPointActions() { auto extensionPointService = berry::Platform::GetExtensionRegistry(); auto customMenuConfigs = extensionPointService->GetConfigurationElementsFor("org.mitk.gui.qt.datamanager.contextMenuActions"); DescriptorActionListType descriptorActionList; m_ConfigElements.clear(); for (const auto& customMenuConfig : qAsConst(customMenuConfigs)) { auto descriptorName = customMenuConfig->GetAttribute("nodeDescriptorName"); auto actionLabel = customMenuConfig->GetAttribute("label"); auto actionClass = customMenuConfig->GetAttribute("class"); if (descriptorName.isEmpty() || actionLabel.isEmpty() || actionClass.isEmpty()) continue; auto descriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(descriptorName); if (nullptr == descriptor) { MITK_WARN << "Cannot add action \"" << actionLabel << "\" to non-existent descriptor \"" << descriptorName << "\"."; continue; } QAction* action = nullptr; auto actionIcon = customMenuConfig->GetAttribute("icon"); if (!actionIcon.isEmpty()) { QIcon icon = !QFile::exists(actionIcon) ? berry::AbstractUICTKPlugin::ImageDescriptorFromPlugin(customMenuConfig->GetContributor()->GetName(), actionIcon) : QIcon(actionIcon); action = new QAction(icon, actionLabel, m_Parent); } else { action = new QAction(actionLabel, m_Parent); } if (nullptr != action) { // See T26938. We do not know why but without the lambda function indirection, the // connection is lost after the content menu was shown for the first time. connect(action, &QAction::triggered, [action, this]() { this->OnExtensionPointActionTriggered(action); }); m_ConfigElements[action] = customMenuConfig; descriptorActionList.push_back(std::make_pair(descriptor, action)); } } this->AddDescriptorActionList(descriptorActionList); } void QmitkDataNodeContextMenu::InitServiceActions() { } void QmitkDataNodeContextMenu::OnContextMenuRequested(const QPoint& /*pos*/) { auto workbenchPartSite = m_WorkbenchPartSite.Lock(); if (workbenchPartSite.IsNull()) return; auto selection = workbenchPartSite->GetWorkbenchWindow()->GetSelectionService()->GetSelection() .Cast(); if (selection.IsNull() || selection->IsEmpty()) return; - m_SelectedNodes = QList::fromStdList(selection->GetSelectedDataNodes()); + auto nodes = selection->GetSelectedDataNodes(); + m_SelectedNodes = QList(nodes.begin(), nodes.end()); if (!m_SelectedNodes.isEmpty()) { this->clear(); auto actions = m_SelectedNodes.size() == 1 ? this->GetActions(m_SelectedNodes.front()) : this->GetActions(m_SelectedNodes); for (auto& action : actions) { auto dataNodeAction = dynamic_cast(action); if (nullptr != dataNodeAction) dataNodeAction->SetSelectedNodes(m_SelectedNodes); } this->addActions(actions); this->popup(QCursor::pos()); } } void QmitkDataNodeContextMenu::OnExtensionPointActionTriggered(QAction* action) { auto configElementIter = m_ConfigElements.find(action); if (m_ConfigElements.end() == configElementIter) { MITK_WARN << "Associated configuration element for action \"" << action->text() << "\" not found."; return; } auto configElement = configElementIter->second; auto contextMenuAction = configElement->CreateExecutableExtension("class"); auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNotNull()) contextMenuAction->SetDataStorage(dataStorage); if ("QmitkCreatePolygonModelAction" == configElement->GetAttribute("class")) { contextMenuAction->SetSmoothed("true" == configElement->GetAttribute("smoothed")); contextMenuAction->SetDecimated(m_SurfaceDecimation); } contextMenuAction->Run(m_SelectedNodes); } void QmitkDataNodeContextMenu::AddColorAction(QWidgetAction* colorAction) { if (nullptr != m_ImageDataNodeDescriptor) { m_ImageDataNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_ImageDataNodeDescriptor, colorAction)); } if (nullptr != m_MultiComponentImageDataNodeDescriptor) { m_MultiComponentImageDataNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_MultiComponentImageDataNodeDescriptor, colorAction)); } if (nullptr != m_DiffusionImageDataNodeDescriptor) { m_DiffusionImageDataNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, colorAction)); } if (nullptr != m_FiberBundleDataNodeDescriptor) { m_FiberBundleDataNodeDescriptor->AddAction(colorAction, false); m_DescriptorActionList.push_back(std::make_pair(m_FiberBundleDataNodeDescriptor, colorAction)); } if (nullptr != m_PeakImageDataNodeDescriptor) { m_PeakImageDataNodeDescriptor->AddAction(colorAction, false); m_DescriptorActionList.push_back(std::make_pair(m_PeakImageDataNodeDescriptor, colorAction)); } if (nullptr != m_SegmentDataNodeDescriptor) { m_SegmentDataNodeDescriptor->AddAction(colorAction, false); m_DescriptorActionList.push_back(std::make_pair(m_SegmentDataNodeDescriptor, colorAction)); } if (nullptr != m_SurfaceDataNodeDescriptor) { m_SurfaceDataNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_SurfaceDataNodeDescriptor, colorAction)); } if (nullptr != m_PointSetNodeDescriptor) { m_PointSetNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PointSetNodeDescriptor, colorAction)); } if (nullptr != m_PlanarLineNodeDescriptor) { m_PlanarLineNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarLineNodeDescriptor, colorAction)); } if (nullptr != m_PlanarCircleNodeDescriptor) { m_PlanarCircleNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarCircleNodeDescriptor, colorAction)); } if (nullptr != m_PlanarEllipseNodeDescriptor) { m_PlanarEllipseNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarEllipseNodeDescriptor, colorAction)); } if (nullptr != m_PlanarAngleNodeDescriptor) { m_PlanarAngleNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarAngleNodeDescriptor, colorAction)); } if (nullptr != m_PlanarFourPointAngleNodeDescriptor) { m_PlanarFourPointAngleNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarFourPointAngleNodeDescriptor, colorAction)); } if (nullptr != m_PlanarRectangleNodeDescriptor) { m_PlanarRectangleNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarRectangleNodeDescriptor, colorAction)); } if (nullptr != m_PlanarPolygonNodeDescriptor) { m_PlanarPolygonNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarPolygonNodeDescriptor, colorAction)); } if (nullptr != m_PlanarPathNodeDescriptor) { m_PlanarPathNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarPathNodeDescriptor, colorAction)); } if (nullptr != m_PlanarDoubleEllipseNodeDescriptor) { m_PlanarDoubleEllipseNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarDoubleEllipseNodeDescriptor, colorAction)); } if (nullptr != m_PlanarBezierCurveNodeDescriptor) { m_PlanarBezierCurveNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarBezierCurveNodeDescriptor, colorAction)); } if (nullptr != m_PlanarSubdivisionPolygonNodeDescriptor) { m_PlanarSubdivisionPolygonNodeDescriptor->AddAction(colorAction, true); m_DescriptorActionList.push_back(std::make_pair(m_PlanarSubdivisionPolygonNodeDescriptor, colorAction)); } } void QmitkDataNodeContextMenu::AddDescriptorActionList(DescriptorActionListType& descriptorActionList) { using ListItem = std::pair; std::sort(descriptorActionList.begin(), descriptorActionList.end(), [](const ListItem& left, const ListItem& right) -> bool { return left.second->text() < right.second->text(); }); for (auto& descriptorActionPair : descriptorActionList) { descriptorActionPair.first->AddAction(descriptorActionPair.second); m_DescriptorActionList.push_back(descriptorActionPair); } } QList QmitkDataNodeContextMenu::GetActions(const mitk::DataNode* node) { QList actions; for(const auto& descriptorActionPair : m_DescriptorActionList) { if (descriptorActionPair.first->CheckNode(node) || "Unknown" == descriptorActionPair.first->GetNameOfClass()) actions.append(descriptorActionPair.second); } return actions; } QList QmitkDataNodeContextMenu::GetActions(const QList& nodes) { QList actions; for (const auto& descriptorActionPair : m_DescriptorActionList) { for (const auto& node : nodes) { if (descriptorActionPair.first->CheckNode(node) || "Unknown" == descriptorActionPair.first->GetNameOfClass()) { auto batchActions = descriptorActionPair.first->GetBatchActions(); if (std::find(batchActions.begin(), batchActions.end(), descriptorActionPair.second) != batchActions.end()) actions.append(descriptorActionPair.second); break; } } } return actions; } diff --git a/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp b/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp index 1adeb0b41b..82dd8e35f3 100644 --- a/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp +++ b/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp @@ -1,452 +1,452 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkChartExampleView.h" #include const std::string QmitkChartExampleView::VIEW_ID = "org.mitk.views.qmitkchartexample"; void QmitkChartExampleView::SetFocus() { m_Controls.m_buttonCreateChart->setFocus(); } void QmitkChartExampleView::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); CreateConnectionsForGUIElements(); connect(m_Controls.m_comboBoxChartType, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::AdaptDataGUI); m_Controls.m_lineEditDataXVector->setText("0;1;2;3;4;5;6;7;8;9"); m_Controls.m_lineEditDataYVector->setText("0;1;2;3;4;5;6;7;8;9"); m_Controls.m_lineEditDataLabel->setText("Test"); m_Controls.m_lineEditXAxisLabel->setText("X-Axis"); m_Controls.m_lineEditYAxisLabel->setText("Y-Axis"); m_Controls.m_lineEditTitle->setText("Title"); m_Controls.m_labelPieData->setVisible(false); m_Controls.m_lineEditPieDataLabel->setVisible(false); m_Controls.m_groupBoxErrors->setVisible(false); m_Controls.m_groupBoxXErrors->setVisible(false); m_Controls.m_groupBoxYErrors->setVisible(false); m_Controls.m_doubleSpinBox_maxZoomX->setValue(10); m_Controls.m_doubleSpinBox_maxZoomY->setValue(10); m_AxisScaleNameToAxisScaleType.emplace("linear", QmitkChartWidget::AxisScale::linear); m_AxisScaleNameToAxisScaleType.emplace("logarithmic", QmitkChartWidget::AxisScale::log); m_LegendPositionNameToLegendPositionType.emplace("bottom middle", QmitkChartWidget::LegendPosition::bottomMiddle); m_LegendPositionNameToLegendPositionType.emplace("bottom right", QmitkChartWidget::LegendPosition::bottomRight); m_LegendPositionNameToLegendPositionType.emplace("top right", QmitkChartWidget::LegendPosition::topRight); m_LegendPositionNameToLegendPositionType.emplace("top left", QmitkChartWidget::LegendPosition::topLeft); m_LegendPositionNameToLegendPositionType.emplace("middle right", QmitkChartWidget::LegendPosition::middleRight); } void QmitkChartExampleView::CreateConnectionsForGUIElements() { connect(m_Controls.m_buttonCreateChart, &QPushButton::clicked, this, &QmitkChartExampleView::CreateChart); connect(m_Controls.m_buttonUpdateData, &QPushButton::clicked, this, &QmitkChartExampleView::UpdateData); connect(m_Controls.m_buttonClearChart, &QPushButton::clicked, this, &QmitkChartExampleView::ClearChart); connect(m_Controls.m_buttonAddData, &QPushButton::clicked, this, &QmitkChartExampleView::AddData); connect(m_Controls.m_comboBoxExistingData, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::UpdateSelectedData); connect(m_Controls.m_checkBoxEnableErrors, &QCheckBox::toggled, this, &QmitkChartExampleView::ShowErrorOptions); connect(m_Controls.m_checkBoxEnableXErrors, &QCheckBox::toggled, this, &QmitkChartExampleView::ShowXErrorOptions); connect(m_Controls.m_checkBoxEnableYErrors, &QCheckBox::toggled, this, &QmitkChartExampleView::ShowYErrorOptions); connect(m_Controls.m_doubleSpinBox_minZoomX, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomX); connect(m_Controls.m_doubleSpinBox_maxZoomX, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomX); connect(m_Controls.m_doubleSpinBox_minZoomY, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomY); connect(m_Controls.m_doubleSpinBox_maxZoomY, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomY); connect(m_Controls.m_comboBoxLegendPosition, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::OnLegendPositionChanged); connect(m_Controls.m_lineEditTitle, &QLineEdit::editingFinished, this, &QmitkChartExampleView::OnTitleChanged); connect(m_Controls.m_lineEditXAxisLabel, &QLineEdit::editingFinished, this, &QmitkChartExampleView::OnXAxisLabelChanged); connect(m_Controls.m_lineEditYAxisLabel, &QLineEdit::editingFinished, this, &QmitkChartExampleView::OnYAxisLabelChanged); connect(m_Controls.m_comboBoxYAxisScale, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::OnYAxisScaleChanged); connect(m_Controls.m_checkBoxShowLegend, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnShowLegendChanged); connect(m_Controls.m_checkBoxStackedData, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnStackedDataChanged); connect(m_Controls.m_checkBoxShowDataPoints, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnShowDataPointsChanged); connect(m_Controls.m_checkBoxShowSubchart, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnShowSubchartChanged); } void QmitkChartExampleView::AddData() { QString lineEditDataX = m_Controls.m_lineEditDataXVector->text(); QString lineEditDataY = m_Controls.m_lineEditDataYVector->text(); auto dataX = ConvertToDoubleVector(lineEditDataX); auto dataY = ConvertToDoubleVector(lineEditDataY); auto dataXandY = CreatePairList(dataX, dataY); QString data = QString::fromStdString(ConvertToText(dataXandY)); std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString(); std::string chartTypeAsString = m_Controls.m_comboBoxChartType->currentText().toStdString(); std::string chartColorAsString = m_Controls.m_comboBoxColor->currentText().toStdString(); std::string chartLineStyleAsString = m_Controls.m_comboBoxLineStyle->currentText().toStdString(); std::string pieLabelsAsString = m_Controls.m_lineEditPieDataLabel->text().toStdString(); if (std::find(labelStorage.begin(), labelStorage.end(), dataLabel) != labelStorage.end()) { m_Controls.m_labelInfo->setText("This data already exists"); m_Controls.m_labelInfo->setStyleSheet("color: red;"); return; } if (dataX.size() != dataY.size()) { m_Controls.m_labelInfo->setText("Data x and y size have to be equal"); m_Controls.m_labelInfo->setStyleSheet("color: red;"); return; } labelStorage.push_back(dataLabel); m_Controls.m_Chart->AddChartExampleData(dataXandY, dataLabel, chartTypeAsString, chartColorAsString, chartLineStyleAsString, pieLabelsAsString); m_Controls.m_comboBoxExistingData->addItem(m_Controls.m_lineEditDataLabel->text()); if (m_Controls.m_checkBoxEnableErrors->isChecked()) { if (m_Controls.m_checkBoxEnableXErrors->isChecked()) { auto errorsPlus = ConvertToDoubleVector(m_Controls.m_lineEditXErrorPlus->text()); auto errorsMinus = ConvertToDoubleVector(m_Controls.m_lineEditXErrorMinus->text()); m_Controls.m_Chart->SetXErrorBars(m_Controls.m_lineEditDataLabel->text().toStdString(), errorsPlus, errorsMinus); } if (m_Controls.m_checkBoxEnableYErrors->isChecked()) { auto errorsPlus = ConvertToDoubleVector(m_Controls.m_lineEditYErrorPlus->text()); auto errorsMinus = ConvertToDoubleVector(m_Controls.m_lineEditYErrorMinus->text()); m_Controls.m_Chart->SetYErrorBars(m_Controls.m_lineEditDataLabel->text().toStdString(), errorsPlus, errorsMinus); } } QString dataOverview; dataOverview.append(m_Controls.m_lineEditDataLabel->text()); dataOverview.append("(").append(m_Controls.m_comboBoxChartType->currentText()); dataOverview.append(", ").append(m_Controls.m_comboBoxLineStyle->currentText()); dataOverview.append(")"); dataOverview.append(":").append(data); m_Controls.m_plainTextEditDataView->appendPlainText(dataOverview); } void QmitkChartExampleView::CreateChart() { auto dataYAxisScaleType = m_AxisScaleNameToAxisScaleType.at(m_Controls.m_comboBoxYAxisScale->currentText().toStdString()); auto xAxisLabel = m_Controls.m_lineEditXAxisLabel->text().toStdString(); auto yAxisLabel = m_Controls.m_lineEditYAxisLabel->text().toStdString(); auto showLegend = m_Controls.m_checkBoxShowLegend->isChecked(); auto legendPosition = m_LegendPositionNameToLegendPositionType.at(m_Controls.m_comboBoxLegendPosition->currentText().toStdString()); auto showDataPoints = m_Controls.m_checkBoxShowDataPoints->isChecked(); auto stackedData = m_Controls.m_checkBoxStackedData->isChecked(); auto showSubchart = m_Controls.m_checkBoxShowSubchart->isChecked(); auto title = m_Controls.m_lineEditTitle->text().toStdString(); m_Controls.m_Chart->SetTitle(title); m_Controls.m_Chart->SetYAxisScale(dataYAxisScaleType); m_Controls.m_Chart->SetXAxisLabel(xAxisLabel); m_Controls.m_Chart->SetYAxisLabel(yAxisLabel); m_Controls.m_Chart->SetShowLegend(showLegend); m_Controls.m_Chart->SetLegendPosition(legendPosition); m_Controls.m_Chart->SetShowErrorBars(true); m_Controls.m_Chart->SetShowDataPoints(showDataPoints); m_Controls.m_Chart->SetStackedData(stackedData); m_Controls.m_Chart->Show(showSubchart); } void QmitkChartExampleView::UpdateData() { if (m_Controls.m_comboBoxExistingData->currentText().isEmpty()) { m_Controls.m_labelInfo->setText("Please enter a valid Datalabel"); m_Controls.m_labelInfo->setStyleSheet("color: red;"); return; } if (m_Controls.m_lineEditDataLabel->text() != m_Controls.m_comboBoxExistingData->currentText()) { return; } QString lineEditDataX = m_Controls.m_lineEditDataXVector->text(); QString lineEditDataY = m_Controls.m_lineEditDataYVector->text(); auto dataX = ConvertToDoubleVector(lineEditDataX); auto dataY = ConvertToDoubleVector(lineEditDataY); auto dataXandY = CreatePairList(dataX, dataY); QString data = QString::fromStdString(ConvertToText(dataXandY)); std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString(); std::string chartTypeAsString = m_Controls.m_comboBoxChartType->currentText().toStdString(); std::string chartColorAsString = m_Controls.m_comboBoxColor->currentText().toStdString(); std::string chartLineStyleAsString = m_Controls.m_comboBoxLineStyle->currentText().toStdString(); std::string pieLabelsAsString = m_Controls.m_lineEditPieDataLabel->text().toStdString(); if (dataX.size() != dataY.size()) { m_Controls.m_labelInfo->setText("Data x and y size have to be equal"); m_Controls.m_labelInfo->setStyleSheet("color: red;"); return; } m_Controls.m_Chart->UpdateChartExampleData(dataXandY, dataLabel, chartTypeAsString, chartColorAsString, chartLineStyleAsString, pieLabelsAsString); } void QmitkChartExampleView::UpdateSelectedData() { std::string label = m_Controls.m_comboBoxExistingData->currentText().toStdString(); auto data = m_Controls.m_Chart->GetDataElementByLabel(label); if (data == nullptr) { return; } auto x = data->GetXData(); auto y = data->GetYData(); - auto xVector = x.toVector().toStdVector(); - auto yVector = y.toVector().toStdVector(); + std::vector xVector(x.begin(), x.end()); + std::vector yVector(y.begin(), y.end()); QString xString = QString::fromStdString(ConvertToText(xVector)); QString yString = QString::fromStdString(ConvertToText(yVector)); auto color = data->GetColor(); auto type = data->GetChartType(); auto style = data->GetLineStyle(); if (type.toString() == "pie") { m_Controls.m_comboBoxLineStyle->setVisible(false); m_Controls.m_labelLineStyle->setVisible(false); m_Controls.m_lineEditPieDataLabel->setVisible(true); m_Controls.m_labelPieData->setVisible(true); auto pieLabelsString = ConvertToText(data->GetPieLabels()); m_Controls.m_lineEditPieDataLabel->setText(QString::fromStdString(pieLabelsString)); } else { m_Controls.m_lineEditPieDataLabel->setVisible(false); m_Controls.m_labelPieData->setVisible(false); m_Controls.m_comboBoxLineStyle->setVisible(true); m_Controls.m_labelLineStyle->setVisible(true); m_Controls.m_comboBoxLineStyle->setCurrentText(style.toString()); } m_Controls.m_lineEditDataXVector->setText(xString); m_Controls.m_lineEditDataYVector->setText(yString); m_Controls.m_lineEditDataLabel->setText(QString::fromStdString(label)); m_Controls.m_comboBoxColor->setCurrentText(color.toString()); m_Controls.m_comboBoxChartType->setCurrentText(type.toString()); } void QmitkChartExampleView::ClearChart() { m_Controls.m_Chart->Clear(); m_Controls.m_plainTextEditDataView->clear(); m_Controls.m_comboBoxExistingData->clear(); labelStorage.clear(); } void QmitkChartExampleView::ShowErrorOptions(bool show) { m_Controls.m_groupBoxErrors->setVisible(show); } void QmitkChartExampleView::ShowXErrorOptions(bool show) { m_Controls.m_groupBoxXErrors->setVisible(show); } void QmitkChartExampleView::ShowYErrorOptions(bool show) { m_Controls.m_groupBoxYErrors->setVisible(show); } void QmitkChartExampleView::AdaptZoomX() { m_Controls.m_Chart->SetMinMaxValueXView(m_Controls.m_doubleSpinBox_minZoomX->value(), m_Controls.m_doubleSpinBox_maxZoomX->value()); m_Controls.m_Chart->Show(); } void QmitkChartExampleView::AdaptZoomY() { m_Controls.m_Chart->SetMinMaxValueYView(m_Controls.m_doubleSpinBox_minZoomY->value(), m_Controls.m_doubleSpinBox_maxZoomY->value()); m_Controls.m_Chart->Show(); } void QmitkChartExampleView::AdaptDataGUI(QString chartType) { if (chartType == "pie") { m_Controls.m_labelPieData->setVisible(true); m_Controls.m_lineEditPieDataLabel->setVisible(true); m_Controls.m_labelLineStyle->setVisible(false); m_Controls.m_comboBoxLineStyle->setVisible(false); } else { m_Controls.m_labelLineStyle->setVisible(true); m_Controls.m_comboBoxLineStyle->setVisible(true); m_Controls.m_labelPieData->setVisible(false); m_Controls.m_lineEditPieDataLabel->setVisible(false); } } void QmitkChartExampleView::OnLegendPositionChanged(const QString &newText) { auto legendPosition = m_LegendPositionNameToLegendPositionType.at(newText.toStdString()); m_Controls.m_Chart->SetLegendPosition(legendPosition); } void QmitkChartExampleView::OnTitleChanged() { auto newTitle = m_Controls.m_lineEditTitle->text(); m_Controls.m_Chart->SetTitle(newTitle.toStdString()); } void QmitkChartExampleView::OnXAxisLabelChanged() { auto newXAxisLabel = m_Controls.m_lineEditXAxisLabel->text(); m_Controls.m_Chart->SetXAxisLabel(newXAxisLabel.toStdString()); } void QmitkChartExampleView::OnYAxisLabelChanged() { auto newYAxisLabel = m_Controls.m_lineEditYAxisLabel->text(); m_Controls.m_Chart->SetYAxisLabel(newYAxisLabel.toStdString()); } void QmitkChartExampleView::OnYAxisScaleChanged(const QString &newYAxisScale) { auto yAxisScale = m_AxisScaleNameToAxisScaleType.at(newYAxisScale.toStdString()); m_Controls.m_Chart->SetYAxisScale(yAxisScale); } void QmitkChartExampleView::OnShowLegendChanged(int newState) { m_Controls.m_Chart->SetShowLegend(newState == Qt::Checked); } void QmitkChartExampleView::OnStackedDataChanged(int newState) { m_Controls.m_Chart->SetStackedData(newState == Qt::Checked); } void QmitkChartExampleView::OnShowDataPointsChanged(int newState) { m_Controls.m_Chart->SetShowDataPoints(newState == Qt::Checked); } void QmitkChartExampleView::OnShowSubchartChanged(int newState) { m_Controls.m_Chart->SetShowSubchart(newState == Qt::Checked); } std::vector< std::pair > QmitkChartExampleView::CreatePairList(std::vector keys, std::vector values) const { std::vector< std::pair > aMap; std::transform(keys.begin(), keys.end(), values.begin(), std::inserter(aMap, aMap.end()), [](double a, double b) { return std::make_pair(a, b); }); return aMap; } std::string QmitkChartExampleView::ConvertToText(std::vector > numbers, std::string delimiter) const { std::ostringstream oss; oss.precision(3); if (!numbers.empty()) { for (const auto& keyValue : numbers) { oss << keyValue.first << ":" << keyValue.second << delimiter; } } auto aString = oss.str(); aString.pop_back(); return aString; } std::string QmitkChartExampleView::ConvertToText(std::vector numbers, std::string delimiter) const { std::ostringstream oss; oss.precision(3); if (!numbers.empty()) { for (auto number : numbers) { oss << number.toDouble() << delimiter; } } auto aString = oss.str(); aString.pop_back(); return aString; } std::string QmitkChartExampleView::ConvertToText(QVariantList list, std::string delimiter) const { std::ostringstream oss; if (!list.isEmpty()) { for (auto element : list) { oss << element.toString().toStdString() << delimiter; } auto aString = oss.str(); aString.pop_back(); return aString; } return ""; } std::vector QmitkChartExampleView::ConvertToDoubleVector(const QString& data, QChar delimiter) const { std::vector output; if (data.isEmpty()) { return output; } for (const QString& entry : data.split(delimiter)) { output.push_back(entry.toDouble()); } return output; } std::vector QmitkChartExampleView::ConvertToStringVector(const QString& data, QChar delimiter) const { std::vector output; if (data.isEmpty()) { return output; } for (const QString& entry : data.split(delimiter)) { output.push_back(entry.toStdString()); } return output; } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp index 4f74a40026..ecd5f692f9 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp @@ -1,522 +1,526 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAbstractView.h" #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkCommonActivator.h" #include "internal/QmitkDataNodeItemModel.h" // mitk Includes #include #include #include #include #include #include #include #include #include // berry Includes #include #include #include #include // CTK Includes #include // Qt Includes #include #include #include #include #include class QmitkAbstractViewPrivate { public: QmitkAbstractViewPrivate(QmitkAbstractView* qq) : q(qq) , m_DataStorageServiceTracker(QmitkCommonActivator::GetContext()) , m_Parent(nullptr) , m_DataNodeItemModel(new QmitkDataNodeItemModel) , m_DataNodeSelectionModel(new QItemSelectionModel(m_DataNodeItemModel)) , m_InDataStorageChanged(false) { m_DataStorageServiceTracker.open(); } ~QmitkAbstractViewPrivate() { delete m_DataNodeSelectionModel; delete m_DataNodeItemModel; m_DataStorageServiceTracker.close(); } /** * Called when a DataStorage Add Event was thrown. Sets * m_InDataStorageChanged to true and calls NodeAdded afterwards. * \see m_InDataStorageChanged */ void NodeAddedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeAdded(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage remove event was thrown. Sets * m_InDataStorageChanged to true and calls NodeRemoved afterwards. * \see m_InDataStorageChanged */ void NodeRemovedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeRemoved(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage changed event was thrown. Sets * m_InDataStorageChanged to true and calls NodeChanged afterwards. * \see m_InDataStorageChanged */ void NodeChangedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeChanged(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * reactions to selection events from views */ void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection) { if(sourcepart.IsNull() || sourcepart.GetPointer() == static_cast(q)) return; if(selection.IsNull()) { q->OnNullSelection(sourcepart); return; } mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); q->OnSelectionChanged(sourcepart, this->DataNodeSelectionToQList(_DataNodeSelection)); } /** * Converts a mitk::DataNodeSelection to a QList (possibly empty) */ QList DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const; QmitkAbstractView* const q; ctkServiceTracker m_DataStorageServiceTracker; /** * Saves the parent of this view (this is the scrollarea created in CreatePartControl(QWidget*) * \see CreatePartControl(QWidget*) */ QWidget* m_Parent; /** * Holds the current selection (selection made by this View !!!) */ QmitkDataNodeSelectionProvider::Pointer m_SelectionProvider; /** * Holds a helper model for firing selection events. */ QmitkDataNodeItemModel* m_DataNodeItemModel; /** * The selection model for the QmitkDataNodeItemModel; */ QItemSelectionModel* m_DataNodeSelectionModel; /** * object to observe BlueBerry selections */ QScopedPointer m_BlueBerrySelectionListener; /** * Saves if this class is currently working on DataStorage changes. * This is a protector variable to avoid recursive calls on event listener functions. */ bool m_InDataStorageChanged; }; QmitkAbstractView::QmitkAbstractView() : d(new QmitkAbstractViewPrivate(this)) { } void QmitkAbstractView::CreatePartControl(QWidget* parent) { // scrollArea auto scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent d->m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(d->m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(d->m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); auto parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setContentsMargins({}); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkAbstractView::AfterCreateQtPartControl() { this->SetSelectionProvider(); // REGISTER DATASTORAGE LISTENER this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER auto* prefs = this->GetPreferences(); if (prefs != nullptr) prefs->OnChanged.AddListener(mitk::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS d->m_BlueBerrySelectionListener.reset(new berry::NullSelectionChangedAdapter( d.data(), &QmitkAbstractViewPrivate::BlueBerrySelectionChanged)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(d->m_BlueBerrySelectionListener.data()); // EMULATE INITIAL SELECTION EVENTS // send the current selection berry::IWorkbenchPart::Pointer activePart = this->GetSite()->GetPage()->GetActivePart(); if (activePart.IsNotNull()) { this->OnSelectionChanged(activePart, this->GetCurrentSelection()); } // send preferences changed event this->OnPreferencesChanged(this->GetPreferences()); } QmitkAbstractView::~QmitkAbstractView() { this->Register(); this->GetDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy) ); this->GetDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); auto* prefs = this->GetPreferences(); if(prefs != nullptr) prefs->OnChanged.RemoveListener(mitk::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(nullptr)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(d->m_BlueBerrySelectionListener.data()); } this->UnRegister(false); } void QmitkAbstractView::SetSelectionProvider() { // REGISTER A SELECTION PROVIDER d->m_SelectionProvider = QmitkDataNodeSelectionProvider::Pointer(new QmitkDataNodeSelectionProvider); d->m_SelectionProvider->SetItemSelectionModel(GetDataNodeSelectionModel()); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(d->m_SelectionProvider)); } QItemSelectionModel *QmitkAbstractView::GetDataNodeSelectionModel() const { return nullptr; } void QmitkAbstractView::OnPreferencesChanged( const mitk::IPreferences* ) { } void QmitkAbstractView::DataStorageModified() { } void QmitkAbstractView::DataStorageChanged(mitk::IDataStorageReference::Pointer /*dsRef*/) { } mitk::IRenderWindowPart* QmitkAbstractView::GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategies strategies) const { berry::IWorkbenchPage::Pointer page = GetSite()->GetPage(); return mitk::WorkbenchUtil::GetRenderWindowPart(page, strategies); } void QmitkAbstractView::RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType) { mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if (renderPart == nullptr) return; if (mitk::IRenderingManager* renderingManager = renderPart->GetRenderingManager()) { renderingManager->RequestUpdateAll(requestType); } else { renderPart->RequestUpdate(requestType); } } void QmitkAbstractView::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkAbstractView::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkAbstractView::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkAbstractView::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkAbstractView::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } mitk::IPreferences* QmitkAbstractView::GetPreferences() const { mitk::CoreServicePointer prefsService(mitk::CoreServices::GetPreferencesService()); auto* prefs = prefsService->GetSystemPreferences(); if (prefs != nullptr) { auto viewSite = const_cast(this)->GetViewSite(); if (viewSite.IsNotNull()) return prefs->Node("/" + viewSite->GetId().toStdString()); } return nullptr; } mitk::DataStorage::Pointer QmitkAbstractView::GetDataStorage() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != nullptr) { return dsService->GetDataStorage()->GetDataStorage(); } return nullptr; } mitk::IDataStorageReference::Pointer QmitkAbstractView::GetDataStorageReference() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != nullptr) { return dsService->GetDataStorage(); } return mitk::IDataStorageReference::Pointer(nullptr); } QList QmitkAbstractView::GetCurrentSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection()); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsCurrentSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); } QList QmitkAbstractView::GetDataManagerSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsDataManagerSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager"); } void QmitkAbstractView::SetDataManagerSelection(const berry::ISelection::ConstPointer &selection, QItemSelectionModel::SelectionFlags flags) const { berry::IViewPart::Pointer datamanagerView = this->GetSite()->GetWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.datamanager"); if (datamanagerView.IsNull()) return; datamanagerView->GetSite()->GetSelectionProvider().Cast()->SetSelection(selection, flags); } void QmitkAbstractView::SynchronizeDataManagerSelection() const { berry::ISelection::ConstPointer currentSelection = this->GetSite()->GetSelectionProvider()->GetSelection(); if (currentSelection.IsNull()) return; SetDataManagerSelection(currentSelection); } void QmitkAbstractView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& /*nodes*/) { } void QmitkAbstractView::OnNullSelection(berry::IWorkbenchPart::Pointer /*part*/) { } QList QmitkAbstractViewPrivate::DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const { - if (currentSelection.IsNull()) return QList(); - return QList::fromStdList(currentSelection->GetSelectedDataNodes()); + if (currentSelection.IsNull()) + return QList(); + + auto nodes = currentSelection->GetSelectedDataNodes(); + + return QList(nodes.begin(), nodes.end()); } void QmitkAbstractView::NodeAdded( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeRemoved( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeChanged( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::FireNodeSelected( mitk::DataNode::Pointer node ) { QList nodes; nodes << node; this->FireNodesSelected(nodes); } void QmitkAbstractView::FireNodesSelected( const QList& nodes ) { // if this is the first call to FireNodesSelected and the selection provider has no QItemSelectiomMode // yet, set our helper model if (d->m_SelectionProvider->GetItemSelectionModel() == nullptr) { d->m_SelectionProvider->SetItemSelectionModel(d->m_DataNodeSelectionModel); } else if (d->m_SelectionProvider->GetItemSelectionModel() != d->m_DataNodeSelectionModel) { MITK_WARN << "A custom data node selection model has been set. Ignoring call to FireNodesSelected()."; return; } if (nodes.empty()) { d->m_DataNodeSelectionModel->clearSelection(); d->m_DataNodeItemModel->clear(); } else { // The helper data node model is just used for sending selection events. // We add the to be selected nodes and set the selection range to everything. d->m_DataNodeItemModel->clear(); foreach(mitk::DataNode::Pointer node, nodes) { d->m_DataNodeItemModel->AddDataNode(node); } d->m_DataNodeSelectionModel->select(QItemSelection(d->m_DataNodeItemModel->index(0,0), d->m_DataNodeItemModel->index(nodes.size()-1, 0)), QItemSelectionModel::ClearAndSelect); } } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp index 674d0e9758..5f3a5efc1d 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp @@ -1,126 +1,127 @@ /*============================================================================ 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. ============================================================================*/ // mitk gui qt common plugin #include "QmitkSelectionServiceConnector.h" #include "internal/QmitkDataNodeSelection.h" // qt widgets module #include "QmitkCustomVariants.h" #include "QmitkEnums.h" // blueberry ui qt plugin #include QmitkSelectionServiceConnector::QmitkSelectionServiceConnector() : m_SelectionService(nullptr) , m_SelectionProvider(nullptr) { m_DataNodeItemModel = std::make_shared(); m_DataNodeSelectionModel = std::make_shared(m_DataNodeItemModel.get()); } QmitkSelectionServiceConnector::~QmitkSelectionServiceConnector() { RemovePostSelectionListener(); RemoveAsSelectionProvider(); } void QmitkSelectionServiceConnector::AddPostSelectionListener(berry::ISelectionService* selectionService) { if (nullptr == selectionService) { return; } m_SelectionService = selectionService; m_BerrySelectionListener.reset(new berry::NullSelectionChangedAdapter(this, &QmitkSelectionServiceConnector::OnServiceSelectionChanged)); m_SelectionService->AddPostSelectionListener(m_BerrySelectionListener.get()); } void QmitkSelectionServiceConnector::RemovePostSelectionListener() { if (nullptr == m_SelectionService) { return; } m_SelectionService->RemovePostSelectionListener(m_BerrySelectionListener.get()); m_SelectionService = nullptr; } void QmitkSelectionServiceConnector::SetAsSelectionProvider(QmitkDataNodeSelectionProvider* selectionProvider) { m_SelectionProvider = selectionProvider; } void QmitkSelectionServiceConnector::RemoveAsSelectionProvider() { m_SelectionProvider = nullptr; } void QmitkSelectionServiceConnector::ChangeServiceSelection(QList nodes) { if (nullptr == m_SelectionProvider) { return; } m_SelectionProvider->SetItemSelectionModel(m_DataNodeSelectionModel.get()); if (nodes.empty()) { m_DataNodeSelectionModel->clearSelection(); m_DataNodeItemModel->clear(); } else { m_DataNodeItemModel->clear(); // fill the temporary helper data node item model with the nodes to select for (const auto& node : nodes) { m_DataNodeItemModel->AddDataNode(node); } m_DataNodeSelectionModel->select(QItemSelection(m_DataNodeItemModel->index(0, 0), m_DataNodeItemModel->index(nodes.size() - 1, 0)), QItemSelectionModel::ClearAndSelect); } } void QmitkSelectionServiceConnector::OnServiceSelectionChanged(const berry::IWorkbenchPart::Pointer& sourcePart, const berry::ISelection::ConstPointer& selection) { if (sourcePart.IsNull()) { return; } QList nodes; if (selection.IsNull()) { emit ServiceNullSelection(sourcePart); return; } // transform valid selection to DataNodeSelection, which allows to retrieve the selected nodes mitk::DataNodeSelection::ConstPointer dataNodeSelection = selection.Cast(); if (dataNodeSelection.IsNull()) { // propagate an empty list nodes = QList(); } else { - nodes = QList::fromStdList(dataNodeSelection->GetSelectedDataNodes()); + auto selectedNodes = dataNodeSelection->GetSelectedDataNodes(); + nodes = QList(selectedNodes.begin(), selectedNodes.end()); } // send new (possibly empty) list of selected nodes emit ServiceSelectionChanged(nodes); }