diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp index e14078520e..f3a995d112 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/SimpleRenderWindowView.cpp @@ -1,212 +1,206 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "SimpleRenderWindowView.h" #include #include "org_mitk_example_gui_customviewer_views_Activator.h" -#include -#include #include #include #include #include #include /** * \brief Helper class adapted from QmitkAbstractRenderEditor by defining the correct plugin context. * * This helper class adapted from QmitkAbstractRenderEditor provides the rendering manager interface. */ // //! [SimpleRenderWindowViewHelper] class AbstractRenderWindowViewPrivate { public: AbstractRenderWindowViewPrivate() - : m_RenderingManagerInterface(mitk::MakeRenderingManagerInterface(mitk::RenderingManager::GetInstance())), - m_PrefServiceTracker(org_mitk_example_gui_customviewer_views_Activator::GetPluginContext()) + : m_RenderingManagerInterface(mitk::MakeRenderingManagerInterface(mitk::RenderingManager::GetInstance())) // //! [SimpleRenderWindowViewHelper] { - m_PrefServiceTracker.open(); } ~AbstractRenderWindowViewPrivate() { delete m_RenderingManagerInterface; } mitk::IRenderingManager *m_RenderingManagerInterface; - ctkServiceTracker m_PrefServiceTracker; - berry::IBerryPreferences::Pointer m_Prefs; }; const std::string SimpleRenderWindowView::VIEW_ID = "org.mitk.customviewer.views.simplerenderwindowview"; SimpleRenderWindowView::SimpleRenderWindowView() : m_RenderWindow(nullptr), d(new AbstractRenderWindowViewPrivate) { } SimpleRenderWindowView::~SimpleRenderWindowView() { } QmitkRenderWindow *SimpleRenderWindowView::GetActiveQmitkRenderWindow() const { return m_RenderWindow; } QHash SimpleRenderWindowView::GetRenderWindows() const { QHash wnds; wnds.insert("axial", m_RenderWindow); return wnds; } QHash SimpleRenderWindowView::GetQmitkRenderWindows() const { QHash wnds; wnds.insert("axial", m_RenderWindow); return wnds; } QmitkRenderWindow *SimpleRenderWindowView::GetRenderWindow(const QString &id) const { if (id == "axial") { return m_RenderWindow; } return nullptr; } QmitkRenderWindow *SimpleRenderWindowView::GetQmitkRenderWindow(const QString &id) const { if (id == "axial") { return m_RenderWindow; } return nullptr; } QmitkRenderWindow *SimpleRenderWindowView::GetQmitkRenderWindow(const mitk::BaseRenderer::ViewDirection &viewDirection) const { if (viewDirection == mitk::BaseRenderer::ViewDirection::AXIAL) { return m_RenderWindow; } return 0; } void SimpleRenderWindowView::SetFocus() { m_RenderWindow->setFocus(); } // //! [SimpleRenderWindowViewCreatePartControl] void SimpleRenderWindowView::CreateQtPartControl(QWidget *parent) { QVBoxLayout *layout = new QVBoxLayout(parent); layout->setContentsMargins(0, 0, 0, 0); m_RenderWindow = new QmitkRenderWindow(parent); layout->addWidget(m_RenderWindow); mitk::DataStorage::Pointer ds = this->GetDataStorage(); m_RenderWindow->GetRenderer()->SetDataStorage(ds); this->RequestUpdate(); } // //! [SimpleRenderWindowViewCreatePartControl] mitk::IRenderingManager *SimpleRenderWindowView::GetRenderingManager() const { // we use the global rendering manager here. This should maybe replaced // by a local one, managing only the render windows specific for the view return d->m_RenderingManagerInterface; } void SimpleRenderWindowView::RequestUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->RequestUpdateAll(requestType); } void SimpleRenderWindowView::ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->ForceImmediateUpdateAll(requestType); } void SimpleRenderWindowView::SetReferenceGeometry(const mitk::TimeGeometry* /*referenceGeometry*/, bool /*resetCamera*/) { // not implemented } bool SimpleRenderWindowView::HasCoupledRenderWindows() const { return false; } mitk::SliceNavigationController *SimpleRenderWindowView::GetTimeNavigationController() const { if (GetRenderingManager()) return GetRenderingManager()->GetTimeNavigationController(); return nullptr; } mitk::Point3D SimpleRenderWindowView::GetSelectedPosition(const QString& /*id*/) const { const mitk::PlaneGeometry* pg = m_RenderWindow->GetSliceNavigationController()->GetCurrentPlaneGeometry(); if (pg) { return pg->GetCenter(); } else { return mitk::Point3D(); } } void SimpleRenderWindowView::SetSelectedPosition(const mitk::Point3D&, const QString&) { } mitk::TimePointType SimpleRenderWindowView::GetSelectedTimePoint(const QString& /*id*/) const { auto timeNavigator = this->GetTimeNavigationController(); if (nullptr != timeNavigator) { return timeNavigator->GetSelectedTimePoint(); } return 0; } void SimpleRenderWindowView::EnableDecorations(bool enable, const QStringList& decorations) { if (decorations.isEmpty() || decorations.contains(DECORATION_MENU)) { m_RenderWindow->ActivateMenuWidget(enable); } } bool SimpleRenderWindowView::IsDecorationEnabled(const QString& decoration) const { if (decoration == DECORATION_MENU) { return m_RenderWindow->GetActivateMenuWidgetFlag(); } return false; } QStringList SimpleRenderWindowView::GetDecorations() const { QStringList decorations; decorations << DECORATION_MENU; return decorations; } diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp index 05e163edb3..1f7eabc4db 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp @@ -1,160 +1,161 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkIsoSurface.h" // MITK headers #include #include #include +#include // Qt-GUI headers #include #include #include QmitkIsoSurface::QmitkIsoSurface(QObject * /*parent*/, const char * /*name*/) : m_Controls(nullptr), m_MitkImage(nullptr), m_SurfaceCounter(0) { } void QmitkIsoSurface::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkIsoSurfaceControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_ImageSelector->SetDataStorage(this->GetDataStorage()); m_Controls->m_ImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); - berry::IPreferences::Pointer prefs = this->GetPreferences(); - if (prefs.IsNotNull()) - m_Controls->thresholdLineEdit->setText(prefs->Get("defaultThreshold", "0")); + auto* prefs = this->GetPreferences(); + if (prefs != nullptr) + m_Controls->thresholdLineEdit->setText(QString::fromStdString(prefs->Get("defaultThreshold", "0"))); } } void QmitkIsoSurface::SetFocus() { m_Controls->m_ImageSelector->setFocus(); } void QmitkIsoSurface::CreateConnections() { if (m_Controls) { connect(m_Controls->m_ImageSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode *)), this, SLOT(ImageSelected(const mitk::DataNode *))); connect(m_Controls->createSurfacePushButton, SIGNAL(clicked()), this, SLOT(CreateSurface())); } } void QmitkIsoSurface::ImageSelected(const mitk::DataNode *item) { // nothing selected (nullptr selection) if (item == nullptr || item->GetData() == nullptr) return; m_MitkImage = dynamic_cast(item->GetData()); } void QmitkIsoSurface::CreateSurface() { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); if (m_MitkImage != nullptr) { // Value Gauss // float gsDev = 1.5; // Value for DecimatePro float targetReduction = 0.05; // ImageToSurface Instance mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode(); mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout << "nullptr Pointer for ManualSegmentationToSurfaceFilter" << std::endl; return; } filter->SetInput(m_MitkImage); filter->SetGaussianStandardDeviation(0.5); filter->SetUseGaussianImageSmooth(true); filter->SetThreshold(getThreshold()); // if( Gauss ) --> TH manipulated for vtkMarchingCube filter->SetTargetReduction(targetReduction); int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys(); if (numOfPolys > 2000000) { QApplication::restoreOverrideCursor(); if (QMessageBox::question(nullptr, "CAUTION!!!", "The number of polygons is greater than 2 000 000. If you continue, the program might " "crash. How do you want to go on?", "Proceed anyway!", "Cancel immediately! (maybe you want to insert an other threshold)!", QString::null, 0, 1) == 1) { return; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); } mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetData(filter->GetOutput()); int layer = 0; ++m_SurfaceCounter; std::ostringstream buffer; buffer << m_SurfaceCounter; std::string surfaceNodeName = "Surface " + buffer.str(); node->GetIntProperty("layer", layer); surfaceNode->SetIntProperty("layer", layer + 1); surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true)); surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName)); this->GetDataStorage()->Add(surfaceNode, node); // to show surfaceContur surfaceNode->SetColor(m_RainbowColor.GetNextColor()); surfaceNode->SetVisibility(true); mitk::IRenderWindowPart *renderPart = this->GetRenderWindowPart(); if (renderPart) { renderPart->RequestUpdate(); } } QApplication::restoreOverrideCursor(); } float QmitkIsoSurface::getThreshold() { return m_Controls->thresholdLineEdit->text().toFloat(); } QmitkIsoSurface::~QmitkIsoSurface() { - berry::IPreferences::Pointer prefs = this->GetPreferences(); - if (prefs.IsNotNull()) - prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text()); + auto* prefs = this->GetPreferences(); + if (prefs != nullptr) + prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text().toStdString()); } diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/mitkPluginActivator.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/mitkPluginActivator.cpp index 50898eff00..7faa4762d0 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/mitkPluginActivator.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/mitkPluginActivator.cpp @@ -1,36 +1,40 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "src/internal/colourimageprocessing/QmitkColourImageProcessingView.h" #include "src/internal/isosurface/QmitkIsoSurface.h" #include "src/internal/simpleexample/QmitkSimpleExampleView.h" #include "src/internal/simplemeasurement/QmitkSimpleMeasurement.h" #include "src/internal/surfaceutilities/QmitkSurfaceUtilities.h" #include "src/internal/viewinitialization/QmitkViewInitializationView.h" #include "src/internal/volumetry/QmitkVolumetryView.h" +#include + +US_INITIALIZE_MODULE + namespace mitk { void PluginActivator::start(ctkPluginContext *context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkColourImageProcessingView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkIsoSurface, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSimpleExampleView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSimpleMeasurement, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkViewInitializationView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkVolumetryView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSurfaceUtilities, context) } void PluginActivator::stop(ctkPluginContext *context) { Q_UNUSED(context) } } diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp index 90af8f2e7e..5a3a4597af 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp @@ -1,418 +1,422 @@ /*============================================================================ 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 "QmitkSimpleExampleView.h" #include #include #include #include #include #include #include "QmitkRenderWindow.h" #include "QmitkStepperAdapter.h" #include "QmitkFFmpegWriter.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkProperties.h" +#include +#include +#include #include #include #include #include -#include const std::string QmitkSimpleExampleView::VIEW_ID = "org.mitk.views.simpleexample"; QmitkSimpleExampleView::QmitkSimpleExampleView() : m_Controls(nullptr), m_NavigatorsInitialized(false), m_Parent(nullptr) { } QmitkSimpleExampleView::~QmitkSimpleExampleView() { } void QmitkSimpleExampleView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Parent = parent; // create GUI widgets m_Controls = new Ui::QmitkSimpleExampleViewControls; m_Controls->setupUi(parent); this->CreateConnections(); this->RenderWindowPartActivated(this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)); } } void QmitkSimpleExampleView::SetFocus() { m_Controls->renderWindowComboBox->setFocus(); } void QmitkSimpleExampleView::RenderWindowPartActivated(mitk::IRenderWindowPart *renderWindowPart) { if (renderWindowPart == nullptr) { m_Parent->setEnabled(false); return; } QHashIterator renderIter(renderWindowPart->GetQmitkRenderWindows()); while (renderIter.hasNext()) { renderIter.next(); m_Controls->renderWindowComboBox->addItem(renderIter.key()); } RenderWindowSelected(m_Controls->renderWindowComboBox->currentText()); m_TimeStepper.reset(new QmitkStepperAdapter(m_Controls->sliceNavigatorTime, renderWindowPart->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample")); m_MovieStepper.reset(new QmitkStepperAdapter(m_Controls->movieNavigatorTime, renderWindowPart->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample")); m_Parent->setEnabled(true); } void QmitkSimpleExampleView::RenderWindowPartDeactivated(mitk::IRenderWindowPart * /*renderWindowPart*/) { m_Parent->setEnabled(false); m_SliceStepper.reset(); m_TimeStepper.reset(); m_MovieStepper.reset(); m_Controls->renderWindowComboBox->clear(); } void QmitkSimpleExampleView::CreateConnections() { if (m_Controls) { connect(m_Controls->renderWindowComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(RenderWindowSelected(QString))); connect(m_Controls->stereoSelect, SIGNAL(activated(int)), this, SLOT(StereoSelectionChanged(int))); connect(m_Controls->reInitializeNavigatorsButton, SIGNAL(clicked()), this, SLOT(InitNavigators())); connect(m_Controls->genMovieButton, SIGNAL(clicked()), this, SLOT(GenerateMovie())); connect(m_Controls->m_TakeScreenshotBtn, SIGNAL(clicked()), this, SLOT(OnTakeScreenshot())); connect(m_Controls->m_TakeHighResScreenShotBtn, SIGNAL(clicked()), this, SLOT(OnTakeHighResolutionScreenshot())); } } void QmitkSimpleExampleView::InitNavigators() { /* get all nodes that have not set "includeInBoundingBox" to false */ mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New( mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); /* calculate bounding geometry of these nodes */ auto bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs); /* initialize the views to the bounding geometry */ m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } /** * Returns path to the ffmpeg lib if configured in preferences. * * This implementation has been reused from MovieMaker view. * * @return The path to ffmpeg lib or empty string if not configured. */ QString QmitkSimpleExampleView::GetFFmpegPath() const { - berry::IPreferences::Pointer preferences = - berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.gui.qt.ext.externalprograms"); + auto* preferences = + mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.gui.qt.ext.externalprograms"); - return preferences.IsNotNull() ? preferences->Get("ffmpeg", "") : ""; + return preferences != nullptr + ? QString::fromStdString(preferences->Get("ffmpeg", "")) + : QString(""); } /** * Reads pixels from specified render window. * * This implementation has been reused from MovieMaker view. * * @param renderWindow * @param x * @param y * @param width * @param height * @return */ static unsigned char *ReadPixels(vtkRenderWindow *renderWindow, int x, int y, int width, int height) { if (renderWindow == nullptr) return nullptr; unsigned char *frame = new unsigned char[width * height * 3]; renderWindow->MakeCurrent(); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, frame); return frame; } /** * Records a movie from the selected render window with a default frame rate of 30 Hz. * * Parts of this implementation have been reused from MovieMaker view. */ void QmitkSimpleExampleView::GenerateMovie() { QmitkRenderWindow *movieRenderWindow = GetSelectedRenderWindow(); mitk::Stepper::Pointer stepper = movieRenderWindow->GetSliceNavigationController()->GetSlice(); QmitkFFmpegWriter *movieWriter = new QmitkFFmpegWriter(m_Parent); const QString ffmpegPath = GetFFmpegPath(); if (ffmpegPath.isEmpty()) { QMessageBox::information( nullptr, "Movie Maker", "

Set path to FFmpeg1 in preferences (Window -> Preferences... " "(Ctrl+P) -> External Programs) to be able to record your movies to video files.

" "

If you are using Linux, chances are good that FFmpeg is included in the official package " "repositories.

" "

[1] Download FFmpeg from ffmpeg.org

"); return; } movieWriter->SetFFmpegPath(GetFFmpegPath()); vtkRenderWindow *renderWindow = movieRenderWindow->renderWindow(); if (renderWindow == nullptr) return; const int border = 3; const int x = border; const int y = border; int width = renderWindow->GetSize()[0] - border * 2; int height = renderWindow->GetSize()[1] - border * 2; if (width & 1) --width; if (height & 1) --height; if (width < 16 || height < 16) return; movieWriter->SetSize(width, height); movieWriter->SetFramerate(30); QString saveFileName = QFileDialog::getSaveFileName(nullptr, "Specify a filename", "", "Movie (*.mp4)"); if (saveFileName.isEmpty()) return; if (!saveFileName.endsWith(".mp4")) saveFileName += ".mp4"; movieWriter->SetOutputPath(saveFileName); const unsigned int numberOfFrames = stepper->GetSteps() - stepper->GetPos(); try { movieWriter->Start(); for (unsigned int currentFrame = 0; currentFrame < numberOfFrames; ++currentFrame) { mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); renderWindow->MakeCurrent(); unsigned char *frame = ReadPixels(renderWindow, x, y, width, height); movieWriter->WriteFrame(frame); delete[] frame; stepper->Next(); } movieWriter->Stop(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } catch (const mitk::Exception &exception) { mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); QMessageBox::critical(nullptr, "Generate Movie", exception.GetDescription()); } } void QmitkSimpleExampleView::StereoSelectionChanged(int id) { /* From vtkRenderWindow.h tells us about stereo rendering: Set/Get what type of stereo rendering to use. CrystalEyes mode uses frame-sequential capabilities available in OpenGL to drive LCD shutter glasses and stereo projectors. RedBlue mode is a simple type of stereo for use with red-blue glasses. Anaglyph mode is a superset of RedBlue mode, but the color output channels can be configured using the AnaglyphColorMask and the color of the original image can be (somewhat maintained using AnaglyphColorSaturation; the default colors for Anaglyph mode is red-cyan. Interlaced stereo mode produces a composite image where horizontal lines alternate between left and right views. StereoLeft and StereoRight modes choose one or the other stereo view. Dresden mode is yet another stereoscopic interleaving. */ auto *renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN); vtkRenderWindow *vtkrenderwindow = renderWindowPart->GetQmitkRenderWindow("3d")->GetVtkRenderWindow(); // note: foreground vtkRenderers (at least the department logo renderer) produce errors in stereoscopic visualization. // Therefore, we disable the logo visualization during stereo rendering. switch (id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); renderWindowPart->EnableDecorations(false, QStringList(mitk::IRenderWindowPart::DECORATION_LOGO)); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); renderWindowPart->EnableDecorations(false, QStringList(mitk::IRenderWindowPart::DECORATION_LOGO)); break; } mitk::BaseRenderer::GetInstance(vtkrenderwindow)->SetMapperID(mitk::BaseRenderer::Standard3D); renderWindowPart->RequestUpdate(); } QmitkRenderWindow *QmitkSimpleExampleView::GetSelectedRenderWindow() const { QString id = m_Controls->renderWindowComboBox->currentText(); if (id.isEmpty()) { return nullptr; } else { return this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow(id); } } void QmitkSimpleExampleView::OnTakeHighResolutionScreenshot() { QString filter; QString fileName = QFileDialog::getSaveFileName( nullptr, "Save screenshot to...", QDir::currentPath(), m_PNGExtension + ";;" + m_JPGExtension, &filter); vtkRenderer *renderer = this->GetSelectedRenderWindow()->GetRenderer()->GetVtkRenderer(); if (renderer == nullptr) return; this->TakeScreenshot(renderer, 4, fileName, filter); } void QmitkSimpleExampleView::OnTakeScreenshot() { QString filter; QString fileName = QFileDialog::getSaveFileName( nullptr, "Save screenshot to...", QDir::currentPath(), m_PNGExtension + ";;" + m_JPGExtension, &filter); QmitkRenderWindow *renWin = this->GetSelectedRenderWindow(); if (renWin == nullptr) return; vtkRenderer *renderer = renWin->GetRenderer()->GetVtkRenderer(); if (renderer == nullptr) return; this->TakeScreenshot(renderer, 1, fileName, filter); } void QmitkSimpleExampleView::TakeScreenshot(vtkRenderer *renderer, unsigned int magnificationFactor, QString fileName, QString filter) { if ((renderer == nullptr) || (magnificationFactor < 1) || fileName.isEmpty()) return; bool doubleBuffering(renderer->GetRenderWindow()->GetDoubleBuffer()); renderer->GetRenderWindow()->DoubleBufferOff(); vtkImageWriter *fileWriter = nullptr; QFileInfo fi(fileName); QString suffix = fi.suffix().toLower(); if (suffix.isEmpty() || (suffix != "png" && suffix != "jpg" && suffix != "jpeg")) { if (filter == m_PNGExtension) { suffix = "png"; } else if (filter == m_JPGExtension) { suffix = "jpg"; } fileName += "." + suffix; } if (suffix.compare("jpg", Qt::CaseInsensitive) == 0 || suffix.compare("jpeg", Qt::CaseInsensitive) == 0) { vtkJPEGWriter *w = vtkJPEGWriter::New(); w->SetQuality(100); w->ProgressiveOff(); fileWriter = w; } else // default is png { fileWriter = vtkPNGWriter::New(); } vtkRenderLargeImage *magnifier = vtkRenderLargeImage::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(magnificationFactor); fileWriter->SetInputConnection(magnifier->GetOutputPort()); fileWriter->SetFileName(fileName.toLatin1()); // vtkRenderLargeImage has problems with different layers, therefore we have to // temporarily deactivate all other layers. // we set the background to white, because it is nicer than black... double oldBackground[3]; renderer->GetBackground(oldBackground); double white[] = {1.0, 1.0, 1.0}; renderer->SetBackground(white); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN); renderWindowPart->EnableDecorations(false); fileWriter->Write(); fileWriter->Delete(); renderWindowPart->EnableDecorations(true); renderer->SetBackground(oldBackground); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void QmitkSimpleExampleView::RenderWindowSelected(const QString &id) { if (!id.isEmpty()) { m_SliceStepper.reset(new QmitkStepperAdapter( m_Controls->sliceNavigator, this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow(id)->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFromSimpleExample")); } } diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp index d32e0cb451..ae6aa52bb7 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp @@ -1,303 +1,302 @@ /*============================================================================ 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 "QmitkSimpleMeasurement.h" #include "ui_QmitkSimpleMeasurementControls.h" #include #include #include #include #include #include -#include QmitkSimpleMeasurement::QmitkSimpleMeasurement() { } QmitkSimpleMeasurement::~QmitkSimpleMeasurement() { // remove all measurements when view is closed for (std::size_t i = 0; i < m_CreatedDistances.size(); i++) { this->GetDataStorage()->Remove(m_CreatedDistances.at(i)); } for (std::size_t i = 0; i < m_CreatedAngles.size(); i++) { this->GetDataStorage()->Remove(m_CreatedAngles.at(i)); } for (std::size_t i = 0; i < m_CreatedPaths.size(); i++) { this->GetDataStorage()->Remove(m_CreatedPaths.at(i)); } if (m_PointSetInteractor.IsNotNull()) { m_SelectedPointSetNode->SetDataInteractor(nullptr); } } void QmitkSimpleMeasurement::Activated() { this->OnSelectionChanged(berry::IWorkbenchPart::Pointer(), this->GetCurrentSelection()); } void QmitkSimpleMeasurement::Deactivated() { } void QmitkSimpleMeasurement::Visible() { } void QmitkSimpleMeasurement::Hidden() { } void QmitkSimpleMeasurement::ActivatedZombieView(berry::SmartPointer /*zombieView*/) { // something else was selected. remove old interactor if (m_PointSetInteractor.IsNotNull()) { m_SelectedPointSetNode->SetDataInteractor(nullptr); } } void QmitkSimpleMeasurement::AddDistanceSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); QString name = "Distance " + QString::number(m_CreatedDistances.size() + 1); mitk::DataNode::Pointer CurrentPointSetNode = mitk::DataNode::New(); CurrentPointSetNode->SetData(pointSet); CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New(name.toStdString())); CurrentPointSetNode->SetProperty("show distances", mitk::BoolProperty::New(true)); // add to ds and remember as created m_CreatedDistances.push_back(CurrentPointSetNode); this->GetDataStorage()->Add(CurrentPointSetNode); // make new selection QList selection; selection.push_back(CurrentPointSetNode); this->FireNodesSelected(selection); this->OnSelectionChanged(berry::IWorkbenchPart::Pointer(), selection); } void QmitkSimpleMeasurement::AddAngleSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); QString name = "Angle " + QString::number(m_CreatedAngles.size() + 1); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New(name.toStdString())); _CurrentPointSetNode->SetProperty("show angles", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedAngles.push_back(_CurrentPointSetNode); // make new selection QList selection; selection.push_back(_CurrentPointSetNode); this->FireNodesSelected(selection); this->OnSelectionChanged(berry::IWorkbenchPart::Pointer(), selection); } void QmitkSimpleMeasurement::AddPathSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); QString name = "Path " + QString::number(m_CreatedPaths.size() + 1); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New(name.toStdString())); _CurrentPointSetNode->SetProperty("show distances", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("show angles", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPaths.push_back(_CurrentPointSetNode); // make new selection QList selection; selection.push_back(_CurrentPointSetNode); this->FireNodesSelected(selection); this->OnSelectionChanged(berry::IWorkbenchPart::Pointer(), selection); } void QmitkSimpleMeasurement::CreateQtPartControl(QWidget *parent) { m_CreatedDistances = std::vector(); m_CreatedAngles = std::vector(); m_CreatedPaths = std::vector(); m_Controls = new Ui::QmitkSimpleMeasurementControls; m_Controls->setupUi(parent); connect( (QObject *)(m_Controls->pbDistance), SIGNAL(clicked()), (QObject *)this, SLOT(AddDistanceSimpleMeasurement())); connect((QObject *)(m_Controls->pbAngle), SIGNAL(clicked()), (QObject *)this, SLOT(AddAngleSimpleMeasurement())); connect((QObject *)(m_Controls->pbPath), SIGNAL(clicked()), (QObject *)this, SLOT(AddPathSimpleMeasurement())); connect((QObject *)(m_Controls->m_Finished), SIGNAL(clicked()), (QObject *)this, SLOT(Finished())); EndEditingMeasurement(); } void QmitkSimpleMeasurement::SetFocus() { m_Controls->m_Finished->setFocus(); } void QmitkSimpleMeasurement::Finished() { OnSelectionChanged(berry::IWorkbenchPart::Pointer(), QList()); } void QmitkSimpleMeasurement::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList &nodes) { mitk::DataNode::Pointer selectedNode; if (nodes.size() > 0) selectedNode = nodes.front(); mitk::PointSet *pointSet = nullptr; if (selectedNode.IsNotNull()) pointSet = dynamic_cast(selectedNode->GetData()); // something else was selected. remove old interactor if (m_PointSetInteractor.IsNotNull()) { m_SelectedPointSetNode->SetDataInteractor(nullptr); } bool pointsetCreatedByThis = false; // only go further if a pointset was selected if (pointSet) { // see if this pointset was created by us std::vector::iterator it = std::find(m_CreatedDistances.begin(), m_CreatedDistances.end(), selectedNode); if (it != m_CreatedDistances.end()) pointsetCreatedByThis = true; it = std::find(m_CreatedAngles.begin(), m_CreatedAngles.end(), selectedNode); if (it != m_CreatedAngles.end()) pointsetCreatedByThis = true; it = std::find(m_CreatedPaths.begin(), m_CreatedPaths.end(), selectedNode); if (it != m_CreatedPaths.end()) pointsetCreatedByThis = true; } // do nothing if it was not created by us or it is no pointset node or we are not activated if (pointsetCreatedByThis) { // otherwise: set text and add interactor for the pointset m_Controls->selectedPointSet->setText(QString::fromStdString(selectedNode->GetName())); m_PointSetInteractor = mitk::PointSetDataInteractor::New(); m_PointSetInteractor->LoadStateMachine("PointSet.xml"); m_PointSetInteractor->SetEventConfig("PointSetConfig.xml"); m_PointSetInteractor->SetDataNode(selectedNode); float green[] = {0, 255, 0}; float red[] = {255, 0, 0}; selectedNode->SetColor(green); if (m_SelectedPointSetNode.IsNotNull()) m_SelectedPointSetNode->SetColor(red); m_SelectedPointSetNode = selectedNode; StartEditingMeasurement(); } else { EndEditingMeasurement(); } } void QmitkSimpleMeasurement::NodeRemoved(const mitk::DataNode *node) { // remove a node if it is destroyed from our created array m_CreatedDistances.erase(std::remove(m_CreatedDistances.begin(), m_CreatedDistances.end(), node), m_CreatedDistances.end()); m_CreatedAngles.erase(std::remove(m_CreatedAngles.begin(), m_CreatedAngles.end(), node), m_CreatedAngles.end()); m_CreatedPaths.erase(std::remove(m_CreatedPaths.begin(), m_CreatedPaths.end(), node), m_CreatedPaths.end()); } void QmitkSimpleMeasurement::StartEditingMeasurement() { m_Controls->explain_label->setVisible(true); m_Controls->m_Finished->setVisible(true); m_Controls->pbDistance->setEnabled(false); m_Controls->pbAngle->setEnabled(false); m_Controls->pbPath->setEnabled(false); UpdateMeasurementList(); } void QmitkSimpleMeasurement::EndEditingMeasurement() { m_Controls->pbDistance->setEnabled(true); m_Controls->pbAngle->setEnabled(true); m_Controls->pbPath->setEnabled(true); m_Controls->explain_label->setVisible(false); m_Controls->m_Finished->setVisible(false); m_Controls->selectedPointSet->setText("None"); UpdateMeasurementList(); } void QmitkSimpleMeasurement::UpdateMeasurementList() { m_Controls->m_MeasurementList->clear(); for (std::size_t i = 0; i < m_CreatedDistances.size(); i++) { QListWidgetItem *newItem = new QListWidgetItem; QString distance; mitk::PointSet::Pointer points = dynamic_cast(m_CreatedDistances.at(i)->GetData()); if (points->GetSize() < 2) { distance = "not available"; } else { distance = QString::number(points->GetPoint(0).EuclideanDistanceTo(points->GetPoint(1))) + " mm"; } QString name = QString(m_CreatedDistances.at(i)->GetName().c_str()) + " (" + distance + ")"; newItem->setText(name); m_Controls->m_MeasurementList->insertItem(m_Controls->m_MeasurementList->count(), newItem); } for (std::size_t i = 0; i < m_CreatedAngles.size() && i < m_CreatedDistances.size(); i++) { QListWidgetItem *newItem = new QListWidgetItem; QString name = m_CreatedDistances.at(i)->GetName().c_str(); newItem->setText(name); m_Controls->m_MeasurementList->insertItem(m_Controls->m_MeasurementList->count(), newItem); } for (std::size_t i = 0; i < m_CreatedPaths.size() && i < m_CreatedDistances.size(); i++) { QListWidgetItem *newItem = new QListWidgetItem; QString name = m_CreatedDistances.at(i)->GetName().c_str(); newItem->setText(name); m_Controls->m_MeasurementList->insertItem(m_Controls->m_MeasurementList->count(), newItem); } } diff --git a/Modules/AppUtil/src/mitkBaseApplication.cpp b/Modules/AppUtil/src/mitkBaseApplication.cpp index 6f7254574e..da46925834 100644 --- a/Modules/AppUtil/src/mitkBaseApplication.cpp +++ b/Modules/AppUtil/src/mitkBaseApplication.cpp @@ -1,889 +1,897 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include +#include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { void outputQtMessage(QtMsgType type, const QMessageLogContext&, const QString& msg) { auto message = msg.toStdString(); switch (type) { case QtDebugMsg: MITK_DEBUG << message; break; case QtInfoMsg: MITK_INFO << message; break; case QtWarningMsg: MITK_WARN << message; break; case QtCriticalMsg: MITK_ERROR << message; break; case QtFatalMsg: MITK_ERROR << message; abort(); default: MITK_INFO << message; break; } } } namespace mitk { const QString BaseApplication::ARG_APPLICATION = "BlueBerry.application"; const QString BaseApplication::ARG_CLEAN = "BlueBerry.clean"; const QString BaseApplication::ARG_CONSOLELOG = "BlueBerry.consoleLog"; const QString BaseApplication::ARG_DEBUG = "BlueBerry.debug"; const QString BaseApplication::ARG_FORCE_PLUGIN_INSTALL = "BlueBerry.forcePlugins"; const QString BaseApplication::ARG_HOME = "BlueBerry.home"; const QString BaseApplication::ARG_NEWINSTANCE = "BlueBerry.newInstance"; const QString BaseApplication::ARG_NO_LAZY_REGISTRY_CACHE_LOADING = "BlueBerry.noLazyRegistryCacheLoading"; const QString BaseApplication::ARG_NO_REGISTRY_CACHE = "BlueBerry.noRegistryCache"; const QString BaseApplication::ARG_PLUGIN_CACHE = "BlueBerry.plugin_cache_dir"; const QString BaseApplication::ARG_PLUGIN_DIRS = "BlueBerry.plugin_dirs"; const QString BaseApplication::ARG_PRELOAD_LIBRARY = "BlueBerry.preloadLibrary"; const QString BaseApplication::ARG_PRODUCT = "BlueBerry.product"; const QString BaseApplication::ARG_PROVISIONING = "BlueBerry.provisioning"; const QString BaseApplication::ARG_REGISTRY_MULTI_LANGUAGE = "BlueBerry.registryMultiLanguage"; const QString BaseApplication::ARG_SPLASH_IMAGE = "BlueBerry.splashscreen"; const QString BaseApplication::ARG_STORAGE_DIR = "BlueBerry.storageDir"; const QString BaseApplication::ARG_XARGS = "xargs"; const QString BaseApplication::ARG_LOG_QT_MESSAGES = "Qt.logMessages"; const QString BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET = "Segmentation.labelSetPreset"; const QString BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS = "Segmentation.labelSuggestions"; const QString BaseApplication::PROP_APPLICATION = "blueberry.application"; const QString BaseApplication::PROP_FORCE_PLUGIN_INSTALL = BaseApplication::ARG_FORCE_PLUGIN_INSTALL; const QString BaseApplication::PROP_NEWINSTANCE = BaseApplication::ARG_NEWINSTANCE; const QString BaseApplication::PROP_NO_LAZY_REGISTRY_CACHE_LOADING = BaseApplication::ARG_NO_LAZY_REGISTRY_CACHE_LOADING; const QString BaseApplication::PROP_NO_REGISTRY_CACHE = BaseApplication::ARG_NO_REGISTRY_CACHE; const QString BaseApplication::PROP_PRODUCT = "blueberry.product"; const QString BaseApplication::PROP_REGISTRY_MULTI_LANGUAGE = BaseApplication::ARG_REGISTRY_MULTI_LANGUAGE; class SplashCloserCallback : public QRunnable { public: SplashCloserCallback(QSplashScreen* splashscreen) : m_Splashscreen(splashscreen) { } void run() override { this->m_Splashscreen->close(); } private: QSplashScreen *m_Splashscreen; // Owned by BaseApplication::Impl }; struct BaseApplication::Impl { ctkProperties m_FWProps; QCoreApplication *m_QApp; int m_Argc; char **m_Argv; #ifdef Q_OS_MAC std::vector m_Argv_macOS; #endif QString m_AppName; QString m_OrgaName; QString m_OrgaDomain; bool m_SingleMode; bool m_SafeMode; QSplashScreen *m_Splashscreen; SplashCloserCallback *m_SplashscreenClosingCallback; bool m_LogQtMessages; QStringList m_PreloadLibs; QString m_ProvFile; Impl(int argc, char **argv) : m_Argc(argc), m_Argv(argv), #ifdef Q_OS_MAC m_Argv_macOS(), #endif m_SingleMode(false), m_SafeMode(true), m_Splashscreen(nullptr), m_SplashscreenClosingCallback(nullptr), m_LogQtMessages(false) { #ifdef Q_OS_MAC /* On macOS the process serial number is passed as an command line argument (-psn_) in certain circumstances. This option causes a Poco exception. We remove it, if present. */ m_Argv_macOS.reserve(argc + 1); const char psn[] = "-psn"; for (int i = 0; i < argc; ++i) { if (0 == strncmp(argv[i], psn, sizeof(psn) - 1)) continue; m_Argv_macOS.push_back(argv[i]); } m_Argv_macOS.push_back(nullptr); m_Argc = static_cast(m_Argv_macOS.size() - 1); m_Argv = m_Argv_macOS.data(); #endif } ~Impl() { delete m_SplashscreenClosingCallback; delete m_Splashscreen; delete m_QApp; } QVariant getProperty(const QString &property) const { auto iter = m_FWProps.find(property); return m_FWProps.end() != iter ? iter.value() : QVariant(); } void handleBooleanOption(const std::string &name, const std::string &) { if (ARG_LOG_QT_MESSAGES.toStdString() == name) { m_LogQtMessages = true; return; } auto fwKey = QString::fromStdString(name); // Translate some keys to proper framework properties if (ARG_CONSOLELOG == fwKey) fwKey = ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG; // For all other options we use the command line option name as the // framework property key. m_FWProps[fwKey] = true; } void handlePreloadLibraryOption(const std::string &, const std::string &value) { m_PreloadLibs.push_back(QString::fromStdString(value)); } void handleClean(const std::string &, const std::string &) { m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN] = ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT; } void initializeCTKPluginFrameworkProperties(Poco::Util::LayeredConfiguration &configuration) { // Add all configuration key/value pairs as framework properties Poco::Util::LayeredConfiguration::Keys keys; Poco::Util::LayeredConfiguration::Keys keyStack; configuration.keys(keyStack); std::vector keyChain; while (!keyStack.empty()) { const auto currSubKey = keyStack.back(); if (!keyChain.empty() && keyChain.back() == currSubKey) { keyChain.pop_back(); keyStack.pop_back(); continue; } Poco::Util::LayeredConfiguration::Keys subKeys; configuration.keys(currSubKey, subKeys); if (subKeys.empty()) { std::string finalKey; keyStack.pop_back(); for (const auto& key : keyChain) finalKey += key + '.'; finalKey += currSubKey; keys.push_back(finalKey); } else { keyChain.push_back(currSubKey); for (const auto& key : subKeys) keyStack.push_back(key); } } for (const auto& key : keys) { if (configuration.hasProperty(key)) { // .ini and command line options overwrite already inserted keys auto qKey = QString::fromStdString(key); m_FWProps[qKey] = QString::fromStdString(configuration.getString(key)); } } } void parseProvisioningFile(const QString &filePath) { // Skip parsing if the file path is empty if (filePath.isEmpty()) return; auto consoleLog = this->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool(); // Read initial plugins from a provisioning file QFileInfo provFile(filePath); QStringList pluginsToStart; if (provFile.exists()) { MITK_INFO(consoleLog) << "Using provisioning file: " << qPrintable(provFile.absoluteFilePath()); ProvisioningInfo provInfo(provFile.absoluteFilePath()); // It can still happen that the encoding is not compatible with the fromUtf8 function (i.e. when // manipulating the LANG variable). The QStringList in provInfo is empty then. if (provInfo.getPluginDirs().empty()) { MITK_ERROR << "Cannot search for provisioning file, the retrieved directory list is empty.\n" << "This can happen if there are some special non-ASCII characters in the install path."; } else { for(const auto& pluginPath : provInfo.getPluginDirs()) ctkPluginFrameworkLauncher::addSearchPath(pluginPath); auto pluginUrlsToStart = provInfo.getPluginsToStart(); for (const auto& url : qAsConst(pluginUrlsToStart)) pluginsToStart.push_back(url.toString()); } } else { MITK_INFO(consoleLog) << "Provisionig file does not exist."; } if (!pluginsToStart.isEmpty()) { m_FWProps[ctkPluginFrameworkLauncher::PROP_PLUGINS] = pluginsToStart; // Use transient start with declared activation policy (this helps when the provisioning file // changes and some plug-ins should not be installed in the application any more). ctkPlugin::StartOptions startOptions(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); m_FWProps[ctkPluginFrameworkLauncher::PROP_PLUGINS_START_OPTIONS] = static_cast(startOptions); } } }; BaseApplication::BaseApplication(int argc, char **argv) : Application(), d(new Impl(argc, argv)) { } BaseApplication::~BaseApplication() { delete d; } void BaseApplication::printHelp(const std::string &, const std::string &) { Poco::Util::HelpFormatter help(this->options()); help.setAutoIndent(); help.setCommand(this->commandName()); help.format(std::cout); exit(EXIT_OK); } void BaseApplication::setApplicationName(const QString &name) { if (nullptr != qApp) qApp->setApplicationName(name); d->m_AppName = name; } QString BaseApplication::getApplicationName() const { return nullptr != qApp ? qApp->applicationName() : d->m_AppName; } void BaseApplication::setOrganizationName(const QString &name) { if (nullptr != qApp) qApp->setOrganizationName(name); d->m_OrgaName = name; } QString BaseApplication::getOrganizationName() const { return nullptr != qApp ? qApp->organizationName() : d->m_OrgaName; } void BaseApplication::setOrganizationDomain(const QString &domain) { if (nullptr != qApp) qApp->setOrganizationDomain(domain); d->m_OrgaDomain = domain; } QString BaseApplication::getOrganizationDomain() const { return nullptr != qApp ? qApp->organizationDomain() : d->m_OrgaDomain; } void BaseApplication::setSingleMode(bool singleMode) { if (nullptr != qApp) return; d->m_SingleMode = singleMode; } bool BaseApplication::getSingleMode() const { return d->m_SingleMode; } void BaseApplication::setSafeMode(bool safeMode) { if (nullptr != qApp && nullptr == d->m_QApp) return; d->m_SafeMode = safeMode; nullptr == d->m_QApp && getSingleMode() ? static_cast(d->m_QApp)->setSafeMode(safeMode) : static_cast(d->m_QApp)->setSafeMode(safeMode); } bool BaseApplication::getSafeMode() const { return d->m_SafeMode; } void BaseApplication::setPreloadLibraries(const QStringList &libraryBaseNames) { d->m_PreloadLibs = libraryBaseNames; } QStringList BaseApplication::getPreloadLibraries() const { return d->m_PreloadLibs; } void BaseApplication::setProvisioningFilePath(const QString &filePath) { d->m_ProvFile = filePath; } QString BaseApplication::getProvisioningFilePath() const { auto provFilePath = d->m_ProvFile; // A null QString means look up a default provisioning file if (provFilePath.isNull() && nullptr != qApp) { QFileInfo appFilePath(QCoreApplication::applicationFilePath()); QDir basePath(QCoreApplication::applicationDirPath()); auto provFileName = appFilePath.baseName() + ".provisioning"; QFileInfo provFile(basePath.absoluteFilePath(provFileName)); #ifdef Q_OS_MAC /* * On macOS, if started from the build directory, the .provisioning file is located at: * * The executable path is: * * In this case we have to cdUp threetimes. * * During packaging the MitkWorkbench.provisioning file is placed at the same * level like the executable. Nothing has to be done. */ if (!provFile.exists()) { basePath.cdUp(); basePath.cdUp(); basePath.cdUp(); provFile = basePath.absoluteFilePath(provFileName); } #endif if (provFile.exists()) { provFilePath = provFile.absoluteFilePath(); } #ifdef CMAKE_INTDIR else { basePath.cdUp(); provFile.setFile(basePath.absoluteFilePath(provFileName)); if (provFile.exists()) provFilePath = provFile.absoluteFilePath(); } #endif } return provFilePath; } void BaseApplication::initializeQt() { if (nullptr != qApp) return; #ifdef Q_OS_LINUX qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--single-process"); // See T29332 #endif // If parameters have been set before, we have to store them to hand them // through to the application auto appName = this->getApplicationName(); auto orgName = this->getOrganizationName(); auto orgDomain = this->getOrganizationDomain(); // Create a QCoreApplication instance this->getQApplication(); // Provide parameters to QCoreApplication this->setApplicationName(appName); this->setOrganizationName(orgName); this->setOrganizationDomain(orgDomain); if (d->m_LogQtMessages) qInstallMessageHandler(outputQtMessage); QWebEngineUrlScheme qtHelpScheme("qthelp"); qtHelpScheme.setFlags(QWebEngineUrlScheme::LocalScheme | QWebEngineUrlScheme::LocalAccessAllowed); QWebEngineUrlScheme::registerScheme(qtHelpScheme); } void BaseApplication::initialize(Poco::Util::Application &self) { // 1. Call the super-class method Poco::Util::Application::initialize(self); // 2. Initialize the Qt framework (by creating a QCoreApplication) this->initializeQt(); // 3. Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // 4. Load the "default" configuration, which involves parsing // an optional .ini file and parsing any // command line arguments this->loadConfiguration(); // 5. Add configuration data from the command line and the // optional .ini file as CTK plugin // framework properties. d->initializeCTKPluginFrameworkProperties(this->config()); // 6. Initialize splash screen if an image path is provided // in the .ini file this->initializeSplashScreen(qApp); // 7. Set the custom CTK Plugin Framework storage directory QString storageDir = this->getCTKFrameworkStorageDir(); if (!storageDir.isEmpty()) + { d->m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE] = storageDir; + // Initialize core service preferences at the exact same location as their predecessor BlueBerry preferences + mitk::CoreServicePointer preferencesService(mitk::CoreServices::GetPreferencesService()); + preferencesService->InitializeStorage(storageDir.toStdString() + "/data/3/prefs.xml"); + } + // 8. Set the library search paths and the pre-load library property this->initializeLibraryPaths(); auto preloadLibs = this->getPreloadLibraries(); if (!preloadLibs.isEmpty()) d->m_FWProps[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES] = preloadLibs; // 9. Initialize the CppMicroServices library. // The initializeCppMicroServices() method reuses the // FRAMEWORK_STORAGE property, so we call it after the // getCTKFrameworkStorageDir method. this->initializeCppMicroServices(); // 10. Parse the (optional) provisioning file and set the // correct framework properties. d->parseProvisioningFile(this->getProvisioningFilePath()); // 11. Set the CTK Plugin Framework properties ctkPluginFrameworkLauncher::setFrameworkProperties(d->m_FWProps); } void BaseApplication::uninitialize() { auto pfw = this->getFramework(); if (pfw) { pfw->stop(); // Wait for up to 10 seconds for the CTK plugin framework to stop pfw->waitForStop(10000); } Poco::Util::Application::uninitialize(); } int BaseApplication::getArgc() const { return d->m_Argc; } char **BaseApplication::getArgv() const { return d->m_Argv; } QString BaseApplication::getCTKFrameworkStorageDir() const { QString storageDir; if (this->getSingleMode()) { // This function checks if an instance is already running and either sends a message to // it containing the command line arguments or checks if a new instance was forced by // providing the BlueBerry.newInstance command line argument. In the latter case, a path // to a temporary directory for the new application's storage directory is returned. storageDir = handleNewAppInstance(static_cast(d->m_QApp), d->m_Argc, d->m_Argv, ARG_NEWINSTANCE); } if (storageDir.isEmpty()) { // This is a new instance and no other instance is already running. We specify the // storage directory here (this is the same code as in berryInternalPlatform.cpp) // so that we can re-use the location for the persistent data location of the // the CppMicroServices library. // Append a hash value of the absolute path of the executable to the data location. // This allows to start the same application from different build or install trees. storageDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/" + this->getOrganizationName() + "/" + this->getApplicationName() + '_'; storageDir += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; } return storageDir; } void BaseApplication::initializeCppMicroServices() { auto storageDir = this->getProperty(ctkPluginConstants::FRAMEWORK_STORAGE).toString(); if (!storageDir.isEmpty()) us::ModuleSettings::SetStoragePath((storageDir + "us" + QDir::separator()).toStdString()); } QCoreApplication *BaseApplication::getQApplication() const { if (nullptr == qApp) { vtkOpenGLRenderWindow::SetGlobalMaximumNumberOfMultiSamples(0); auto defaultFormat = QVTKOpenGLNativeWidget::defaultFormat(); defaultFormat.setSamples(0); QSurfaceFormat::setDefaultFormat(defaultFormat); #ifdef Q_OS_OSX QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); #endif QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); d->m_QApp = this->getSingleMode() ? static_cast(new QmitkSingleApplication(d->m_Argc, d->m_Argv, this->getSafeMode())) : static_cast(new QmitkSafeApplication(d->m_Argc, d->m_Argv, this->getSafeMode())); } return qApp; } void BaseApplication::initializeLibraryPaths() { QStringList suffixes; suffixes << "plugins"; #ifdef Q_OS_WINDOWS suffixes << "bin/plugins"; #ifdef CMAKE_INTDIR suffixes << "bin/" CMAKE_INTDIR "/plugins"; #endif #else suffixes << "lib/plugins"; #ifdef CMAKE_INTDIR suffixes << "lib/" CMAKE_INTDIR "/plugins"; #endif #endif #ifdef Q_OS_MAC suffixes << "../../plugins"; #endif // We add a couple of standard library search paths for plug-ins QDir appDir(QCoreApplication::applicationDirPath()); // Walk one directory up and add bin and lib sub-dirs; this might be redundant appDir.cdUp(); for (const auto& suffix : qAsConst(suffixes)) ctkPluginFrameworkLauncher::addSearchPath(appDir.absoluteFilePath(suffix)); } int BaseApplication::main(const std::vector &args) { // Start the plugin framework and all installed plug-ins according to their auto-start setting QStringList arguments; for (auto const &arg : args) arguments.push_back(QString::fromStdString(arg)); if (nullptr != d->m_Splashscreen) { // A splash screen is displayed. Create the closing callback. d->m_SplashscreenClosingCallback = new SplashCloserCallback(d->m_Splashscreen); } return ctkPluginFrameworkLauncher::run(d->m_SplashscreenClosingCallback, QVariant::fromValue(arguments)).toInt(); } void BaseApplication::defineOptions(Poco::Util::OptionSet &options) { Poco::Util::Option helpOption("help", "h", "print this help text"); helpOption.callback(Poco::Util::OptionCallback(this, &BaseApplication::printHelp)); options.addOption(helpOption); Poco::Util::Option newInstanceOption(ARG_NEWINSTANCE.toStdString(), "", "forces a new instance of this application"); newInstanceOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(newInstanceOption); Poco::Util::Option cleanOption(ARG_CLEAN.toStdString(), "", "cleans the plugin cache"); cleanOption.callback(Poco::Util::OptionCallback(d, &Impl::handleClean)); options.addOption(cleanOption); Poco::Util::Option productOption(ARG_PRODUCT.toStdString(), "", "the id of the product to be launched"); productOption.argument("").binding(PROP_PRODUCT.toStdString()); options.addOption(productOption); Poco::Util::Option appOption(ARG_APPLICATION.toStdString(), "", "the id of the application extension to be executed"); appOption.argument("").binding(PROP_APPLICATION.toStdString()); options.addOption(appOption); Poco::Util::Option provOption(ARG_PROVISIONING.toStdString(), "", "the location of a provisioning file"); provOption.argument("").binding(ARG_PROVISIONING.toStdString()); options.addOption(provOption); Poco::Util::Option storageDirOption(ARG_STORAGE_DIR.toStdString(), "", "the location for storing persistent application data"); storageDirOption.argument("").binding(ctkPluginConstants::FRAMEWORK_STORAGE.toStdString()); options.addOption(storageDirOption); Poco::Util::Option consoleLogOption(ARG_CONSOLELOG.toStdString(), "", "log messages to the console"); consoleLogOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(consoleLogOption); Poco::Util::Option debugOption(ARG_DEBUG.toStdString(), "", "enable debug mode"); debugOption.argument("", false).binding(ctkPluginFrameworkLauncher::PROP_DEBUG.toStdString()); options.addOption(debugOption); Poco::Util::Option forcePluginOption(ARG_FORCE_PLUGIN_INSTALL.toStdString(), "", "force installing plug-ins with same symbolic name"); forcePluginOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(forcePluginOption); Poco::Util::Option preloadLibsOption(ARG_PRELOAD_LIBRARY.toStdString(), "", "preload a library"); preloadLibsOption.argument("") .repeatable(true) .callback(Poco::Util::OptionCallback(d, &Impl::handlePreloadLibraryOption)); options.addOption(preloadLibsOption); Poco::Util::Option noRegistryCacheOption(ARG_NO_REGISTRY_CACHE.toStdString(), "", "do not use a cache for the registry"); noRegistryCacheOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(noRegistryCacheOption); Poco::Util::Option noLazyRegistryCacheLoadingOption(ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString(), "", "do not use lazy cache loading for the registry"); noLazyRegistryCacheLoadingOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(noLazyRegistryCacheLoadingOption); Poco::Util::Option registryMultiLanguageOption(ARG_REGISTRY_MULTI_LANGUAGE.toStdString(), "", "enable multi-language support for the registry"); registryMultiLanguageOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(registryMultiLanguageOption); Poco::Util::Option splashScreenOption(ARG_SPLASH_IMAGE.toStdString(), "", "optional picture to use as a splash screen"); splashScreenOption.argument("").binding(ARG_SPLASH_IMAGE.toStdString()); options.addOption(splashScreenOption); Poco::Util::Option xargsOption(ARG_XARGS.toStdString(), "", "Extended argument list"); xargsOption.argument("").binding(ARG_XARGS.toStdString()); options.addOption(xargsOption); Poco::Util::Option logQtMessagesOption(ARG_LOG_QT_MESSAGES.toStdString(), "", "log Qt messages"); logQtMessagesOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(logQtMessagesOption); Poco::Util::Option labelSetPresetOption(ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), "", "use this label set preset for new segmentations"); labelSetPresetOption.argument("").binding(ARG_SEGMENTATION_LABELSET_PRESET.toStdString()); options.addOption(labelSetPresetOption); Poco::Util::Option labelSuggestionsOption(ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), "", "use this list of predefined suggestions for segmentation labels"); labelSuggestionsOption.argument("").binding(ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString()); options.addOption(labelSuggestionsOption); Poco::Util::Application::defineOptions(options); } QSharedPointer BaseApplication::getFramework() const { return ctkPluginFrameworkLauncher::getPluginFramework(); } ctkPluginContext *BaseApplication::getFrameworkContext() const { auto framework = getFramework(); return framework ? framework->getPluginContext() : nullptr; } void BaseApplication::initializeSplashScreen(QCoreApplication * application) const { auto pixmapFileNameProp = d->getProperty(ARG_SPLASH_IMAGE); if (!pixmapFileNameProp.isNull()) { auto pixmapFileName = pixmapFileNameProp.toString(); QFileInfo checkFile(pixmapFileName); if (checkFile.exists() && checkFile.isFile()) { QPixmap pixmap(checkFile.absoluteFilePath()); d->m_Splashscreen = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint); d->m_Splashscreen->show(); application->processEvents(); } } } QHash BaseApplication::getFrameworkProperties() const { return d->m_FWProps; } int BaseApplication::run() { this->init(d->m_Argc, d->m_Argv); return Application::run(); } void BaseApplication::setProperty(const QString &property, const QVariant &value) { d->m_FWProps[property] = value; } QVariant BaseApplication::getProperty(const QString &property) const { return d->getProperty(property); } void BaseApplication::installTranslator(QTranslator* translator) { this->getQApplication()->installTranslator(translator); } bool BaseApplication::isRunning() { auto app = dynamic_cast(this->getQApplication()); if (nullptr != app) app->isRunning(); mitkThrow() << "Method not implemented."; } void BaseApplication::sendMessage(const QByteArray msg) { auto app = dynamic_cast(this->getQApplication()); if (nullptr != app) app->sendMessage(msg); mitkThrow() << "Method not implemented."; } } diff --git a/Modules/Core/files.cmake b/Modules/Core/files.cmake index eab67f18d2..313085b1be 100644 --- a/Modules/Core/files.cmake +++ b/Modules/Core/files.cmake @@ -1,323 +1,329 @@ file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") set(CPP_FILES mitkCoreActivator.cpp mitkCoreObjectFactoryBase.cpp mitkCoreObjectFactory.cpp mitkCoreServices.cpp mitkException.cpp Algorithms/mitkBaseDataSource.cpp Algorithms/mitkClippedSurfaceBoundsCalculator.cpp Algorithms/mitkCompareImageDataFilter.cpp Algorithms/mitkCompositePixelValueToString.cpp Algorithms/mitkConvert2Dto3DImageFilter.cpp Algorithms/mitkDataNodeSource.cpp Algorithms/mitkExtractSliceFilter.cpp Algorithms/mitkExtractSliceFilter2.cpp Algorithms/mitkHistogramGenerator.cpp Algorithms/mitkImageChannelSelector.cpp Algorithms/mitkImageSliceSelector.cpp Algorithms/mitkImageSource.cpp Algorithms/mitkImageTimeSelector.cpp Algorithms/mitkImageToImageFilter.cpp Algorithms/mitkImageToSurfaceFilter.cpp Algorithms/mitkMultiComponentImageDataComparisonFilter.cpp Algorithms/mitkPlaneGeometryDataToSurfaceFilter.cpp Algorithms/mitkPointSetSource.cpp Algorithms/mitkPointSetToPointSetFilter.cpp Algorithms/mitkRGBToRGBACastImageFilter.cpp Algorithms/mitkSubImageSelector.cpp Algorithms/mitkSurfaceSource.cpp Algorithms/mitkSurfaceToImageFilter.cpp Algorithms/mitkSurfaceToSurfaceFilter.cpp Algorithms/mitkUIDGenerator.cpp Algorithms/mitkVolumeCalculator.cpp Algorithms/mitkTemporalJoinImagesFilter.cpp Controllers/mitkBaseController.cpp Controllers/mitkCallbackFromGUIThread.cpp Controllers/mitkCameraController.cpp Controllers/mitkCameraRotationController.cpp Controllers/mitkCrosshairManager.cpp Controllers/mitkLimitedLinearUndo.cpp Controllers/mitkOperationEvent.cpp Controllers/mitkPlanePositionManager.cpp Controllers/mitkProgressBar.cpp Controllers/mitkRenderingManager.cpp Controllers/mitkSliceNavigationController.cpp Controllers/mitkSliceNavigationHelper.cpp Controllers/mitkStatusBar.cpp Controllers/mitkStepper.cpp Controllers/mitkTestManager.cpp Controllers/mitkUndoController.cpp Controllers/mitkVerboseLimitedLinearUndo.cpp Controllers/mitkVtkLayerController.cpp DataManagement/mitkAnatomicalStructureColorPresets.cpp DataManagement/mitkArbitraryTimeGeometry.cpp DataManagement/mitkAbstractTransformGeometry.cpp DataManagement/mitkAnnotationProperty.cpp DataManagement/mitkApplicationCursor.cpp DataManagement/mitkApplyTransformMatrixOperation.cpp DataManagement/mitkBaseData.cpp DataManagement/mitkBaseGeometry.cpp DataManagement/mitkBaseProperty.cpp DataManagement/mitkChannelDescriptor.cpp DataManagement/mitkClippingProperty.cpp DataManagement/mitkColorProperty.cpp DataManagement/mitkDataNode.cpp DataManagement/mitkDataStorage.cpp DataManagement/mitkEnumerationProperty.cpp DataManagement/mitkFloatPropertyExtension.cpp DataManagement/mitkGeometry3D.cpp DataManagement/mitkGeometryData.cpp DataManagement/mitkGeometryTransformHolder.cpp DataManagement/mitkGroupTagProperty.cpp DataManagement/mitkGenericIDRelationRule.cpp DataManagement/mitkIdentifiable.cpp DataManagement/mitkImageAccessorBase.cpp DataManagement/mitkImageCaster.cpp DataManagement/mitkImageCastPart1.cpp DataManagement/mitkImageCastPart2.cpp DataManagement/mitkImageCastPart3.cpp DataManagement/mitkImageCastPart4.cpp DataManagement/mitkImage.cpp DataManagement/mitkImageDataItem.cpp DataManagement/mitkImageDescriptor.cpp DataManagement/mitkImageReadAccessor.cpp DataManagement/mitkImageStatisticsHolder.cpp DataManagement/mitkImageVtkAccessor.cpp DataManagement/mitkImageVtkReadAccessor.cpp DataManagement/mitkImageVtkWriteAccessor.cpp DataManagement/mitkImageWriteAccessor.cpp DataManagement/mitkIntPropertyExtension.cpp DataManagement/mitkIPersistenceService.cpp DataManagement/mitkIPropertyAliases.cpp DataManagement/mitkIPropertyDescriptions.cpp DataManagement/mitkIPropertyExtensions.cpp DataManagement/mitkIPropertyFilters.cpp DataManagement/mitkIPropertyOwner.cpp DataManagement/mitkIPropertyPersistence.cpp DataManagement/mitkIPropertyProvider.cpp DataManagement/mitkLandmarkProjectorBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjector.cpp DataManagement/mitkLevelWindow.cpp DataManagement/mitkLevelWindowManager.cpp DataManagement/mitkLevelWindowPreset.cpp DataManagement/mitkLevelWindowProperty.cpp DataManagement/mitkLine.cpp DataManagement/mitkLookupTable.cpp DataManagement/mitkLookupTableProperty.cpp DataManagement/mitkLookupTables.cpp # specializations of GenericLookupTable DataManagement/mitkMaterial.cpp DataManagement/mitkMemoryUtilities.cpp DataManagement/mitkModalityProperty.cpp DataManagement/mitkModifiedLock.cpp DataManagement/mitkNodePredicateAnd.cpp DataManagement/mitkNodePredicateBase.cpp DataManagement/mitkNodePredicateCompositeBase.cpp DataManagement/mitkNodePredicateData.cpp DataManagement/mitkNodePredicateDataType.cpp DataManagement/mitkNodePredicateDataUID.cpp DataManagement/mitkNodePredicateDimension.cpp DataManagement/mitkNodePredicateFirstLevel.cpp DataManagement/mitkNodePredicateFunction.cpp DataManagement/mitkNodePredicateGeometry.cpp DataManagement/mitkNodePredicateNot.cpp DataManagement/mitkNodePredicateOr.cpp DataManagement/mitkNodePredicateProperty.cpp DataManagement/mitkNodePredicateDataProperty.cpp DataManagement/mitkNodePredicateSource.cpp DataManagement/mitkNodePredicateSubGeometry.cpp DataManagement/mitkNumericConstants.cpp DataManagement/mitkPlaneGeometry.cpp DataManagement/mitkPlaneGeometryData.cpp DataManagement/mitkPlaneOperation.cpp DataManagement/mitkPlaneOrientationProperty.cpp DataManagement/mitkPointOperation.cpp DataManagement/mitkPointSet.cpp DataManagement/mitkPointSetShapeProperty.cpp DataManagement/mitkProperties.cpp DataManagement/mitkPropertyAliases.cpp DataManagement/mitkPropertyDescriptions.cpp DataManagement/mitkPropertyExtension.cpp DataManagement/mitkPropertyExtensions.cpp DataManagement/mitkPropertyFilter.cpp DataManagement/mitkPropertyFilters.cpp DataManagement/mitkPropertyKeyPath.cpp DataManagement/mitkPropertyList.cpp DataManagement/mitkPropertyListReplacedObserver.cpp DataManagement/mitkPropertyNameHelper.cpp DataManagement/mitkPropertyObserver.cpp DataManagement/mitkPropertyPersistence.cpp DataManagement/mitkPropertyPersistenceInfo.cpp DataManagement/mitkPropertyRelationRuleBase.cpp DataManagement/mitkProportionalTimeGeometry.cpp DataManagement/mitkRenderingModeProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkRestorePlanePositionOperation.cpp DataManagement/mitkRotationOperation.cpp DataManagement/mitkScaleOperation.cpp DataManagement/mitkSlicedData.cpp DataManagement/mitkSlicedGeometry3D.cpp DataManagement/mitkSmartPointerProperty.cpp DataManagement/mitkStandaloneDataStorage.cpp DataManagement/mitkStringProperty.cpp DataManagement/mitkSurface.cpp DataManagement/mitkSurfaceOperation.cpp DataManagement/mitkSourceImageRelationRule.cpp DataManagement/mitkThinPlateSplineCurvedGeometry.cpp DataManagement/mitkTimeGeometry.cpp DataManagement/mitkTransferFunction.cpp DataManagement/mitkTransferFunctionInitializer.cpp DataManagement/mitkTransferFunctionProperty.cpp DataManagement/mitkTemporoSpatialStringProperty.cpp DataManagement/mitkUIDManipulator.cpp DataManagement/mitkVector.cpp DataManagement/mitkVectorProperty.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkWeakPointerProperty.cpp DataManagement/mitkIPropertyRelations.cpp DataManagement/mitkPropertyRelations.cpp Interactions/mitkAction.cpp Interactions/mitkBindDispatcherInteractor.cpp Interactions/mitkDataInteractor.cpp Interactions/mitkDispatcher.cpp Interactions/mitkDisplayActionEventBroadcast.cpp Interactions/mitkDisplayActionEventFunctions.cpp Interactions/mitkDisplayActionEventHandler.cpp Interactions/mitkDisplayActionEventHandlerDesynchronized.cpp Interactions/mitkDisplayActionEventHandlerStd.cpp Interactions/mitkDisplayActionEventHandlerSynchronized.cpp Interactions/mitkDisplayCoordinateOperation.cpp Interactions/mitkEventConfig.cpp Interactions/mitkEventFactory.cpp Interactions/mitkEventRecorder.cpp Interactions/mitkEventStateMachine.cpp Interactions/mitkInteractionEventConst.cpp Interactions/mitkInteractionEvent.cpp Interactions/mitkInteractionEventHandler.cpp Interactions/mitkInteractionEventObserver.cpp Interactions/mitkInteractionKeyEvent.cpp Interactions/mitkInteractionPositionEvent.cpp Interactions/mitkInteractionSchemeSwitcher.cpp Interactions/mitkInternalEvent.cpp Interactions/mitkMouseDoubleClickEvent.cpp Interactions/mitkMouseMoveEvent.cpp Interactions/mitkMousePressEvent.cpp Interactions/mitkMouseReleaseEvent.cpp Interactions/mitkMouseWheelEvent.cpp Interactions/mitkPointSetDataInteractor.cpp Interactions/mitkSinglePointDataInteractor.cpp Interactions/mitkStateMachineAction.cpp Interactions/mitkStateMachineCondition.cpp Interactions/mitkStateMachineContainer.cpp Interactions/mitkStateMachineState.cpp Interactions/mitkStateMachineTransition.cpp Interactions/mitkVtkEventAdapter.cpp Interactions/mitkVtkInteractorStyle.cxx Interactions/mitkXML2EventParser.cpp IO/mitkAbstractFileIO.cpp IO/mitkAbstractFileReader.cpp IO/mitkAbstractFileWriter.cpp IO/mitkCustomMimeType.cpp IO/mitkFileReader.cpp IO/mitkFileReaderRegistry.cpp IO/mitkFileReaderSelector.cpp IO/mitkFileReaderWriterBase.cpp IO/mitkFileWriter.cpp IO/mitkFileWriterRegistry.cpp IO/mitkFileWriterSelector.cpp IO/mitkGeometry3DToXML.cpp IO/mitkIFileIO.cpp IO/mitkIFileReader.cpp IO/mitkIFileWriter.cpp IO/mitkGeometryDataReaderService.cpp IO/mitkGeometryDataWriterService.cpp IO/mitkImageGenerator.cpp IO/mitkImageVtkLegacyIO.cpp IO/mitkImageVtkXmlIO.cpp IO/mitkIMimeTypeProvider.cpp IO/mitkIOConstants.cpp IO/mitkIOMimeTypes.cpp IO/mitkIOUtil.cpp IO/mitkItkImageIO.cpp IO/mitkItkLoggingAdapter.cpp IO/mitkLegacyFileReaderService.cpp IO/mitkLegacyFileWriterService.cpp IO/mitkLocaleSwitch.cpp IO/mitkLog.cpp IO/mitkMimeType.cpp IO/mitkMimeTypeProvider.cpp IO/mitkOperation.cpp IO/mitkPixelType.cpp IO/mitkPointSetReaderService.cpp IO/mitkPointSetWriterService.cpp IO/mitkProportionalTimeGeometryToXML.cpp IO/mitkRawImageFileReader.cpp IO/mitkStandardFileLocations.cpp IO/mitkSurfaceStlIO.cpp IO/mitkSurfaceVtkIO.cpp IO/mitkSurfaceVtkLegacyIO.cpp IO/mitkSurfaceVtkXmlIO.cpp IO/mitkUtf8Util.cpp IO/mitkVtkLoggingAdapter.cpp IO/mitkPreferenceListReaderOptionsFunctor.cpp IO/mitkIOMetaInformationPropertyConstants.cpp + IO/mitkIPreferences.cpp + IO/mitkPreferences.cpp + IO/mitkIPreferencesService.cpp + IO/mitkPreferencesService.cpp + IO/mitkIPreferencesStorage.cpp + IO/mitkXMLPreferencesStorage.cpp Rendering/mitkAbstractAnnotationRenderer.cpp Rendering/mitkAnnotationUtils.cpp Rendering/mitkBaseRenderer.cpp Rendering/mitkBaseRendererHelper.cpp #Rendering/mitkGLMapper.cpp Moved to deprecated LegacyGL Module Rendering/mitkGradientBackground.cpp Rendering/mitkImageVtkMapper2D.cpp Rendering/mitkMapper.cpp Rendering/mitkAnnotation.cpp Rendering/mitkPlaneGeometryDataMapper2D.cpp Rendering/mitkPlaneGeometryDataVtkMapper3D.cpp Rendering/mitkPointSetVtkMapper2D.cpp Rendering/mitkPointSetVtkMapper3D.cpp Rendering/mitkRenderWindowBase.cpp Rendering/mitkRenderWindow.cpp Rendering/mitkRenderWindowFrame.cpp #Rendering/mitkSurfaceGLMapper2D.cpp Moved to deprecated LegacyGL Module Rendering/mitkSurfaceVtkMapper2D.cpp Rendering/mitkSurfaceVtkMapper3D.cpp Rendering/mitkVtkEventProvider.cpp Rendering/mitkVtkMapper.cpp Rendering/mitkVtkPropRenderer.cpp Rendering/mitkVtkWidgetRendering.cpp Rendering/vtkMitkLevelWindowFilter.cpp Rendering/vtkMitkRectangleProp.cpp Rendering/vtkMitkRenderProp.cpp Rendering/vtkMitkThickSlicesFilter.cpp Rendering/vtkNeverTranslucentTexture.cpp ) set(RESOURCE_FILES Interactions/globalConfig.xml Interactions/DisplayInteraction.xml Interactions/DisplayConfigMITKBase.xml Interactions/DisplayConfigPACSBase.xml Interactions/DisplayConfigCrosshair.xml Interactions/DisplayConfigRotation.xml Interactions/DisplayConfigActivateCoupling.xml Interactions/DisplayConfigSwivel.xml Interactions/DisplayConfigPACSPan.xml Interactions/DisplayConfigPACSScroll.xml Interactions/DisplayConfigPACSZoom.xml Interactions/DisplayConfigPACSLevelWindow.xml Interactions/DisplayConfigBlockLMB.xml Interactions/PointSet.xml Interactions/PointSetConfig.xml mitkLevelWindowPresets.xml mitkAnatomicalStructureColorPresets.xml ) diff --git a/Modules/Core/include/mitkCoreServices.h b/Modules/Core/include/mitkCoreServices.h index 833cc313c8..3d1512fc48 100644 --- a/Modules/Core/include/mitkCoreServices.h +++ b/Modules/Core/include/mitkCoreServices.h @@ -1,178 +1,187 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKCORESERVICES_H #define MITKCORESERVICES_H #include "MitkCoreExports.h" #include #include #include #include #include #include #include namespace mitk { struct IMimeTypeProvider; class IPropertyAliases; class IPropertyDescriptions; class IPropertyExtensions; class IPropertyFilters; class IPropertyPersistence; class IPropertyRelations; + class IPreferencesService; /** * @brief Access MITK core services. * * This class can be used to conveniently access common * MITK Core service objects. Some getter methods where implementations * exist in the core library are guaranteed to return a non-nullptr service object. * * To ensure that CoreServices::Unget() is called after the caller * has finished using a service object, you should use the CoreServicePointer * helper class which calls Unget() when it goes out of scope: * * \code * CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); * // Do something with shaderRepo * \endcode * * @see CoreServicePointer */ class MITKCORE_EXPORT CoreServices { public: /** * @brief Get an IPropertyAliases instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyAliases instance. */ static IPropertyAliases *GetPropertyAliases(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyDescriptions instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyDescriptions instance. */ static IPropertyDescriptions *GetPropertyDescriptions(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyExtensions instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyExtensions instance. */ static IPropertyExtensions *GetPropertyExtensions(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyFilters instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyFilters instance. */ static IPropertyFilters *GetPropertyFilters(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyPersistence instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyPersistence instance. */ static IPropertyPersistence *GetPropertyPersistence(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyRelations instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyRelations instance. */ static IPropertyRelations *GetPropertyRelations(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IMimeTypeProvider instance. * @param context The module context of the module getting the service. * @return A non-nullptr IMimeTypeProvider instance. */ static IMimeTypeProvider *GetMimeTypeProvider(us::ModuleContext *context = us::GetModuleContext()); + /** + * @brief Get an IPreferencesService instance. + * @param context The module context of the module getting the service. + * @return A non-nullptr IPreferencesService instance. + * @sa IPreferences + */ + static IPreferencesService *GetPreferencesService(us::ModuleContext *context = us::GetModuleContext()); + /** * @brief Unget a previously acquired service instance. * @param service The service instance to be released. * @param context * @return \c true if ungetting the service was successful, \c false otherwise. */ template static bool Unget(S *service, us::ModuleContext *context = us::GetModuleContext()) { return Unget(context, us_service_interface_iid(), service); } private: static bool Unget(us::ModuleContext *context, const std::string &interfaceId, void *service); // purposely not implemented CoreServices(); CoreServices(const CoreServices &); CoreServices &operator=(const CoreServices &); }; /** * @brief A RAII helper class for core service objects. * * This is class is intended for usage in local scopes; it calls * CoreServices::Unget(S*) in its destructor. You should not construct * multiple CoreServicePointer instances using the same service pointer, * unless it is retrieved by a new call to a CoreServices getter method. * * @see CoreServices */ template class MITK_LOCAL CoreServicePointer { public: explicit CoreServicePointer(S *service, us::ModuleContext* context = us::GetModuleContext()) : m_Service(service), m_Context(context) { assert(service); } ~CoreServicePointer() { try { CoreServices::Unget(m_Service, m_Context); } catch (const std::exception &e) { MITK_ERROR << e.what(); } catch (...) { MITK_ERROR << "Ungetting core service failed."; } } S *operator->() const { return m_Service; } private: S *const m_Service; us::ModuleContext* m_Context; }; } #endif // MITKCORESERVICES_H diff --git a/Modules/Core/include/mitkIPreferences.h b/Modules/Core/include/mitkIPreferences.h new file mode 100644 index 0000000000..bdf31f2c17 --- /dev/null +++ b/Modules/Core/include/mitkIPreferences.h @@ -0,0 +1,297 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef mitkIPreferences_h +#define mitkIPreferences_h + +#include + +#include + +#include +#include +#include + +namespace mitk +{ + /** + * \brief Interface to application preferences. + * + * %Preferences are implemented as nodes in a tree structure. Each preference node may consist of + * properties, i.e. key-value pairs, and child preferences nodes. The lifetime of nodes is managed + * by their respective parent node. + * + * Use CoreServices::GetPreferencesService() and IPreferencesService::GetSystemPreferences() to + * access the application preferences, i.e. the preferences root node. + * + * Use the Node() method to traverse through the tree. + * + * Getters and setters for various data types, e.g. GetInt() and PutInt(), are provided to conveniently + * access properties as their intended data types. All preferences are ultimately stored as strings. + * + * Call Flush() to enforce the persistence of the whole (!) preferences tree. Preferences are flushed + * automatically at least on a regular application shutdown. + * + * Structural changes of a preference node can be observed via IPreferences::OnChanged. + * Property changes of a preference node can be observed via IPreferences::OnPropertyChanged. + * + * \sa CoreServices::GetPreferencesService() + * \sa IPreferencesService + */ + class MITKCORE_EXPORT IPreferences + { + public: + /** + * \brief Event object sent on IPreferences::OnPropertyChanged events. + */ + class MITKCORE_EXPORT ChangeEvent + { + public: + ChangeEvent(IPreferences* source, const std::string& property, const std::string& oldValue, const std::string& newValue); + + IPreferences* GetSource() const; + std::string GetProperty() const; + std::string GetOldValue() const; + std::string GetNewValue() const; + + private: + IPreferences* m_Source; + std::string m_Property; + std::string m_OldValue; + std::string m_NewValue; + }; + + virtual ~IPreferences(); + + /** + * \brief Get a property value as string. + * + * If the property cannot be found, return the provided default value instead. + * + * \param key Name of the property + * \param def Default value + * + * \return Property value or default value + */ + virtual std::string Get(const std::string& key, const std::string& def) const = 0; + + /** + * \brief Set a property value. + * + * Create the property if not yet existent. Otherwise change its value. + * + * Trigger an IPreferences::OnPropertyChanged event if the new value is different + * or if a new property has been created, except the string value is empty in + * the latter case. + */ + virtual void Put(const std::string& key, const std::string& value) = 0; + + /** + * \brief Get a property value as \c int. + * + * Convenience wrapper of Get() undertaking string to integer conversion. + * + * \throw Exception The property value is not a valid string representation of an \c int value. + */ + virtual int GetInt(const std::string& key, int def) const = 0; + + /** + * \brief Set an \c int property value. + * + * Convenience wrapper of Put() undertaking integer to string conversion. + */ + virtual void PutInt(const std::string& key, int value) = 0; + + /** + * \brief Get a property value as \c bool. + * + * Convenience wrapper of Get() checking if the string value literally equals \c "true". + * Returns false otherwise. The comparison is case-insensitive. + */ + virtual bool GetBool(const std::string& key, bool def) const = 0; + + /** + * \brief Set a \c bool property value. + * + * Convenience wrapper of Put() using the literal strings \c "true" and \c "false" to + * encode the \c bool value. + */ + virtual void PutBool(const std::string& key, bool value) = 0; + + /** + * \brief Get a property value as \c float. + * + * Convenience wrapper of Get() undertaking string to \c float conversion. + * + * \throw Exception The property value is not a valid string representation of a \c float value. + */ + virtual float GetFloat(const std::string& key, float def) const = 0; + + /** + * \brief Set a \c float property value. + * + * Convenience wrapper of Put() undertaking \c float to string conversion. + */ + virtual void PutFloat(const std::string& key, float value) = 0; + + /** + * \brief Get a property value as \c double. + * + * Convenience wrapper of Get() undertaking string to \c double conversion. + * + * \throw Exception The property value is not a valid string representation of a \c double value. + */ + virtual double GetDouble(const std::string& key, double def) const = 0; + + /** + * \brief Set a \c double property value. + * + * Convenience wrapper of Put() undertaking \c double to string conversion. + */ + virtual void PutDouble(const std::string& key, double value) = 0; + + /** + * \brief Get a property value as typeless binary representation. + * + * Decode a Base64-encoded property value into a typeless binary representation. + * Use \c reinterpret_cast to restore the original type: + * + * \code{.cpp} + * // Restore position and size of a widget from preferences + * std::vector geometry = preferences->GetByteArray("widget geometry", nullptr, 0); + * widget->restoreGeometry(QByteArray(reinterpret_cast(geometry.data())), geometry.size()); + * \endcode + * + * \param key Name of the property + * \param def Raw pointer to the default binary data or \c nullptr + * \param size Size of the default binary data in bytes or \c 0 in case of \c nullptr + * + * \return Decoded binary data encapsulated in a vector of bytes. Use \c std::vector::data() to get a raw pointer to the data. + */ + virtual std::vector GetByteArray(const std::string& key, const std::byte* def, size_t size) const = 0; + + /** + * \brief Put binary data into a property value. + * + * The Base64 algorithm is used to encode binary data into a valid text representation. + * Use \c reinterpret_cast to pass a raw pointer to binary data and specify its total + * number of bytes: + * + * \code{.cpp} + * // Store position and size of a widget in preferences + * QByteArray geometry = widget->saveGeometry(); + * preferences->PutByteArray("widget geometry", reinterpret_cast(geometry.data()), geometry.size()); + * \endcode + * + * \param key Name of the property + * \param array Raw pointer to binary data + * \param size Size of the binary data in bytes + */ + virtual void PutByteArray(const std::string& key, const std::byte* array, size_t size) = 0; + + /** + * \brief Write all (!) preferences to disk. + * + * Enforce the persistence of the whole preferences tree. + * + * \note Preferences are flushed automatically at least on a regular application shutdown. + * + * \sa IPreferencesStorage::Flush() + */ + virtual void Flush() = 0; + + /** + * \brief Remove a property from this preferences node. + * + * \param key Name of the property + */ + virtual void Remove(const std::string& key) = 0; + + /** + * \brief Remove all properties from this preferences node. + */ + virtual void Clear() = 0; + + /** + * \brief Get the names of all properties of this preferences node. + */ + virtual std::vector Keys() const = 0; + + /** + * \brief Get the name of this preferences node. + * + * The name can be used in an absolute or relative path separated by forward slashes to address a specific properties node. + * + * \sa AbsolutePath() const + * \sa Node() + */ + virtual std::string Name() const = 0; + + /** + * \brief Get the absolute path (relative to the root node) of this preferences node. + * + * \sa Name() const + * \sa Node() + */ + virtual std::string AbsolutePath() const = 0; + + /** + * \brief Get the names of all direct child preference nodes. + */ + virtual std::vector ChildrenNames() const = 0; + + /** + * \brief Get the parent preferences node or \c nullptr in case of the root node. + */ + virtual IPreferences* Parent() = 0; + + /** + * \sa Parent() + */ + virtual const IPreferences* Parent() const = 0; + + /** + * \brief Get the root preferences node. + */ + virtual IPreferences* Root() = 0; + + /** + * \sa Root() + */ + virtual const IPreferences* Root() const = 0; + + /** + * \brief Get (and possibly create) the preferences node specified by the given path. + * + * The path is considered to be absolute if it starts with a forward slash. It is relative to + * this preferences node otherwise. If any preferences node does not yet exist during traversal, + * it is created on the fly. + * + * \sa Name() const + * \sa AbsolutePath() const + */ + virtual IPreferences* Node(const std::string& path) = 0; + + /** + * \brief Remove this preferences node from its parent node. + * + * \note Since preferences nodes are owned by their parents, this preferences node + * is immediately deleted after removal. + */ + virtual void RemoveNode() = 0; + + Message1 OnChanged; /**< \brief Notify on structural node changes. */ + Message1 OnPropertyChanged; /**< \brief Notify on property changes. */ + }; +} + +#endif diff --git a/Modules/Core/include/mitkIPreferencesService.h b/Modules/Core/include/mitkIPreferencesService.h new file mode 100644 index 0000000000..3597af1aff --- /dev/null +++ b/Modules/Core/include/mitkIPreferencesService.h @@ -0,0 +1,84 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef mitkIPreferencesService_h +#define mitkIPreferencesService_h + +#include +#include + +#include + +namespace mitk +{ + class IPreferences; + + /** + * \brief A service for persistent application preferences. + * + * \sa CoreServices::GetPreferencesService() + * \sa IPreferences + * + * \ingroup MicroServices_Interfaces + */ + class MITKCORE_EXPORT IPreferencesService + { + public: + /** + * \brief If initialized, ask the preferences backend to flush preferences, i.e. write them to disk. + */ + virtual ~IPreferencesService(); + + /** + * \brief Initialize the preferences backend. + * + * Load preferences from the specified file. If the file does not yet exist, + * create an empty preferences storage. + * + * This method must be called once at the start of an application before + * accessing any preferences via GetSystemPreferences(). + * + * \throw Exception The method is called more than once. + * + * \sa IPreferencesStorage + */ + virtual void InitializeStorage(const std::filesystem::path& filename) = 0; + + /** + * \brief For internal use only. + * + * This method is only used for testing purposes. + * Do not use in production code. + */ + virtual void UninitializeStorage(bool removeFile = true) = 0; + + /** + * \brief Access preferences. + * + * The system preferences should be considered as resource and as such their + * lifetime is coupled to this service. It is recommended to access the + * preferences always through this method as needed instead of keeping + * a pointer permanently. + * + * \note The term "system preferences" is kept for historical reasons to stay as + * API-compatible as possible to the previous preferences service. A more + * precise term would be "application preferences". + * + * \return The root node of the preferences tree. + */ + virtual IPreferences* GetSystemPreferences() = 0; + }; +} + +MITK_DECLARE_SERVICE_INTERFACE(mitk::IPreferencesService, "org.mitk.IPreferencesService") + +#endif diff --git a/Modules/Core/include/mitkIPreferencesStorage.h b/Modules/Core/include/mitkIPreferencesStorage.h new file mode 100644 index 0000000000..950a7176c1 --- /dev/null +++ b/Modules/Core/include/mitkIPreferencesStorage.h @@ -0,0 +1,76 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef mitkIPreferencesStorage_h +#define mitkIPreferencesStorage_h + +#include + +#include + +#include +#include + +namespace mitk +{ + /** + * \brief The backend for persistent preferences. + * + * This interface and its implementation is internally used by the IPreferencesService + * to hold the preferences root node and to store and restore the preferences from disk. + */ + class MITKCORE_EXPORT IPreferencesStorage + { + public: + /** + * \brief Constructor. Load preferences from the specified file. + * + * If the file does not yet exist, create an empty preferences storage. + */ + explicit IPreferencesStorage(const std::filesystem::path& filename); + + /** + * \brief Destructor. Write preferences to disk for the last time. + */ + virtual ~IPreferencesStorage(); + + /** + * \brief Get the preferences root node. + * + * The preferences root node is owned by the preferences storage. + */ + virtual IPreferences* GetRoot(); + + /** + * \sa GetRoot() + */ + virtual const IPreferences* GetRoot() const; + + /** + * \brief Get the filename of the preferences storage. + */ + virtual std::filesystem::path GetFilename() const; + + /** + * \brief Write the in-memory preferences to disk. + * + * Usually called by clients indirectly through IPreferences::Flush(). + */ + virtual void Flush() = 0; + + protected: + std::filesystem::path m_Filename; + std::unique_ptr m_Root; + }; +} + +#endif \ No newline at end of file diff --git a/Modules/Core/src/IO/mitkIPreferences.cpp b/Modules/Core/src/IO/mitkIPreferences.cpp new file mode 100644 index 0000000000..cdae3f9b6f --- /dev/null +++ b/Modules/Core/src/IO/mitkIPreferences.cpp @@ -0,0 +1,45 @@ +/*============================================================================ + +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::IPreferences::ChangeEvent::ChangeEvent(IPreferences* source, const std::string& property, const std::string& oldValue, const std::string& newValue) + : m_Source(source), + m_Property(property), + m_OldValue(oldValue), + m_NewValue(newValue) +{ +} + +mitk::IPreferences* mitk::IPreferences::ChangeEvent::GetSource() const +{ + return m_Source; +} + +std::string mitk::IPreferences::ChangeEvent::GetProperty() const +{ + return m_Property; +} + +std::string mitk::IPreferences::ChangeEvent::GetOldValue() const +{ + return m_OldValue; +} + +std::string mitk::IPreferences::ChangeEvent::GetNewValue() const +{ + return m_NewValue; +} + +mitk::IPreferences::~IPreferences() +{ +} diff --git a/Plugins/org.blueberry.core.runtime/src/berryIPreferences.cpp b/Modules/Core/src/IO/mitkIPreferencesService.cpp similarity index 81% rename from Plugins/org.blueberry.core.runtime/src/berryIPreferences.cpp rename to Modules/Core/src/IO/mitkIPreferencesService.cpp index acaa0f5dd7..d9fd1e1662 100644 --- a/Plugins/org.blueberry.core.runtime/src/berryIPreferences.cpp +++ b/Modules/Core/src/IO/mitkIPreferencesService.cpp @@ -1,21 +1,17 @@ /*============================================================================ 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 "berryIPreferences.h" +#include -namespace berry { - -IPreferences::~IPreferences () +mitk::IPreferencesService::~IPreferencesService() { } - -} diff --git a/Modules/Core/src/IO/mitkIPreferencesStorage.cpp b/Modules/Core/src/IO/mitkIPreferencesStorage.cpp new file mode 100644 index 0000000000..9d9141ee6d --- /dev/null +++ b/Modules/Core/src/IO/mitkIPreferencesStorage.cpp @@ -0,0 +1,37 @@ +/*============================================================================ + +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::IPreferencesStorage::IPreferencesStorage(const std::filesystem::path& filename) + : m_Filename(filename) +{ +} + +mitk::IPreferencesStorage::~IPreferencesStorage() +{ +} + +mitk::IPreferences* mitk::IPreferencesStorage::GetRoot() +{ + return m_Root.get(); +} + +const mitk::IPreferences* mitk::IPreferencesStorage::GetRoot() const +{ + return m_Root.get(); +} + +std::filesystem::path mitk::IPreferencesStorage::GetFilename() const +{ + return m_Filename; +} diff --git a/Modules/Core/src/IO/mitkPreferences.cpp b/Modules/Core/src/IO/mitkPreferences.cpp new file mode 100644 index 0000000000..cc9c22172e --- /dev/null +++ b/Modules/Core/src/IO/mitkPreferences.cpp @@ -0,0 +1,298 @@ +/*============================================================================ + +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 "mitkPreferences.h" + +#include +#include + +#include +#include + +mitk::Preferences::Preferences(const Properties& properties, const std::string& name, Preferences* parent, IPreferencesStorage* storage) + : m_Properties(properties), + m_Path(parent != nullptr ? parent->AbsolutePath() + (parent->AbsolutePath() == "/" ? "" : "/") + name : "/"), + m_Name(name), + m_Parent(parent), + m_Root(parent != nullptr ? parent->m_Root : this), + m_Storage(storage) +{ + if (storage == nullptr) + mitkThrow() << "Storage must not be null!"; + + if (parent != nullptr) + parent->m_Children.emplace_back(this); +} + +mitk::Preferences::~Preferences() +{ +} + +std::string mitk::Preferences::Get(const std::string& key, const std::string& def) const +{ + auto iter = m_Properties.find(key); + + return iter != m_Properties.end() + ? iter->second + : def; +} + +void mitk::Preferences::Put(const std::string& key, const std::string& value) +{ + this->Put(key, value, [](const auto& value) { return value; }); +} + +int mitk::Preferences::GetInt(const std::string& key, int def) const +{ + auto iter = m_Properties.find(key); + + if (iter == m_Properties.end()) + return def; + + try + { + return std::stoi(iter->second); + } + catch (...) + { + mitkThrow() << "The property [\"" << key << "\": \"" << iter->second << "\"] does not represent a valid int value!"; + } +} + +void mitk::Preferences::PutInt(const std::string& key, int value) +{ + this->Put(key, value, [](const auto& value) { return std::to_string(value); }); +} + +bool mitk::Preferences::GetBool(const std::string& key, bool def) const +{ + auto iter = m_Properties.find(key); + + return iter != m_Properties.end() + ? boost::algorithm::to_lower_copy(iter->second) == "true" + : def; +} + +void mitk::Preferences::PutBool(const std::string& key, bool value) +{ + this->Put(key, value, [](const auto& value) { return value ? "true" : "false"; }); +} + +float mitk::Preferences::GetFloat(const std::string& key, float def) const +{ + auto iter = m_Properties.find(key); + + if (iter == m_Properties.end()) + return def; + + try + { + return std::stof(iter->second); + } + catch (...) + { + mitkThrow() << "The property [\"" << key << "\": \"" << iter->second << "\"] does not represent a valid float value!"; + } +} + +void mitk::Preferences::PutFloat(const std::string& key, float value) +{ + this->Put(key, value, [](const auto& value) { return std::to_string(value); }); +} + +double mitk::Preferences::GetDouble(const std::string& key, double def) const +{ + auto iter = m_Properties.find(key); + + if (iter == m_Properties.end()) + return def; + + try + { + return std::stod(iter->second); + } + catch (...) + { + mitkThrow() << "The property [\"" << key << "\": \"" << iter->second << "\"] does not represent a valid double value!"; + } +} + +void mitk::Preferences::PutDouble(const std::string& key, double value) +{ + this->Put(key, value, [](const auto& value) { return std::to_string(value); }); +} + +std::vector mitk::Preferences::GetByteArray(const std::string& key, const std::byte* def, size_t size) const +{ + using namespace boost::beast::detail; + + auto iter = m_Properties.find(key); + + if (iter == m_Properties.end()) + { + std::vector array(size); + std::copy(def, def + size, array.data()); + + return array; + } + + const auto& encodedArray = iter->second; + std::vector array(base64::decoded_size(encodedArray.size())); + auto sizes = base64::decode(array.data(), encodedArray.data(), encodedArray.size()); + + array.resize(sizes.first); + + return array; +} + +void mitk::Preferences::PutByteArray(const std::string& key, const std::byte* array, size_t size) +{ + this->Put>(key, std::make_pair(array, size), [](const auto& value) { + using namespace boost::beast::detail; + + std::vector encodedArray(base64::encoded_size(value.second) + 1, '\0'); + base64::encode(encodedArray.data(), value.first, value.second); + + return std::string(encodedArray.data()); + }); +} + +void mitk::Preferences::Remove(const std::string& key) +{ + m_Properties.erase(key); + this->OnChanged(this); +} + +void mitk::Preferences::Clear() +{ + m_Properties.clear(); + this->OnChanged(this); +} + +std::vector mitk::Preferences::Keys() const +{ + std::vector keys; + + for (const auto& property : m_Properties) + keys.push_back(property.first); + + return keys; +} + +std::vector mitk::Preferences::ChildrenNames() const +{ + std::vector names; + + for (const auto& child : m_Children) + names.push_back(child->Name()); + + return names; +} + +mitk::IPreferences* mitk::Preferences::Parent() +{ + return m_Parent; +} + +const mitk::IPreferences* mitk::Preferences::Parent() const +{ + return m_Parent; +} + +mitk::IPreferences* mitk::Preferences::Root() +{ + return m_Root; +} + +const mitk::IPreferences* mitk::Preferences::Root() const +{ + return m_Root; +} + +mitk::IPreferences* mitk::Preferences::Node(const std::string& path) +{ + if (path.empty()) + return this; + + if (path[0] == '/') + return m_Root->Node(path.substr(1)); + + std::string name; + std::string remainingPath; + + auto pos = path.find('/'); + + if (pos != std::string::npos) + { + name = path.substr(0, pos); + remainingPath = path.substr(pos + 1); + } + else + { + name = path; + } + + IPreferences* node = nullptr; + + for (const auto& child : m_Children) + { + if (child->m_Name == name) + { + node = child.get(); + break; + } + } + + if (node == nullptr) + { + node = new Preferences(Properties(), name, this, m_Storage); + this->OnChanged(this); + } + + if (pos != std::string::npos) + node = node->Node(remainingPath); + + return node; +} + +void mitk::Preferences::RemoveNode() +{ + auto& siblings = m_Parent->m_Children; + auto isMyself = [this](const std::unique_ptr& sibling) { return sibling.get() == this; }; + + siblings.erase(std::find_if(siblings.begin(), siblings.end(), isMyself)); +} + +std::string mitk::Preferences::Name() const +{ + return m_Name; +} + +std::string mitk::Preferences::AbsolutePath() const +{ + return m_Path; +} + +void mitk::Preferences::Flush() +{ + m_Storage->Flush(); +} + +const mitk::Preferences::Properties& mitk::Preferences::GetProperties() const +{ + return m_Properties; +} + +const std::vector>& mitk::Preferences::GetChildren() const +{ + return m_Children; +} diff --git a/Modules/Core/src/IO/mitkPreferences.h b/Modules/Core/src/IO/mitkPreferences.h new file mode 100644 index 0000000000..1d6e43d5f8 --- /dev/null +++ b/Modules/Core/src/IO/mitkPreferences.h @@ -0,0 +1,103 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef mitkPreferences_h +#define mitkPreferences_h + +#include + +#include +#include + +namespace mitk +{ + class IPreferencesStorage; + + /** + * \brief Implementation of the IPreferences interface. + * + * Only used through the IPreferences interface. + * + * \sa IPreferences + */ + class Preferences : public IPreferences + { + public: + using Properties = std::unordered_map; + + Preferences(const Properties& properties, const std::string& name, Preferences* parent, IPreferencesStorage* storage); + ~Preferences() override; + + Preferences(const Preferences&) = delete; + Preferences& operator=(const Preferences&) = delete; + + Preferences(Preferences&&) = default; + Preferences& operator=(Preferences&&) = default; + + std::string Get(const std::string& key, const std::string& def) const override; + void Put(const std::string& key, const std::string& value) override; + + int GetInt(const std::string& key, int def) const override; + void PutInt(const std::string& key, int value) override; + + bool GetBool(const std::string& key, bool def) const override; + void PutBool(const std::string& key, bool value) override; + + float GetFloat(const std::string& key, float def) const override; + void PutFloat(const std::string& key, float value) override; + + double GetDouble(const std::string& key, double def) const override; + void PutDouble(const std::string& key, double value) override; + + std::vector GetByteArray(const std::string& key, const std::byte* def, size_t size) const override; + void PutByteArray(const std::string& key, const std::byte* array, size_t size) override; + + void Remove(const std::string& key) override; + void Clear() override; + std::vector Keys() const override; + std::vector ChildrenNames() const override; + IPreferences* Parent() override; + const IPreferences* Parent() const override; + IPreferences* Root() override; + const IPreferences* Root() const override; + IPreferences* Node(const std::string& path) override; + void RemoveNode() override; + std::string Name() const override; + std::string AbsolutePath() const override; + void Flush() override; + + const Properties& GetProperties() const; + const std::vector>& GetChildren() const; + + private: + template + void Put(const std::string& key, const T& value, const std::function& toString) + { + const auto oldValue = m_Properties[key]; + const auto newValue = toString(value); + m_Properties[key] = newValue; + + if (oldValue != newValue) + this->OnPropertyChanged(ChangeEvent(this, key, oldValue, newValue)); + } + + Properties m_Properties; + std::vector> m_Children; + std::string m_Path; + std::string m_Name; + Preferences* m_Parent; + Preferences* m_Root; + IPreferencesStorage* m_Storage; + }; +} + +#endif diff --git a/Modules/Core/src/IO/mitkPreferencesService.cpp b/Modules/Core/src/IO/mitkPreferencesService.cpp new file mode 100644 index 0000000000..731ed4da39 --- /dev/null +++ b/Modules/Core/src/IO/mitkPreferencesService.cpp @@ -0,0 +1,49 @@ +/*============================================================================ + +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 "mitkPreferencesService.h" +#include "mitkXMLPreferencesStorage.h" + +#include + +mitk::PreferencesService::PreferencesService() +{ +} + +mitk::PreferencesService::~PreferencesService() +{ + if (m_Storage) + m_Storage->Flush(); +} + +void mitk::PreferencesService::InitializeStorage(const std::filesystem::path& filename) +{ + if (m_Storage) + mitkThrow() << "The preferences service must be initialized only once to guarantee valid preferences pointers during its lifetime."; + + m_Storage = std::make_unique(filename); +} + +void mitk::PreferencesService::UninitializeStorage(bool removeFile) +{ + if (m_Storage && removeFile) + std::filesystem::remove(m_Storage->GetFilename()); + + m_Storage.reset(nullptr); +} + +mitk::IPreferences* mitk::PreferencesService::GetSystemPreferences() +{ + return m_Storage + ? m_Storage->GetRoot() + : nullptr; +} diff --git a/Modules/Core/src/IO/mitkPreferencesService.h b/Modules/Core/src/IO/mitkPreferencesService.h new file mode 100644 index 0000000000..43bf80dc9c --- /dev/null +++ b/Modules/Core/src/IO/mitkPreferencesService.h @@ -0,0 +1,46 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef mitkPreferencesService_h +#define mitkPreferencesService_h + +#include + +#include + +namespace mitk +{ + class IPreferencesStorage; + + /** + * \brief Implementation of the IPreferencesService interface. + * + * Only used through the IPreferencesService interface. + * + * \sa IPreferencesService + */ + class PreferencesService : public IPreferencesService + { + public: + PreferencesService(); + ~PreferencesService() override; + + void InitializeStorage(const std::filesystem::path& filename) override; + void UninitializeStorage(bool removeFile) override; + IPreferences* GetSystemPreferences() override; + + private: + std::unique_ptr m_Storage; + }; +} + +#endif diff --git a/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp b/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp new file mode 100644 index 0000000000..c0ee7f6c7a --- /dev/null +++ b/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp @@ -0,0 +1,114 @@ +/*============================================================================ + +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 "mitkXMLPreferencesStorage.h" +#include "mitkPreferences.h" + +#include + +#include + +namespace +{ + std::string GetStringAttribute(const tinyxml2::XMLElement* xmlElement, const char* name) + { + const auto* attribute = xmlElement->Attribute(name); + + return attribute != nullptr + ? attribute + : ""; + } + + mitk::Preferences* Deserialize(const tinyxml2::XMLElement* xmlPreferenceElement, mitk::Preferences* parentPreferences, mitk::IPreferencesStorage* storage) + { + const std::string name = GetStringAttribute(xmlPreferenceElement, "name"); + + const auto* xmlPropertyElement = xmlPreferenceElement->FirstChildElement("property"); + mitk::Preferences::Properties properties; + + while (xmlPropertyElement != nullptr) + { + properties[GetStringAttribute(xmlPropertyElement, "name")] = GetStringAttribute(xmlPropertyElement, "value"); + xmlPropertyElement = xmlPropertyElement->NextSiblingElement("property"); + } + + auto* preferences = new mitk::Preferences(properties, name, parentPreferences, storage); + + const auto* xmlPreferenceChildElement = xmlPreferenceElement->FirstChildElement("preferences"); + + while (xmlPreferenceChildElement != nullptr) + { + Deserialize(xmlPreferenceChildElement, preferences, storage); + xmlPreferenceChildElement = xmlPreferenceChildElement->NextSiblingElement("preferences"); + } + + return preferences; + } + + void Serialize(const mitk::Preferences* preferences, tinyxml2::XMLNode* xmlParentNode) + { + auto* xmlDocument = xmlParentNode->GetDocument(); + + auto* xmlPreferenceElement = xmlDocument->NewElement("preferences"); + xmlPreferenceElement->SetAttribute("name", preferences->Name().c_str()); + + for (const auto& [name, value] : preferences->GetProperties()) + { + auto* xmlPropertyElement = xmlDocument->NewElement("property"); + xmlPropertyElement->SetAttribute("name", name.c_str()); + xmlPropertyElement->SetAttribute("value", value.c_str()); + + xmlPreferenceElement->InsertEndChild(xmlPropertyElement); + } + + xmlParentNode->InsertEndChild(xmlPreferenceElement); + + for (const auto& child : preferences->GetChildren()) + Serialize(child.get(), xmlPreferenceElement); + } +} + +mitk::XMLPreferencesStorage::XMLPreferencesStorage(const std::filesystem::path& filename) + : IPreferencesStorage(filename) +{ + if (std::filesystem::exists(filename)) + { + tinyxml2::XMLDocument xmlDocument; + + if (xmlDocument.LoadFile(filename.string().c_str()) == tinyxml2::XML_SUCCESS) + { + m_Root.reset(Deserialize(xmlDocument.RootElement(), nullptr, this)); + return; + } + else + { + MITK_ERROR << "Could not load preferences from \"" << filename.string() << "\"!"; + } + } + + m_Root = std::make_unique(Preferences::Properties(), "", nullptr, this); +} + +mitk::XMLPreferencesStorage::~XMLPreferencesStorage() +{ +} + +void mitk::XMLPreferencesStorage::Flush() +{ + tinyxml2::XMLDocument xmlDocument; + xmlDocument.InsertEndChild(xmlDocument.NewDeclaration()); + + Serialize(static_cast(m_Root.get()), &xmlDocument); + + if (xmlDocument.SaveFile(m_Filename.string().c_str()) != tinyxml2::XML_SUCCESS) + MITK_ERROR << "Could not save preferences to \"" << m_Filename.string() << "\"!"; +} diff --git a/Modules/Core/src/IO/mitkXMLPreferencesStorage.h b/Modules/Core/src/IO/mitkXMLPreferencesStorage.h new file mode 100644 index 0000000000..b982ee62a1 --- /dev/null +++ b/Modules/Core/src/IO/mitkXMLPreferencesStorage.h @@ -0,0 +1,33 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef mitkXMLPreferencesStorage_h +#define mitkXMLPreferencesStorage_h + +#include + +namespace mitk +{ + /** + * \brief See IPreferencesStorage. + */ + class XMLPreferencesStorage : public IPreferencesStorage + { + public: + explicit XMLPreferencesStorage(const std::filesystem::path& filename); + ~XMLPreferencesStorage() override; + + void Flush() override; + }; +} + +#endif diff --git a/Modules/Core/src/mitkCoreActivator.cpp b/Modules/Core/src/mitkCoreActivator.cpp index 54bd9a77b8..594cdf5490 100644 --- a/Modules/Core/src/mitkCoreActivator.cpp +++ b/Modules/Core/src/mitkCoreActivator.cpp @@ -1,365 +1,368 @@ /*============================================================================ 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 "mitkCoreActivator.h" #include #include // File IO #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkLegacyFileWriterService.h" #include #include #include // PropertyRelationRules #include // Micro Services #include #include #include #include #include #include #include #include #include #include // ITK "injects" static initialization code for IO factories // via the itkImageIOFactoryRegisterManager.h header (which // is generated in the application library build directory). // To ensure that the code is called *before* the CppMicroServices // static initialization code (which triggers the Activator::Start // method), we include the ITK header here. #include void HandleMicroServicesMessages(us::MsgType type, const char *msg) { switch (type) { case us::DebugMsg: MITK_DEBUG << msg; break; case us::InfoMsg: MITK_INFO << msg; break; case us::WarningMsg: MITK_WARN << msg; break; case us::ErrorMsg: MITK_ERROR << msg; break; } } void AddMitkAutoLoadPaths(const std::string &programPath) { us::ModuleSettings::AddAutoLoadPath(programPath); #ifdef __APPLE__ // Walk up three directories since that is where the .dylib files are located // for build trees. std::string additionalPath = programPath; bool addPath = true; for (int i = 0; i < 3; ++i) { std::size_t index = additionalPath.find_last_of('/'); if (index != std::string::npos) { additionalPath = additionalPath.substr(0, index); } else { addPath = false; break; } } if (addPath) { us::ModuleSettings::AddAutoLoadPath(additionalPath); } #endif } void AddPropertyPersistence(const mitk::PropertyKeyPath& propPath) { mitk::CoreServicePointer persistenceService(mitk::CoreServices::GetPropertyPersistence()); auto info = mitk::PropertyPersistenceInfo::New(); if (propPath.IsExplicit()) { std::string name = mitk::PropertyKeyPathToPropertyName(propPath); std::string key = name; std::replace(key.begin(), key.end(), '.', '_'); info->SetNameAndKey(name, key); } else { std::string key = mitk::PropertyKeyPathToPersistenceKeyRegEx(propPath); std::string keyTemplate = mitk::PropertyKeyPathToPersistenceKeyTemplate(propPath); std::string propRegEx = mitk::PropertyKeyPathToPropertyRegEx(propPath); std::string propTemplate = mitk::PropertyKeyPathToPersistenceNameTemplate(propPath); info->UseRegEx(propRegEx, propTemplate, key, keyTemplate); } persistenceService->AddInfo(info); } class FixedNiftiImageIO : public itk::NiftiImageIO { public: /** Standard class typedefs. */ typedef FixedNiftiImageIO Self; typedef itk::NiftiImageIO Superclass; typedef itk::SmartPointer Pointer; /** Method for creation through the object factory. */ itkNewMacro(Self) /** Run-time type information (and related methods). */ itkTypeMacro(FixedNiftiImageIO, Superclass) bool SupportsDimension(unsigned long dim) override { return dim > 1 && dim < 5; } }; void MitkCoreActivator::Load(us::ModuleContext *context) { // Handle messages from CppMicroServices us::installMsgHandler(HandleMicroServicesMessages); this->m_Context = context; // Add the current application directory to the auto-load paths. // This is useful for third-party executables. std::string programPath = mitk::IOUtil::GetProgramPath(); if (programPath.empty()) { MITK_WARN << "Could not get the program path."; } else { AddMitkAutoLoadPaths(programPath); } // m_RenderingManager = mitk::RenderingManager::New(); // context->RegisterService(renderingManager.GetPointer()); m_PlanePositionManager.reset(new mitk::PlanePositionManagerService); context->RegisterService(m_PlanePositionManager.get()); m_PropertyAliases.reset(new mitk::PropertyAliases); context->RegisterService(m_PropertyAliases.get()); m_PropertyDescriptions.reset(new mitk::PropertyDescriptions); context->RegisterService(m_PropertyDescriptions.get()); m_PropertyExtensions.reset(new mitk::PropertyExtensions); context->RegisterService(m_PropertyExtensions.get()); m_PropertyFilters.reset(new mitk::PropertyFilters); context->RegisterService(m_PropertyFilters.get()); m_PropertyPersistence.reset(new mitk::PropertyPersistence); context->RegisterService(m_PropertyPersistence.get()); m_PropertyRelations.reset(new mitk::PropertyRelations); context->RegisterService(m_PropertyRelations.get()); + m_PreferencesService.reset(new mitk::PreferencesService); + context->RegisterService(m_PreferencesService.get()); + m_MimeTypeProvider.reset(new mitk::MimeTypeProvider); m_MimeTypeProvider->Start(); m_MimeTypeProviderReg = context->RegisterService(m_MimeTypeProvider.get()); this->RegisterDefaultMimeTypes(); this->RegisterItkReaderWriter(); this->RegisterVtkReaderWriter(); // Add custom Reader / Writer Services m_FileReaders.push_back(new mitk::PointSetReaderService()); m_FileWriters.push_back(new mitk::PointSetWriterService()); m_FileReaders.push_back(new mitk::GeometryDataReaderService()); m_FileWriters.push_back(new mitk::GeometryDataWriterService()); m_FileReaders.push_back(new mitk::RawImageFileReaderService()); //add properties that should be persistent (if possible/supported by the writer) AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_DESCRIPTION()); AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_INPUTLOCATION()); AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_MIME_CATEGORY()); AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_MIME_NAME()); AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_VERSION()); AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_OPTIONS_ANY()); AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIDestinationUIDPropertyKeyPath()); AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIRelationUIDPropertyKeyPath()); AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIRuleIDPropertyKeyPath()); AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath("","").AddAnyElement()); /* There IS an option to exchange ALL vtkTexture instances against vtkNeverTranslucentTextureFactory. This code is left here as a reminder, just in case we might need to do that some time. vtkNeverTranslucentTextureFactory* textureFactory = vtkNeverTranslucentTextureFactory::New(); vtkObjectFactory::RegisterFactory( textureFactory ); textureFactory->Delete(); */ this->RegisterLegacyWriter(); } void MitkCoreActivator::Unload(us::ModuleContext *) { for (auto &elem : m_FileReaders) { delete elem; } for (auto &elem : m_FileWriters) { delete elem; } for (auto &elem : m_FileIOs) { delete elem; } for (auto &elem : m_LegacyWriters) { delete elem; } // The mitk::ModuleContext* argument of the Unload() method // will always be 0 for the Mitk library. It makes no sense // to use it at this stage anyway, since all libraries which // know about the module system have already been unloaded. // we need to close the internal service tracker of the // MimeTypeProvider class here. Otherwise it // would hold on to the ModuleContext longer than it is // actually valid. m_MimeTypeProviderReg.Unregister(); m_MimeTypeProvider->Stop(); for (std::vector::const_iterator mimeTypeIter = m_DefaultMimeTypes.begin(), iterEnd = m_DefaultMimeTypes.end(); mimeTypeIter != iterEnd; ++mimeTypeIter) { delete *mimeTypeIter; } } void MitkCoreActivator::RegisterDefaultMimeTypes() { // Register some default mime-types std::vector mimeTypes = mitk::IOMimeTypes::Get(); for (std::vector::const_iterator mimeTypeIter = mimeTypes.begin(), iterEnd = mimeTypes.end(); mimeTypeIter != iterEnd; ++mimeTypeIter) { m_DefaultMimeTypes.push_back(*mimeTypeIter); m_Context->RegisterService(m_DefaultMimeTypes.back()); } } void MitkCoreActivator::RegisterItkReaderWriter() { std::list allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); for (auto &allobject : allobjects) { auto *io = dynamic_cast(allobject.GetPointer()); // NiftiImageIO does not provide a correct "SupportsDimension()" methods // and the supported read/write extensions are not ordered correctly if (dynamic_cast(io)) continue; // Use a custom mime-type for GDCMImageIO below if (dynamic_cast(allobject.GetPointer())) { // MITK provides its own DICOM reader (which internally uses GDCMImageIO). continue; } if (io) { m_FileIOs.push_back(new mitk::ItkImageIO(io)); } else { MITK_WARN << "Error ImageIO factory did not return an ImageIOBase: " << (allobject)->GetNameOfClass(); } } FixedNiftiImageIO::Pointer itkNiftiIO = FixedNiftiImageIO::New(); mitk::ItkImageIO *niftiIO = new mitk::ItkImageIO(mitk::IOMimeTypes::NIFTI_MIMETYPE(), itkNiftiIO.GetPointer(), 0); m_FileIOs.push_back(niftiIO); } void MitkCoreActivator::RegisterVtkReaderWriter() { m_FileIOs.push_back(new mitk::SurfaceVtkXmlIO()); m_FileIOs.push_back(new mitk::SurfaceStlIO()); m_FileIOs.push_back(new mitk::SurfaceVtkLegacyIO()); m_FileIOs.push_back(new mitk::ImageVtkXmlIO()); m_FileIOs.push_back(new mitk::ImageVtkLegacyIO()); } void MitkCoreActivator::RegisterLegacyWriter() { std::list allobjects = itk::ObjectFactoryBase::CreateAllInstance("IOWriter"); for (auto i = allobjects.begin(); i != allobjects.end(); ++i) { mitk::FileWriter::Pointer io = dynamic_cast(i->GetPointer()); if (io) { std::string description = std::string("Legacy ") + io->GetNameOfClass() + " Writer"; mitk::IFileWriter *writer = new mitk::LegacyFileWriterService(io, description); m_LegacyWriters.push_back(writer); } else { MITK_ERROR << "Error IOWriter override is not of type mitk::FileWriter: " << (*i)->GetNameOfClass() << std::endl; } } } US_EXPORT_MODULE_ACTIVATOR(MitkCoreActivator) // Call CppMicroservices initialization code at the end of the file. // This especially ensures that VTK object factories have already // been registered (VTK initialization code is injected by implicitly // include VTK header files at the top of this file). US_INITIALIZE_MODULE diff --git a/Modules/Core/src/mitkCoreActivator.h b/Modules/Core/src/mitkCoreActivator.h index 4a77077c8b..e2a579ef92 100644 --- a/Modules/Core/src/mitkCoreActivator.h +++ b/Modules/Core/src/mitkCoreActivator.h @@ -1,80 +1,82 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKCOREACTIVATOR_H_ #define MITKCOREACTIVATOR_H_ // File IO #include #include #include #include #include #include #include #include #include #include #include +#include // Micro Services #include #include #include #include #include /* * This is the module activator for the "Mitk" module. It registers core services * like ... */ class MitkCoreActivator : public us::ModuleActivator { public: void Load(us::ModuleContext *context) override; void Unload(us::ModuleContext *) override; private: void HandleModuleEvent(const us::ModuleEvent moduleEvent); void RegisterDefaultMimeTypes(); void RegisterItkReaderWriter(); void RegisterVtkReaderWriter(); void RegisterLegacyWriter(); // mitk::RenderingManager::Pointer m_RenderingManager; std::unique_ptr m_PlanePositionManager; std::unique_ptr m_PropertyAliases; std::unique_ptr m_PropertyDescriptions; std::unique_ptr m_PropertyExtensions; std::unique_ptr m_PropertyFilters; std::unique_ptr m_PropertyPersistence; std::unique_ptr m_PropertyRelations; std::unique_ptr m_MimeTypeProvider; + std::unique_ptr m_PreferencesService; // File IO std::vector m_FileReaders; std::vector m_FileWriters; std::vector m_FileIOs; std::vector m_LegacyWriters; std::vector m_DefaultMimeTypes; us::ServiceRegistration m_MimeTypeProviderReg; us::ModuleContext *m_Context; }; #endif // MITKCOREACTIVATOR_H_ diff --git a/Modules/Core/src/mitkCoreServices.cpp b/Modules/Core/src/mitkCoreServices.cpp index acf5c6963f..720730347f 100644 --- a/Modules/Core/src/mitkCoreServices.cpp +++ b/Modules/Core/src/mitkCoreServices.cpp @@ -1,127 +1,133 @@ /*============================================================================ 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 "mitkCoreServices.h" #include #include #include #include #include #include #include +#include #include #include #include #include #include namespace mitk { std::mutex &s_ContextToServicesMapMutex() { static std::mutex mutex; return mutex; } std::map> &s_ContextToServicesMap() { static std::map> serviceMap; return serviceMap; } template static S *GetCoreService(us::ModuleContext *context) { if (context == nullptr) context = us::GetModuleContext(); S *coreService = nullptr; us::ServiceReference serviceRef = context->GetServiceReference(); if (serviceRef) { coreService = context->GetService(serviceRef); } assert(coreService && "Asserting non-nullptr MITK core service"); { std::lock_guard l(s_ContextToServicesMapMutex()); s_ContextToServicesMap()[context].insert(std::make_pair(coreService, serviceRef)); } return coreService; } IPropertyAliases *CoreServices::GetPropertyAliases(us::ModuleContext *context) { return GetCoreService(context); } IPropertyDescriptions *CoreServices::GetPropertyDescriptions(us::ModuleContext *context) { return GetCoreService(context); } IPropertyExtensions *CoreServices::GetPropertyExtensions(us::ModuleContext *context) { return GetCoreService(context); } IPropertyFilters *CoreServices::GetPropertyFilters(us::ModuleContext *context) { return GetCoreService(context); } IPropertyPersistence *CoreServices::GetPropertyPersistence(us::ModuleContext *context) { return GetCoreService(context); } IPropertyRelations *CoreServices::GetPropertyRelations(us::ModuleContext *context) { return GetCoreService(context); } IMimeTypeProvider *CoreServices::GetMimeTypeProvider(us::ModuleContext *context) { return GetCoreService(context); } + IPreferencesService *CoreServices::GetPreferencesService(us::ModuleContext *context) + { + return GetCoreService(context); + } + bool CoreServices::Unget(us::ModuleContext *context, const std::string & /*interfaceId*/, void *service) { bool success = false; std::lock_guard l(s_ContextToServicesMapMutex()); auto iter = s_ContextToServicesMap().find(context); if (iter != s_ContextToServicesMap().end()) { auto iter2 = iter->second.find(service); if (iter2 != iter->second.end()) { us::ServiceReferenceU serviceRef = iter2->second; if (serviceRef) { success = context->UngetService(serviceRef); if (success) { iter->second.erase(iter2); } } } } return success; } } diff --git a/Modules/Core/test/files.cmake b/Modules/Core/test/files.cmake index 1a8abcb9b6..e75b1a306d 100644 --- a/Modules/Core/test/files.cmake +++ b/Modules/Core/test/files.cmake @@ -1,198 +1,199 @@ # tests with no extra command line parameter set(MODULE_TESTS # IMPORTANT: If you plan to deactivate / comment out a test please write a bug number to the commented out line of code. # # Example: #mitkMyTest #this test is commented out because of bug 12345 # # It is important that the bug is open and that the test will be activated again before the bug is closed. This assures that # no test is forgotten after it was commented out. If there is no bug for your current problem, please add a new one and # mark it as critical. ################## DISABLED TESTS ################################################# #mitkAbstractTransformGeometryTest.cpp #seems as tested class mitkExternAbstractTransformGeometry doesn't exist any more #mitkStateMachineContainerTest.cpp #rewrite test, indirect since no longer exported Bug 14529 #mitkRegistrationBaseTest.cpp #tested class mitkRegistrationBase doesn't exist any more #mitkSegmentationInterpolationTest.cpp #file doesn't exist! #mitkPipelineSmartPointerCorrectnessTest.cpp #file doesn't exist! #mitkITKThreadingTest.cpp #test outdated because itk::Semaphore was removed from ITK #mitkAbstractTransformPlaneGeometryTest.cpp #mitkVtkAbstractTransformPlaneGeometry doesn't exist any more #mitkTestUtilSharedLibrary.cpp #Linker problem with this test... #mitkTextOverlay2DSymbolsRenderingTest.cpp #Implementation of the tested feature is not finished yet. Ask Christoph or see bug 15104 for details. ################# RUNNING TESTS ################################################### mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkDataNodeTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkFileReaderRegistryTest.cpp #mitkFileWriterRegistryTest.cpp mitkFloatToStringTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometry3DEqualTest.cpp mitkGeometryDataIOTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkImageCastTest.cpp mitkImageDataItemTest.cpp mitkImageGeneratorTest.cpp mitkIOUtilTest.cpp mitkBaseDataTest.cpp mitkImportItkImageTest.cpp mitkGrabItkImageMemoryTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetTest.cpp mitkPointSetEqualTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetOnEmptyTest.cpp mitkPointSetLocaleTest.cpp mitkPointSetWriterTest.cpp mitkPointSetPointOperationsTest.cpp mitkProgressBarTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp mitkPropertyPersistenceTest.cpp mitkPropertyPersistenceInfoTest.cpp mitkPropertyRelationRuleBaseTest.cpp mitkPropertyRelationsTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkSurfaceTest.cpp mitkSurfaceEqualTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeGeometryTest.cpp mitkProportionalTimeGeometryTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp mitkStepperTest.cpp mitkRenderingManagerTest.cpp mitkCompositePixelValueToStringTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkNodePredicateDataPropertyTest.cpp mitkNodePredicateFunctionTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp mitkPlanePositionManagerTest.cpp mitkAffineTransformBaseTest.cpp mitkPropertyAliasesTest.cpp mitkPropertyDescriptionsTest.cpp mitkPropertyExtensionsTest.cpp mitkPropertyFiltersTest.cpp mitkPropertyKeyPathTest.cpp mitkTinyXMLTest.cpp mitkRawImageFileReaderTest.cpp mitkInteractionEventTest.cpp mitkLookupTableTest.cpp mitkSTLFileReaderTest.cpp mitkPointTypeConversionTest.cpp mitkVectorTypeConversionTest.cpp mitkMatrixTypeConversionTest.cpp mitkArrayTypeConversionTest.cpp mitkSurfaceToImageFilterTest.cpp mitkBaseGeometryTest.cpp mitkImageToSurfaceFilterTest.cpp mitkEqualTest.cpp mitkLineTest.cpp mitkArbitraryTimeGeometryTest.cpp mitkItkImageIOTest.cpp mitkLevelWindowManagerTest.cpp mitkVectorPropertyTest.cpp mitkTemporoSpatialStringPropertyTest.cpp mitkPropertyNameHelperTest.cpp mitkNodePredicateGeometryTest.cpp mitkNodePredicateSubGeometryTest.cpp mitkPreferenceListReaderOptionsFunctorTest.cpp mitkGenericIDRelationRuleTest.cpp mitkSourceImageRelationRuleTest.cpp mitkTemporalJoinImagesFilterTest.cpp + mitkPreferencesTest.cpp ) set(MODULE_RENDERING_TESTS mitkPointSetDataInteractorTest.cpp mitkSurfaceVtkMapper2DTest.cpp mitkSurfaceVtkMapper2D3DTest.cpp ) # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkImageTimeSelectorTest.cpp #only runs on images mitkImageAccessorTest.cpp #only runs on images ) set(MODULE_SURFACE_TESTS mitkSurfaceVtkWriterTest.cpp #only runs on surfaces ) # list of images for which the tests are run set(MODULE_TESTIMAGE US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) set(MODULE_TESTSURFACE binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkEventConfigTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkImageVtkMapper2DOpacityTransferFunctionTest.cpp mitkImageVtkMapper2DLookupTableTest.cpp mitkSurfaceVtkMapper3DTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp mitkPointSetVtkMapper2DTest.cpp mitkPointSetVtkMapper2DImageTest.cpp mitkPointSetVtkMapper2DGlyphTypeTest.cpp mitkPointSetVtkMapper2DTransformedPointsTest.cpp mitkVTKRenderWindowSizeTest.cpp mitkMultiComponentImageDataComparisonFilterTest.cpp mitkImageToItkTest.cpp mitkImageSliceSelectorTest.cpp mitkPointSetReaderTest.cpp mitkImageEqualTest.cpp mitkRotatedSlice4DTest.cpp mitkPlaneGeometryDataMapper2DTest.cpp ) # Currently not working on windows because of a rendering timing issue # see bug 18083 for details if(NOT WIN32) set(MODULE_CUSTOM_TESTS ${MODULE_CUSTOM_TESTS} mitkSurfaceDepthSortingTest.cpp) endif() set(RESOURCE_FILES Interactions/AddAndRemovePoints.xml Interactions/globalConfig.xml Interactions/StatemachineTest.xml Interactions/StatemachineConfigTest.xml ) diff --git a/Modules/Core/test/mitkPreferencesTest.cpp b/Modules/Core/test/mitkPreferencesTest.cpp new file mode 100644 index 0000000000..d8e4fe6bca --- /dev/null +++ b/Modules/Core/test/mitkPreferencesTest.cpp @@ -0,0 +1,175 @@ +/*============================================================================ + +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 + +class mitkPreferencesTestSuite : public mitk::TestFixture +{ + CPPUNIT_TEST_SUITE(mitkPreferencesTestSuite); + + MITK_TEST(Node); + MITK_TEST(OnChanged); + MITK_TEST(OnPropertyChanged); + MITK_TEST(GetInt); + MITK_TEST(GetFloat); + + CPPUNIT_TEST_SUITE_END(); + + int m_NumberOfOnChangedEvents = 0; + int m_NumberOfOnPropertyChangedEvents = 0; + +public: + + void setUp() override + { + const auto filename = mitk::IOUtil::CreateTemporaryFile("prefs_XXXXXX.xml"); + std::filesystem::remove(filename); // We need a temporary filename, not an actual file + + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + preferencesService->InitializeStorage(filename); + } + + void tearDown() override + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + preferencesService->UninitializeStorage(); + } + + void Node() + { + auto* preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); + + // a > aa + // b > bb > bbb + // b > bb2 + + auto* aPrefs = preferences->Node("a"); + aPrefs->Node("aa"); + auto* bPrefs = aPrefs->Node("/b"); + bPrefs->Node("bb/bbb"); + preferences->Node("/b/bb2"); + auto* bbPrefs = bPrefs->Node("bb"); + + auto nodeNames = preferences->ChildrenNames(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(nodeNames.size())); + CPPUNIT_ASSERT(std::find(nodeNames.begin(), nodeNames.end(), "a") != nodeNames.end()); + CPPUNIT_ASSERT(std::find(nodeNames.begin(), nodeNames.end(), "b") != nodeNames.end()); + + nodeNames = aPrefs->ChildrenNames(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(nodeNames.size())); + CPPUNIT_ASSERT(std::find(nodeNames.begin(), nodeNames.end(), "aa") != nodeNames.end()); + + nodeNames = bPrefs->ChildrenNames(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(nodeNames.size())); + CPPUNIT_ASSERT(std::find(nodeNames.begin(), nodeNames.end(), "bb") != nodeNames.end()); + CPPUNIT_ASSERT(std::find(nodeNames.begin(), nodeNames.end(), "bb2") != nodeNames.end()); + + nodeNames = bbPrefs->ChildrenNames(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(nodeNames.size())); + CPPUNIT_ASSERT(std::find(nodeNames.begin(), nodeNames.end(), "bbb") != nodeNames.end()); + CPPUNIT_ASSERT_EQUAL(std::string("/b/bb/bbb"), bbPrefs->Node("bbb")->AbsolutePath()); + } + + void CountOnChangedEvents(const mitk::IPreferences*) + { + ++m_NumberOfOnChangedEvents; + } + + void OnChanged() + { + auto* preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); + preferences->OnChanged += mitk::MessageDelegate1(this, &mitkPreferencesTestSuite::CountOnChangedEvents); + + CPPUNIT_ASSERT_EQUAL(0, m_NumberOfOnChangedEvents); + + preferences->Node("a"); + CPPUNIT_ASSERT_EQUAL(1, m_NumberOfOnChangedEvents); + + preferences->Node("a"); + CPPUNIT_ASSERT_EQUAL(1, m_NumberOfOnChangedEvents); + + preferences->Node("a/aa/aaa"); + CPPUNIT_ASSERT_EQUAL(1, m_NumberOfOnChangedEvents); + + preferences->Node("b/bb"); + CPPUNIT_ASSERT_EQUAL(2, m_NumberOfOnChangedEvents); + + preferences->Node("b"); + CPPUNIT_ASSERT_EQUAL(2, m_NumberOfOnChangedEvents); + } + + void CountOnPropertyChangedEvents(const mitk::IPreferences::ChangeEvent& e) + { + ++m_NumberOfOnPropertyChangedEvents; + + CPPUNIT_ASSERT_EQUAL(std::string("pref"), e.GetProperty()); + CPPUNIT_ASSERT_EQUAL(std::string(""), e.GetOldValue()); + CPPUNIT_ASSERT_EQUAL(std::string("something"), e.GetNewValue()); + } + + void OnPropertyChanged() + { + auto* preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); + preferences->OnPropertyChanged += mitk::MessageDelegate1(this, &mitkPreferencesTestSuite::CountOnPropertyChangedEvents); + + CPPUNIT_ASSERT_EQUAL(0, m_NumberOfOnPropertyChangedEvents); + + preferences->Put("pref", ""); + CPPUNIT_ASSERT_EQUAL(0, m_NumberOfOnPropertyChangedEvents); + + preferences->Put("pref", "something"); + CPPUNIT_ASSERT_EQUAL(1, m_NumberOfOnPropertyChangedEvents); + } + + void GetInt() + { + auto* preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); + const int expectedValue = 42; + + preferences->PutInt("integer", expectedValue); + CPPUNIT_ASSERT_EQUAL(expectedValue, preferences->GetInt("integer", 0)); + + preferences->Put("overflow", "4200000000"); + CPPUNIT_ASSERT_THROW(preferences->GetInt("overflow", 0), mitk::Exception); + + preferences->Put("string", "fourty two"); + CPPUNIT_ASSERT_THROW(preferences->GetInt("string", 0), mitk::Exception); + } + + void GetFloat() + { + auto* preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); + float expectedValue = 3.14f; + + preferences->PutFloat("float", expectedValue); + CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedValue, preferences->GetFloat("float", 0.0f), mitk::eps); + + preferences->Put("overflow", "3.14e100"); + CPPUNIT_ASSERT_THROW(preferences->GetFloat("overflow", 0.0f), mitk::Exception); + + preferences->Put("string", "pi"); + CPPUNIT_ASSERT_THROW(preferences->GetFloat("string", 0.0f), mitk::Exception); + } +}; + +MITK_TEST_SUITE_REGISTRATION(mitkPreferences) diff --git a/Plugins/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp b/Plugins/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp index 537f7e8c7b..a83f280559 100644 --- a/Plugins/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp +++ b/Plugins/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp @@ -1,90 +1,89 @@ /*============================================================================ 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 "berrySystemTestExpression.h" #include "berryExpressions.h" #include "berryExpressionPlugin.h" -#include #include namespace berry { const QString SystemTestExpression::ATT_PROPERTY= "property"; const uint SystemTestExpression::HASH_INITIAL = qHash("berry::SystemTestExpression"); SystemTestExpression::SystemTestExpression(const IConfigurationElement::Pointer& element) { fProperty = element->GetAttribute(ATT_PROPERTY); Expressions::CheckAttribute(ATT_PROPERTY, fProperty); fExpectedValue = element->GetAttribute(ATT_VALUE); Expressions::CheckAttribute(ATT_VALUE, fExpectedValue); } SystemTestExpression::SystemTestExpression(Poco::XML::Element* element) { fProperty= QString::fromStdString(element->getAttribute(ATT_PROPERTY.toStdString())); Expressions::CheckAttribute(ATT_PROPERTY, fProperty.size() > 0 ? fProperty : QString()); fExpectedValue = QString::fromStdString(element->getAttribute(ATT_VALUE.toStdString())); Expressions::CheckAttribute(ATT_VALUE, fExpectedValue.size() > 0 ? fExpectedValue : QString()); } SystemTestExpression::SystemTestExpression(const QString &property, const QString &expectedValue) : fProperty(property), fExpectedValue(expectedValue) { } EvaluationResult::ConstPointer SystemTestExpression::Evaluate(IEvaluationContext* /*context*/) const { QString str = ExpressionPlugin::GetDefault()->GetPluginContext()->getProperty(fProperty).toString(); if (str.isEmpty()) return EvaluationResult::FALSE_EVAL; return EvaluationResult::ValueOf(str == fExpectedValue); } void SystemTestExpression::CollectExpressionInfo(ExpressionInfo* info) const { info->MarkSystemPropertyAccessed(); } bool SystemTestExpression::operator==(const Object* object) const { if (const SystemTestExpression* that = dynamic_cast(object)) { return this->fProperty == that->fProperty && this->fExpectedValue == that->fExpectedValue; } return false; } uint SystemTestExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + qHash(fExpectedValue) * HASH_FACTOR + qHash(fProperty); } QString SystemTestExpression::ToString() const { return QString(":WIN32_LEAN_AND_MEAN>") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/berryConfig.h.in" "${CMAKE_CURRENT_BINARY_DIR}/berryConfig.h" @ONLY) diff --git a/Plugins/org.blueberry.core.runtime/documentation/doxygen/modules.dox b/Plugins/org.blueberry.core.runtime/documentation/doxygen/modules.dox index 5508603d74..2b2c9601e1 100644 --- a/Plugins/org.blueberry.core.runtime/documentation/doxygen/modules.dox +++ b/Plugins/org.blueberry.core.runtime/documentation/doxygen/modules.dox @@ -1,16 +1,16 @@ /** \defgroup org_blueberry_core_runtime org.blueberry.core.runtime \ingroup BlueBerryPlugins - \brief Provides runtime services like preferences. + \brief Provides runtime services. */ /** \defgroup org_blueberry_core_runtime_internal Internal \ingroup org_blueberry_core_runtime \brief This subcategory includes the internal classes of the org.blueberry.core.runtime plugin. Other plugins must not rely on these classes. They contain implementation details and their interface may change at any time. We mean it. */ diff --git a/Plugins/org.blueberry.core.runtime/files.cmake b/Plugins/org.blueberry.core.runtime/files.cmake index e954d8f930..d929567bec 100644 --- a/Plugins/org.blueberry.core.runtime/files.cmake +++ b/Plugins/org.blueberry.core.runtime/files.cmake @@ -1,141 +1,133 @@ set(MOC_H_FILES src/berryPlugin.h src/internal/berryApplicationContainer.h src/internal/berryApplicationDescriptor.h src/internal/berryApplicationHandle.h src/internal/berryCTKPluginListener.h src/internal/berryCTKPluginActivator.h src/internal/berryErrorApplication.h src/internal/berryExtensionRegistry.h - src/internal/berryPreferencesService.h ) set(CACHED_RESOURCE_FILES plugin.xml ) set(SRC_CPP_FILES berryBackingStoreException.cpp berryContributorFactory.cpp berryCoreException.cpp berryDebugBreakpointManager.cpp berryDebugUtil.cpp berryException.cpp berryExtensionType.cpp berryIAdaptable.cpp berryIAdapterManager.cpp berryIDebugObjectListener.cpp berryILog.cpp - berryIPreferences.cpp berryIProduct.cpp - berryIBerryPreferences.cpp - berryIPreferencesService.cpp berryIProductProvider.h berryListenerList.h berryLog.cpp berryMultiStatus.cpp berryObject.cpp berryObjectGeneric.h berryObjectList.h berryObjects.cpp berryObjectString.cpp berryObjectStringMap.cpp berryObjectTypeInfo.cpp berryOperationCanceledException.cpp berryPlatform.cpp berryPlatformException.cpp berryPlatformObject.cpp berryPlugin.cpp berryReflection.cpp berrySafeRunner.cpp berrySmartPointer.h berryStatus.cpp berryWeakPointer.h # application application/berryIApplication.cpp application/berryIApplicationContext.cpp dynamichelpers/berryExtensionTracker.cpp dynamichelpers/berryIExtensionChangeHandler.cpp dynamichelpers/berryIExtensionTracker.cpp # registry registry/berryIConfigurationElement.cpp registry/berryIContributor.cpp registry/berryIExecutableExtension.cpp registry/berryIExecutableExtensionFactory.cpp registry/berryIExtension.cpp registry/berryIExtensionPoint.cpp registry/berryIExtensionPointFilter.cpp registry/berryIExtensionRegistry.cpp registry/berryInvalidRegistryObjectException.cpp registry/berryIRegistryEventListener.cpp registry/berryRegistryConstants.cpp ) set(INTERNAL_CPP_FILES - berryAbstractPreferencesStorage.cpp berryApplicationContainer.cpp berryApplicationDescriptor.cpp berryApplicationHandle.cpp berryCombinedEventDelta.cpp berryConfigurationElement.h berryConfigurationElement.cpp berryConfigurationElementAttribute.cpp berryConfigurationElementDescription.cpp berryConfigurationElementHandle.cpp berryCTKPluginActivator.cpp berryCTKPluginListener.cpp berryCTKPluginUtils.cpp berryErrorApplication.cpp berryExtension.cpp berryExtensionHandle.cpp berryExtensionPoint.cpp berryExtensionPointHandle.cpp berryExtensionRegistry.cpp berryExtensionsParser.cpp berryHandle.cpp berryIBranding.cpp berryInternalPlatform.cpp berryIObjectManager.cpp berryIRuntimeConstants.cpp berryLogImpl.cpp berryKeyedElement.cpp berryKeyedHashSet.cpp berryMainApplicationLauncher.cpp - berryPreferences.cpp - berryPreferencesService.cpp berryProduct.cpp berryProductExtensionBranding.cpp berryProviderExtensionBranding.cpp berryRegistryContribution.cpp berryRegistryContributor.cpp berryRegistryObjectFactory.cpp berryRegistryIndexChildren.cpp berryRegistryIndexElement.cpp berryRegistryMessages.cpp berryRegistryObject.cpp berryRegistryObjectManager.cpp berryRegistryObjectReferenceMap.cpp berryRegistryProperties.cpp berryRegistryStrategy.cpp berryRegistryTimestamp.cpp berryRegistrySupport.cpp berrySimpleExtensionPointFilter.cpp berryTemporaryObjectManager.cpp berryThirdLevelConfigurationElementHandle.cpp - berryXMLPreferencesStorage.cpp ) set(CPP_FILES ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp deleted file mode 100644 index c5cd9fb0fd..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "berryIBerryPreferences.h" - -namespace berry { - -IBerryPreferences::~IBerryPreferences () -{ -} - -IBerryPreferences::ChangeEvent::ChangeEvent(IBerryPreferences* source, const QString& property, - const QString& oldValue, const QString& newValue) - : m_Source(source) - , m_Property(property) - , m_OldValue(oldValue) - , m_NewValue(newValue) -{ -} - -IBerryPreferences* IBerryPreferences::ChangeEvent::GetSource() const -{ - return m_Source; -} - -QString IBerryPreferences::ChangeEvent::GetProperty() const -{ - return m_Property; -} - -QString IBerryPreferences::ChangeEvent::GetOldValue() const -{ - return m_OldValue; -} - -QString IBerryPreferences::ChangeEvent::GetNewValue() const -{ - return m_NewValue; -} - -} diff --git a/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.h b/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.h deleted file mode 100644 index f5da10242f..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.h +++ /dev/null @@ -1,67 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYIBERRYPREFERENCES_H_ -#define BERRYIBERRYPREFERENCES_H_ - -#include - -#include "berryIPreferences.h" -#include "berryMessage.h" - - -namespace berry -{ - - /** - * Like IEclipsePreferences an extension to the osgi-IPreferences - * to send out events when nodes or values changed in a node. - */ - struct org_blueberry_core_runtime_EXPORT IBerryPreferences : virtual public IPreferences - { - berryObjectMacro(berry::IBerryPreferences); - - class org_blueberry_core_runtime_EXPORT ChangeEvent { - IBerryPreferences* const m_Source; - const QString m_Property; - const QString m_OldValue; - const QString m_NewValue; - - public: - - ChangeEvent(IBerryPreferences* source, const QString& property, - const QString& oldValue, const QString& newValue); - - IBerryPreferences* GetSource() const; - QString GetProperty() const; - QString GetOldValue() const; - QString GetNewValue() const; - }; - - ~IBerryPreferences() override; - - /** - * Invoked when this node was changed, that is when a property - * was changed or when a new child node was inserted. - */ - berry::Message1 OnChanged; - - /** - * Adds a property change listener to this preferences node. - * The listener will be informed about property changes of - * this preference node, but not about changes to child nodes. - */ - berry::Message1 OnPropertyChanged; - }; - -} // namespace berry - -#endif /*BERRYIBERRYPREFERENCES_H_*/ diff --git a/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h b/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h deleted file mode 100644 index 6a60f24605..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h +++ /dev/null @@ -1,40 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYIBERRYPREFERENCESSERVICE_H_ -#define BERRYIBERRYPREFERENCESSERVICE_H_ - -#include "berryIPreferencesService.h" - -namespace berry -{ - -struct IBerryPreferencesService : public IPreferencesService -{ - /** - * Try to import the prefs from the given file. - * Existing properties will be overridden! - * Returns true if the preferences could be imported. - */ - virtual void ImportPreferences(const QString& f, const QString& name="") = 0; - - /** - * Exports the current system preferences to the given file. - */ - virtual void ExportPreferences(const QString& f, const QString& name="") = 0; - -}; - -} // namespace berry - -Q_DECLARE_INTERFACE(berry::IBerryPreferencesService, "org.blueberry.core.runtime.IBerryPreferencesService") - -#endif /*BERRYIBERRYPREFERENCESSERVICE_H_*/ diff --git a/Plugins/org.blueberry.core.runtime/src/berryIPreferences.h b/Plugins/org.blueberry.core.runtime/src/berryIPreferences.h deleted file mode 100644 index 6df73b2edf..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/berryIPreferences.h +++ /dev/null @@ -1,709 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYIPREFERENCES_H_ -#define BERRYIPREFERENCES_H_ - -#include - -#include "berryObject.h" -#include "berryBackingStoreException.h" - - -namespace berry -{ - - /** - * A node in a hierarchical collection of preference data. - * - *

- * This interface allows applications to store and retrieve user and system - * preference data. This data is stored persistently in an - * implementation-dependent backing store. Typical implementations include flat - * files, OS-specific registries, directory servers and SQL databases. - * - *

- * For each bundle, there is a separate tree of nodes for each user, and one for - * system preferences. The precise description of "user" and "system" will vary - * from one bundle to another. Typical information stored in the user preference - * tree might include font choice, and color choice for a bundle which interacts - * with the user via a servlet. Typical information stored in the system - * preference tree might include installation data, or things like high score - * information for a game program. - * - *

- * Nodes in a preference tree are named in a similar fashion to directories in a - * hierarchical file system. Every node in a preference tree has a node name - * (which is not necessarily unique), a unique absolute path name , - * and a path name relative to each ancestor including itself. - * - *

- * The root node has a node name of the empty QString object (""). - * Every other node has an arbitrary node name, specified at the time it is - * created. The only restrictions on this name are that it cannot be the empty - * string, and it cannot contain the slash character ('/'). - * - *

- * The root node has an absolute path name of "/". Children of the - * root node have absolute path names of "/" + <node name> - * . All other nodes have absolute path names of <parent's absolute - * path name> + "/" + <node name> . Note that - * all absolute path names begin with the slash character. - * - *

- * A node n 's path name relative to its ancestor a is simply the - * string that must be appended to a 's absolute path name in order to - * form n 's absolute path name, with the initial slash character (if - * present) removed. Note that: - *

    - *
  • No relative path names begin with the slash character. - *
  • Every node's path name relative to itself is the empty string. - *
  • Every node's path name relative to its parent is its node name (except - * for the root node, which does not have a parent). - *
  • Every node's path name relative to the root is its absolute path name - * with the initial slash character removed. - *
- * - *

- * Note finally that: - *

    - *
  • No path name contains multiple consecutive slash characters. - *
  • No path name with the exception of the root's absolute path name end in - * the slash character. - *
  • Any string that conforms to these two rules is a valid path name. - *
- * - *

- * Each Preference node has zero or more properties associated with - * it, where a property consists of a name and a value. The bundle writer is - * free to choose any appropriate names for properties. Their values can be of - * type QString,long,int,bool, - * std::vector,float, or double but they can - * always be accessed as if they were QString objects. - * - *

- * All node name and property name comparisons are case-sensitive. - * - *

- * All of the methods that modify preference data are permitted to operate - * asynchronously; they may return immediately, and changes will eventually - * propagate to the persistent backing store, with an implementation-dependent - * delay. The flush method may be used to synchronously force updates - * to the backing store. - * - *

- * Implementations must automatically attempt to flush to the backing store any - * pending updates for a bundle's preferences when the bundle is stopped or - * otherwise ungets the IPreferences Service. - * - *

- * The methods in this class may be invoked concurrently by multiple threads in - * a single Java Virtual Machine (JVM) without the need for external - * synchronization, and the results will be equivalent to some serial execution. - * If this class is used concurrently by multiple JVMs that store their - * preference data in the same backing store, the data store will not be - * corrupted, but no other guarantees are made concerning the consistency of the - * preference data. - * - * - * @version $Revision$ - */ - struct org_blueberry_core_runtime_EXPORT IPreferences : virtual public Object - { - berryObjectMacro(berry::IPreferences); - - ~IPreferences() override; - - /** - * Associates the specified value with the specified key in this node. - * - * @param key key with which the specified value is to be associated. - * @param value value to be associated with the specified key. - * @throws NullPointerException if key or value is - * null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - */ - virtual void Put(const QString& key, const QString& value) = 0; - - /** - * Returns the value associated with the specified key in this - * node. Returns the specified default if there is no value associated with - * the key, or the backing store is inaccessible. - * - * @param key key whose associated value is to be returned. - * @param def the value to be returned in the event that this node has no - * value associated with key or the backing store is - * inaccessible. - * @return the value associated with key, or def if - * no value is associated with key. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @throws NullPointerException if key is null. (A - * null default is permitted.) - */ - virtual QString Get(const QString& key, const QString& def) const = 0; - - /** - * Removes the value associated with the specified key in this - * node, if any. - * - * @param key key whose mapping is to be removed from this node. - * @see #Get - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - */ - virtual void Remove(const QString& key) = 0; - - /** - * Removes all of the properties (key-value associations) in this node. This - * call has no effect on any descendants of this node. - * - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #Remove(const QString&) - */ - virtual void Clear() = 0; - - /** - * Associates a QString object representing the specified - * int value with the specified key in this node. The - * associated string is the one that would be returned if the int - * value were passed to Integer.toString(int). This method is - * intended for use in conjunction with {@link #GetInt}method. - * - *

- * Implementor's note: it is not necessary that the property value - * be represented by a QString object in the backing store. If the - * backing store supports integer values, it is not unreasonable to use - * them. This implementation detail is not visible through the - * IPreferences API, which allows the value to be read as an - * int (with getInt or a QString (with - * get) type. - * - * @param key key with which the string form of value is to be associated. - * @param value value whose string form is to be associated with - * key. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #GetInt - */ - virtual void PutInt(const QString& key, int value) = 0; - - /** - * Returns the int value represented by the QString - * object associated with the specified key in this node. The - * QString object is converted to an int as by - * Integer.parseInt(QString). Returns the specified default if - * there is no value associated with the key, the backing store - * is inaccessible, or if Integer.parseInt(QString) would throw a - * NumberFormatException if the associated value were - * passed. This method is intended for use in conjunction with the - * {@link #PutInt}method. - * - * @param key key whose associated value is to be returned as an - * int. - * @param def the value to be returned in the event that this node has no - * value associated with key or the associated value - * cannot be interpreted as an int or the backing store is - * inaccessible. - * @return the int value represented by the QString - * object associated with key in this node, or - * def if the associated value does not exist or cannot - * be interpreted as an int type. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #PutInt(const QString&,int) - * @see #Get - */ - virtual int GetInt(const QString& key, int def) const = 0; - - /** - * Associates a QString object representing the specified - * long value with the specified key in this node. The - * associated QString object is the one that would be returned if - * the long value were passed to Long.toString(long). - * This method is intended for use in conjunction with the {@link #GetLong} - * method. - * - *

- * Implementor's note: it is not necessary that the value - * be represented by a QString type in the backing store. If the - * backing store supports long values, it is not unreasonable to - * use them. This implementation detail is not visible through the - * IPreferences API, which allows the value to be read as a - * long (with getLong or a QString (with - * get) type. - * - * @param key key with which the string form of value - * is to be associated. - * @param value value whose string form is to be associated with - * key. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #GetLong - */ - virtual void PutLong(const QString& key, long value) = 0; - - /** - * Returns the long value represented by the QString - * object associated with the specified key in this node. The - * QString object is converted to a long as by - * Long.parseLong(QString). Returns the specified default if - * there is no value associated with the key, the backing store - * is inaccessible, or if Long.parseLong(QString) would throw a - * NumberFormatException if the associated value were - * passed. This method is intended for use in conjunction with the - * {@link #PutLong}method. - * - * @param key key whose associated value is to be returned as a - * long value. - * @param def the value to be returned in the event that this node has no - * value associated with key or the associated value - * cannot be interpreted as a long type or the backing - * store is inaccessible. - * @return the long value represented by the QString - * object associated with key in this node, or - * def if the associated value does not exist or cannot - * be interpreted as a long type. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #PutLong(const QString&,long) - * @see #Get - */ - virtual long GetLong(const QString& key, long def) const = 0; - - /** - * Associates a QString object representing the specified - * bool value with the specified key in this node. The - * associated string is "true" if the value is true, and "false" - * if it is false. This method is intended for use in - * conjunction with the {@link #GetBool}method. - * - *

- * Implementor's note: it is not necessary that the value be - * represented by a string in the backing store. If the backing store - * supports bool values, it is not unreasonable to use them. - * This implementation detail is not visible through the IPreferences - * API, which allows the value to be read as a bool - * (with getBool) or a QString (with get) - * type. - * - * @param key key with which the string form of value is to be - * associated. - * @param value value whose string form is to be associated with - * key. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #GetBool - * @see #Get - */ - virtual void PutBool(const QString& key, bool value) = 0; - - /** - * Returns the bool value represented by the QString - * object associated with the specified key in this node. Valid - * strings are "true", which represents true, and "false", which - * represents false. Case is ignored, so, for example, "TRUE" - * and "False" are also valid. This method is intended for use in - * conjunction with the {@link #PutBool}method. - * - *

- * Returns the specified default if there is no value associated with the - * key, the backing store is inaccessible, or if the associated - * value is something other than "true" or "false", ignoring case. - * - * @param key key whose associated value is to be returned as a - * bool. - * @param def the value to be returned in the event that this node has no - * value associated with key or the associated value - * cannot be interpreted as a bool or the backing store - * is inaccessible. - * @return the bool value represented by the std::string - * object associated with key in this node, or - * null if the associated value does not exist or cannot - * be interpreted as a bool. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #Get - * @see #PutBool - */ - virtual bool GetBool(const QString& key, bool def) const = 0; - - /** - * Associates a QString object representing the specified - * float value with the specified key in this node. - * The associated QString object is the one that would be returned - * if the float value were passed to - * Float.toString(float). This method is intended for use in - * conjunction with the {@link #GetFloat}method. - * - *

- * Implementor's note: it is not necessary that the value be - * represented by a string in the backing store. If the backing store - * supports float values, it is not unreasonable to use them. - * This implementation detail is not visible through the IPreferences - * API, which allows the value to be read as a float (with - * getFloat) or a QString (with get) type. - * - * @param key key with which the string form of value is to be - * associated. - * @param value value whose string form is to be associated with - * key. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #GetFloat - */ - virtual void PutFloat(const QString& key, float value) = 0; - - /** - * Returns the float value represented by the QString - * object associated with the specified key in this node. The - * QString object is converted to a float value as by - * Float.parseFloat(QString). Returns the specified default if - * there is no value associated with the key, the backing store - * is inaccessible, or if Float.parseFloat(QString) would throw a - * NumberFormatException if the associated value were passed. - * This method is intended for use in conjunction with the {@link #PutFloat} - * method. - * - * @param key key whose associated value is to be returned as a - * float value. - * @param def the value to be returned in the event that this node has no - * value associated with key or the associated value - * cannot be interpreted as a float type or the backing - * store is inaccessible. - * @return the float value represented by the string associated - * with key in this node, or def if the - * associated value does not exist or cannot be interpreted as a - * float type. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @throws NullPointerException if key is null. - * @see #PutFloat - * @see #Get - */ - virtual float GetFloat(const QString& key, float def) const = 0; - - /** - * Associates a QString object representing the specified - * double value with the specified key in this node. - * The associated QString object is the one that would be returned - * if the double value were passed to - * Double.toString(double). This method is intended for use in - * conjunction with the {@link #GetDouble}method - * - *

- * Implementor's note: it is not necessary that the value be - * represented by a string in the backing store. If the backing store - * supports double values, it is not unreasonable to use them. - * This implementation detail is not visible through the IPreferences - * API, which allows the value to be read as a double (with - * getDouble) or a QString (with get) - * type. - * - * @param key key with which the string form of value is to be - * associated. - * @param value value whose string form is to be associated with - * key. - * @throws NullPointerException if key is null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #GetDouble - */ - virtual void PutDouble(const QString& key, double value) = 0; - - /** - * Returns the double value represented by the QString - * object associated with the specified key in this node. The - * QString object is converted to a double value as by - * Double.parseDouble(QString). Returns the specified default if - * there is no value associated with the key, the backing store - * is inaccessible, or if Double.parseDouble(QString) would throw - * a NumberFormatException if the associated value were passed. - * This method is intended for use in conjunction with the - * {@link #PutDouble}method. - * - * @param key key whose associated value is to be returned as a - * double value. - * @param def the value to be returned in the event that this node has no - * value associated with key or the associated value - * cannot be interpreted as a double type or the backing - * store is inaccessible. - * @return the double value represented by the QString - * object associated with key in this node, or - * def if the associated value does not exist or cannot - * be interpreted as a double type. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the the {@link #Remove()}method. - * @throws NullPointerException if key is null. - * @see #PutDouble - * @see #Get - */ - virtual double GetDouble(const QString& key, double def) const = 0; - - /** - * Associates a QByteArray object representing the specified - * QByteArray with the specified key in this node. The - * associated QByteArray object is stored in Base64 encoding. - * This method is intended for use in conjunction with the - * {@link #GetByteArray}method. - * - * @param key key with which the string form of value - * is to be associated. - * @param value value whose string form is to be associated with - * key. - * @throws NullPointerException if key or value is - * null. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #GetByteArray - * @see #Get - */ - virtual void PutByteArray(const QString& key, const QByteArray& value) = 0; - - /** - * Returns the QByteArray value represented by the QString - * object associated with the specified key in this node. Valid - * QString objects are Base64 encoded binary data, as - * defined in RFC 2045 , - * Section 6.8, with one minor change: the string must consist solely of - * characters from the Base64 Alphabet ; no newline characters or - * extraneous characters are permitted. This method is intended for use in - * conjunction with the {@link #PutByteArray}method. - * - *

- * Returns the specified default if there is no value associated with the - * key, the backing store is inaccessible, or if the associated - * value is not a valid Base64 encoded byte array (as defined above). - * - * @param key key whose associated value is to be returned as a - * std::vector object. - * @param def the value to be returned in the event that this node has no - * value associated with key or the associated value - * cannot be interpreted as a std::vector type, or the backing - * store is inaccessible. - * @return the std::vector value represented by the QString - * object associated with key in this node, or - * def if the associated value does not exist or cannot - * be interpreted as a std::vector. - * @throws NullPointerException if key is null. (A - * null value for def is permitted.) - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #Get - * @see #PutByteArray - */ - virtual QByteArray GetByteArray(const QString& key, const QByteArray& def) const = 0; - - /** - * Returns all of the keys that have an associated value in this node. (The - * returned array will be of size zero if this node has no preferences and - * not null!) - * - * @return an array of the keys that have an associated value in this node. - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - */ - virtual QStringList Keys() const = 0; - - /** - * Returns the names of the children of this node. (The returned array will - * be of size zero if this node has no children and not null!) - * - * @return the names of the children of this node. - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - */ - virtual QStringList ChildrenNames() const = 0; - - /** - * Returns the parent of this node, or null if this is the root. - * - * @return the parent of this node. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - */ - virtual IPreferences::Pointer Parent() const = 0; - - /** - * Returns a named IPreferences object (node), creating it and any - * of its ancestors if they do not already exist. Accepts a relative or - * absolute pathname. Absolute pathnames (which begin with '/') - * are interpreted relative to the root of this node. Relative pathnames - * (which begin with any character other than '/') are - * interpreted relative to this node itself. The empty string ("") - * is a valid relative pathname, referring to this node itself. - * - *

- * If the returned node did not exist prior to this call, this node and any - * ancestors that were created by this call are not guaranteed to become - * persistent until the flush method is called on the returned - * node (or one of its descendants). - * - * @param pathName the path name of the IPreferences object to - * return. - * @return the specified IPreferences object. - * @throws IllegalArgumentException if the path name is invalid. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @throws NullPointerException if path name is null. - * @see #Flush() - */ - virtual IPreferences::Pointer Node(const QString& pathName) = 0; - - /** - * Returns true if the named node exists. Accepts a relative or absolute - * pathname. Absolute pathnames (which begin with '/') are - * interpreted relative to the root of this node. Relative pathnames (which - * begin with any character other than '/') are interpreted - * relative to this node itself. The pathname "" is valid, and - * refers to this node itself. - * - *

- * If this node (or an ancestor) has already been removed with the - * {@link #Remove()}method, it is legal to invoke this method, - * but only with the pathname ""; the invocation will return - * false. Thus, the idiom p.nodeExists("") may be - * used to test whether p has been removed. - * - * @param pathName the path name of the node whose existence is to be - * checked. - * @return true if the specified node exists. - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method and - * pathname is not the empty string (""). - * @throws IllegalArgumentException if the path name is invalid (i.e., it - * contains multiple consecutive slash characters, or ends with a - * slash character and is more than one character long). - */ - virtual bool NodeExists(const QString& pathName) const = 0; - - /** - * Removes this node and all of its descendants, invalidating any properties - * contained in the removed nodes. Once a node has been removed, attempting - * any method other than name(),absolutePath() or - * nodeExists("") on the corresponding IPreferences - * instance will fail with an IllegalStateException. (The - * methods defined on Object can still be invoked on a node after - * it has been removed; they will not throw IllegalStateException.) - * - *

- * The removal is not guaranteed to be persistent until the flush - * method is called on the parent of this node. - * - * @throws IllegalStateException if this node (or an ancestor) has already - * been removed with the {@link #Remove()}method. - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @see #Flush() - */ - virtual void RemoveNode() = 0; - - /** - * Returns this node's name, relative to its parent. - * - * @return this node's name, relative to its parent. - */ - virtual QString Name() const = 0; - - /** - * Returns this node's absolute path name. Note that: - *

    - *
  • Root node - The path name of the root node is "/". - *
  • Slash at end - Path names other than that of the root node may not - * end in slash ('/'). - *
  • Unusual names -"." and ".." have no - * special significance in path names. - *
  • Illegal names - The only illegal path names are those that contain - * multiple consecutive slashes, or that end in slash and are not the root. - *
- * - * @return this node's absolute path name. - */ - virtual QString AbsolutePath() const = 0; - - /** - * Forces any changes in the contents of this node and its descendants to - * the persistent store. - * - *

- * Once this method returns successfully, it is safe to assume that all - * changes made in the subtree rooted at this node prior to the method - * invocation have become permanent. - * - *

- * Implementations are free to flush changes into the persistent store at - * any time. They do not need to wait for this method to be called. - * - *

- * When a flush occurs on a newly created node, it is made persistent, as - * are any ancestors (and descendants) that have yet to be made persistent. - * Note however that any properties value changes in ancestors are not - * guaranteed to be made persistent. - * - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #Sync() - */ - virtual void Flush() = 0; - - /** - * Ensures that future reads from this node and its descendants reflect any - * changes that were committed to the persistent store (from any VM) prior - * to the sync invocation. As a side-effect, forces any changes - * in the contents of this node and its descendants to the persistent store, - * as if the flush method had been invoked on this node. - * - * @throws BackingStoreException if this operation cannot be completed due - * to a failure in the backing store, or inability to communicate - * with it. - * @throws IllegalStateException if this node (or an ancestor) has been - * removed with the {@link #Remove()}method. - * @see #Flush() - */ - virtual void Sync() = 0; - - /** - * Sets a flag to the parameter block which can be used to - * block berry messages in order to prevent callback functions to be called. - * - * @param block boolean to set the flag - */ - virtual void BlockSignals(bool block) = 0; - }; - -} // namespace berry - -#endif /*BERRYIPREFERENCES_H_*/ diff --git a/Plugins/org.blueberry.core.runtime/src/berryIPreferencesService.cpp b/Plugins/org.blueberry.core.runtime/src/berryIPreferencesService.cpp deleted file mode 100644 index 915eabde36..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/berryIPreferencesService.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include "berryIPreferencesService.h" - -namespace berry -{ - -IPreferencesService::~IPreferencesService() -{ -} - -} diff --git a/Plugins/org.blueberry.core.runtime/src/berryIPreferencesService.h b/Plugins/org.blueberry.core.runtime/src/berryIPreferencesService.h deleted file mode 100644 index 66c9016d9c..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/berryIPreferencesService.h +++ /dev/null @@ -1,71 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYIPREFERENCESSERVICE_H_ -#define BERRYIPREFERENCESSERVICE_H_ - -#include - -#include - -namespace berry -{ - -template class SmartPointer; - -struct IPreferences; - -/** - * The Preferences Service. - * - *

- * Each bundle using this service has its own set of preference trees: one for - * system preferences, and one for each user. - * - *

- * A PreferencesService object is specific to the bundle which - * obtained it from the service registry. If a bundle wishes to allow another - * bundle to access its preferences, it should pass its - * PreferencesService object to that bundle. - * - */ -struct org_blueberry_core_runtime_EXPORT IPreferencesService -{ - virtual ~IPreferencesService(); - - /** - * Returns the root system node for the calling bundle. - * - * @return The root system node for the calling bundle. - */ - virtual SmartPointer GetSystemPreferences() = 0; - - /** - * Returns the root node for the specified user and the calling bundle. - * - * @param name The user for which to return the preference root node. - * @return The root node for the specified user and the calling bundle. - */ - virtual SmartPointer GetUserPreferences(const QString& name) = 0; - - /** - * Returns the names of users for which node trees exist. - * - * @return The names of users for which node trees exist. - */ - virtual QStringList GetUsers() const = 0; -}; - -} // namespace berry - -Q_DECLARE_INTERFACE(berry::IPreferencesService, "org.blueberry.service.IPreferencesService") - -#endif /*BERRYIPREFERENCESSERVICE_H_*/ diff --git a/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp b/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp index a30ccd79f3..5f56017ae6 100644 --- a/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp +++ b/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp @@ -1,247 +1,247 @@ /*============================================================================ 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 "berryPlatform.h" #include #include "internal/berryInternalPlatform.h" #include "internal/berryIRuntimeConstants.h" #include namespace berry { const QString Platform::PI_RUNTIME = IRuntimeConstants::PI_RUNTIME(); const int Platform::OS_FREE_BSD = BERRY_OS_FREE_BSD; const int Platform::OS_AIX = BERRY_OS_AIX; const int Platform::OS_HPUX = BERRY_OS_HPUX; const int Platform::OS_TRU64 = BERRY_OS_TRU64; const int Platform::OS_LINUX = BERRY_OS_LINUX; const int Platform::OS_MAC_OS_X = BERRY_OS_MAC_OS_X; const int Platform::OS_NET_BSD = BERRY_OS_NET_BSD; const int Platform::OS_OPEN_BSD = BERRY_OS_OPEN_BSD; const int Platform::OS_IRIX = BERRY_OS_IRIX; const int Platform::OS_SOLARIS = BERRY_OS_SOLARIS; const int Platform::OS_QNX = BERRY_OS_QNX; const int Platform::OS_VXWORKS = BERRY_OS_VXWORKS; const int Platform::OS_CYGWIN = BERRY_OS_CYGWIN; const int Platform::OS_UNKNOWN_UNIX = BERRY_OS_UNKNOWN_UNIX; const int Platform::OS_WINDOWS_NT = BERRY_OS_WINDOWS_NT; const int Platform::OS_WINDOWS_CE = BERRY_OS_WINDOWS_CE; const int Platform::OS_VMS = BERRY_OS_VMS; const int Platform::ARCH_ALPHA = BERRY_ARCH_ALPHA; const int Platform::ARCH_IA32 = BERRY_ARCH_IA32; const int Platform::ARCH_IA64 = BERRY_ARCH_IA64; const int Platform::ARCH_MIPS = BERRY_ARCH_MIPS; const int Platform::ARCH_HPPA = BERRY_ARCH_HPPA; const int Platform::ARCH_PPC = BERRY_ARCH_PPC; const int Platform::ARCH_POWER = BERRY_ARCH_POWER; const int Platform::ARCH_SPARC = BERRY_ARCH_SPARC; const int Platform::ARCH_AMD64 = BERRY_ARCH_AMD64; const int Platform::ARCH_ARM = BERRY_ARCH_ARM; const QString Platform::PROP_QTPLUGIN_PATH = "BlueBerry.qtplugin_path"; const QString Platform::PROP_NEWINSTANCE = "BlueBerry.newInstance"; const QString Platform::PROP_APPLICATION = "BlueBerry.application"; const QString Platform::PROP_PLUGIN_DIRS = "BlueBerry.plugin_dirs"; const QString Platform::PROP_FORCE_PLUGIN_INSTALL = "BlueBerry.forcePlugins"; const QString Platform::PROP_IGNOREAPP = "BlueBerry.ignoreApp"; const QString Platform::PROP_XARGS = "xargs"; QDir Platform::GetConfigurationPath() { ctkLocation* location = GetConfigurationLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetConfigurationLocation() { return InternalPlatform::GetInstance()->GetConfigurationLocation(); } IAdapterManager* Platform::GetAdapterManager() { return InternalPlatform::GetInstance()->GetAdapterManager(); } IExtensionRegistry *Platform::GetExtensionRegistry() { return InternalPlatform::GetInstance()->GetExtensionRegistry(); } -IPreferencesService *Platform::GetPreferencesService() +mitk::IPreferencesService *Platform::GetPreferencesService() { return InternalPlatform::GetInstance()->GetPreferencesService(); } //PlatformEvents& Platform::GetEvents() //{ // return InternalPlatform::GetInstance()->GetEvents(); //} QDir Platform::GetInstallPath() { ctkLocation* location = GetInstallLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetInstallLocation() { return InternalPlatform::GetInstance()->GetInstallLocation(); } QDir Platform::GetInstancePath() { ctkLocation* location = GetInstanceLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetInstanceLocation() { return InternalPlatform::GetInstance()->GetInstanceLocation(); } int Platform::GetOS() { return BERRY_OS; } int Platform::GetOSArch() { return BERRY_ARCH; } bool Platform::IsUnix() { #ifdef BERRY_OS_FAMILY_UNIX return true; #else return false; #endif } bool Platform::IsWindows() { #ifdef BERRY_OS_FAMILY_WINDOWS return true; #else return false; #endif } bool Platform::IsBSD() { #ifdef BERRY_OS_FAMILY_BSD return true; #else return false; #endif } bool Platform::IsLinux() { #ifdef BERRY_OS_FAMILY_LINUX return true; #else return false; #endif } bool Platform::IsVMS() { #ifdef BERRY_OS_FAMILY_VMS return true; #else return false; #endif } bool Platform::GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool /*create*/) { statePath = GetStateLocation(plugin); return true; } QDir Platform::GetStateLocation(const QSharedPointer& plugin) { return InternalPlatform::GetInstance()->GetStateLocation(plugin); } QDir Platform::GetUserPath() { ctkLocation* location = GetUserLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetUserLocation() { return InternalPlatform::GetInstance()->GetUserLocation(); } bool Platform::IsRunning() { return InternalPlatform::GetInstance()->IsRunning(); } QStringList Platform::GetApplicationArgs() { return InternalPlatform::GetInstance()->GetApplicationArgs(); } QSharedPointer Platform::GetPlugin(const QString& symbolicName) { return InternalPlatform::GetInstance()->GetPlugin(symbolicName); } QList > Platform::GetPlugins(const QString& symbolicName, const QString& version) { return InternalPlatform::GetInstance()->GetPlugins(symbolicName, version); } QVariant berry::Platform::GetDebugOption(const QString& option) { return InternalPlatform::GetInstance()->GetOption(option); } IProduct::Pointer berry::Platform::GetProduct() { return InternalPlatform::GetInstance()->GetProduct(); } } diff --git a/Plugins/org.blueberry.core.runtime/src/berryPlatform.h b/Plugins/org.blueberry.core.runtime/src/berryPlatform.h index bc387e20f2..93adec4ea1 100644 --- a/Plugins/org.blueberry.core.runtime/src/berryPlatform.h +++ b/Plugins/org.blueberry.core.runtime/src/berryPlatform.h @@ -1,494 +1,494 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRY_Platform_INCLUDED #define BERRY_Platform_INCLUDED // // Platform Identification // #define BERRY_OS_FREE_BSD 0x0001 #define BERRY_OS_AIX 0x0002 #define BERRY_OS_HPUX 0x0003 #define BERRY_OS_TRU64 0x0004 #define BERRY_OS_LINUX 0x0005 #define BERRY_OS_MAC_OS_X 0x0006 #define BERRY_OS_NET_BSD 0x0007 #define BERRY_OS_OPEN_BSD 0x0008 #define BERRY_OS_IRIX 0x0009 #define BERRY_OS_SOLARIS 0x000a #define BERRY_OS_QNX 0x000b #define BERRY_OS_VXWORKS 0x000c #define BERRY_OS_CYGWIN 0x000d #define BERRY_OS_UNKNOWN_UNIX 0x00ff #define BERRY_OS_WINDOWS_NT 0x1001 #define BERRY_OS_WINDOWS_CE 0x1011 #define BERRY_OS_VMS 0x2001 #if defined(__FreeBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_FREE_BSD #elif defined(_AIX) || defined(__TOS_AIX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_AIX #elif defined(hpux) || defined(_hpux) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_HPUX #elif defined(__digital__) || defined(__osf__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_TRU64 #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__TOS_LINUX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_LINUX #elif defined(__APPLE__) || defined(__TOS_MACOS__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_MAC_OS_X #elif defined(__NetBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_NET_BSD #elif defined(__OpenBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_OPEN_BSD #elif defined(sgi) || defined(__sgi) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_IRIX #elif defined(sun) || defined(__sun) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_SOLARIS #elif defined(__QNX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_QNX #elif defined(unix) || defined(__unix) || defined(__unix__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_UNKNOWN_UNIX #elif defined(_WIN32_WCE) #define BERRY_OS_FAMILY_WINDOWS 1 #define BERRY_OS BERRY_OS_WINDOWS_CE #elif defined(_WIN32) || defined(_WIN64) #define BERRY_OS_FAMILY_WINDOWS 1 #define BERRY_OS BERRY_OS_WINDOWS_NT #elif defined(__CYGWIN__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_CYGWIN #elif defined(__VMS) #define BERRY_OS_FAMILY_VMS 1 #define BERRY_OS BERRY_OS_VMS #endif // // Hardware Architecture and Byte Order // #define BERRY_ARCH_ALPHA 0x01 #define BERRY_ARCH_IA32 0x02 #define BERRY_ARCH_IA64 0x03 #define BERRY_ARCH_MIPS 0x04 #define BERRY_ARCH_HPPA 0x05 #define BERRY_ARCH_PPC 0x06 #define BERRY_ARCH_POWER 0x07 #define BERRY_ARCH_SPARC 0x08 #define BERRY_ARCH_AMD64 0x09 #define BERRY_ARCH_ARM 0x0a #if defined(__ALPHA) || defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA) #define BERRY_ARCH BERRY_ARCH_ALPHA #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) #define BERRY_ARCH BERRY_ARCH_IA32 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(_IA64) || defined(__IA64__) || defined(__ia64__) || defined(__ia64) || defined(_M_IA64) #define BERRY_ARCH BERRY_ARCH_IA64 #if defined(hpux) || defined(_hpux) #define BERRY_ARCH_BIG_ENDIAN 1 #else #define BERRY_ARCH_LITTLE_ENDIAN 1 #endif #elif defined(__x86_64__) #define BERRY_ARCH BERRY_ARCH_AMD64 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(_M_X64) #define BERRY_ARCH BERRY_ARCH_AMD64 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(_M_MRX000) #define BERRY_ARCH BERRY_ARCH_MIPS #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__hppa) || defined(__hppa__) #define BERRY_ARCH BERRY_ARCH_HPPA #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__PPC) || defined(__POWERPC__) || defined(__powerpc) || defined(__PPC__) || \ defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC) || defined(_M_PPC) #define BERRY_ARCH BERRY_ARCH_PPC #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_ARCH_PWR3) || \ defined(_ARCH_PWR4) || defined(__THW_RS6000) #define BERRY_ARCH BERRY_ARCH_POWER #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__sparc__) || defined(__sparc) || defined(sparc) #define BERRY_ARCH BERRY_ARCH_SPARC #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM) #define BERRY_ARCH BERRY_ARCH_ARM #if defined(__ARMEB__) #define BERRY_ARCH_BIG_ENDIAN 1 #else #define BERRY_ARCH_LITTLE_ENDIAN 1 #endif #endif #include #include #include #include struct ctkLocation; class ctkPlugin; namespace Poco { class Path; } +namespace mitk +{ + class IPreferencesService; +} + namespace berry { struct IAdapterManager; struct IBundle; struct IExtensionPointService; struct IExtensionRegistry; -struct IPreferencesService; struct IProduct; /** * The central class of the BlueBerry Platform Runtime. This class cannot * be instantiated or subclassed by clients; all functionality is provided * by static methods. Features include: *

    *
  • the platform registry of installed plug-ins
  • *
  • the platform adapter manager
  • *
  • the platform log
  • *
*

* Most users don't have to worry about Platform's lifecycle. However, if your * code can call methods of this class when Platform is not running, it becomes * necessary to check {@link #IsRunning()} before making the call. A runtime * exception might be thrown or incorrect result might be returned if a method * from this class is called while Platform is not running. *

*/ class org_blueberry_core_runtime_EXPORT Platform { public: static const QString PI_RUNTIME; static const int OS_FREE_BSD; static const int OS_AIX; static const int OS_HPUX; static const int OS_TRU64; static const int OS_LINUX; static const int OS_MAC_OS_X; static const int OS_NET_BSD; static const int OS_OPEN_BSD; static const int OS_IRIX; static const int OS_SOLARIS; static const int OS_QNX; static const int OS_VXWORKS; static const int OS_CYGWIN; static const int OS_UNKNOWN_UNIX; static const int OS_WINDOWS_NT; static const int OS_WINDOWS_CE; static const int OS_VMS; static const int ARCH_ALPHA; static const int ARCH_IA32; static const int ARCH_IA64; static const int ARCH_MIPS; static const int ARCH_HPPA; static const int ARCH_PPC; static const int ARCH_POWER; static const int ARCH_SPARC; static const int ARCH_AMD64; static const int ARCH_ARM; static const QString PROP_QTPLUGIN_PATH; static const QString PROP_NEWINSTANCE; static const QString PROP_PLUGIN_DIRS; static const QString PROP_FORCE_PLUGIN_INSTALL; static const QString PROP_APPLICATION; static const QString PROP_IGNOREAPP; static const QString PROP_XARGS; /** * Returns the adapter manager used for extending * IAdaptable objects. * * @return the adapter manager for this platform * @see IAdapterManager */ static IAdapterManager* GetAdapterManager(); /** * Returns the extension registry for this platform. * May return null if the registry has not been created yet. * * @return existing extension registry or null * @see IExtensionRegistry */ static IExtensionRegistry* GetExtensionRegistry(); /** * Return the interface into the preference mechanism. The returned * object can be used for such operations as searching for preference - * values across multiple scopes and preference import/export. - *

- * Clients are also able to acquire the IPreferencesService service via - * CTK mechanisms and use it for preference functions. - *

+ * values across multiple scopes. * * @return an object to interface into the preference mechanism */ - static IPreferencesService* GetPreferencesService(); + static mitk::IPreferencesService* GetPreferencesService(); /** * Returns the product which was selected when running this BlueBerry instance * or null if none * @return the current product or null if none */ static SmartPointer GetProduct(); /** * Returns the identified option. A null QString * is returned if no such option is found. Options are specified * in the general form <plug-in id>/<option-path>. * For example, org.blueberry.core.runtime/debug *

* Clients are also able to acquire the \c DebugOptions service * and query it for debug options. *

* @param option the name of the option to lookup * @return the value of the requested debug option or QString::null */ static QVariant GetDebugOption(const QString& option); /** * Returns the path of the configuration information * used to run this instance of the BlueBerry platform. * The configuration area typically * contains the list of plug-ins available for use, various settings * (those shared across different instances of the same configuration) * and any other such data needed by plug-ins. * An empty path is returned if the platform is running without a configuration location. * * @return the location of the platform's configuration data area * @deprecatedSince{2015_05} Use GetConfigurationLocation() instead. */ QT_DEPRECATED static QDir GetConfigurationPath(); /** * Returns the location of the configuration information * used to run this instance of BlueBerry. The configuration area typically * contains the list of plug-ins available for use, various settings * (those shared across different instances of the same configuration) * and any other such data needed by plug-ins. * null is returned if the platform is running without a configuration location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::CONFIGURATION_FILTER. *

* @return the location of the platform's configuration data area or null if none * @see ctkLocation::CONFIGURATION_FILTER */ static ctkLocation* GetConfigurationLocation(); /** * Returns the path of the base installation for the running platform * * @return the location of the platform's installation area or null if none * @deprecatedSince{2015_05} Use GetInstallLocation() instead. */ QT_DEPRECATED static QDir GetInstallPath(); /** * Returns the location of the base installation for the running platform * null is returned if the platform is running without a configuration location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::INSTALL_FILTER. *

* @return the location of the platform's installation area or null if none * @see ctkLocation::INSTALL_FILTER */ static ctkLocation* GetInstallLocation(); /** * Returns the path of the platform's working directory (also known as the instance data area). * An empty path is returned if the platform is running without an instance location. * * @return the location of the platform's instance data area or null if none * @deprecatedSince{2015_05} Use GetInstanceLocation() instead. */ QT_DEPRECATED static QDir GetInstancePath(); /** * Returns the location of the platform's working directory (also known as the instance data area). * null is returned if the platform is running without an instance location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::INSTANCE_FILTER. *

* @return the location of the platform's instance data area or null if none * @see ctkLocation::INSTANCE_FILTER */ static ctkLocation* GetInstanceLocation(); /** * Returns the path in the local file system of the * plug-in state area for the given plug-in. * If the plug-in state area did not exist prior to this call, * it is created. *

* The plug-in state area is a file directory within the * platform's metadata area where a plug-in is free to create files. * The content and structure of this area is defined by the plug-in, * and the particular plug-in is solely responsible for any files * it puts there. It is recommended for plug-in preference settings and * other configuration parameters. *

* * @param statePath * @param plugin the plug-in whose state location is returned * @param create * @return a local file system path * TODO Investigate the usage of a service factory * @deprecatedSince{2015_05} Use GetStateLocation instead. */ QT_DEPRECATED static bool GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create = true); /** * Returns the location in the local file system of the * plug-in state area for the given plug-in. * If the plug-in state area did not exist prior to this call, * it is created. *

* The plug-in state area is a file directory within the * platform's metadata area where a plug-in is free to create files. * The content and structure of this area is defined by the plug-in, * and the particular plug-in is solely responsible for any files * it puts there. It is recommended for plug-in preference settings and * other configuration parameters. *

* * @param plugin the plugin whose state location if returned * @return a local file system path * @throws ctkIllegalStateException if no instance location was specified * @throws RuntimeException if the plug-in state area could not be created. */ static QDir GetStateLocation(const QSharedPointer& plugin); /** * Returns the path of the platform's user data area. The user data area is a location on the system * which is specific to the system's current user. By default it is located relative to the * location given by the System property "user.home". * An empty path is returned if the platform is running without an user location. * * @return the location of the platform's user data area or null if none * @deprecatedSince{2015_05} Use GetUserLocation() instead. */ QT_DEPRECATED static QDir GetUserPath(); /** * Returns the location of the platform's user data area. The user data area is a location on the system * which is specific to the system's current user. By default it is located relative to the * location given by the system property "user.home". * null is returned if the platform is running without an user location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::USER_FILTER. *

* @return the location of the platform's user data area or null if none * @see ctkLocation::USER_FILTER */ static ctkLocation* GetUserLocation(); static int GetOS(); static int GetOSArch(); static bool IsUnix(); static bool IsWindows(); static bool IsBSD(); static bool IsLinux(); static bool IsVMS(); static bool IsRunning(); /** * Returns the applications command line arguments which * have not been consumed by the platform. */ static QStringList GetApplicationArgs(); /** * Returns the resolved plug-in with the specified symbolic name that has the * highest version. If no resolved plug-ins are installed that have the * specified symbolic name then null is returned. *

* Note that clients may want to filter * the results based on the state of the plug-ins. *

* @param symbolicName the symbolic name of the plug-in to be returned. * @return the plug-in that has the specified symbolic name with the * highest version, or null if no plug-in is found. */ static QSharedPointer GetPlugin(const QString& symbolicName); /** * Returns all plug-ins with the specified symbolic name. If no resolved plug-ins * with the specified symbolic name can be found, an empty list is returned. * If the version argument is not null then only the plug-ins that have * the specified symbolic name and a version greater than or equal to the * specified version are returned. The returned plug-ins are ordered in * descending plug-in version order. *

* Note that clients may want to filter * the results based on the state of the plug-ins. *

* @param symbolicName the symbolic name of the plug-ins that are to be returned. * @param version the version that the returned plug-in versions must match, * or QString() if no version matching is to be done. * @return the list of plug-ins with the specified name that match the * specified version and match rule, or null if no plug-ins are found. */ static QList > GetPlugins(const QString& symbolicName, const QString& version = QString()); private: Platform(); }; } // namespace #endif // BERRY_Platform_INCLUDED diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.cpp deleted file mode 100644 index ad62f111b5..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include "berryAbstractPreferencesStorage.h" - -#include - -namespace berry -{ - - AbstractPreferencesStorage::AbstractPreferencesStorage( const QString& _File ) - : m_File(_File) - , m_Root(nullptr) - { - - } - - AbstractPreferencesStorage::~AbstractPreferencesStorage() - { - - } - - IPreferences::Pointer AbstractPreferencesStorage::GetRoot() const - { - return m_Root; - } - - QString AbstractPreferencesStorage::GetFile() const - { - return m_File; - } - - void AbstractPreferencesStorage::SetFile( const QString& f ) - { - m_File = f; - } -} diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h b/Plugins/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h deleted file mode 100644 index 345e97e89b..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h +++ /dev/null @@ -1,78 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYABSTRACTPREFERENCESSTORAGE_H_ -#define BERRYABSTRACTPREFERENCESSTORAGE_H_ - -#include - -#include - - -namespace berry -{ - -struct IPreferences; - - /// - /// Interface to flush Preferences. - /// - class org_blueberry_core_runtime_EXPORT AbstractPreferencesStorage : public Object - { - - public: - - berryObjectMacro(berry::AbstractPreferencesStorage); - - /// - /// Saves the path, sets the root initially to 0. - /// In subclasses try to read data from file here. - /// - AbstractPreferencesStorage(const QString& _File); - - /// - /// Pure virtual (abstract class) - /// - ~AbstractPreferencesStorage() override; - - /// - /// Flushes the given (or all) prefs persistently - /// - virtual void Flush(IPreferences* prefs) = 0; - - /// - /// Returns the root prefs - /// - virtual SmartPointer GetRoot() const; - - /// - /// Returns the path of the file - /// - virtual QString GetFile() const; - - /// - /// Sets the file - /// - virtual void SetFile(const QString& f); - - protected: - - /// - /// Path to the file where the data is stored - /// - QString m_File; - /// - /// Pointer to the root Preferences - /// - SmartPointer m_Root; - }; -} -#endif /* BERRYABSTRACTPREFERENCESSTORAGE_H_ */ diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp index 1db15fcebf..e95b2dbebc 100755 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp @@ -1,293 +1,284 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryCTKPluginActivator.h" #include #include #include #include "berryApplicationContainer.h" #include "berryPlatform.h" #include "berryInternalPlatform.h" #include "berryErrorApplication.h" -#include "berryPreferencesService.h" #include "berryExtensionRegistry.h" #include "berryRegistryConstants.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include "berryRegistryContributor.h" #include #include namespace berry { static const QString XP_APPLICATIONS = "org.blueberry.osgi.applications"; ctkPluginContext* org_blueberry_core_runtime_Activator::context = nullptr; QScopedPointer org_blueberry_core_runtime_Activator::appContainer; const bool org_blueberry_core_runtime_Activator::DEBUG = false; void org_blueberry_core_runtime_Activator::start(ctkPluginContext* context) { this->context = context; BERRY_REGISTER_EXTENSION_CLASS(ErrorApplication, context) RegistryProperties::SetContext(context); //ProcessCommandLine(); this->startRegistry(); - preferencesService.reset(new PreferencesService(context->getDataFile("").absolutePath())); - prefServiceReg = context->registerService(preferencesService.data()); - // // register a listener to catch new plugin installations/resolutions. // pluginListener.reset(new CTKPluginListener(m_ExtensionPointService)); // context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // // populate the registry with all the currently installed plugins. // // There is a small window here while processPlugins is being // // called where the pluginListener may receive a ctkPluginEvent // // to add/remove a plugin from the registry. This is ok since // // the registry is a synchronized object and will not add the // // same bundle twice. // pluginListener->processPlugins(context->getPlugins()); this->startAppContainer(); InternalPlatform::GetInstance()->Start(context); } void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context) { InternalPlatform::GetInstance()->Stop(context); //pluginListener.reset(); //Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID); - prefServiceReg.unregister(); - preferencesService->ShutDown(); - preferencesService.reset(); - prefServiceReg = 0; - this->stopRegistry(); RegistryProperties::SetContext(nullptr); stopAppContainer(); this->context = nullptr; } ctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext() { return context; } ApplicationContainer* org_blueberry_core_runtime_Activator::GetContainer() { return appContainer.data(); } #if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) #include QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == nullptr) return QString(); Dl_info info = {nullptr,nullptr,nullptr,nullptr}; if(dladdr(symbol, &info) == 0) { return QString(); } else if(info.dli_fname) { QFile soPath(info.dli_fname); int index = soPath.fileName().lastIndexOf('.'); QString pluginId = soPath.fileName().left(index); if (pluginId.startsWith("lib")) pluginId = pluginId.mid(3); return pluginId.replace('_', '.'); } return QString(); } #elif defined(Q_CC_MSVC) #include #include #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4091) #endif #include #ifdef _MSC_VER # pragma warning(pop) #endif QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == nullptr) return QString(); if (ctk::DebugSymInitialize()) { std::vector moduleBuffer(sizeof(IMAGEHLP_MODULE64)); PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front(); pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64); if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo)) { QString pluginId = pModuleInfo->ModuleName; return pluginId.replace('_', '.'); } } return QString(); } #endif QSharedPointer org_blueberry_core_runtime_Activator::GetPlugin(const SmartPointer& contributor) { if (RegistryContributor::Pointer regContributor = contributor.Cast()) { bool okay = false; long id = regContributor->GetActualId().toLong(&okay); if (okay) { if (context != nullptr) { return context->getPlugin(id); } } else { // try using the name of the contributor below } } auto plugins = context->getPlugins(); //Return the first plugin that is not installed or uninstalled for (auto plugin : qAsConst(plugins)) { if (!(plugin->getState() == ctkPlugin::INSTALLED || plugin->getState() == ctkPlugin::UNINSTALLED)) { return plugin; } } return QSharedPointer(); } org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator() : userRegistryKey(new QObject()) , masterRegistryKey(new QObject()) { } org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator() { } void org_blueberry_core_runtime_Activator::startRegistry() { // see if the customer suppressed the creation of default registry QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString(); if (property.compare("false", Qt::CaseInsensitive) == 0) return; // check to see if we need to use null as a userToken if (context->getProperty(RegistryConstants::PROP_REGISTRY_nullptr_USER_TOKEN).toString().compare("true", Qt::CaseInsensitive) == 0) { userRegistryKey.reset(nullptr); } // Determine primary and alternative registry locations. BlueBerry extension registry cache // can be found in one of the two locations: // a) in the local configuration area (standard location passed in by the platform) -> priority // b) in the shared configuration area (typically, shared install is used) QList registryLocations; QList readOnlyLocations; RegistryStrategy* strategy = nullptr; //Location configuration = OSGIUtils.getDefault().getConfigurationLocation(); QString configuration = context->getDataFile("").absoluteFilePath(); if (configuration.isEmpty()) { RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, "true"); RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_REGISTRY_CACHE_LOADING, "true"); strategy = new RegistryStrategy(QList(), QList(), masterRegistryKey.data()); } else { //File primaryDir = new File(configuration.getURL().getPath() + '/' + STORAGE_DIR); //bool primaryReadOnly = configuration.isReadOnly(); QString primaryDir = configuration; bool primaryReadOnly = false; //Location parentLocation = configuration.getParentLocation(); QString parentLocation; if (!parentLocation.isEmpty()) { // File secondaryDir = new File(parentLocation.getURL().getFile() + '/' + IRegistryConstants.RUNTIME_NAME); // registryLocations << primaryDir << secondaryDir; // readOnlyLocations << primaryReadOnly << true; // secondary BlueBerry location is always read only } else { registryLocations << primaryDir; readOnlyLocations << primaryReadOnly; } strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data()); } auto registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data()); defaultRegistry.reset(registry); registryServiceReg = context->registerService(registry); //commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext()); } void org_blueberry_core_runtime_Activator::stopRegistry() { if (!defaultRegistry.isNull()) { registryServiceReg.unregister(); defaultRegistry->Stop(masterRegistryKey.data()); } // if (!commandRegistration.isNull()) // { // commandRegistration.unregister(); // } } void org_blueberry_core_runtime_Activator::startAppContainer() { appContainer.reset(new ApplicationContainer(context, defaultRegistry.data())); appContainer->Start(); } void org_blueberry_core_runtime_Activator::stopAppContainer() { appContainer->Stop(); } } diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h b/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h index b6de976f32..4b86a40527 100755 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h @@ -1,91 +1,87 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYCTKPLUGINACTIVATOR_H #define BERRYCTKPLUGINACTIVATOR_H #include #include #include namespace berry { class ApplicationContainer; -class PreferencesService; struct IConfigurationElement; struct IContributor; struct IExtensionRegistry; class org_blueberry_core_runtime_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_PLUGIN_METADATA(IID "org_blueberry_core_runtime") Q_INTERFACES(ctkPluginActivator) public: static const bool DEBUG; org_blueberry_core_runtime_Activator(); ~org_blueberry_core_runtime_Activator() override; void start(ctkPluginContext* context) override; void stop(ctkPluginContext* context) override; static ctkPluginContext* getPluginContext(); static ApplicationContainer* GetContainer(); /** * Returns the plug-in id of the plug-in that contains the provided symbol, or * a null QString if the plug-in could not be determined. */ static QString getPluginId(void* symbol); // helper method to get a bundle from a contributor. static QSharedPointer GetPlugin(const SmartPointer& contributor); private: void startRegistry(); void stopRegistry(); void startAppContainer(); void stopAppContainer(); static ctkPluginContext* context; //QScopedPointer pluginListener; - QScopedPointer preferencesService; - ctkServiceRegistration prefServiceReg; - QScopedPointer defaultRegistry; ctkServiceRegistration registryServiceReg; static QScopedPointer appContainer; QScopedPointer userRegistryKey; QScopedPointer masterRegistryKey; }; typedef org_blueberry_core_runtime_Activator CTKPluginActivator; } #endif // BERRYCTKPLUGINACTIVATOR_H diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp index 3092128274..d83da9b8cc 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp @@ -1,1341 +1,1340 @@ /*============================================================================ 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 "berryExtensionRegistry.h" #include "berryCombinedEventDelta.h" #include "berryConfigurationElement.h" #include "berryConfigurationElementAttribute.h" #include "berryConfigurationElementDescription.h" #include "berryExtension.h" #include "berryExtensionHandle.h" #include "berryExtensionPoint.h" #include "berryExtensionPointHandle.h" #include "berryExtensionsParser.h" #include "berryIConfigurationElement.h" #include "berryIExtension.h" #include "berryIExtensionPoint.h" #include "berrySimpleExtensionPointFilter.h" #include "berryMultiStatus.h" -#include "berryPlatform.h" #include "berryRegistryConstants.h" #include "berryRegistryContribution.h" #include "berryRegistryContributor.h" #include "berryRegistryMessages.h" #include "berryRegistryObjectFactory.h" #include "berryRegistryObjectManager.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include "berryStatus.h" #include #include namespace berry { struct ExtensionRegistry::ListenerInfo { IExtensionPointFilter filter; IRegistryEventListener* listener; ListenerInfo(IRegistryEventListener* listener, const IExtensionPointFilter& filter) : filter(filter), listener(listener) { } /** * Used by ListenerList to ensure uniqueness. */ bool operator==(const ListenerInfo& another) const { return another.listener == this->listener; } }; void ExtensionRegistry::Add(const SmartPointer &element) { QWriteLocker l(&access); eventDelta = CombinedEventDelta::RecordAddition(); BasicAdd(element, true); FireRegistryChangeEvent(); eventDelta.Reset(); } QString ExtensionRegistry::AddExtension(int extension) { Extension::Pointer addedExtension = registryObjects->GetObject(extension, RegistryObjectManager::EXTENSION).Cast(); QString extensionPointToAddTo = addedExtension->GetExtensionPointIdentifier(); ExtensionPoint::Pointer extPoint = registryObjects->GetExtensionPointObject(extensionPointToAddTo); //orphan extension if (extPoint.IsNull()) { registryObjects->AddOrphan(extensionPointToAddTo, extension); return QString(); } // otherwise, link them QList newExtensions = extPoint->GetRawChildren(); newExtensions.push_back(extension); Link(extPoint, newExtensions); if (!eventDelta.IsNull()) eventDelta.RememberExtension(extPoint, extension); return extPoint->GetNamespace(); //return RecordChange(extPoint, extension, ExtensionDelta::ADDED); } QString ExtensionRegistry::AddExtensionPoint(int extPoint) { ExtensionPoint::Pointer extensionPoint = registryObjects->GetObject(extPoint, RegistryObjectManager::EXTENSION_POINT).Cast(); if (!eventDelta.IsNull()) eventDelta.RememberExtensionPoint(extensionPoint); QList orphans = registryObjects->RemoveOrphans(extensionPoint->GetUniqueIdentifier()); if (orphans.empty()) return QString(); Link(extensionPoint, orphans); if (!eventDelta.IsNull()) eventDelta.RememberExtensions(extensionPoint, orphans); return extensionPoint->GetNamespace(); //return RecordChange(extensionPoint, orphans, ExtensionDelta::ADDED); } QSet ExtensionRegistry::AddExtensionsAndExtensionPoints(const SmartPointer& element) { // now add and resolve extensions and extension points QSet affectedNamespaces; QList extPoints = element->GetExtensionPoints(); for (int i = 0; i < extPoints.size(); i++) { QString namespaze = this->AddExtensionPoint(extPoints[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } QList extensions = element->GetExtensions(); for (int i = 0; i < extensions.size(); i++) { QString namespaze = this->AddExtension(extensions[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } return affectedNamespaces; } void ExtensionRegistry::AddListenerInternal(IRegistryEventListener* listener, const IExtensionPointFilter& filter) { listeners.Add(ListenerInfo(listener, filter)); } void ExtensionRegistry::BasicAdd(const SmartPointer& element, bool link) { registryObjects->AddContribution(element); if (!link) return; AddExtensionsAndExtensionPoints(element); SetObjectManagers(registryObjects->CreateDelegatingObjectManager( registryObjects->GetAssociatedObjects(element->GetContributorId()))); } void ExtensionRegistry::SetObjectManagers(const SmartPointer& manager) { if (!eventDelta.IsNull()) eventDelta.SetObjectManager(manager); } void ExtensionRegistry::BasicRemove(const QString& contributorId) { // ignore anonymous namespaces RemoveExtensionsAndExtensionPoints(contributorId); QHash associatedObjects = registryObjects->GetAssociatedObjects(contributorId); registryObjects->RemoveObjects(associatedObjects); registryObjects->AddNavigableObjects(associatedObjects); // put the complete set of navigable objects SetObjectManagers(registryObjects->CreateDelegatingObjectManager(associatedObjects)); registryObjects->RemoveContribution(contributorId); registryObjects->RemoveContributor(contributorId); } void ExtensionRegistry::FireRegistryChangeEvent() { // if there is nothing to say, just bail out if (listeners.IsEmpty()) { return; } // for thread safety, create tmp collections QList tmpListeners = listeners.GetListeners(); // do the notification asynchronously //strategy->ScheduleChangeEvent(tmpListeners, tmpDeltas, this); this->ScheduleChangeEvent(tmpListeners, eventDelta); } //RegistryDelta ExtensionRegistry::GetDelta(const QString& namespaze) const //{ // // is there a delta for the plug-in? // RegistryDelta existingDelta = deltas.value(namespaze); // if (existingDelta != null) // return existingDelta; // //if not, create one // RegistryDelta delta = new RegistryDelta(); // deltas.put(namespace, delta); // return delta; //} void ExtensionRegistry::Link(const SmartPointer& extPoint, const QList& extensions) { extPoint->SetRawChildren(extensions); registryObjects->Add(extPoint, true); } //QString ExtensionRegistry::RecordChange(const SmartPointer& extPoint, int extension, int kind) //{ // // avoid computing deltas when there are no listeners // if (listeners.isEmpty()) // return QString(); // ExtensionDelta extensionDelta = new ExtensionDelta(); // extensionDelta.setExtension(extension); // extensionDelta.setExtensionPoint(extPoint.getObjectId()); // extensionDelta.setKind(kind); // getDelta(extPoint.getNamespace()).addExtensionDelta(extensionDelta); // return extPoint.getNamespace(); //} //QString ExtensionRegistry::RecordChange(const SmartPointer& extPoint, const QList& extensions, int kind) //{ // if (listeners.isEmpty()) // return null; // QString namespace = extPoint.getNamespace(); // if (extensions == null || extensions.length == 0) // return namespace; // RegistryDelta pluginDelta = getDelta(extPoint.getNamespace()); // for (int i = 0; i < extensions.length; i++) { // ExtensionDelta extensionDelta = new ExtensionDelta(); // extensionDelta.setExtension(extensions[i]); // extensionDelta.setExtensionPoint(extPoint.getObjectId()); // extensionDelta.setKind(kind); // pluginDelta.addExtensionDelta(extensionDelta); // } // return namespace; //} QString ExtensionRegistry::RemoveExtension(int extensionId) { Extension::Pointer extension = registryObjects->GetObject(extensionId, RegistryObjectManager::EXTENSION).Cast(); registryObjects->RemoveExtensionFromNamespaceIndex(extensionId, extension->GetNamespaceIdentifier()); QString xptName = extension->GetExtensionPointIdentifier(); ExtensionPoint::Pointer extPoint = registryObjects->GetExtensionPointObject(xptName); if (extPoint.IsNull()) { registryObjects->RemoveOrphan(xptName, extensionId); return QString(); } // otherwise, unlink the extension from the extension point QList existingExtensions = extPoint->GetRawChildren(); QList newExtensions; if (existingExtensions.size() > 1) { for (int i = 0; i < existingExtensions.size(); ++i) if (existingExtensions[i] != extension->GetObjectId()) newExtensions.push_back(existingExtensions[i]); } Link(extPoint, newExtensions); if (!eventDelta.IsNull()) eventDelta.RememberExtension(extPoint, extensionId); return extPoint->GetNamespace(); //return recordChange(extPoint, extension.getObjectId(), IExtensionDelta.REMOVED); } QString ExtensionRegistry::RemoveExtensionPoint(int extPoint) { ExtensionPoint::Pointer extensionPoint = registryObjects->GetObject( extPoint, RegistryObjectManager::EXTENSION_POINT).Cast(); registryObjects->RemoveExtensionPointFromNamespaceIndex(extPoint, extensionPoint->GetNamespace()); QList existingExtensions = extensionPoint->GetRawChildren(); if (!existingExtensions.empty()) { registryObjects->AddOrphans(extensionPoint->GetUniqueIdentifier(), existingExtensions); Link(extensionPoint, QList()); } if (!eventDelta.IsNull()) { eventDelta.RememberExtensionPoint(extensionPoint); eventDelta.RememberExtensions(extensionPoint, existingExtensions); } return extensionPoint->GetNamespace(); //return recordChange(extensionPoint, existingExtensions, IExtensionDelta.REMOVED); } QSet ExtensionRegistry::RemoveExtensionsAndExtensionPoints(const QString& contributorId) { QSet affectedNamespaces; QList extensions = registryObjects->GetExtensionsFrom(contributorId); for (int i = 0; i < extensions.size(); i++) { QString namespaze = this->RemoveExtension(extensions[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } // remove extension points QList extPoints = registryObjects->GetExtensionPointsFrom(contributorId); for (int i = 0; i < extPoints.size(); i++) { QString namespaze = this->RemoveExtensionPoint(extPoints[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } return affectedNamespaces; } struct ExtensionRegistry::QueueElement { QList listenerInfos; CombinedEventDelta scheduledDelta; QueueElement() { } QueueElement(const QList& infos, const CombinedEventDelta& delta) : listenerInfos(infos), scheduledDelta(delta) { } }; class ExtensionRegistry::RegistryEventThread : public QThread { private: QAtomicInt stop; ExtensionRegistry* registry; Queue& queue; public: RegistryEventThread(ExtensionRegistry* registry, Queue& queue) : stop(0), registry(registry), queue(queue) { this->setObjectName("Extension Registry Event Dispatcher"); } void interrupt() { stop.fetchAndStoreOrdered(1); } void run() override { while (!stop.fetchAndAddOrdered(0)) { QueueElement element; { Queue::Locker l(&queue); while (queue.empty()) queue.wait(); element = queue.takeFirst(); } registry->ProcessChangeEvent(element.listenerInfos, element.scheduledDelta); } } }; bool ExtensionRegistry::CheckReadWriteAccess(QObject* key, bool persist) const { if (masterToken == key) return true; if (userToken == key && !persist) return true; return false; } void ExtensionRegistry::LogError(const QString& owner, const QString& contributionName, const ctkException& e) { QString message = QString("Could not parse XML contribution for \"%1\". Any contributed extensions " "and extension points will be ignored.").arg(QString(owner) + "/" + contributionName); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, message, e, BERRY_STATUS_LOC)); Log(status); } void ExtensionRegistry::CreateExtensionData(const QString& contributorId, const ConfigurationElementDescription& description, const SmartPointer& parent, bool persist) { ConfigurationElement::Pointer currentConfigurationElement = GetElementFactory()->CreateConfigurationElement(persist); currentConfigurationElement->SetContributorId(contributorId); currentConfigurationElement->SetName(description.GetName()); QList descriptionProperties = description.GetAttributes(); QList properties; if (!descriptionProperties.empty()) { for (int i = 0; i < descriptionProperties.size(); i++) { properties.push_back(descriptionProperties[i].GetName()); properties.push_back(Translate(descriptionProperties[i].GetValue(), nullptr)); } } currentConfigurationElement->SetProperties(properties); QString value = description.GetValue(); if (!value.isEmpty()) currentConfigurationElement->SetValue(value); GetObjectManager()->Add(currentConfigurationElement, true); // process children QList children = description.GetChildren(); if (!children.empty()) { for (int i = 0; i < children.size(); i++) { CreateExtensionData(contributorId, children[i], currentConfigurationElement, persist); } } QList newValues = parent->GetRawChildren(); newValues.push_back(currentConfigurationElement->GetObjectId()); parent->SetRawChildren(newValues); currentConfigurationElement->SetParentId(parent->GetObjectId()); currentConfigurationElement->SetParentType(parent.Cast() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::EXTENSION); } bool ExtensionRegistry::RemoveObject(const SmartPointer& registryObject, bool isExtensionPoint, QObject* token) { if (!CheckReadWriteAccess(token, registryObject->ShouldPersist())) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.removeExtension() method. Check if proper access token is supplied."); int id = registryObject->GetObjectId(); QWriteLocker l(&access); eventDelta = CombinedEventDelta::RecordRemoval(); if (isExtensionPoint) { RemoveExtensionPoint(id); } else { RemoveExtension(id); } QHash removed; removed.insert(id, registryObject); // There is some asymmetry between extension and extension point removal. Removing extension point makes // extensions "orphans" but does not remove them. As a result, only extensions needs to be processed. if (!isExtensionPoint) { registryObjects->AddAssociatedObjects(removed, registryObject); } registryObjects->RemoveObjects(removed); registryObjects->AddNavigableObjects(removed); IObjectManager::Pointer manager = registryObjects->CreateDelegatingObjectManager(removed); //GetDelta(namespaze)->SetObjectManager(manager); //eventDelta->SetObjectManager(manager); registryObjects->UnlinkChildFromContributions(id); FireRegistryChangeEvent(); eventDelta.Reset(); return true; } void ExtensionRegistry::SetFileManager(const QString& /*cacheBase*/, bool /*isCacheReadOnly*/) { // if (cacheStorageManager != nullptr) // cacheStorageManager->Close(); // close existing file manager first // if (cacheBase != null) { // cacheStorageManager = new StorageManager(cacheBase, isCacheReadOnly ? "none" : null, isCacheReadOnly); //$NON-NLS-1$ // try { // cacheStorageManager.open(!isCacheReadOnly); // } catch (IOException e) { // // Ignore the exception. The registry will be rebuilt from source. // } // } } void ExtensionRegistry::EnterRead() { access.lockForRead(); } void ExtensionRegistry::ExitRead() { access.unlock(); } void ExtensionRegistry::SetElementFactory() { if (isMultiLanguage) { throw ctkRuntimeException("Multi-language registry not supported yet."); //theRegistryObjectFactory = new RegistryObjectFactoryMulti(this); } else { theRegistryObjectFactory.reset(new RegistryObjectFactory(this)); } } //TableReader ExtensionRegistry::getTableReader() const //{ // return theTableReader; //} bool ExtensionRegistry::CheckCache() { // for (int index = 0; index < strategy.getLocationsLength(); index++) { // File possibleCacheLocation = strategy.getStorage(index); // if (possibleCacheLocation == null) // break; // bail out on the first null // setFileManager(possibleCacheLocation, strategy.isCacheReadOnly(index)); // if (cacheStorageManager != null) { // // check this new location: // File cacheFile = null; // try { // cacheFile = cacheStorageManager.lookup(TableReader.getTestFileName(), false); // } catch (IOException e) { // //Ignore the exception. The registry will be rebuilt from the xml files. // } // if (cacheFile != null && cacheFile.isFile()) // return true; // found the appropriate location // } // } return false; } void ExtensionRegistry::StopChangeEventScheduler() { if (!eventThread.isNull()) { Queue::Locker l(&queue); eventThread->interrupt(); eventThread->wait(); eventThread.reset(); } } SmartPointer ExtensionRegistry::GetObjectManager() const { return registryObjects; } void ExtensionRegistry::AddListener(IRegistryEventListener* listener, const QString& extensionPointId) { AddListenerInternal(listener, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr) : IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId))); } void ExtensionRegistry::AddListener(IRegistryEventListener* listener, const IExtensionPointFilter& filter) { this->AddListenerInternal(listener, filter); } QList > ExtensionRegistry::GetConfigurationElementsFor(const QString& extensionPointId) const { // this is just a convenience API - no need to do any sync'ing here int lastdot = extensionPointId.lastIndexOf('.'); if (lastdot == -1) { QList(); } return GetConfigurationElementsFor(extensionPointId.left(lastdot), extensionPointId.mid(lastdot + 1)); } QList > ExtensionRegistry::GetConfigurationElementsFor(const QString& pluginId, const QString& extensionPointSimpleId) const { // this is just a convenience API - no need to do any sync'ing here IExtensionPoint::Pointer extPoint = this->GetExtensionPoint(pluginId, extensionPointSimpleId); if (extPoint.IsNull()) return QList(); return extPoint->GetConfigurationElements(); } QList > ExtensionRegistry::GetConfigurationElementsFor(const QString& pluginId, const QString& extensionPointName, const QString& extensionId) const { // this is just a convenience API - no need to do any sync'ing here IExtension::Pointer extension = this->GetExtension(pluginId, extensionPointName, extensionId); if (extension.IsNull()) return QList(); return extension->GetConfigurationElements(); } SmartPointer ExtensionRegistry::GetExtension(const QString& extensionId) const { if (extensionId.isEmpty()) return IExtension::Pointer(); int lastdot = extensionId.lastIndexOf('.'); if (lastdot == -1) return IExtension::Pointer(); QString namespaze = extensionId.left(lastdot); QList extensions; { QReadLocker l(&access); extensions = registryObjects->GetExtensionsFromNamespace(namespaze); } for (int i = 0; i < extensions.size(); i++) { ExtensionHandle::Pointer suspect = extensions[i]; if (extensionId == suspect->GetUniqueIdentifier()) return suspect; } return IExtension::Pointer(); } SmartPointer ExtensionRegistry::GetExtension(const QString& extensionPointId, const QString& extensionId) const { // this is just a convenience API - no need to do any sync'ing here int lastdot = extensionPointId.lastIndexOf('.'); if (lastdot == -1) return IExtension::Pointer(); return GetExtension(extensionPointId.left(lastdot), extensionPointId.mid(lastdot + 1), extensionId); } SmartPointer ExtensionRegistry::GetExtension(const QString& pluginId, const QString& extensionPointName, const QString& extensionId) const { // this is just a convenience API - no need to do any sync'ing here IExtensionPoint::Pointer extPoint = GetExtensionPoint(pluginId, extensionPointName); if (extPoint.IsNotNull()) return extPoint->GetExtension(extensionId); return IExtension::Pointer(); } SmartPointer ExtensionRegistry::GetExtensionPoint(const QString& xptUniqueId) const { QReadLocker l(&access); return registryObjects->GetExtensionPointHandle(xptUniqueId); } SmartPointer ExtensionRegistry::GetExtensionPoint(const QString& elementName, const QString& xpt) const { QReadLocker l(&access); return registryObjects->GetExtensionPointHandle(elementName + '.' + xpt); } QList > ExtensionRegistry::GetExtensionPoints() const { QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionPointsHandles(); } QList result; foreach(ExtensionPointHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensionPoints(const QString& namespaceName) const { QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionPointsFromNamespace(namespaceName); } QList result; foreach(ExtensionPointHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensions(const QString& namespaceName) const { QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionsFromNamespace(namespaceName); } QList result; foreach (ExtensionHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensions(const SmartPointer& contributor) const { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen QString contributorId = regContributor->GetActualId(); QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionsFromContributor(contributorId); } QList result; foreach (ExtensionHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensionPoints(const SmartPointer& contributor) const { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen QString contributorId = regContributor->GetActualId(); QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionPointsFromContributor(contributorId); } QList result; foreach (ExtensionPointHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList ExtensionRegistry::GetNamespaces() const { QReadLocker l(&access); QList namespaceElements = registryObjects->GetNamespacesIndex().Elements(); QList namespaceNames; for (int i = 0; i < namespaceElements.size(); i++) { namespaceNames.push_back(namespaceElements[i]->GetKey()); } return namespaceNames; } bool ExtensionRegistry::HasContributor(const SmartPointer& contributor) const { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen QString contributorId = regContributor->GetActualId(); return HasContributor(contributorId); } bool ExtensionRegistry::HasContributor(const QString& contributorId) const { QReadLocker l(&access); return registryObjects->HasContribution(contributorId); } void ExtensionRegistry::Remove(const QString& removedContributorId, long timestamp) { Remove(removedContributorId); if (timestamp != 0) aggregatedTimestamp.Remove(timestamp); } void ExtensionRegistry::RemoveContributor(const SmartPointer& contributor, QObject* key) { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen if (!CheckReadWriteAccess(key, true)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.removeContributor() method. Check if proper access token is supplied."); QString contributorId = regContributor->GetActualId(); Remove(contributorId); } void ExtensionRegistry::Remove(const QString& removedContributorId) { QWriteLocker l(&access); eventDelta = CombinedEventDelta::RecordRemoval(); BasicRemove(removedContributorId); FireRegistryChangeEvent(); eventDelta.Reset(); } void ExtensionRegistry::RemoveListener(IRegistryEventListener* listener) { listeners.Remove(ListenerInfo(listener, IExtensionPointFilter(nullptr))); } ExtensionRegistry::ExtensionRegistry(RegistryStrategy* registryStrategy, QObject* masterToken, QObject* userToken) : registryObjects(nullptr), isMultiLanguage(false), mlErrorLogged(false), eventThread(nullptr) { isMultiLanguage = RegistryProperties::GetProperty(RegistryConstants::PROP_REGISTRY_MULTI_LANGUAGE) == "true"; if (registryStrategy != nullptr) strategy.reset(registryStrategy); else strategy.reset(new RegistryStrategy(QList(), QList(), nullptr)); this->masterToken = masterToken; this->userToken = userToken; registryObjects = new RegistryObjectManager(this); bool isRegistryFilledFromCache = false; // indicates if registry was able to use cache to populate it's content if (strategy->CacheUse()) { // Try to read the registry from the cache first. If that fails, create a new registry QTime timer; if (Debug()) timer.start(); //The cache is made of several files, find the real names of these other files. If all files are found, try to initialize the objectManager if (CheckCache()) { // TODO Registry Cache // try { // theTableReader.setTableFile(cacheStorageManager.lookup(TableReader.TABLE, false)); // theTableReader.setExtraDataFile(cacheStorageManager.lookup(TableReader.EXTRA, false)); // theTableReader.setMainDataFile(cacheStorageManager.lookup(TableReader.MAIN, false)); // theTableReader.setContributionsFile(cacheStorageManager.lookup(TableReader.CONTRIBUTIONS, false)); // theTableReader.setContributorsFile(cacheStorageManager.lookup(TableReader.CONTRIBUTORS, false)); // theTableReader.setNamespacesFile(cacheStorageManager.lookup(TableReader.NAMESPACES, false)); // theTableReader.setOrphansFile(cacheStorageManager.lookup(TableReader.ORPHANS, false)); // long timestamp = strategy.getContributionsTimestamp(); // isRegistryFilledFromCache = registryObjects.init(timestamp); // if (isRegistryFilledFromCache) // aggregatedTimestamp.set(timestamp); // } catch (IOException e) { // // The registry will be rebuilt from the xml files. Make sure to clear anything filled // // from cache so that we won't have partially filled items. // isRegistryFilledFromCache = false; // clearRegistryCache(); // log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_bad_cache, e)); // } } // if (!isRegistryFilledFromCache) // { // // set cache storage manager to a first writable location // for (int index = 0; index < strategy.getLocationsLength(); index++) { // if (!strategy.isCacheReadOnly(index)) { // setFileManager(strategy.getStorage(index), false); // break; // } // } // } if (Debug() && isRegistryFilledFromCache) BERRY_INFO << "Reading registry cache: " << timer.elapsed() << "ms"; if (Debug()) { if (!isRegistryFilledFromCache) BERRY_INFO << "Reloading registry from manifest files..."; else BERRY_INFO << "Using registry cache..."; } } if (DebugEvents()) { struct DebugRegistryListener : public IRegistryEventListener { void Added(const QList& extensions) override { BERRY_INFO << "Registry extensions ADDED:"; foreach(IExtension::Pointer extension, extensions) { BERRY_INFO << "\t" << extension->GetExtensionPointUniqueIdentifier() << " - " << extension->GetNamespaceIdentifier() << "." << extension->GetSimpleIdentifier(); } } void Removed(const QList& extensions) override { BERRY_INFO << "Registry extensions REMOVED:"; foreach(IExtension::Pointer extension, extensions) { BERRY_INFO << "\t" << extension->GetExtensionPointUniqueIdentifier() << " - " << extension->GetNamespaceIdentifier() << "." << extension->GetSimpleIdentifier(); } } void Added(const QList& extensionPoints) override { BERRY_INFO << "Registry extension-points ADDED:"; foreach(IExtensionPoint::Pointer extensionPoint, extensionPoints) { BERRY_INFO << "\t" << extensionPoint->GetUniqueIdentifier(); } } void Removed(const QList& extensionPoints) override { BERRY_INFO << "Registry extension-points REMOVED:"; foreach(IExtensionPoint::Pointer extensionPoint, extensionPoints) { BERRY_INFO << "\t" << extensionPoint->GetUniqueIdentifier(); } } }; debugRegistryListener.reset(new DebugRegistryListener()); AddListener(debugRegistryListener.data()); } // Do extra start processing if specified in the registry strategy strategy->OnStart(this, isRegistryFilledFromCache); } ExtensionRegistry::~ExtensionRegistry() { } void ExtensionRegistry::Stop(QObject* /*key*/) { // If the registry creator specified a key token, check that the key mathches it // (it is assumed that registry owner keeps the key to prevent unautorized accesss). if (masterToken != nullptr && masterToken != nullptr) { throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.stop() method. Check if proper access token is supplied."); //$NON-NLS-1$ } // Do extra stop processing if specified in the registry strategy strategy->OnStop(this); StopChangeEventScheduler(); // if (cacheStorageManager == nullptr) // return; // if (!registryObjects.isDirty() || cacheStorageManager.isReadOnly()) { // cacheStorageManager.close(); // theTableReader.close(); // return; // } // File tableFile = null; // File mainFile = null; // File extraFile = null; // File contributionsFile = null; // File contributorsFile = null; // File namespacesFile = null; // File orphansFile = null; // TableWriter theTableWriter = new TableWriter(this); // try { // cacheStorageManager.lookup(TableReader.TABLE, true); // cacheStorageManager.lookup(TableReader.MAIN, true); // cacheStorageManager.lookup(TableReader.EXTRA, true); // cacheStorageManager.lookup(TableReader.CONTRIBUTIONS, true); // cacheStorageManager.lookup(TableReader.CONTRIBUTORS, true); // cacheStorageManager.lookup(TableReader.NAMESPACES, true); // cacheStorageManager.lookup(TableReader.ORPHANS, true); // tableFile = File.createTempFile(TableReader.TABLE, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // mainFile = File.createTempFile(TableReader.MAIN, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // extraFile = File.createTempFile(TableReader.EXTRA, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // contributionsFile = File.createTempFile(TableReader.CONTRIBUTIONS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // contributorsFile = File.createTempFile(TableReader.CONTRIBUTORS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // namespacesFile = File.createTempFile(TableReader.NAMESPACES, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // orphansFile = File.createTempFile(TableReader.ORPHANS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // theTableWriter.setTableFile(tableFile); // theTableWriter.setExtraDataFile(extraFile); // theTableWriter.setMainDataFile(mainFile); // theTableWriter.setContributionsFile(contributionsFile); // theTableWriter.setContributorsFile(contributorsFile); // theTableWriter.setNamespacesFile(namespacesFile); // theTableWriter.setOrphansFile(orphansFile); // } catch (IOException e) { // cacheStorageManager.close(); // return; //Ignore the exception since we can recompute the cache // } // try { // long timestamp; // // A bit of backward compatibility: if registry was modified, but timestamp was not, // // it means that the new timestamp tracking mechanism was not used. In this case // // explicitly obtain timestamps for all contributions. Note that this logic // // maintains a problem described in the bug 104267 for contributions that // // don't use the timestamp tracking mechanism. // if (aggregatedTimestamp.isModifed()) // timestamp = aggregatedTimestamp.getContentsTimestamp(); // use timestamp tracking // else // timestamp = strategy.getContributionsTimestamp(); // use legacy approach // if (theTableWriter.saveCache(registryObjects, timestamp)) // cacheStorageManager.update(new QString[] {TableReader.TABLE, TableReader.MAIN, TableReader.EXTRA, TableReader.CONTRIBUTIONS, TableReader.CONTRIBUTORS, TableReader.NAMESPACES, TableReader.ORPHANS}, new QString[] {tableFile.getName(), mainFile.getName(), extraFile.getName(), contributionsFile.getName(), contributorsFile.getName(), namespacesFile.getName(), orphansFile.getName()}); // } catch (IOException e) { // //Ignore the exception since we can recompute the cache // } // theTableReader.close(); // cacheStorageManager.close(); } void ExtensionRegistry::ClearRegistryCache() { // QString[] keys = new QString[] {TableReader.TABLE, TableReader.MAIN, TableReader.EXTRA, TableReader.CONTRIBUTIONS, TableReader.ORPHANS}; // for (int i = 0; i < keys.length; i++) // try { // cacheStorageManager.remove(keys[i]); // } catch (IOException e) { // log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, IStatus.ERROR, RegistryMessages.meta_registryCacheReadProblems, e)); // } aggregatedTimestamp.Reset(); } RegistryObjectFactory* ExtensionRegistry::GetElementFactory() { if (theRegistryObjectFactory.isNull()) SetElementFactory(); return theRegistryObjectFactory.data(); } void ExtensionRegistry::Log(const SmartPointer& status) const { strategy->Log(status); } QString ExtensionRegistry::Translate(const QString& key, QTranslator* resources) const { if (isMultiLanguage) return key; return strategy->Translate(key, resources); } bool ExtensionRegistry::Debug() const { return strategy->Debug(); } bool ExtensionRegistry::DebugEvents() const { return strategy->DebugRegistryEvents(); } bool ExtensionRegistry::UseLazyCacheLoading() const { return strategy->CacheLazyLoading(); } long ExtensionRegistry::ComputeState() const { return strategy->GetContainerTimestamp(); } QObject* ExtensionRegistry::CreateExecutableExtension(const SmartPointer& defaultContributor, const QString& className, const QString& requestedContributorName) { return strategy->CreateExecutableExtension(defaultContributor, className, requestedContributorName); } void ExtensionRegistry::ProcessChangeEvent( const QList& listenerInfos, const CombinedEventDelta& scheduledDelta) { for (int i = 0; i < listenerInfos.size(); i++) { const ListenerInfo& listenerInfo = listenerInfos[i]; IRegistryEventListener* extensionListener = listenerInfo.listener; QList extensions = scheduledDelta.GetExtensions(listenerInfo.filter); QList extensionPoints = scheduledDelta.GetExtensionPoints(listenerInfo.filter); // notification order - on addition: extension points; then extensions if (scheduledDelta.IsAddition()) { if (!extensionPoints.empty()) extensionListener->Added(extensionPoints); if (!extensions.empty()) extensionListener->Added(extensions); } else { // on removal: extensions; then extension points if (!extensions.empty()) extensionListener->Removed(extensions); if (!extensionPoints.empty()) extensionListener->Removed(extensionPoints); } } IObjectManager::Pointer manager = scheduledDelta.GetObjectManager(); if (manager.IsNotNull()) manager->Close(); } void ExtensionRegistry::ScheduleChangeEvent(const QList& listenerInfos, const CombinedEventDelta& scheduledDelta) { QueueElement newElement(listenerInfos, scheduledDelta); if (eventThread.isNull()) { eventThread.reset(new RegistryEventThread(this, queue)); eventThread->start(); } { Queue::Locker l(&queue); queue.push_back(newElement); queue.notify(); } } bool ExtensionRegistry::AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& contributionName, QTranslator* translationBundle, QObject* key, long timestamp) { bool result = AddContribution(is, contributor, persist, contributionName, translationBundle, key); if (timestamp != 0) aggregatedTimestamp.Add(timestamp); return result; } bool ExtensionRegistry::AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& contributionName, QTranslator* translationBundle, QObject* key) { if (!CheckReadWriteAccess(key, persist)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddContribution() method. Check if proper access token is supplied."); RegistryContributor::Pointer internalContributor = contributor.Cast(); registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present QString ownerName = internalContributor->GetActualName(); QString message = QString("Problems parsing plug-in manifest for: \"%1\".").arg(ownerName); MultiStatus::Pointer problems(new MultiStatus(RegistryMessages::OWNER_NAME, ExtensionsParser::PARSE_PROBLEM, message, BERRY_STATUS_LOC)); ExtensionsParser parser(problems, this); RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(internalContributor->GetActualId(), persist); try { QXmlInputSource xmlInput(is); bool success = parser.parseManifest(strategy->GetXMLParser(), &xmlInput, contributionName, GetObjectManager().GetPointer(), contribution, translationBundle); int status = problems->GetSeverity(); if (status != IStatus::OK_TYPE || !success) { Log(problems); if (status == IStatus::ERROR_TYPE || status == IStatus::CANCEL_TYPE || !success) return false; } } catch (const ctkException& e) { LogError(ownerName, contributionName, e); return false; } Add(contribution); // the add() method does synchronization return true; } bool ExtensionRegistry::AddExtensionPoint(const QString& identifier, const SmartPointer& contributor, bool persist, const QString& label, const QString& schemaReference, QObject* token) { if (!CheckReadWriteAccess(token, persist)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddExtensionPoint() method. Check if proper access token is supplied."); RegistryContributor::Pointer internalContributor = contributor.Cast(); registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present QString contributorId = internalContributor->GetActualId(); // Extension point Id might not be null if (identifier.isEmpty()) { QString message = QString("Missing ID for the extension point \"%1\". Element ignored.").arg(label); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, message, BERRY_STATUS_LOC)); Log(status); } // addition wraps in a contribution RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(contributorId, persist); ExtensionPoint::Pointer currentExtPoint = GetElementFactory()->CreateExtensionPoint(persist); QString uniqueId; QString namespaceName; int simpleIdStart = identifier.lastIndexOf('.'); if (simpleIdStart == -1) { namespaceName = contribution->GetDefaultNamespace(); uniqueId = namespaceName + '.' + identifier; } else { namespaceName = identifier.left(simpleIdStart); uniqueId = identifier; } currentExtPoint->SetUniqueIdentifier(uniqueId); currentExtPoint->SetNamespace(namespaceName); QString labelNLS = Translate(label, nullptr); currentExtPoint->SetLabel(labelNLS); currentExtPoint->SetSchema(schemaReference); if (!GetObjectManager()->AddExtensionPoint(currentExtPoint, true)) { if (Debug()) { QString msg = QString("Ignored duplicate extension point \"%1\" supplied by \"%2\".").arg(uniqueId).arg(contribution->GetDefaultNamespace()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); Log(status); } return false; } currentExtPoint->SetContributorId(contributorId); // array format: {Number of extension points, Number of extensions, Extension Id} QList contributionChildren; // Put the extension points into this namespace contributionChildren.push_back(1); contributionChildren.push_back(0); contributionChildren.push_back(currentExtPoint->GetObjectId()); contribution->SetRawChildren(contributionChildren); Add(contribution); return true; } bool ExtensionRegistry::AddExtension(const QString& identifier, const SmartPointer& contributor, bool persist, const QString& label, const QString& extensionPointId, const ConfigurationElementDescription& configurationElements, QObject* token) { if (!CheckReadWriteAccess(token, persist)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddExtensionPoint() method. Check if proper access token is supplied."); // prepare namespace information RegistryContributor::Pointer internalContributor = contributor.Cast(); registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present QString contributorId = internalContributor->GetActualId(); // addition wraps in a contribution RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(contributorId, persist); Extension::Pointer currentExtension = GetElementFactory()->CreateExtension(persist); QString simpleId; QString namespaceName; int simpleIdStart = identifier.lastIndexOf('.'); if (simpleIdStart != -1) { simpleId = identifier.mid(simpleIdStart + 1); namespaceName = identifier.left(simpleIdStart); } else { simpleId = identifier; namespaceName = contribution->GetDefaultNamespace(); } currentExtension->SetSimpleIdentifier(simpleId); currentExtension->SetNamespaceIdentifier(namespaceName); QString extensionLabelNLS = Translate(label, nullptr); currentExtension->SetLabel(extensionLabelNLS); QString targetExtensionPointId; if (extensionPointId.indexOf('.') == -1) // No dots -> namespace name added at the start targetExtensionPointId = contribution->GetDefaultNamespace() + '.' + extensionPointId; else targetExtensionPointId = extensionPointId; currentExtension->SetExtensionPointIdentifier(targetExtensionPointId); // if we have an Id specified, check for duplicates. Only issue warning if duplicate found // as it might still work fine - depending on the access pattern. if (!simpleId.isNull() && Debug()) { QString uniqueId = namespaceName + '.' + simpleId; IExtension::Pointer existingExtension = GetExtension(uniqueId); if (existingExtension.IsNotNull()) { QString currentSupplier = contribution->GetDefaultNamespace(); QString existingSupplier = existingExtension->GetContributor()->GetName(); QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".") .arg(currentSupplier).arg(existingSupplier).arg(uniqueId); IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); Log(status); return false; } } GetObjectManager()->Add(currentExtension, true); CreateExtensionData(contributorId, configurationElements, currentExtension, persist); currentExtension->SetContributorId(contributorId); QList contributionChildren; contributionChildren.push_back(0); contributionChildren.push_back(1); contributionChildren.push_back(currentExtension->GetObjectId()); contribution->SetRawChildren(contributionChildren); Add(contribution); return true; } bool ExtensionRegistry::RemoveExtension(const SmartPointer& extension, QObject* token) { ExtensionHandle::Pointer handle = extension.Cast(); if (handle.IsNull()) return false; return RemoveObject(handle->GetObject(), false, token); } bool ExtensionRegistry::RemoveExtensionPoint(const SmartPointer& extensionPoint, QObject* token) { ExtensionPointHandle::Pointer handle = extensionPoint.Cast(); if (handle.IsNull()) return false; return RemoveObject(handle->GetObject(), true, token); } QList > ExtensionRegistry::GetAllContributors() const { QList result; QReadLocker l(&access); foreach(RegistryContributor::Pointer contributor, registryObjects->GetContributors().values()) { result.push_back(contributor); } return result; } bool ExtensionRegistry::IsMultiLanguage() const { return isMultiLanguage; } QList ExtensionRegistry::Translate(const QList& nonTranslated, const SmartPointer& contributor, const QLocale& locale) const { return strategy->Translate(nonTranslated, contributor, locale); } QLocale ExtensionRegistry::GetLocale() const { return strategy->GetLocale(); } void ExtensionRegistry::LogMultiLangError() const { if (mlErrorLogged) // only log this error ones return; IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, QString("The requested multi-language operation is not enabled. See runtime option \"") + RegistryConstants::PROP_REGISTRY_MULTI_LANGUAGE + "\".", ctkInvalidArgumentException(""), BERRY_STATUS_LOC)); Log(status); mlErrorLogged = true; } } diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp index 639d550046..f59a422aa6 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp @@ -1,499 +1,497 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryInternalPlatform.h" #include "berryLog.h" #include "berryLogImpl.h" #include "berryPlatform.h" #include "berryPlatformException.h" #include "berryDebugUtil.h" #include "berryPlatformException.h" #include "berryCTKPluginActivator.h" #include "berryPlatformException.h" #include "berryApplicationContainer.h" #include "berryProduct.h" #include "berryIBranding.h" //#include "event/berryPlatformEvents.h" //#include "berryPlatformLogChannel.h" #include -#include #include #include #include #include #include #include #include #include #include #include #include #include +#include +#include + +#include + +US_INITIALIZE_MODULE + namespace berry { QMutex InternalPlatform::m_Mutex; bool InternalPlatform::DEBUG = false; bool InternalPlatform::DEBUG_PLUGIN_PREFERENCES = false; InternalPlatform::InternalPlatform() : m_Initialized(false) , m_ConsoleLog(false) , m_Context(nullptr) { } InternalPlatform::~InternalPlatform() { } InternalPlatform* InternalPlatform::GetInstance() { QMutexLocker lock(&m_Mutex); static InternalPlatform instance; return &instance; } bool InternalPlatform::ConsoleLog() const { return m_ConsoleLog; } QVariant InternalPlatform::GetOption(const QString& option, const QVariant& defaultValue) const { ctkDebugOptions* options = GetDebugOptions(); if (options != nullptr) { return options->getOption(option, defaultValue); } return QVariant(); } IAdapterManager* InternalPlatform::GetAdapterManager() const { AssertInitialized(); return nullptr; } SmartPointer InternalPlatform::GetProduct() const { if (product.IsNotNull()) return product; ApplicationContainer* container = org_blueberry_core_runtime_Activator::GetContainer(); IBranding* branding = container == nullptr ? nullptr : container->GetBranding(); if (branding == nullptr) return IProduct::Pointer(); IProduct::Pointer brandingProduct = branding->GetProduct(); if (!brandingProduct) { brandingProduct = new Product(branding); } product = brandingProduct; return product; } void InternalPlatform::InitializePluginPaths() { QMutexLocker lock(&m_Mutex); // Add search paths for Qt plugins for(const auto& qtPluginPath : m_Context->getProperty(Platform::PROP_QTPLUGIN_PATH).toStringList()) { if (qtPluginPath.isEmpty()) continue; if (QFile::exists(qtPluginPath)) { QCoreApplication::addLibraryPath(qtPluginPath); } else if (m_ConsoleLog) { BERRY_WARN << "Qt plugin path does not exist: " << qtPluginPath.toStdString(); } } // Add a default search path. It is assumed that installed applications // provide their Qt plugins in that path. static const QString defaultQtPluginPath = QCoreApplication::applicationDirPath() + "/plugins"; if (QFile::exists(defaultQtPluginPath)) { QCoreApplication::addLibraryPath(defaultQtPluginPath); } if (m_ConsoleLog) { std::string pathList; foreach(QString libPath, QCoreApplication::libraryPaths()) { pathList += (pathList.empty() ? "" : ", ") + libPath.toStdString(); } BERRY_INFO << "Qt library search paths: " << pathList; } /* m_ConfigPath.setPath(m_Context->getProperty("application.configDir").toString()); m_InstancePath.setPath(m_Context->getProperty("application.dir").toString()); QString installPath = m_Context->getProperty(Platform::PROP_HOME).toString(); if (installPath.isEmpty()) { m_InstallPath = m_InstancePath; } else { m_InstallPath.setPath(installPath); } QString dataLocation = m_Context->getProperty(Platform::PROP_STORAGE_DIR).toString(); if (!storageDir.isEmpty()) { if (dataLocation.at(dataLocation.size()-1) != '/') { dataLocation += '/'; } m_UserPath.setPath(dataLocation); } else { // Append a hash value of the absolute path of the executable to the data location. // This allows to start the same application from different build or install trees. dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + this->getOrganizationName() + "/" + this->getApplicationName() + '_'; dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; m_UserPath.setPath(dataLocation); } BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.absolutePath(); QFileInfo userFile(m_UserPath.absolutePath()); if (!QDir().mkpath(userFile.absoluteFilePath()) || !userFile.isWritable()) { QString tmpPath = QDir::temp().absoluteFilePath(QString::fromStdString(this->commandName())); BERRY_WARN << "Storage dir " << userFile.absoluteFilePath() << " is not writable. Falling back to temporary path " << tmpPath; QDir().mkpath(tmpPath); userFile.setFile(tmpPath); } m_BaseStatePath.setPath(m_UserPath.absolutePath() + "/bb-metadata/bb-plugins"); QString logPath(m_UserPath.absoluteFilePath(QString::fromStdString(this->commandName()) + ".log")); m_PlatformLogChannel = new Poco::SimpleFileChannel(logPath.toStdString()); */ } ctkDebugOptions* InternalPlatform::GetDebugOptions() const { return m_DebugTracker.isNull() ? nullptr : m_DebugTracker->getService(); } IApplicationContext* InternalPlatform::GetApplicationContext() const { QList refs; try { refs = m_Context->getServiceReferences("(blueberry.application.type=main.thread)"); } catch (const std::invalid_argument&) { return nullptr; } if (refs.isEmpty()) return nullptr; // assumes the application context is available as a service IApplicationContext* result = m_Context->getService(refs.front()); if (result != nullptr) { m_Context->ungetService(refs.front()); return result; } return nullptr; } void InternalPlatform::Start(ctkPluginContext* context) { this->m_Context = context; m_ConsoleLog = m_Context->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool(); OpenServiceTrackers(); this->InitializePluginPaths(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::RestoreState(m_UserPath); #endif InitializeDebugFlags(); this->m_Initialized = true; } void InternalPlatform::Stop(ctkPluginContext* /*context*/) { AssertInitialized(); this->m_Initialized = false; CloseServiceTrackers(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::SaveState(m_UserPath); #endif this->m_Context = nullptr; } void InternalPlatform::AssertInitialized() const { if (!m_Initialized) { throw PlatformException("The Platform has not been initialized yet!"); } } void InternalPlatform::OpenServiceTrackers() { ctkPluginContext* context = this->m_Context; instanceLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::INSTANCE_FILTER))); instanceLocation->open(); userLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::USER_FILTER))); userLocation->open(); configurationLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::CONFIGURATION_FILTER))); configurationLocation->open(); installLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::INSTALL_FILTER))); installLocation->open(); - m_PreferencesTracker.reset(new ctkServiceTracker(context)); - m_PreferencesTracker->open(); - m_RegistryTracker.reset(new ctkServiceTracker(context)); m_RegistryTracker->open(); m_DebugTracker.reset(new ctkServiceTracker(context)); m_DebugTracker->open(); } void InternalPlatform::CloseServiceTrackers() { - if (!m_PreferencesTracker.isNull()) - { - m_PreferencesTracker->close(); - m_PreferencesTracker.reset(); - } if (!m_RegistryTracker.isNull()) { m_RegistryTracker->close(); m_RegistryTracker.reset(); } if (!m_DebugTracker.isNull()) { m_DebugTracker->close(); m_DebugTracker.reset(); } if (!configurationLocation.isNull()) { configurationLocation->close(); configurationLocation.reset(); } if (!installLocation.isNull()) { installLocation->close(); installLocation.reset(); } if (!instanceLocation.isNull()) { instanceLocation->close(); instanceLocation.reset(); } if (!userLocation.isNull()) { userLocation->close(); userLocation.reset(); } } void InternalPlatform::InitializeDebugFlags() { DEBUG = this->GetOption(Platform::PI_RUNTIME + "/debug", false).toBool(); if (DEBUG) { DEBUG_PLUGIN_PREFERENCES = GetOption(Platform::PI_RUNTIME + "/preferences/plugin", false).toBool(); } } IExtensionRegistry* InternalPlatform::GetExtensionRegistry() { return m_RegistryTracker.isNull() ? nullptr : m_RegistryTracker->getService(); } -IPreferencesService *InternalPlatform::GetPreferencesService() +mitk::IPreferencesService *InternalPlatform::GetPreferencesService() { - return m_PreferencesTracker.isNull() ? nullptr : m_PreferencesTracker->getService(); + return mitk::CoreServices::GetPreferencesService(); } ctkLocation* InternalPlatform::GetConfigurationLocation() { this->AssertInitialized(); return configurationLocation->getService(); } ctkLocation* InternalPlatform::GetInstallLocation() { this->AssertInitialized(); return installLocation->getService(); } ctkLocation* InternalPlatform::GetInstanceLocation() { this->AssertInitialized(); return instanceLocation->getService(); } QDir InternalPlatform::GetStateLocation(const QSharedPointer& plugin) { ctkLocation* service = GetInstanceLocation(); if (service == nullptr) { throw ctkIllegalStateException("No instance data can be specified."); } QUrl url = GetInstanceLocation()->getDataArea(plugin->getSymbolicName()); if (!url.isValid()) { throw ctkIllegalStateException("The instance data location has not been specified yet."); } QDir location(url.toLocalFile()); if (!location.exists()) { if (!location.mkpath(location.absolutePath())) { throw PlatformException(QString("Could not create plugin state location \"%1\"").arg(location.absolutePath())); } } return location; } //PlatformEvents& InternalPlatform::GetEvents() //{ // return m_Events; //} ctkLocation* InternalPlatform::GetUserLocation() { this->AssertInitialized(); return userLocation->getService(); } ILog *InternalPlatform::GetLog(const QSharedPointer &plugin) const { LogImpl* result = m_Logs.value(plugin->getPluginId()); if (result != nullptr) return result; // ExtendedLogService logService = (ExtendedLogService) extendedLogTracker.getService(); // Logger logger = logService == null ? null : logService.getLogger(bundle, PlatformLogWriter.EQUINOX_LOGGER_NAME); // result = new Log(bundle, logger); // ExtendedLogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService(); // logReader.addLogListener(result, result); // logs.put(bundle, result); // return result; result = new LogImpl(plugin); m_Logs.insert(plugin->getPluginId(), result); return result; } bool InternalPlatform::IsRunning() const { QMutexLocker lock(&m_Mutex); try { return m_Initialized && m_Context && m_Context->getPlugin()->getState() == ctkPlugin::ACTIVE; } catch (const ctkIllegalStateException&) { return false; } } QSharedPointer InternalPlatform::GetPlugin(const QString &symbolicName) { QList > plugins = m_Context->getPlugins(); QSharedPointer res(nullptr); foreach(QSharedPointer plugin, plugins) { if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 && plugin->getSymbolicName() == symbolicName) { if (res.isNull()) { res = plugin; } else if (res->getVersion().compare(plugin->getVersion()) < 0) { res = plugin; } } } return res; } QList > InternalPlatform::GetPlugins(const QString &symbolicName, const QString &version) { QList > plugins = m_Context->getPlugins(); QMap > selected; ctkVersion versionObj(version); foreach(QSharedPointer plugin, plugins) { if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 && plugin->getSymbolicName() == symbolicName) { if (plugin->getVersion().compare(versionObj) > -1) { selected.insert(plugin->getVersion(), plugin); } } } QList > sortedPlugins = selected.values(); QList > reversePlugins; qCopyBackward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end()); return reversePlugins; } QStringList InternalPlatform::GetApplicationArgs() const { QStringList result; IApplicationContext* appContext = this->GetApplicationContext(); if (appContext) { QHash args = appContext->GetArguments(); result = args[IApplicationContext::APPLICATION_ARGS].toStringList(); } return result; } } diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h index c6a3c63abd..d787dbeab9 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h @@ -1,146 +1,149 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYINTERNALPLATFORM_H_ #define BERRYINTERNALPLATFORM_H_ #include #include #include #include struct ctkDebugOptions; struct ctkLocation; class ctkPluginFrameworkFactory; class ctkPluginContext; +namespace mitk +{ + class IPreferencesService; +} + namespace berry { struct IAdapterManager; struct IApplicationContext; struct IExtensionRegistry; -struct IPreferencesService; struct IProduct; struct ILog; class LogImpl; class PlatformLogChannel; class InternalPlatform { private: static QMutex m_Mutex; bool m_Initialized; bool m_Running; bool m_ConsoleLog; ctkPluginContext* m_Context; - QScopedPointer > m_PreferencesTracker; QScopedPointer > m_RegistryTracker; QScopedPointer > m_DebugTracker; QScopedPointer> configurationLocation; QScopedPointer> installLocation; QScopedPointer> instanceLocation; QScopedPointer> userLocation; mutable SmartPointer product; mutable QHash m_Logs; //PlatformEvents m_Events; //PlatformEvent m_EventStarted; //std::map m_ArgMap; InternalPlatform(); //InternalPlatform(const InternalPlatform&) : m_EventStarted(PlatformEvent::EV_PLATFORM_STARTED) {}; void AssertInitialized() const; void OpenServiceTrackers(); void CloseServiceTrackers(); void InitializeDebugFlags(); void InitializeLocations(); ctkDebugOptions* GetDebugOptions() const; IApplicationContext* GetApplicationContext() const; void InitializePluginPaths(); public: static bool DEBUG; static bool DEBUG_PLUGIN_PREFERENCES; virtual ~InternalPlatform(); static InternalPlatform* GetInstance(); void Start(ctkPluginContext* context); void Stop(ctkPluginContext* context); IAdapterManager* GetAdapterManager() const; SmartPointer GetProduct() const; IExtensionRegistry* GetExtensionRegistry(); - IPreferencesService* GetPreferencesService(); + mitk::IPreferencesService* GetPreferencesService(); bool ConsoleLog() const; QVariant GetOption(const QString& option, const QVariant& defaultValue = QVariant()) const; ctkLocation* GetConfigurationLocation(); ctkLocation* GetInstallLocation(); ctkLocation* GetInstanceLocation(); QDir GetStateLocation(const QSharedPointer& plugin); ctkLocation* GetUserLocation(); /** * Returns a log for the given plugin. Creates a new one if needed. * XXX change this into a LogMgr service that would keep track of the map. See if it can be a service factory. * It would contain all the logging methods that are here. * Relate to RuntimeLog if appropriate. * The system log listener needs to be optional: turned on or off. What about a system property? :-) */ ILog* GetLog(const QSharedPointer& plugin) const; //PlatformEvents& GetEvents(); bool IsRunning() const; QStringList GetApplicationArgs() const; QSharedPointer GetPlugin(const QString& symbolicName); QList > GetPlugins(const QString& symbolicName, const QString& version); }; } // namespace berry #endif /*BERRYINTERNALPLATFORM_H_*/ diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp deleted file mode 100644 index 7ad5801806..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.cpp +++ /dev/null @@ -1,512 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include "berryPreferences.h" -#include "berryAbstractPreferencesStorage.h" - -#include - -#include - -namespace berry -{ - - Preferences::Preferences(const PropertyMap& _Properties - , const QString& _Name - , Preferences* _Parent - , AbstractPreferencesStorage* _Storage) - : m_Properties(_Properties) - , m_Path(_Parent ? _Parent->AbsolutePath() + (_Parent->AbsolutePath() == "/" ? "": "/") + _Name : "/") - , m_Name(_Name) - , m_Parent(_Parent) - , m_Root(_Parent ? _Parent->m_Root : this) - , m_Removed(false) - , m_Storage(_Storage) - , m_BlockSignal(false) - { - // root node if parent is 0 - if (_Parent != nullptr) - { - // save as child in parent - _Parent->m_Children.push_back(Preferences::Pointer(this)); - } - } - - bool Preferences::Has(const QString& key ) const - { - QMutexLocker scopedMutex(&m_Mutex); - return this->Has_unlocked(key); - } - - bool Preferences::Has_unlocked(const QString& key ) const - { - return (m_Properties.find(key) != m_Properties.end()); - } - - bool Preferences::IsDirty() const - { - QMutexLocker scopedMutex(&m_Mutex); - - bool dirty = m_Dirty; - for (ChildrenList::const_iterator it = m_Children.begin() - ; it != m_Children.end(); ++it) - { - // break condition: if one node is dirty the whole tree is dirty - if(dirty) - break; - else - dirty = (*it)->IsDirty(); - } - - return dirty; - } - - QString Preferences::ToString() const - { - return QString("Preferences[") + m_Path + "]"; - } - - bool Preferences::Equals(const Preferences* rhs) const - { - if(rhs == nullptr) - return false; - - return (this->m_Path == rhs->m_Path); - } - - Preferences::PropertyMap Preferences::GetProperties() const - { - QMutexLocker scopedMutex(&m_Mutex); - return m_Properties; - } - - Preferences::ChildrenList Preferences::GetChildren() const - { - QMutexLocker scopedMutex(&m_Mutex); - return m_Children; - } - - QString Preferences::AbsolutePath() const - { - return m_Path; - } - - QStringList Preferences::ChildrenNames() const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - QStringList names; - for (ChildrenList::const_iterator it = m_Children.begin() - ; it != m_Children.end(); ++it) - { - names.push_back((*it)->Name()); - } - return names; - } - - AbstractPreferencesStorage* Preferences::GetStorage() const - { - return m_Storage; - } - - void Preferences::Clear() - { - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - m_Properties.clear(); - } - this->SetDirty(true); - } - - void Preferences::Flush() - { - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - } - - m_Storage->Flush(this); - - // if something is written, make the tree undirty - // there is a race condition here: after flushing, another thread - // could modify this object before we can set dirty to false, - // but we cannot hold a lock before flushing because the operation - // will call other methods on this object, which would lead - // to a recursive lock. - this->SetDirty(false); - } - - QString Preferences::Get(const QString& key, const QString& def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? m_Properties[key] : def; - } - - bool Preferences::GetBool(const QString& key, bool def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? (m_Properties[key] == "true" ? true: false) : def; - } - - QByteArray Preferences::GetByteArray(const QString& key, const QByteArray& def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? QByteArray::fromBase64(m_Properties[key].toLatin1()) : def; - } - - double Preferences::GetDouble(const QString& key, double def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? m_Properties[key].toDouble() : def; - } - - float Preferences::GetFloat(const QString& key, float def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? m_Properties[key].toFloat() : def; - } - - int Preferences::GetInt(const QString& key, int def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? m_Properties[key].toInt() : def; - } - - long Preferences::GetLong(const QString& key, long def) const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return this->Has_unlocked(key) ? m_Properties[key].toLong() : def; - } - - QStringList Preferences::Keys() const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - - return m_Properties.keys(); - } - - QString Preferences::Name() const - { - return m_Name; - } - - IPreferences::Pointer Preferences::Node(const QString& path) - { - QMutexLocker scopedMutex(&m_Mutex); - return this->Node_unlocked(path); - } - - Preferences::Pointer Preferences::Node_unlocked(const QString& path) - { - QString pathName = path; - - AssertValid_unlocked(); - AssertPath_unlocked(pathName); - - Preferences::Pointer node; - - // self reference - if(pathName == "") - return Preferences::Pointer(this); - // absolute path - else if(pathName[0] == '/') - { - pathName = pathName.mid(1); - // call root with this relative path - if (this == m_Root) - return m_Root->Node_unlocked(pathName); - else - return m_Root->Node(pathName).Cast(); - } - // relative path - else - { - // check if pathName contains anymore names - QString name = pathName; - - // create new child nodes as long as there are names in the path - int pos = pathName.indexOf('/'); - // cut from the beginning - if(pos != -1) - { - name = pathName.left(pos); - pathName = pathName.mid(pos+1); - } - - // now check if node exists->if not: make new - for (ChildrenList::iterator it = m_Children.begin() - ; it != m_Children.end(); it++) - { - // node found - if((*it)->Name() == name && (*it)->IsRemoved() == false) - { - node = *it; - break; - } - } - - // node not found create new one - if(node.IsNull()) - { - // the new node automatically pushes itself into the children array of *this* - Preferences::Pointer newNode(new Preferences(PropertyMap(), name, this, m_Storage)); - node = newNode.GetPointer(); - // this branch is dirty now -> prefs must be rewritten persistently - this->SetDirty_unlocked(true); - } - - // call Node() again if there are any names left on the path - if(pos != -1) - { - if (this == node.GetPointer()) - node = node->Node_unlocked(pathName); - else - node = node->Node(pathName).Cast(); - } - } - - return node; - } - - bool Preferences::NodeExists(const QString& path) const - { - QString pathName = path; - - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - AssertPath_unlocked(pathName); - - bool nodeExists = false; - - // absolute path - if(pathName[0] == '/') - { - pathName = pathName.mid(1); - // call root with this relative path - return m_Root->NodeExists(pathName); - } - // relative path - else - { - // check if pathName contains anymore names - QString name = pathName; - - // create new child nodes as long as there are names in the path - int pos = pathName.indexOf("/"); - // cut from the beginning - if(pos != -1) - { - name = pathName.left(pos); - pathName = pathName.mid(pos+1); - } - - // now check if node exists->if not: make new - for (ChildrenList::const_iterator it = m_Children.begin() - ; it != m_Children.end(); it++) - { - // node found - if((*it)->Name() == name) - { - // call recursively if more names on the path exist - if(pos != -1) - nodeExists = (*it)->NodeExists(pathName); - else - nodeExists = true; - break; - } - } - } - - return nodeExists; - } - - void Preferences::Put(const QString& key, const QString& value) - { - QString oldValue; - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - oldValue = m_Properties[key]; - m_Properties[key] = value; - } - if (oldValue != value) - { - this->SetDirty(true); - if (!m_BlockSignal) - { - this->OnPropertyChanged(ChangeEvent(this, key, oldValue, value)); - } - } - } - - void Preferences::PutByteArray(const QString& key, const QByteArray& value) - { - this->Put(key, value.toBase64().data()); - } - - void Preferences::PutBool(const QString& key, bool value) - { - this->Put(key, value ? "true" : "false"); - } - - void Preferences::PutDouble(const QString& key, double value) - { - this->Put(key, QString::number(value)); - } - - void Preferences::PutFloat(const QString& key, float value) - { - this->Put(key, QString::number(value)); - } - - void Preferences::PutInt(const QString& key, int value) - { - this->Put(key, QString::number(value)); - } - - void Preferences::PutLong(const QString& key, long value) - { - this->Put(key, QString::number(value)); - } - - void Preferences::Remove(const QString& key) - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - PropertyMap::iterator it = m_Properties.find(key); - if(it != m_Properties.end()) - m_Properties.erase(it); - } - - void Preferences::RemoveNode() - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - this->SetRemoved_unlocked(true); - m_Parent->m_Children.erase(std::find(m_Parent->m_Children.begin(), m_Parent->m_Children.end(), - Preferences::Pointer(this))); - } - - void Preferences::Sync() - { - this->Flush(); - } - - void Preferences::BlockSignals(bool block) - { - m_BlockSignal = block; - } - - void Preferences::AssertValid_unlocked() const - { - if(m_Removed) - { - throw ctkIllegalStateException(QString("no node at '") + m_Path + "'"); - } - } - - void Preferences::AssertPath_unlocked(const QString& pathName) - { - if(pathName.indexOf("//") != -1) - { - throw ctkInvalidArgumentException(QString("Illegal // in m_Path m_Name '") + pathName + "'"); - } - int strLength = pathName.size(); - if(strLength > 1 && pathName[strLength-1] == '/') - { - throw ctkInvalidArgumentException(QString("Trailing / in m_Path m_Name '") + pathName + "'"); - } - } - - IPreferences::Pointer Preferences::Parent() const - { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - return IPreferences::Pointer(m_Parent); - } - - void Preferences::SetDirty( bool _Dirty ) - { - { - QMutexLocker scopedMutex(&m_Mutex); - m_Dirty = _Dirty; - } - if(_Dirty) - { - if (!m_BlockSignal) - { - this->OnChanged.Send(this); - } - } - } - - void Preferences::SetDirty_unlocked( bool _Dirty ) - { - m_Dirty = _Dirty; - if(_Dirty) - if (!m_BlockSignal) - { - this->OnChanged.Send(this); - } -/* - for (ChildrenList::iterator it = m_Children.begin() - ; it != m_Children.end(); ++it) - { - (*it)->SetDirty(_Dirty); - } -*/ - - } - - void Preferences::SetRemoved( bool _Removed ) - { - QMutexLocker scopedMutex(&m_Mutex); - this->SetRemoved_unlocked(_Removed); - } - - void Preferences::SetRemoved_unlocked( bool _Removed ) - { - m_Removed = _Removed; - - for (ChildrenList::iterator it = m_Children.begin() - ; it != m_Children.end(); ++it) - { - (*it)->SetRemoved(_Removed); - } - - } - -/* - Preferences::ChildrenList& Preferences::GetChildren() const - { - return m_Children; - }*/ - - - bool Preferences::IsRemoved() const - { - QMutexLocker scopedMutex(&m_Mutex); - return m_Removed; - } - - Preferences::~Preferences() - { - } -} diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.h b/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.h deleted file mode 100644 index d5336cec58..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferences.h +++ /dev/null @@ -1,348 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYPREFERENCES_H_ -#define BERRYPREFERENCES_H_ - -#include - -#include "berryIBerryPreferences.h" - -#include -#include - -namespace berry -{ - class AbstractPreferencesStorage; - - /** - * Implementation of the OSGI Preferences Interface. - * Wraps a DOMNode. - */ - class org_blueberry_core_runtime_EXPORT Preferences: public IBerryPreferences - { - - public: - - berryObjectMacro(berry::Preferences); - - /** - * Maps a string key to a string value - */ - typedef QHash PropertyMap; - - /** - * The list of Child nodes - */ - typedef QList ChildrenList; - - /** - * Constructs a new preference node. - * \param _Properties the key->value pairs of this preference node - * \param _Path the absolute path to this node, e.g. "/general/editors/font" - * \param _Name the name of this node, e.g. "font" - * \param _FileName the absolute path to the file in which this preferences tree will be saved to - * \param _Parent the parent node or 0 if this is the root - * \param _Root the root of this preference tree - */ - Preferences(const PropertyMap& _Properties, - const QString& _Name, - Preferences* _Parent, - AbstractPreferencesStorage* _Storage); - - ~Preferences() override; - - /** - * Prints out the absolute path of the preference node. - */ - QString ToString() const override; - - /** - * Returns if this node and his silblings have to be rewritten persistently - */ - bool IsDirty() const; - - /** - * Returns if this node is removed - */ - bool IsRemoved() const; - - /** - * Returns if this node has property with a specific key - */ - bool Has(const QString& key) const; - - /** - * Returns true if the absolute paths are the same - */ - bool Equals(const Preferences* rhs) const; - - /** - * Returns all Properties as map. - */ - PropertyMap GetProperties() const; - - /** - * Returns a reference to the children list in order to add or remove nodes. - * *ATTENTION*: Should only be used - * when constructing the preferences tree from a persistent location. Normally, one would - * only use the IPreferences methods - */ - ChildrenList GetChildren() const; - - //# Begin of IPreferences methods - - /** - * \see IPreferences::AbsolutePath() - */ - QString AbsolutePath() const override; - - /** - * \see IPreferences::ChildrenNames() - */ - QStringList ChildrenNames() const override; - - /** - * \see IPreferences::ChildrenNames() - */ - virtual AbstractPreferencesStorage* GetStorage() const; - - /** - * \see IPreferences::Clear() - */ - void Clear() override; - - /** - * \see IPreferences::Flush() - */ - void Flush() override; - - /** - * \see IPreferences::Get() - */ - QString Get(const QString& key, const QString& def) const override; - - /** - * \see IPreferences::GetBool() - */ - bool GetBool(const QString& key, bool def) const override; - - /** - * \see IPreferences::GetByteArray() - */ - QByteArray GetByteArray(const QString& key, const QByteArray& def) const override; - - /** - * \see IPreferences::GetDouble() - */ - double GetDouble(const QString& key, double def) const override; - - /** - * \see IPreferences::GetFloat() - */ - float GetFloat(const QString& key, float def) const override; - - /** - * \see IPreferences::GetInt() - */ - int GetInt(const QString& key, int def) const override; - - /** - * \see IPreferences::GetLong() - */ - long GetLong(const QString& key, long def) const override; - - /** - * \see IPreferences::Keys() - */ - QStringList Keys() const override; - - /** - * \see IPreferences::Name() - */ - QString Name() const override; - - /** - * \see IPreferences::Node() - */ - IPreferences::Pointer Node(const QString& pathName) override; - - /** - * \see IPreferences::NodeExists() - */ - bool NodeExists(const QString& pathName) const override; - - /** - * \see IPreferences::Parent() - */ - IPreferences::Pointer Parent() const override; - - /** - * \see IPreferences::Put() - */ - void Put(const QString& key, const QString& value) override; - - /** - * \see IPreferences::PutByteArray() - */ - void PutByteArray(const QString& key, const QByteArray& value) override; - - /** - * \see IPreferences::PutBool() - */ - void PutBool(const QString& key, bool value) override; - - /** - * \see IPreferences::PutDouble() - */ - void PutDouble(const QString& key, double value) override; - - /** - * \see IPreferences::Sync() - */ - void PutFloat(const QString& key, float value) override; - - /** - * \see IPreferences::PutInt() - */ - void PutInt(const QString& key, int value) override; - - /** - * \see IPreferences::PutLong() - */ - void PutLong(const QString& key, long value) override; - - /** - * \see IPreferences::Remove() - */ - void Remove(const QString& key) override; - - /** - * \see IPreferences::RemoveNode() - */ - void RemoveNode() override; - - /** - * \see IPreferences::Sync() - */ - void Sync() override; - - /** - * \see IPreferences::BlockSignals() - */ - void BlockSignals(bool block) override; - - //# End of IPreferences methods - - protected: - - /** - * Checks if this node is about to be removed. - * \throws IllegalStateException - */ - void AssertValid_unlocked() const; - - /** - * Checks a path value for validity. - * \throws invalid_argument - */ - static void AssertPath_unlocked(const QString& pathName); - -// /** -// * Converts any value to a string (using stream operator "<<") -// */ -// template -// static QString ToString(const T& obj, int precision = 12 ) -// { -// std::ostringstream s; -// std::locale C("C"); -// s.imbue(C); -// s.precision(precision); s << obj; return s.str(); -// } - - bool Has_unlocked(const QString& key) const; - - Preferences::Pointer Node_unlocked(const QString& pathName); - - /** - * Sets the dirty flag recursively on all child nodes. - */ - void SetDirty(bool _Dirty); - void SetDirty_unlocked(bool _Dirty); - - /** - * Sets the removed flag recursively on all child nodes. - */ - void SetRemoved(bool _Removed); - void SetRemoved_unlocked(bool _Removed); - - protected: - - /** - * Holds all Key/Value Pairs. - */ - QHash m_Properties; - - /** - * Holds all child nodes (explicit ownership). - */ - QList m_Children; - - /** - * Saves the absolute path of this node (calculated in the constructor) - */ - const QString m_Path; - - /** - * Saves the name of this node (set when read from backend) - */ - const QString m_Name; - - /** - * Saves the parent of this node - */ - Preferences* const m_Parent; - - /** - * Saves the root of this tree - */ - Preferences* const m_Root; - - /** - * Saves if something changed on this branch. - * Meaning that you would have to rewrite it. - */ - bool m_Dirty; - - /** - * Saves if this Node is removed (will not be saved to the backend). - */ - bool m_Removed; - - /** - * A storage to call the flush method. - */ - AbstractPreferencesStorage* const m_Storage; - - /** - * A mutex to avoid concurrency crashes. Mutable because we need to use Mutex::lock() in const functions - */ - mutable QMutex m_Mutex; - - /** - * A flag to block berry messages in order to prevent callback functions to be called. - */ - bool m_BlockSignal; - }; - -} - -#endif /* BERRYPREFERENCES_H_ */ diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferencesService.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryPreferencesService.cpp deleted file mode 100644 index 8063212c86..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferencesService.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include "berryPreferencesService.h" -#include "berryXMLPreferencesStorage.h" -#include "berryIPreferences.h" - -#include "berryPlatform.h" - -#include -#include - - -QString berry::PreferencesService::GetDefaultPreferencesDirPath() -{ - return Platform::GetUserPath().absolutePath() + "/.BlueBerryPrefs"; -} - -QString berry::PreferencesService::GetDefaultPreferencesFileName() -{ - return "prefs.xml"; -} - -berry::PreferencesService::PreferencesService(const QString& _PreferencesDir) -: m_PreferencesDir(_PreferencesDir) -{ - if(m_PreferencesDir.isEmpty()) - m_PreferencesDir = GetDefaultPreferencesDirPath(); - - QDir prefDir(m_PreferencesDir); - if(!prefDir.exists()) - QDir().mkpath(m_PreferencesDir); - - QString defaultName = GetDefaultPreferencesFileName(); - QStringList prefFiles = prefDir.entryList(QStringList(QString("*") + defaultName), - QDir::Files | QDir::Readable | QDir::Writable); - foreach(QString prefFile, prefFiles) - { - int pos = prefFile.lastIndexOf(defaultName); - QString userName = prefFile.left(pos); - // set the storage to 0 (will be loaded later) - m_PreferencesStorages[userName] = AbstractPreferencesStorage::Pointer(nullptr); - } -} - -berry::PreferencesService::~PreferencesService() -{ - this->ShutDown(); -} - -berry::IPreferences::Pointer berry::PreferencesService::GetSystemPreferences() -{ - QMutexLocker scopedMutex(&m_Mutex); - // sys prefs are indicated by an empty user QString - return this->GetUserPreferences_unlocked(""); -} - -berry::IPreferences::Pointer berry::PreferencesService::GetUserPreferences(const QString& name) -{ - QMutexLocker scopedMutex(&m_Mutex); - return this->GetUserPreferences_unlocked(name); -} - -berry::IPreferences::Pointer berry::PreferencesService::GetUserPreferences_unlocked(const QString& name) -{ - IPreferences::Pointer userPrefs(nullptr); - - QHash::const_iterator it - = m_PreferencesStorages.find(name); - - // does not exist or is not loaded yet - if(it == m_PreferencesStorages.end() || it.value().IsNull()) - { - QString path = m_PreferencesDir; - - if(name.isEmpty()) - path = path + '/' + GetDefaultPreferencesFileName(); - else - path = path + '/' + name + GetDefaultPreferencesFileName(); - - XMLPreferencesStorage::Pointer storage(new XMLPreferencesStorage(path)); - m_PreferencesStorages[name] = storage; - } - - userPrefs = m_PreferencesStorages[name]->GetRoot(); - - return userPrefs; -} - -QStringList berry::PreferencesService::GetUsers() const -{ - QMutexLocker scopedMutex(&m_Mutex); - QStringList users; - - for (QHash::const_iterator it = m_PreferencesStorages.begin(); - it != m_PreferencesStorages.end(); ++it) - { - users.push_back(it.key()); - } - - return users; -} - -void berry::PreferencesService::ImportPreferences(const QString& f, const QString& name) -{ - QHash::const_iterator it - = m_PreferencesStorages.find(name); - - if(it == m_PreferencesStorages.end() || it.value() == 0) - { - this->GetUserPreferences(name); - } - - //Poco::File defaultFile = it->second->GetFile(); - XMLPreferencesStorage::Pointer storage(new XMLPreferencesStorage(f)); - - IPreferences::Pointer rootOfImportedPrefs = storage->GetRoot(); - IPreferences::Pointer rootOfOldPrefs = m_PreferencesStorages[name]->GetRoot(); - - // make backup of old - QString exportFilePath = QDateTime::currentDateTime().toString(); - exportFilePath = GetDefaultPreferencesDirPath() + '/' + exportFilePath + "prefs.xml"; - this->ExportPreferences(exportFilePath, name); - - if(rootOfImportedPrefs.IsNotNull()) - { - this->ImportNode(rootOfImportedPrefs, rootOfOldPrefs); - } - -} - -void berry::PreferencesService::ShutDown() -{ - // flush all preferences - for (QHash::const_iterator it = m_PreferencesStorages.begin(); - it != m_PreferencesStorages.end(); ++it) - { - // the preferences storage may be 0 if the corresponding file was never loaded - if(it.value() != 0) - it.value()->GetRoot()->Flush(); - } -} - -void berry::PreferencesService::ImportNode(const IPreferences::Pointer& nodeToImport, - const IPreferences::Pointer& rootOfOldPrefs) -{ - //# overwrite properties - IPreferences::Pointer oldNode - = rootOfOldPrefs->Node(nodeToImport->AbsolutePath()); // get corresponding node in "old" tree - - QStringList keys = nodeToImport->Keys(); // get all keys for properties - foreach(QString key, keys) - { - oldNode->Put(key, nodeToImport->Get(key, "")); // set property in old node to the value of the imported. - // properties not existing in imported are left untouched - } - - // do it for all children - QStringList childrenNames = nodeToImport->ChildrenNames(); - foreach (QString childName, childrenNames) - { - // with node->Node() you get the child node with the name - this->ImportNode(nodeToImport->Node(childName), rootOfOldPrefs); - } -} - -void berry::PreferencesService::ExportPreferences(const QString& f, const QString& name ) -{ - QHash::const_iterator it - = m_PreferencesStorages.find(name); - - if(it.value() == 0) - { - this->GetUserPreferences(name); - } - AbstractPreferencesStorage::Pointer storage = it.value(); - QString temp = storage->GetFile(); - storage->SetFile(f); - storage->GetRoot()->Flush(); - storage->SetFile(temp); -} diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferencesService.h b/Plugins/org.blueberry.core.runtime/src/internal/berryPreferencesService.h deleted file mode 100644 index 97b6663caf..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryPreferencesService.h +++ /dev/null @@ -1,115 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYPREFERENCESSERVICE_H_ -#define BERRYPREFERENCESSERVICE_H_ - -#include - -#include "berryIBerryPreferencesService.h" - -#include -#include -#include - -namespace berry -{ - -class AbstractPreferencesStorage; - - /** - * Implementation of the IPreferencesService Interface - */ - class org_blueberry_core_runtime_EXPORT PreferencesService : public QObject, public IBerryPreferencesService - { - Q_OBJECT - Q_INTERFACES(berry::IBerryPreferencesService berry::IPreferencesService) - - public: - - /// - /// Returns the default name for the preferences data file - /// - static QString GetDefaultPreferencesFileName(); - - /// - /// Returns the path to the directory where all preference data is stored. - /// - static QString GetDefaultPreferencesDirPath(); - - /// - /// Reads in all users for which preferences exist. - /// - PreferencesService(const QString& _PreferencesDir=""); - - /// - /// Nothing to do here so far. - /// - ~PreferencesService() override; - - /** - * If no system preference file exists create a new AbstractPreferencesStorage. - * \see IPreferencesService::GetSystemPreferences() - */ - SmartPointer GetSystemPreferences() override; - - /** - * If no user preference file exists create a new AbstractPreferencesStorage. - * \see IPreferencesService::GetUserPreferences() - */ - SmartPointer GetUserPreferences(const QString& name) override; - - /** - * \see IPreferencesService::GetUsers() - */ - QStringList GetUsers() const override; - - - /// - /// \see IPreferencesService::ImportPreferences() - /// - void ImportPreferences(const QString &f, const QString& name="") override; - - /// - /// \see IPreferencesService::ExportPreferences() - /// - void ExportPreferences(const QString &f, const QString& name="") override; - - /// - /// flushes all preferences - /// - virtual void ShutDown(); - - protected: - - SmartPointer GetUserPreferences_unlocked(const QString& name); - - /// - /// Helper func for ImportPreferences(). Imports all nodes of an IPreferences tree recursively - /// - void ImportNode(const SmartPointer& nodeToImport, const SmartPointer& rootOfOldPrefs); - /// - /// Holds the directory where the preferences files will be stored - /// - QString m_PreferencesDir; - /// - /// Maps all user names to their preference storage. - /// - QHash > m_PreferencesStorages; - /// - /// A mutex to avoid concurrency crashes. Mutable because we need to use Mutex::lock() in const functions - /// - mutable QMutex m_Mutex; - - }; -} // namespace berry - -#endif /*BERRYPREFERENCESSERVICE_H_*/ diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryProperties.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryProperties.cpp index 0a27acca76..484f2cb43c 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryProperties.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryProperties.cpp @@ -1,54 +1,52 @@ /*============================================================================ 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 "berryRegistryProperties.h" -#include - #include namespace berry { QHash RegistryProperties::registryProperties; ctkPluginContext* RegistryProperties::context = nullptr; void RegistryProperties::SetContext(ctkPluginContext* context) { RegistryProperties::context = context; } QString RegistryProperties::GetProperty(const QString& propertyName) { QHash::const_iterator i = registryProperties.find(propertyName); if (i != registryProperties.end() && !i.value().isNull()) return i.value(); return GetContextProperty(propertyName); } QString RegistryProperties::GetProperty(const QString& property, const QString& defaultValue) { QString result = RegistryProperties::GetProperty(property); return result.isNull() ? defaultValue : result; } void RegistryProperties::SetProperty(const QString& propertyName, const QString& propertyValue) { registryProperties.insert(propertyName, propertyValue); } QString RegistryProperties::GetContextProperty(const QString& propertyName) { return context->getProperty(propertyName).toString(); } } diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryXMLPreferencesStorage.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryXMLPreferencesStorage.cpp deleted file mode 100644 index c05eb6138c..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryXMLPreferencesStorage.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include "berryXMLPreferencesStorage.h" -#include "berryPreferences.h" - -#include "berryLog.h" -#define WARNMSG BERRY_WARN("XMLPreferencesStorage") - -#include "Poco/File.h" -#include "Poco/DOM/DOMParser.h" -#include "Poco/DOM/DOMWriter.h" -#include "Poco/DOM/Element.h" -#include "Poco/XML/XMLWriter.h" -#include "Poco/DOM/Document.h" -#include "Poco/DOM/NodeIterator.h" -#include "Poco/DOM/NodeFilter.h" -#include "Poco/DOM/AutoPtr.h" -#include "Poco/SAX/InputSource.h" -#include "Poco/DOM/NamedNodeMap.h" -#include "Poco/DOM/NodeList.h" -#include "Poco/DOM/Element.h" -#include "Poco/Exception.h" -#include "Poco/SAX/SAXException.h" - -using Poco::XML::DOMParser; -using Poco::XML::InputSource; -using Poco::XML::Document; -using Poco::XML::NodeIterator; -using Poco::XML::NodeFilter; -using Poco::XML::Node; -using Poco::XML::Element; -using Poco::XML::AutoPtr; -using Poco::Exception; - -#include -#include - -namespace berry -{ - - - XMLPreferencesStorage::XMLPreferencesStorage( const QString& file ) - : AbstractPreferencesStorage(file) - { - Poco::File _File(file.toStdString()); - // file already exists - try{ - if(_File.exists()) - { - // build preferences tree from file - InputSource src(_File.path()); - DOMParser parser; - AutoPtr pDoc = parser.parse(&src); - this->ToPreferencesTree(pDoc->documentElement(), nullptr); - } - } - catch (Poco::XML::SAXParseException& exc) - { - const std::string tempString = _File.path()+".backup"; - BERRY_INFO << exc.what(); - BERRY_INFO << "Preferences could not be loaded."; - BERRY_INFO << "Creating " << tempString; - BERRY_INFO << "and resetting to default values."; - _File.copyTo(tempString); - this->m_Root = nullptr; - } - - // if root is null make new one - if(this->m_Root.IsNull()) - { - this->m_Root = Preferences::Pointer(new Preferences(Preferences::PropertyMap(), "", nullptr, this)); - } - } - - - - void XMLPreferencesStorage::Flush(IPreferences* /*_Preferences*/) - { -#ifdef _MSC_VER - std::locale localeBackup; // See bug #18575: Do not remove these lines! In case of any issues regarding - std::locale::global(std::locale("")); // the formatting of numbers, try to set the numeric facet. The C locale is NOT -#endif // available here at application shutdown (possibly a bug in MSVC 2013 standard - // library), i.e., it is already partly deconstructed. - try - { - this->ToDOMTree(dynamic_cast(this->m_Root.GetPointer()), nullptr); - // flush dom to file - Poco::XML::DOMWriter writer; - //writer.setNewLine("\n"); - writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT); - std::ofstream f; - f.open (qPrintable(this->m_File)); - - // PRECISION setting - // f.precision(10); - writer.writeNode(f, m_Document); - - f.close(); - } - catch (std::exception& e) - { - WARNMSG << e.what(); - } - -#ifdef _MSC_VER - std::locale::global(localeBackup); -#endif - } - - XMLPreferencesStorage::~XMLPreferencesStorage() - { - } - - void XMLPreferencesStorage::ToPreferencesTree( Poco::XML::Node* DOMNode, Preferences* prefParentNode ) - { - // collect properties from attributes - Preferences::PropertyMap properties; - Poco::XML::Element* elem = dynamic_cast(DOMNode); - std::string name = elem->getAttribute("name"); - - // create a new Preferences node - Preferences::Pointer newNode(new Preferences(properties, QString::fromStdString(name), prefParentNode, this)); - // save the new Preferences node as root node if needed - if(prefParentNode == nullptr) - m_Root = newNode; - - // recursion: now go on for all child nodes of DOMNode - Poco::XML::NodeList* childNodes = elem->childNodes(); - Poco::XML::Node* currentNode = nullptr; - Poco::XML::Element* prop = nullptr; - std::string key; - std::string value; - - for (unsigned int i = 0; i != childNodes->length(); ++i) - { - currentNode = childNodes->item(i); - - if(currentNode->nodeName() == "preferences") - this->ToPreferencesTree(currentNode, newNode.GetPointer()); - else if(currentNode->nodeName() == "property") - { - prop = dynamic_cast(currentNode); - key = prop->getAttribute("name"); - value = prop->getAttribute("value"); - newNode->Put(QString::fromStdString(key), QString::fromStdString(value)); - } - } - - childNodes->release(); - } - - void XMLPreferencesStorage::ToDOMTree( Preferences* prefNode, Poco::XML::Node* parentDOMNode ) - { - if(parentDOMNode == nullptr) - { - m_Document = new Poco::XML::Document; - parentDOMNode = m_Document; - } - - //# create DOMNode from Preferences - Element* newNode = m_Document->createElement("preferences"); - newNode->setAttribute("name", prefNode->Name().toStdString()); - - // make attributes - Preferences::PropertyMap properties = prefNode->GetProperties(); - for (Preferences::PropertyMap::iterator it = properties.begin() - ; it != properties.end(); it++) - { - Element* newProp = m_Document->createElement("property"); - newProp->setAttribute("name", it.key().toStdString()); - newProp->setAttribute("value", it.value().toStdString()); - newNode->appendChild(newProp); - } - // save in parentDOMNode - parentDOMNode->appendChild(newNode); - - // recursion: now do that for all child Preferences nodes - Preferences::ChildrenList children = prefNode->GetChildren(); - for (Preferences::ChildrenList::iterator it = children.begin() - ; it != children.end(); it++) - { - this->ToDOMTree((*it).GetPointer(), newNode); - } - - newNode->release(); - } -} diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryXMLPreferencesStorage.h b/Plugins/org.blueberry.core.runtime/src/internal/berryXMLPreferencesStorage.h deleted file mode 100644 index 161c9c3d4d..0000000000 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryXMLPreferencesStorage.h +++ /dev/null @@ -1,75 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef BERRYXMLPREFERENCES_H_ -#define BERRYXMLPREFERENCES_H_ - -#include -#include "berryAbstractPreferencesStorage.h" - -#include "Poco/AutoPtr.h" - -namespace Poco { -namespace XML { -class Node; -class Document; -} -} - -namespace berry -{ - class Preferences; - /// - /// Implementation of the OSGI Preferences Interface. - /// Wraps a DOMNode. - /// - class org_blueberry_core_runtime_EXPORT XMLPreferencesStorage: public AbstractPreferencesStorage - { - public: - /// - /// For use with berry::SmartPtr - /// - berryObjectMacro(berry::XMLPreferencesStorage); - /// - /// Construct a new XML-based PreferencesStorage - /// - XMLPreferencesStorage(const QString& _File); - - /// - /// To be implemented in the subclasses. - /// - void Flush(IPreferences* _Preferences) override; - - /// - /// Nothing to do here - /// - ~XMLPreferencesStorage() override; - - protected: - /// - /// Construct Preferences tree from DOM tree (recursive) - /// Construct a PreferencesNode from the DOMNode by using prefParentNode - /// - void ToPreferencesTree(Poco::XML::Node* DOMNode, Preferences* prefParentNode); - /// - /// Construct DOM tree from Preferences tree (recursive) - /// Construct a DOMNode from the prefNode by using parentDOMNode - /// - void ToDOMTree(Preferences* prefNode, Poco::XML::Node* parentDOMNode); - - protected: - - Poco::AutoPtr m_Document; - - }; -} - -#endif /* BERRYXMLPREFERENCES_H_ */ diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp index 6a53ce2d23..eb0c5b3afe 100644 --- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp +++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp @@ -1,85 +1,83 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryHelpEditorInput.h" #include "berryHelpEditorInputFactory.h" -#include - #include namespace berry { HelpEditorInput::HelpEditorInput(const QUrl &url) : url(url) { } bool HelpEditorInput::Exists() const { return !url.isEmpty(); } QString HelpEditorInput::GetName() const { if (url.isEmpty()) return "Untitled"; return url.toString(); } QString HelpEditorInput::GetToolTipText() const { return url.toString(); } QIcon HelpEditorInput::GetIcon() const { return QIcon(); } const IPersistableElement* HelpEditorInput::GetPersistable() const { return this; } Object* HelpEditorInput::GetAdapter(const QString& adapterType) const { return PlatformObject::GetAdapter(adapterType); } QString HelpEditorInput::GetFactoryId() const { return HelpEditorInputFactory::GetFactoryId(); } void HelpEditorInput::SaveState(const SmartPointer& memento) const { HelpEditorInputFactory::SaveState(memento, this); } bool HelpEditorInput::operator==(const berry::Object* o) const { const HelpEditorInput* input = dynamic_cast(o); if (input) return this->url == input->url; return false; } QUrl HelpEditorInput::GetUrl() const { return url; } } diff --git a/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp b/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp index 6b76453f60..d1960b8dd7 100644 --- a/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp +++ b/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp @@ -1,157 +1,152 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtLogView.h" #include "berryQtLogPlugin.h" -#include -#include #include #include #include #include #include +#include +#include + namespace berry { QtLogView::QtLogView(QWidget *parent) : QWidget(parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IBerryPreferences::Pointer prefs - = (prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log")) - .Cast(); + auto* prefService = berry::Platform::GetPreferencesService(); + auto* prefs = prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log"); prefs->PutBool("ShowAdvancedFields", false); prefs->PutBool("ShowCategory", true); bool showAdvancedFields = false; ui.setupUi(this); model = QtLogPlugin::GetInstance()->GetLogModel(); model->SetShowAdvancedFiels( showAdvancedFields ); filterModel = new QSortFilterProxyModel(this); filterModel->setSourceModel(model); filterModel->setFilterKeyColumn(-1); #ifdef __APPLE__ QFont fnt = ui.tableView->font(); fnt.setPointSize(11); ui.tableView->setFont(fnt); #endif ui.tableView->setModel(filterModel); ui.tableView->verticalHeader()->setVisible(false); ui.tableView->horizontalHeader()->setStretchLastSection(true); connect( ui.filterContent, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotFilterChange( const QString& ) ) ); connect( filterModel, SIGNAL( rowsInserted ( const QModelIndex &, int, int ) ), this, SLOT( slotRowAdded( const QModelIndex &, int , int ) ) ); connect( ui.SaveToClipboard, SIGNAL( clicked()),this, SLOT(on_SaveToClipboard_clicked())); ui.ShowAdvancedFields->setChecked( showAdvancedFields ); ui.filterContent->setClearButtonEnabled(true); } QtLogView::~QtLogView() { } void QtLogView::slotScrollDown( ) { ui.tableView->scrollToBottom(); } void QtLogView::slotFilterChange( const QString& q ) { filterModel->setFilterRegExp(QRegExp(q, Qt::CaseInsensitive, QRegExp::FixedString)); } void QtLogView::slotRowAdded ( const QModelIndex & /*parent*/, int /*start*/, int /*end*/ ) { ui.tableView->setVisible(false); ui.tableView->resizeRowsToContents(); //only resize columns when first entry is added static bool first = true; if(first) { ui.tableView->resizeColumnsToContents(); first = false; } ui.tableView->setVisible(true); QTimer::singleShot(0,this,SLOT( slotScrollDown() ) ); } void QtLogView::showEvent( QShowEvent * /*event*/ ) { ui.tableView->setVisible(false); ui.tableView->resizeColumnsToContents(); ui.tableView->resizeRowsToContents(); ui.tableView->setVisible(true); } void QtLogView::on_ShowAdvancedFields_clicked( bool checked ) { ui.tableView->setVisible(false); QtLogPlugin::GetInstance()->GetLogModel()->SetShowAdvancedFiels( checked ); ui.tableView->resizeColumnsToContents(); ui.tableView->setVisible(true); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IBerryPreferences::Pointer prefs - = (prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log")) - .Cast(); + auto* prefService = berry::Platform::GetPreferencesService(); + auto* prefs = prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log"); prefs->PutBool("ShowAdvancedFields", checked); prefs->Flush(); } void QtLogView::on_ShowCategory_clicked( bool checked ) { ui.tableView->setVisible(false); QtLogPlugin::GetInstance()->GetLogModel()->SetShowCategory( checked ); ui.tableView->resizeColumnsToContents(); ui.tableView->setVisible(true); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IBerryPreferences::Pointer prefs - = (prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log")) - .Cast(); + auto* prefService = berry::Platform::GetPreferencesService(); + auto* prefs = prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log"); prefs->PutBool("ShowCategory", checked); prefs->Flush(); } void QtLogView::on_SaveToClipboard_clicked() { QClipboard *clipboard = QApplication::clipboard(); QString loggingMessagesAsText = QString(""); for (int i=0; imodel()->rowCount(); i++) { for (int j=0; jmodel()->columnCount(); j++) { QModelIndex index = ui.tableView->model()->index(i, j); loggingMessagesAsText += ui.tableView->model()->data(index, Qt::DisplayRole).toString() + " "; } loggingMessagesAsText += "\n"; } clipboard->setText(loggingMessagesAsText); } } diff --git a/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp b/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp index a4f9ff3922..ec1b20951b 100644 --- a/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp +++ b/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp @@ -1,335 +1,333 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtPlatformLogModel.h" #include "berryQtLogPlugin.h" -#include "berryPlatform.h" - #include "mbilogLoggingTypes.h" #include #include #include #include #include #include #include #include namespace berry { const QString QtPlatformLogModel::Error = QString("Error"); const QString QtPlatformLogModel::Warn = QString("Warning"); const QString QtPlatformLogModel::Fatal = QString("Fatal"); const QString QtPlatformLogModel::Info = QString("Info"); const QString QtPlatformLogModel::Debug = QString("Debug"); void QtPlatformLogModel::slotFlushLogEntries() { m_Mutex.lock(); QList *tmp=m_Active; m_Active=m_Pending; m_Pending=tmp; m_Mutex.unlock(); int num = static_cast(m_Pending->size()); if (num > 0) { int row = static_cast(m_Entries.size()); this->beginInsertRows(QModelIndex(), row, row+num-1); do { m_Entries.push_back(m_Pending->front()); m_Pending->pop_front(); } while(--num); this->endInsertRows(); } } void QtPlatformLogModel::addLogEntry(const mbilog::LogMessage &msg) { m_Mutex.lock(); //mbilog::BackendCout::FormatSmart(msg); FormatSmart is not static any more. So commented out this statement. Todo: fix m_Active->push_back(ExtendedLogMessage(msg)); m_Mutex.unlock(); emit signalFlushLogEntries(); } void QtPlatformLogModel::SetShowAdvancedFiels( bool showAdvancedFiels ) { if( m_ShowAdvancedFiels != showAdvancedFiels ) { m_ShowAdvancedFiels = showAdvancedFiels; this->beginResetModel(); this->endResetModel(); } } void QtPlatformLogModel::SetShowCategory( bool showCategory ) { if( m_ShowCategory != showCategory ) { m_ShowCategory = showCategory; this->beginResetModel(); this->endResetModel(); } } void QtPlatformLogModel::addLogEntry(const ctkPluginFrameworkEvent& event) { int level = mbilog::Info; if (event.getType() == ctkPluginFrameworkEvent::PLUGIN_ERROR) { level = mbilog::Error; } else if (event.getType() == ctkPluginFrameworkEvent::FRAMEWORK_WAIT_TIMEDOUT || event.getType() == ctkPluginFrameworkEvent::PLUGIN_WARNING) { level = mbilog::Warn; } mbilog::LogMessage msg(level,"n/a",-1,"n/a"); QString str; QDebug dbg(&str); dbg << event; msg.message = str.toStdString(); //msg.moduleName = event.getPlugin()->getSymbolicName().toStdString(); addLogEntry(msg); } QtPlatformLogModel::QtPlatformLogModel(QObject* parent) : QAbstractTableModel(parent), m_ShowAdvancedFiels(false), m_ShowCategory(true) { m_Active=new QList; m_Pending=new QList; connect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() ), Qt::QueuedConnection ); QtLogPlugin::GetInstance()->GetContext()->connectFrameworkListener(this, SLOT(addLogEntry(ctkPluginFrameworkEvent))); myBackend = new QtLogBackend(this); } QtPlatformLogModel::~QtPlatformLogModel() { disconnect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() )); QtLogPlugin::GetInstance()->GetContext()->disconnectFrameworkListener(this); // dont delete and unregister backend, only deactivate it to avoid thread syncronization issues cause mbilog::UnregisterBackend is not threadsafe // will be fixed. // delete myBackend; // delete m_Active; // delete m_Pending; m_Mutex.lock(); myBackend->Deactivate(); m_Mutex.unlock(); } // QT Binding int QtPlatformLogModel::rowCount(const QModelIndex&) const { return static_cast(m_Entries.size()); } int QtPlatformLogModel::columnCount(const QModelIndex&) const { int returnValue = 2; if( m_ShowAdvancedFiels ) returnValue += 7; if( m_ShowCategory ) returnValue += 1; return returnValue; } /* struct LogEntry { LogEntry(const std::string& msg, const std::string& src, std::time_t t) : message(msg.c_str()), moduleName(src.c_str()),time(std::clock()) { } QString message; clock_t time; QString level; QString filePath; QString lineNumber; QString moduleName; QString category; QString function; LogEntry(const mbilog::LogMessage &msg) { message = msg.message.c_str(); filePath = msg.filePath; std::stringstream out; out << msg.lineNumber; lineNumber = out.str().c_str(); moduleName = msg.moduleName; category = msg.category.c_str(); function = msg.functionName; time=std::clock(); } }; */ QVariant QtPlatformLogModel::data(const QModelIndex& index, int role) const { const ExtendedLogMessage *msg = &m_Entries[index.row()]; if (role == Qt::DisplayRole) { switch (index.column()) { case 0: if (m_ShowAdvancedFiels) return msg->getTime(); else return msg->getLevel(); case 1: if (m_ShowAdvancedFiels) return msg->getLevel(); else return msg->getMessage(); case 2: if (m_ShowAdvancedFiels) return msg->getMessage(); else return msg->getCategory(); case 3: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getCategory(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getModuleName(); else break; case 4: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getModuleName(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getFunctionName(); else break; case 5: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getFunctionName(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getPath(); else break; case 6: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getPath(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getLine(); else break; case 7: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getLine(); else break; } } else if( role == Qt::DecorationRole ) { if ( (m_ShowAdvancedFiels && index.column()==1) || (!m_ShowAdvancedFiels && index.column()==0) ) { QString file ( ":/org_blueberry_ui_qt_log/information.png" ); if( msg->message.level == mbilog::Error ) file = ":/org_blueberry_ui_qt_log/error.png"; else if( msg->message.level == mbilog::Warn ) file = ":/org_blueberry_ui_qt_log/warning.png"; else if( msg->message.level == mbilog::Debug ) file = ":/org_blueberry_ui_qt_log/debug.png"; else if( msg->message.level == mbilog::Fatal ) file = ":/org_blueberry_ui_qt_log/fatal.png"; QIcon icon(file); return QVariant(icon); } } return QVariant(); } QVariant QtPlatformLogModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { if( m_ShowAdvancedFiels && m_ShowCategory ) { switch (section) { case 0: return QVariant(" Time "); case 1: return QVariant(" Level "); case 2: return QVariant(" Message "); case 3: return QVariant(" Category "); case 4: return QVariant(" Module "); case 5: return QVariant(" Function "); case 6: return QVariant(" File "); case 7: return QVariant(" Line "); } } else if (m_ShowAdvancedFiels && !m_ShowCategory) { switch (section) { case 0: return QVariant(" Time "); case 1: return QVariant(" Level "); case 2: return QVariant(" Message "); case 3: return QVariant(" Module "); case 4: return QVariant(" Function "); case 5: return QVariant(" File "); case 6: return QVariant(" Line "); } } else //!m_ShowAdvancedFiels, m_ShowCategory is not handled seperately because it only activates case 2 { switch (section) { case 0: return QVariant(" Level "); case 1: return QVariant(" Message "); case 2: return QVariant(" Category "); } } } return QVariant(); } QVariant QtPlatformLogModel::ExtendedLogMessage::getTime() const { std::stringstream ss; std::locale C("C"); ss.imbue(C); ss << std::setw(7) << std::setprecision(3) << std::fixed << ((double)this->time)/CLOCKS_PER_SEC; return QVariant(QString(ss.str().c_str())); } QString QtPlatformLogModel::GetDataAsString() { QString returnValue(""); for (int message=0; messagerowCount(QModelIndex()); message++) { for (int column=0; columncolumnCount(QModelIndex()); column++) { returnValue += " " + this->data(this->index(message,column),Qt::DisplayRole).toString(); } returnValue += "\n"; } return returnValue; } } diff --git a/Plugins/org.blueberry.ui.qt/CMakeLists.txt b/Plugins/org.blueberry.ui.qt/CMakeLists.txt index 78f964fda1..362c65471a 100644 --- a/Plugins/org.blueberry.ui.qt/CMakeLists.txt +++ b/Plugins/org.blueberry.ui.qt/CMakeLists.txt @@ -1,29 +1,30 @@ project(org_blueberry_ui_qt) set(PLUGIN_exported_include_suffixes src src/actions src/application src/commands src/guitk src/handlers src/intro src/model src/presentations src/services src/testing src/tweaklets src/util ) if(MITK_USE_Qt5) set(PLUGIN_package_depends PUBLIC Qt5|Widgets+PrintSupport+Svg ) endif() mitk_create_plugin( EXPORT_DIRECTIVE BERRY_UI_QT EXPORTED_INCLUDE_SUFFIXES ${PLUGIN_exported_include_suffixes} + MODULE_DEPENDS PUBLIC MitkCore PACKAGE_DEPENDS ${PLUGIN_package_depends} ) diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp b/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp index ced8de1866..55db6af9cd 100755 --- a/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp +++ b/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp @@ -1,59 +1,58 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtWorkbenchAdvisor.h" #include "internal/berryQtGlobalEventFilter.h" #include "berryWorkbenchPlugin.h" -#include "berryQtPreferences.h" - -#include -#include -#include #include +#include #include #include #include #include #include #include +#include +#include + namespace berry { void QtWorkbenchAdvisor::Initialize(IWorkbenchConfigurer::Pointer configurer) { WorkbenchAdvisor::Initialize(configurer); - IPreferencesService* prefService = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); - QString styleName = prefs->Get(QtPreferences::QT_STYLE_NAME, ""); - QString fontName = prefs->Get(QtPreferences::QT_FONT_NAME, "Open Sans"); - QString fontSize = prefs->Get(QtPreferences::QT_FONT_SIZE, "9"); + auto* prefService = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* prefs = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); + auto styleName = QString::fromStdString(prefs->Get(QtPreferences::QT_STYLE_NAME, "")); + auto fontName = QString::fromStdString(prefs->Get(QtPreferences::QT_FONT_NAME, "Open Sans")); + auto fontSize = QString::fromStdString(prefs->Get(QtPreferences::QT_FONT_SIZE, "9")); ctkServiceReference serviceRef = WorkbenchPlugin::GetDefault()->GetPluginContext()->getServiceReference(); if (serviceRef) { IQtStyleManager* styleManager = WorkbenchPlugin::GetDefault()->GetPluginContext()->getService(serviceRef); styleManager->SetStyle(styleName); styleManager->SetFont(fontName); styleManager->SetFontSize(fontSize.toInt()); styleManager->UpdateWorkbenchFont(); } QObject* eventFilter = new QtGlobalEventFilter(qApp); qApp->installEventFilter(eventFilter); } } diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp index fdd32b5938..4899d5b439 100644 --- a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp @@ -1,140 +1,141 @@ /*============================================================================ 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 "berryWorkbenchWindowAdvisor.h" #include #include #include #include #include -#include -#include #include "internal/berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchPlugin.h" +#include +#include + namespace berry { IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer() { return windowConfigurer; } WorkbenchWindowAdvisor::WorkbenchWindowAdvisor( const IWorkbenchWindowConfigurer::Pointer& configurer) { poco_assert(configurer.IsNotNull()); this->windowConfigurer = configurer; } WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor() { } void WorkbenchWindowAdvisor::PreWindowOpen() { // do nothing } ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor( IActionBarConfigurer::Pointer configurer) { ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer)); return actionBarAdvisor; } void WorkbenchWindowAdvisor::PostWindowRestore() { // do nothing } void WorkbenchWindowAdvisor::OpenIntro() { // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call // introOpened flag needs to be global IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer(); QString key = "introOpened"; //$NON-NLS-1$ ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast(); if (introOpened && introOpened->GetValue()) { return; } wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true))); - IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); + auto* workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true); IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager(); bool hasIntro = introManager->HasIntro(); bool isNewIntroContentAvailable = introManager->IsNewContentAvailable(); if (hasIntro && (showIntro || isNewIntroContentAvailable)) { introManager ->ShowIntro(GetWindowConfigurer()->GetWindow(), false); workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } } void WorkbenchWindowAdvisor::PostWindowCreate() { // do nothing } void WorkbenchWindowAdvisor::PostWindowOpen() { // do nothing } bool WorkbenchWindowAdvisor::PreWindowShellClose() { // do nothing, but allow the close() to proceed return true; } void WorkbenchWindowAdvisor::PostWindowClose() { // do nothing } void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell) { this->GetWindowConfigurer().Cast()->CreateDefaultContents(shell); } QWidget* WorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* /*parent*/) { return nullptr; } bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer /*memento*/) { // do nothing return true; } bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer /*memento*/) { // do nothing return true; } } diff --git a/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp b/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp index c9723dd2e1..cb95a0b968 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp @@ -1,284 +1,276 @@ /*============================================================================ 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 "berryAbstractUICTKPlugin.h" #include "internal/berryBundleUtility.h" #include "berryWorkbenchPlugin.h" #include "berryQtStyleManager.h" #include "berryPlatformUI.h" -#include "berryIPreferencesService.h" -#include "berryIPreferences.h" #include #include #include #include +#include +#include +#include + +#include + +US_INITIALIZE_MODULE + namespace berry { const QString AbstractUICTKPlugin::FN_DIALOG_SETTINGS = "dialog_settings.xml"; AbstractUICTKPlugin::AbstractUICTKPlugin() - : preferencesService(nullptr) { } // IDialogSettings getDialogSettings() { // if (dialogSettings == null) { // loadDialogSettings(); // } // return dialogSettings; // } // ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = createImageRegistry(); // initializeImageRegistry(imageRegistry); // } // return imageRegistry; // } -IPreferencesService* AbstractUICTKPlugin::GetPreferencesService() const +mitk::IPreferencesService* AbstractUICTKPlugin::GetPreferencesService() const { - // Create the preference store lazily. - if (preferencesService == nullptr) - { - ctkServiceReference serviceRef = m_Context->getServiceReference(); - if (!serviceRef) - { - BERRY_ERROR << "Preferences service not available"; - } - preferencesService = m_Context->getService(serviceRef); - } - return preferencesService; + return mitk::CoreServices::GetPreferencesService(); } -SmartPointer AbstractUICTKPlugin::GetPreferences() const +mitk::IPreferences* AbstractUICTKPlugin::GetPreferences() const { - IPreferencesService* prefService = this->GetPreferencesService(); - if (prefService == nullptr) return IPreferences::Pointer(nullptr); - - return prefService->GetSystemPreferences(); + return this->GetPreferencesService()->GetSystemPreferences(); } IWorkbench* AbstractUICTKPlugin::GetWorkbench() { return PlatformUI::GetWorkbench(); } // ImageRegistry createImageRegistry() // { // // //If we are in the UI Thread use that // if (Display.getCurrent() != null) // { // return new ImageRegistry(Display.getCurrent()); // } // // if (PlatformUI.isWorkbenchRunning()) // { // return new ImageRegistry(PlatformUI.getWorkbench().getDisplay()); // } // // //Invalid thread access if it is not the UI Thread // //and the workbench is not created. // throw new SWTError(SWT.ERROR_THREAD_INVALID_ACCESS); // } // void initializeImageRegistry(ImageRegistry reg) { // // spec'ed to do nothing // } // void loadDialogSettings() { // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // // // bug 69387: The instance area should not be created (in the call to // // #getStateLocation) if -data @none or -data @noDefault was used // IPath dataLocation = getStateLocationOrNull(); // if (dataLocation != null) { // // try r/w state area in the local file system // String readWritePath = dataLocation.append(FN_DIALOG_SETTINGS) // .toOSString(); // File settingsFile = new File(readWritePath); // if (settingsFile.exists()) { // try { // dialogSettings.load(readWritePath); // } catch (IOException e) { // // load failed so ensure we have an empty settings // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // } // // return; // } // } // // // otherwise look for bundle specific dialog settings // URL dsURL = BundleUtility.find(getBundle(), FN_DIALOG_SETTINGS); // if (dsURL == null) { // return; // } // // InputStream is = null; // try { // is = dsURL.openStream(); // BufferedReader reader = new BufferedReader( // new InputStreamReader(is, "utf-8")); //$NON-NLS-1$ // dialogSettings.load(reader); // } catch (IOException e) { // // load failed so ensure we have an empty settings // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // } finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // // do nothing // } // } // } // void refreshPluginActions() { // // If the workbench is not started yet, or is no longer running, do nothing. // if (!PlatformUI.isWorkbenchRunning()) { // return; // } // // // startup() is not guaranteed to be called in the UI thread, // // but refreshPluginActions must run in the UI thread, // // so use asyncExec. See bug 6623 for more details. // Display.getDefault().asyncExec(new Runnable() { // public void run() { // WWinPluginAction.refreshActionList(); // } // }); // } // void saveDialogSettings() { // if (dialogSettings == null) { // return; // } // // try { // IPath path = getStateLocationOrNull(); // if(path == null) { // return; // } // String readWritePath = path // .append(FN_DIALOG_SETTINGS).toOSString(); // dialogSettings.save(readWritePath); // } catch (IOException e) { // // spec'ed to ignore problems // } catch (IllegalStateException e) { // // spec'ed to ignore problems // } // } void AbstractUICTKPlugin::start(ctkPluginContext* context) { Plugin::start(context); // Should only attempt refreshPluginActions() once the bundle // has been fully started. Otherwise, action delegates // can be created while in the process of creating // a triggering action delegate (if UI events are processed during startup). // Also, if the start throws an exception, the bundle will be shut down. // We don't want to have created any delegates if this happens. // See bug 63324 for more details. // bundleListener = new BundleListener() // { // public void bundleChanged(BundleEvent event) // { // if (event.getBundle() == getBundle()) // { // if (event.getType() == BundleEvent.STARTED) // { // // We're getting notified that the bundle has been started. // // Make sure it's still active. It may have been shut down between // // the time this event was queued and now. // if (getBundle().getState() == Bundle.ACTIVE) // { // refreshPluginActions(); // } // fc.removeBundleListener(this); // } // } // } // }; // context.addBundleListener(bundleListener); // bundleListener is removed in stop(BundleContext) } void AbstractUICTKPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) // try // { // if (bundleListener != null) // { // context.removeBundleListener(bundleListener); // } // saveDialogSettings(); // savePreferenceStore(); // preferenceStore = null; // if (imageRegistry != null) // imageRegistry.dispose(); // imageRegistry = null; //} Plugin::stop(context); } QIcon AbstractUICTKPlugin::ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath) { if (pluginId.isEmpty() || imageFilePath.isEmpty()) { throw ctkInvalidArgumentException("argument cannot be empty"); } // if the plug-in is not ready then there is no image QSharedPointer plugin = BundleUtility::FindPlugin(pluginId); if (!BundleUtility::IsReady(plugin.data())) { return QIcon(); } QByteArray imgContent = plugin->getResource(imageFilePath); if (imageFilePath.endsWith(".svg", Qt::CaseInsensitive)) return QtStyleManager::ThemeIcon(imgContent); QImage image = QImage::fromData(imgContent); QPixmap pixmap = QPixmap::fromImage(image); return QIcon(pixmap); } QIcon AbstractUICTKPlugin::GetMissingIcon() { return QIcon(":/org.blueberry.ui.qt/icon_missing.png"); } } diff --git a/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h b/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h index 1c2582ff86..f6bcab8dad 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h +++ b/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h @@ -1,194 +1,166 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYABSTRACTUICTKPLUGIN_H_ #define BERRYABSTRACTUICTKPLUGIN_H_ #include #include +namespace mitk +{ + class IPreferencesService; + class IPreferences; +} + namespace berry { template class SmartPointer; -struct IPreferences; -struct IPreferencesService; struct IWorkbench; /** * \ingroup org_blueberry_ui_qt * * Abstract base class for plug-ins that integrate with the BlueBerry platform UI. *

* Subclasses obtain the following capabilities: *

*

- * Preferences - *

    - *
  • The platform core runtime contains general support for plug-in - * preferences (org.blueberry.core.runtime.Preferences). - * This class provides appropriate conversion to the older JFace preference - * API (org.blueberry.jface.preference.IPreferenceStore).
  • - *
  • The method getPreferenceStore returns the JFace preference - * store (cf. Plugin.getPluginPreferences which returns - * a core runtime preferences object.
  • - *
  • Subclasses may reimplement initializeDefaultPreferences - * to set up any default values for preferences using JFace API. In this - * case, initializeDefaultPluginPreferences should not be - * overridden.
  • - *
  • Subclasses may reimplement - * initializeDefaultPluginPreferences to set up any default - * values for preferences using core runtime API. In this - * case, initializeDefaultPreferences should not be - * overridden.
  • - *
  • Preferences are also saved automatically on plug-in shutdown. - * However, saving preferences immediately after changing them is - * strongly recommended, since that ensures that preference settings - * are not lost even in the event of a platform crash.
  • - *
* Dialogs *
    *
  • The dialog store is read the first time getDialogSettings * is called.
  • *
  • The dialog store allows the plug-in to "record" important choices made * by the user in a wizard or dialog, so that the next time the * wizard/dialog is used the widgets can be defaulted to better values. A * wizard could also use it to record the last 5 values a user entered into * an editable combo - to show "recent values".
  • *
  • The dialog store is found in the file whose name is given by the * constant FN_DIALOG_STORE. A dialog store file is first * looked for in the plug-in's read/write state area; if not found there, * the plug-in's install directory is checked. * This allows a plug-in to ship with a read-only copy of a dialog store * file containing initial values for certain settings.
  • *
  • Plug-in code can call saveDialogSettings to cause settings to * be saved in the plug-in's read/write state area. A plug-in may opt to do * this each time a wizard or dialog is closed to ensure the latest * information is always safe on disk.
  • *
  • Dialog settings are also saved automatically on plug-in shutdown.
  • *
*

* For easy access to your plug-in object, use the singleton pattern. Declare a * static variable in your plug-in class for the singleton. Store the first * (and only) instance of the plug-in class in the singleton when it is created. * Then access the singleton when needed through a static getDefault * method. *

*

* See the description on {@link Plugin}. *

*/ class BERRY_UI_QT AbstractUICTKPlugin : public Plugin { Q_OBJECT private: /** * The name of the dialog settings file (value * "dialog_settings.xml"). */ static const QString FN_DIALOG_SETTINGS; - /** - * Storage for preferences. - */ - mutable IPreferencesService* preferencesService; - public: /** * Creates an abstract UI plug-in runtime object. *

* Plug-in runtime classes are ctkPluginActivators and so must * have an default constructor. This method is called by the runtime when * the associated bundle is being activated. */ AbstractUICTKPlugin(); /** * Returns the preferences service for this UI plug-in. * This preferences service is used to hold persistent settings for this plug-in in * the context of a workbench. Some of these settings will be user controlled, * whereas others may be internal setting that are never exposed to the user. - *

- * If an error occurs reading the preferences service, an empty preference service is - * quietly created, initialized with defaults, and returned. - *

* * @return the preferences service */ - IPreferencesService* GetPreferencesService() const; + mitk::IPreferencesService* GetPreferencesService() const; - SmartPointer GetPreferences() const; + mitk::IPreferences* GetPreferences() const; /** * Returns the Platform UI workbench. *

* This method exists as a convenience for plugin implementors. The * workbench can also be accessed by invoking PlatformUI.getWorkbench(). *

* @return IWorkbench the workbench for this plug-in */ IWorkbench* GetWorkbench(); public: /** * The AbstractUIPlugin implementation of this Plugin * method refreshes the plug-in actions. Subclasses may extend this method, * but must send super first. * * \param context */ void start(ctkPluginContext* context) override; /** * The AbstractUIPlugin implementation of this Plugin * method saves this plug-in's preference and dialog stores and shuts down * its image registry (if they are in use). Subclasses may extend this * method, but must send super last. A try-finally statement should * be used where necessary to ensure that super.shutdown() is * always done. */ void stop(ctkPluginContext* context) override; /** * Creates and returns a new image descriptor for an image file located * within the specified plug-in. *

* This is a convenience method that simply locates the image file in * within the plug-in (no image registries are involved). The path is * relative to the root of the plug-in, and takes into account files * coming from plug-in fragments. The path may include $arg$ elements. * However, the path must not have a leading "." or path separator. * Clients should use a path like "icons/mysample.gif" rather than * "./icons/mysample.gif" or "/icons/mysample.gif". *

* * @param pluginId the id of the plug-in containing the image file; * null is returned if the plug-in does not exist * @param imageFilePath the relative path of the image file, relative to the * root of the plug-in; the path must be legal * @return an image descriptor, or null if no image * could be found */ static QIcon ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath); static QIcon GetMissingIcon(); }; } // namespace berry #endif /*BERRYABSTRACTUICTKPLUGIN_H_*/ diff --git a/Plugins/org.blueberry.ui.qt/src/berryIPreferencePage.h b/Plugins/org.blueberry.ui.qt/src/berryIPreferencePage.h index 50457de92a..9705df4679 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryIPreferencePage.h +++ b/Plugins/org.blueberry.ui.qt/src/berryIPreferencePage.h @@ -1,105 +1,104 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYIPREFERENCEPAGE_H_ #define BERRYIPREFERENCEPAGE_H_ #include "berryObject.h" -#include "berryIPreferences.h" #include "berryIWorkbench.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface for workbench preference pages. *

* Clients should implement this interface and include the name of their class * in an extension contributed to the workbench's preference extension point * (named "org.blueberry.ui.preferencePages"). * For example, the plug-in's XML markup might contain: * \code{.unparsed} * * * \endcode *

*/ struct BERRY_UI_QT IPreferencePage: virtual public Object { berryObjectMacro(berry::IPreferencePage); ~IPreferencePage() override; /** * Initializes this preference page for the given workbench. *

* This method is called automatically as the preference page is being created * and initialized. Clients must not call this method. *

* * @param workbench the workbench */ virtual void Init(IWorkbench::Pointer workbench) = 0; /** * Creates the top level control for this preference * page under the given parent widget. *

* Implementors are responsible for ensuring that * the created control can be accessed via GetControl *

* * @param parent the parent widget */ virtual void CreateControl(void* parent) = 0; /** * Returns the top level control for this dialog page. *

* May return null if the control * has not been created yet. *

* * @return the top level control or null */ virtual void* GetControl() const = 0; /// /// Invoked when the OK button was clicked in the preferences dialog /// virtual bool PerformOk() = 0; /// /// Invoked when the Cancel button was clicked in the preferences dialog /// virtual void PerformCancel() = 0; /// /// Invoked when the user performed an import. As the values of the preferences may have changed /// you should read all values again from the preferences service. /// virtual void Update() = 0; }; } Q_DECLARE_INTERFACE(berry::IPreferencePage, "org.blueberry.ui.IPreferencePage") #endif /*BERRYIPREFERENCEPAGE_H_*/ diff --git a/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.cpp b/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.cpp index 093ad7ce9c..0f449b505c 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.cpp @@ -1,75 +1,74 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryPlatformUI.h" -#include "berryPlatform.h" #include "berryIConfigurationElement.h" #include "internal/berryWorkbench.h" #include "berryUIException.h" #include namespace berry { QString PlatformUI::PLUGIN_ID() { static QString str = "org.blueberry.ui"; return str; } const QString PlatformUI::XP_WORKBENCH = PlatformUI::PLUGIN_ID() + ".workbench"; const QString PlatformUI::XP_VIEWS = PlatformUI::PLUGIN_ID() + ".views"; const int PlatformUI::RETURN_OK = 0; const int PlatformUI::RETURN_RESTART = 1; const int PlatformUI::RETURN_UNSTARTABLE = 2; const int PlatformUI::RETURN_EMERGENCY_CLOSE = 3; int PlatformUI::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { return Workbench::CreateAndRunWorkbench(display, advisor); } Display* PlatformUI::CreateDisplay() { return Workbench::CreateDisplay(); } IWorkbench* PlatformUI::GetWorkbench() { if (Workbench::GetInstance() == nullptr) { // app forgot to call createAndRunWorkbench beforehand throw Poco::IllegalStateException("Workbench has not been created yet."); } return Workbench::GetInstance(); } bool PlatformUI::IsWorkbenchRunning() { return Workbench::GetInstance() != nullptr && Workbench::GetInstance()->IsRunning(); } TestableObject::Pointer PlatformUI::GetTestableObject() { return Workbench::GetWorkbenchTestable(); } PlatformUI::PlatformUI() { } } diff --git a/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.cpp b/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.cpp index 4ac42c04d5..36859849c2 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.cpp @@ -1,25 +1,23 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtPreferences.h" -#include - namespace berry { -const QString QtPreferences::QT_STYLES_NODE = "qtstyles"; -const QString QtPreferences::QT_STYLE_NAME = "stylename"; -const QString QtPreferences::QT_STYLE_SEARCHPATHS = "searchpaths"; -const QString QtPreferences::QT_FONT_NAME = "fontname"; -const QString QtPreferences::QT_FONT_SIZE = "fontsize"; -const QString QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES = "show_toolbar_category_names"; +const std::string QtPreferences::QT_STYLES_NODE = "qtstyles"; +const std::string QtPreferences::QT_STYLE_NAME = "stylename"; +const std::string QtPreferences::QT_STYLE_SEARCHPATHS = "searchpaths"; +const std::string QtPreferences::QT_FONT_NAME = "fontname"; +const std::string QtPreferences::QT_FONT_SIZE = "fontsize"; +const std::string QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES = "show_toolbar_category_names"; } diff --git a/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.h b/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.h index 853490e646..268c85a904 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.h +++ b/Plugins/org.blueberry.ui.qt/src/berryQtPreferences.h @@ -1,34 +1,34 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYQTPREFERENCES_H_ #define BERRYQTPREFERENCES_H_ #include #include namespace berry { struct BERRY_UI_QT QtPreferences { - static const QString QT_STYLES_NODE; // = "qtstyles"; - static const QString QT_STYLE_NAME; // = "stylename"; - static const QString QT_STYLE_SEARCHPATHS; // = "searchpaths"; - static const QString QT_FONT_NAME; // = "fontname"; - static const QString QT_FONT_SIZE; // = "fontsize"; - static const QString QT_SHOW_TOOLBAR_CATEGORY_NAMES; // = "show_toolbar_category_names"; + static const std::string QT_STYLES_NODE; // = "qtstyles"; + static const std::string QT_STYLE_NAME; // = "stylename"; + static const std::string QT_STYLE_SEARCHPATHS; // = "searchpaths"; + static const std::string QT_FONT_NAME; // = "fontname"; + static const std::string QT_FONT_SIZE; // = "fontsize"; + static const std::string QT_SHOW_TOOLBAR_CATEGORY_NAMES; // = "show_toolbar_category_names"; }; } #endif /* BERRYQTPREFERENCES_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp b/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp index 70a70532ab..3b508115c7 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp @@ -1,405 +1,403 @@ /*============================================================================ 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 "berryQtStyleManager.h" #include #include #include #include #include #include #include #include #include #include #include -#include #include -#include -#include +#include -#include "berryQtPreferences.h" #include "berryWorkbenchPlugin.h" +#include + namespace berry { static QString ParseColor(const QString &subject, const QString &pattern, const QString &fallback) { QRegularExpression re(pattern, QRegularExpression::CaseInsensitiveOption); auto match = re.match(subject); return match.hasMatch() ? match.captured(1) : fallback; } QIcon QtStyleManager::ThemeIcon(const QByteArray &originalSVG) { auto styleSheet = qApp->styleSheet(); if (styleSheet.isEmpty()) return QPixmap::fromImage(QImage::fromData(originalSVG)); auto iconColor = ParseColor(styleSheet, QStringLiteral("iconColor\\s*[=:]\\s*(#[0-9a-f]{6})"), QStringLiteral("#000000")); auto iconAccentColor = ParseColor(styleSheet, QStringLiteral("iconAccentColor\\s*[=:]\\s*(#[0-9a-f]{6})"), QStringLiteral("#ffffff")); auto themedSVG = QString(originalSVG).replace(QStringLiteral("#00ff00"), iconColor, Qt::CaseInsensitive); themedSVG = themedSVG.replace(QStringLiteral("#ff00ff"), iconAccentColor, Qt::CaseInsensitive); return QPixmap::fromImage(QImage::fromData(themedSVG.toLatin1())); } QIcon QtStyleManager::ThemeIcon(const QString &resourcePath) { QFile resourceFile(resourcePath); if (resourceFile.open(QIODevice::ReadOnly)) { auto originalSVG = resourceFile.readAll(); return ThemeIcon(originalSVG); } BERRY_WARN << "Could not read " << resourcePath; return QIcon(); } QtStyleManager::QtStyleManager() { AddDefaultStyle(); AddDefaultFonts(); ReadPreferences(); } void QtStyleManager::ReadPreferences() { - IPreferencesService* prefService = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); + auto* stylePref = WorkbenchPlugin::GetDefault()->GetPreferences()->Node(QtPreferences::QT_STYLES_NODE); - QString paths = stylePref->Get(QtPreferences::QT_STYLE_SEARCHPATHS, ""); + QString paths = QString::fromStdString(stylePref->Get(QtPreferences::QT_STYLE_SEARCHPATHS, "")); QStringList pathList = paths.split(";", QString::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddStyles(it.next()); } - QString styleName = stylePref->Get(QtPreferences::QT_STYLE_NAME, ""); + QString styleName = QString::fromStdString(stylePref->Get(QtPreferences::QT_STYLE_NAME, "")); // if a style is contributed via the Qt resource mechanism, it may not be // registered yet. if (Contains(styleName)) // do not update the style in the QApplication instance, // since it might not be created yet SetStyle(styleName, false); else SetDefaultStyle(false); } QtStyleManager::~QtStyleManager() { for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i) { delete i.value(); } } void QtStyleManager::AddDefaultStyle() { #ifndef _APPLE_ AddStyle(":/org.blueberry.ui.qt/darkstyle.qss", "Dark"); AddStyle(":/org.blueberry.ui.qt/lightstyle.qss", "Light"); defaultStyle = styles[":/org.blueberry.ui.qt/darkstyle.qss"]; #endif } void QtStyleManager::AddDefaultFonts() { m_customFontNames.append(QString("<>")); m_customFontNames.append(QString("Fira Sans")); QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/FiraSans/FiraSans.ttf"); m_customFontNames.append(QString("Light Fira Sans")); QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/LightFiraSans/LightFiraSans.ttf"); m_customFontNames.append(QString("Roboto")); QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/Roboto/Roboto.ttf"); m_customFontNames.push_back(QString("Open Sans")); QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/OpenSans/OpenSans-Regular.ttf"); m_customFontNames.push_back(QString("xkcd")); QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/xkcd/xkcd.ttf"); } void QtStyleManager::ClearStyles() { for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end(); ) { if (!i.value()->fileName.startsWith(':')) { delete i.value(); i = styles.erase(i); } else ++i; } SetDefaultStyle(); } QtStyleManager::Style QtStyleManager::GetStyle() const { return Style(currentStyle->name, currentStyle->fileName); } QString QtStyleManager::GetStylesheet() const { return currentStyle->stylesheet; } QString QtStyleManager::GetActiveTabStylesheet() const { return currentStyle->activeTabStylesheet; } QString QtStyleManager::GetTabStylesheet() const { return currentStyle->tabStylesheet; } void QtStyleManager::AddStyle(const QString& styleFileName, const QString& styleName) { auto newStyle = new ExtStyle(); if (styleName.isEmpty()) { QFileInfo info(styleFileName); newStyle->name = info.completeBaseName(); } else { newStyle->name = styleName; } newStyle->fileName = styleFileName; styles.insert(newStyle->fileName, newStyle); } void QtStyleManager::GetFonts(QStringList& fontNames) const { fontNames = m_customFontNames; } QString QtStyleManager::GetFont() const { return m_currentFont; } void QtStyleManager::AddStyles(const QString& path) { QDirIterator dirIt(path); while (dirIt.hasNext()) { QString current = dirIt.next(); QFileInfo info = dirIt.fileInfo(); if (info.isFile() && info.isReadable()) { QString fileName = info.fileName(); if (fileName.endsWith("-tab.qss") || fileName.endsWith("-activetab.qss")) continue; if (fileName.endsWith(".qss")) AddStyle(current); } } } void QtStyleManager::ReadStyleData(ExtStyle* style) { QString tabStyleFileName(style->fileName); QString activeTabStyleFileName(style->fileName); int index = style->fileName.lastIndexOf(".qss"); tabStyleFileName.replace(index, 4, "-tab.qss"); activeTabStyleFileName.replace(index, 4, "-activetab.qss"); QFile styleFile(style->fileName); if (styleFile.open(QIODevice::ReadOnly)) { QTextStream in(&styleFile); style->stylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << style->fileName.toStdString(); } QFile tabStyleFile(tabStyleFileName); if (tabStyleFile.open(QIODevice::ReadOnly)) { QTextStream in(&tabStyleFile); style->tabStylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << tabStyleFileName.toStdString(); } QFile activeTabStyleFile(activeTabStyleFileName); if (activeTabStyleFile.open(QIODevice::ReadOnly)) { QTextStream in(&activeTabStyleFile); style->activeTabStylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << activeTabStyleFileName.toStdString(); } } void QtStyleManager::RemoveStyle(const QString& styleFileName) { if (currentStyle->fileName == styleFileName) { SetDefaultStyle(); } delete styles.take(styleFileName); } void QtStyleManager::RemoveStyles(const QString& repo) { if (repo.isEmpty()) { ClearStyles(); return; } for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end();) { ExtStyle* style = i.value(); QFileInfo info(style->fileName); if (info.absolutePath() == repo) { if (style->name == currentStyle->name) { SetDefaultStyle(); } i = styles.erase(i); delete style; } else { ++i; } } } void QtStyleManager::GetStyles(StyleList& styleNames) const { for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i) styleNames.push_back(Style(i.value()->name, i.value()->fileName)); } void QtStyleManager::SetStyle(const QString& fileName) { SetStyle(fileName, true); } void QtStyleManager::SetStyle(const QString& fileName, bool update) { if (fileName.isEmpty()) { SetDefaultStyle(); return; } FileNameToStyleMap::const_iterator i = styles.find(fileName); ExtStyle* style = nullptr; if (i == styles.end()) { BERRY_WARN << "Style " + fileName.toStdString() << " does not exist"; style = defaultStyle; } else { style = i.value(); } currentStyle = style; ReadStyleData(style); if (update) { qApp->setStyleSheet(currentStyle->stylesheet); PlatformUI::GetWorkbench()->UpdateTheme(); } } void QtStyleManager::SetFont(const QString& fontName) { m_currentFont = fontName; } void QtStyleManager::SetFontSize(const int fontSize) { m_currentFontSize = fontSize; } void QtStyleManager::UpdateWorkbenchFont() { if( m_currentFont == QString( "<>" ) || m_currentFont == QString( "" )) { qApp->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont)); } else { QFont font; font.setFamily(m_currentFont); font.setPointSize(m_currentFontSize); qApp->setFont(font); } qApp->setStyleSheet(currentStyle->stylesheet); PlatformUI::GetWorkbench()->UpdateTheme(); } QtStyleManager::Style QtStyleManager::GetDefaultStyle() const { return Style(defaultStyle->name, defaultStyle->fileName); } void QtStyleManager::SetDefaultStyle() { SetDefaultStyle(true); } void QtStyleManager::SetDefaultStyle(bool update) { SetStyle(defaultStyle->fileName, update); } bool QtStyleManager::Contains(const QString& fileName) const { return styles.contains(fileName); } } diff --git a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.cpp b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.cpp index 54942f9169..d3d52e9cb1 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.cpp @@ -1,113 +1,111 @@ /*============================================================================ 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 "berryWorkbenchPreferenceConstants.h" -#include - namespace berry { -const QString WorkbenchPreferenceConstants::LINK_NAVIGATOR_TO_EDITOR = +const std::string WorkbenchPreferenceConstants::LINK_NAVIGATOR_TO_EDITOR = "LINK_NAVIGATOR_TO_EDITOR"; -const QString WorkbenchPreferenceConstants::OPEN_NEW_PERSPECTIVE = +const std::string WorkbenchPreferenceConstants::OPEN_NEW_PERSPECTIVE = "OPEN_NEW_PERSPECTIVE"; -const QString WorkbenchPreferenceConstants::OPEN_PERSPECTIVE_WINDOW = +const std::string WorkbenchPreferenceConstants::OPEN_PERSPECTIVE_WINDOW = "OPEN_PERSPECTIVE_WINDOW"; -const QString WorkbenchPreferenceConstants::OPEN_PERSPECTIVE_PAGE = +const std::string WorkbenchPreferenceConstants::OPEN_PERSPECTIVE_PAGE = "OPEN_PERSPECTIVE_PAGE"; -const QString WorkbenchPreferenceConstants::OPEN_PERSPECTIVE_REPLACE = +const std::string WorkbenchPreferenceConstants::OPEN_PERSPECTIVE_REPLACE = "OPEN_PERSPECTIVE_REPLACE"; -const QString WorkbenchPreferenceConstants::NO_NEW_PERSPECTIVE = +const std::string WorkbenchPreferenceConstants::NO_NEW_PERSPECTIVE = "NO_NEW_PERSPECTIVE"; -const QString WorkbenchPreferenceConstants::DEFAULT_PERSPECTIVE_ID = +const std::string WorkbenchPreferenceConstants::DEFAULT_PERSPECTIVE_ID = "defaultPerspectiveId"; -const QString WorkbenchPreferenceConstants::PRESENTATION_FACTORY_ID = +const std::string WorkbenchPreferenceConstants::PRESENTATION_FACTORY_ID = "presentationFactoryId"; -const QString WorkbenchPreferenceConstants::DOCK_PERSPECTIVE_BAR = +const std::string WorkbenchPreferenceConstants::DOCK_PERSPECTIVE_BAR = "DOCK_PERSPECTIVE_BAR"; -const QString WorkbenchPreferenceConstants::PERSPECTIVE_BAR_SIZE = +const std::string WorkbenchPreferenceConstants::PERSPECTIVE_BAR_SIZE = "PERSPECTIVE_BAR_SIZE"; -const QString WorkbenchPreferenceConstants::INITIAL_FAST_VIEW_BAR_LOCATION = +const std::string WorkbenchPreferenceConstants::INITIAL_FAST_VIEW_BAR_LOCATION = "initialFastViewBarLocation"; -const QString WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT = +const std::string WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT = "preferredSashLayout"; -const QString WorkbenchPreferenceConstants::TOP_RIGHT = "topRight"; -const QString WorkbenchPreferenceConstants::TOP_LEFT = "topLeft"; -const QString WorkbenchPreferenceConstants::LEFT = "left"; -const QString WorkbenchPreferenceConstants::BOTTOM = "bottom"; -const QString WorkbenchPreferenceConstants::RIGHT = "right"; -const QString WorkbenchPreferenceConstants::SHOW_INTRO = "showIntro"; -const QString WorkbenchPreferenceConstants::SHOW_TRADITIONAL_STYLE_TABS = +const std::string WorkbenchPreferenceConstants::TOP_RIGHT = "topRight"; +const std::string WorkbenchPreferenceConstants::TOP_LEFT = "topLeft"; +const std::string WorkbenchPreferenceConstants::LEFT = "left"; +const std::string WorkbenchPreferenceConstants::BOTTOM = "bottom"; +const std::string WorkbenchPreferenceConstants::RIGHT = "right"; +const std::string WorkbenchPreferenceConstants::SHOW_INTRO = "showIntro"; +const std::string WorkbenchPreferenceConstants::SHOW_TRADITIONAL_STYLE_TABS = "SHOW_TRADITIONAL_STYLE_TABS"; -const QString WorkbenchPreferenceConstants::SHOW_TEXT_ON_PERSPECTIVE_BAR = +const std::string WorkbenchPreferenceConstants::SHOW_TEXT_ON_PERSPECTIVE_BAR = "SHOW_TEXT_ON_PERSPECTIVE_BAR"; -const QString WorkbenchPreferenceConstants::SHOW_OPEN_ON_PERSPECTIVE_BAR = +const std::string WorkbenchPreferenceConstants::SHOW_OPEN_ON_PERSPECTIVE_BAR = "SHOW_OPEN_ON_PERSPECTIVE_BAR"; -const QString WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU = +const std::string WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU = "SHOW_OTHER_IN_PERSPECTIVE_MENU"; -const QString WorkbenchPreferenceConstants::HELP_CONTENTS_ACTION_TEXT = +const std::string WorkbenchPreferenceConstants::HELP_CONTENTS_ACTION_TEXT = "helpContentsActionText"; -const QString WorkbenchPreferenceConstants::HELP_SEARCH_ACTION_TEXT = +const std::string WorkbenchPreferenceConstants::HELP_SEARCH_ACTION_TEXT = "helpSearchActionText"; -const QString WorkbenchPreferenceConstants::DYNAMIC_HELP_ACTION_TEXT = +const std::string WorkbenchPreferenceConstants::DYNAMIC_HELP_ACTION_TEXT = "dynamicHelpActionText"; -const QString WorkbenchPreferenceConstants::ENABLE_ANIMATIONS = +const std::string WorkbenchPreferenceConstants::ENABLE_ANIMATIONS = "ENABLE_ANIMATIONS"; -const QString WorkbenchPreferenceConstants::USE_COLORED_LABELS = +const std::string WorkbenchPreferenceConstants::USE_COLORED_LABELS = "USE_COLORED_LABELS"; -const QString WorkbenchPreferenceConstants::KEY_CONFIGURATION_ID = +const std::string WorkbenchPreferenceConstants::KEY_CONFIGURATION_ID = "KEY_CONFIGURATION_ID"; -const QString WorkbenchPreferenceConstants::EDITOR_MINIMUM_CHARACTERS = +const std::string WorkbenchPreferenceConstants::EDITOR_MINIMUM_CHARACTERS = "EDITOR_MINIMUM_CHARACTERS"; -const QString WorkbenchPreferenceConstants::VIEW_MINIMUM_CHARACTERS = +const std::string WorkbenchPreferenceConstants::VIEW_MINIMUM_CHARACTERS = "VIEW_MINIMUM_CHARACTERS"; -const QString WorkbenchPreferenceConstants::SHOW_SYSTEM_JOBS = +const std::string WorkbenchPreferenceConstants::SHOW_SYSTEM_JOBS = "SHOW_SYSTEM_JOBS"; -const QString WorkbenchPreferenceConstants::CURRENT_THEME_ID = +const std::string WorkbenchPreferenceConstants::CURRENT_THEME_ID = "CURRENT_THEME_ID"; -const QString WorkbenchPreferenceConstants::CLOSE_EDITORS_ON_EXIT = +const std::string WorkbenchPreferenceConstants::CLOSE_EDITORS_ON_EXIT = "CLOSE_EDITORS_ON_EXIT"; -const QString WorkbenchPreferenceConstants::SHOW_PROGRESS_ON_STARTUP = +const std::string WorkbenchPreferenceConstants::SHOW_PROGRESS_ON_STARTUP = "SHOW_PROGRESS_ON_STARTUP"; -const QString WorkbenchPreferenceConstants::SHOW_MEMORY_MONITOR = +const std::string WorkbenchPreferenceConstants::SHOW_MEMORY_MONITOR = "SHOW_MEMORY_MONITOR"; -const QString +const std::string WorkbenchPreferenceConstants::USE_WINDOW_WORKING_SET_BY_DEFAULT = "USE_WINDOW_WORKING_SET_BY_DEFAULT"; -const QString WorkbenchPreferenceConstants::SHOW_FILTERED_TEXTS = +const std::string WorkbenchPreferenceConstants::SHOW_FILTERED_TEXTS = "SHOW_FILTERED_TEXTS"; -const QString WorkbenchPreferenceConstants::ENABLE_DETACHED_VIEWS = +const std::string WorkbenchPreferenceConstants::ENABLE_DETACHED_VIEWS = "ENABLE_DETACHED_VIEWS"; -const QString +const std::string WorkbenchPreferenceConstants::PROMPT_WHEN_SAVEABLE_STILL_OPEN = "PROMPT_WHEN_SAVEABLE_STILL_OPEN"; -const QString WorkbenchPreferenceConstants::PERSPECTIVE_BAR_EXTRAS = +const std::string WorkbenchPreferenceConstants::PERSPECTIVE_BAR_EXTRAS = "PERSPECTIVE_BAR_EXTRAS"; -const QString WorkbenchPreferenceConstants::LOCK_TRIM = "LOCK_TRIM"; -const QString WorkbenchPreferenceConstants::ENABLE_NEW_MIN_MAX = +const std::string WorkbenchPreferenceConstants::LOCK_TRIM = "LOCK_TRIM"; +const std::string WorkbenchPreferenceConstants::ENABLE_NEW_MIN_MAX = "ENABLE_MIN_MAX"; -const QString WorkbenchPreferenceConstants::DISABLE_NEW_FAST_VIEW = +const std::string WorkbenchPreferenceConstants::DISABLE_NEW_FAST_VIEW = "disableNewFastView"; -const QString +const std::string WorkbenchPreferenceConstants::ENABLE_32_STICKY_CLOSE_BEHAVIOR = "ENABLE_32_STICKY_CLOSE_BEHAVIOR"; -const QString WorkbenchPreferenceConstants::VIEW_TAB_POSITION = +const std::string WorkbenchPreferenceConstants::VIEW_TAB_POSITION = "VIEW_TAB_POSITION"; -const QString WorkbenchPreferenceConstants::EDITOR_TAB_POSITION = +const std::string WorkbenchPreferenceConstants::EDITOR_TAB_POSITION = "EDITOR_TAB_POSITION"; -const QString WorkbenchPreferenceConstants::SHOW_MULTIPLE_EDITOR_TABS = +const std::string WorkbenchPreferenceConstants::SHOW_MULTIPLE_EDITOR_TABS = "SHOW_MULTIPLE_EDITOR_TABS"; -const QString WorkbenchPreferenceConstants::DISABLE_OPEN_EDITOR_IN_PLACE = +const std::string WorkbenchPreferenceConstants::DISABLE_OPEN_EDITOR_IN_PLACE = "DISABLE_OPEN_EDITOR_IN_PLACE"; } diff --git a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.h b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.h index 6c2df07203..7d819da288 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.h +++ b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPreferenceConstants.h @@ -1,554 +1,555 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYWORKBENCHPREFERENCECONSTANTS_H_ #define BERRYWORKBENCHPREFERENCECONSTANTS_H_ #include +#include namespace berry { /** * Preference ids exposed by the BlueBerry Platform User Interface. These * preference settings can be obtained from the UI plug-in's preference store. * * @see PlatformUI#PLUGIN_ID * @note This class is not intended to be extended by clients. */ struct BERRY_UI_QT WorkbenchPreferenceConstants { /** * A named preference for whether to show an editor when its input file is * selected in the Navigator (and vice versa). *

* Value is of type boolean. *

*/ - static const QString LINK_NAVIGATOR_TO_EDITOR; // "LINK_NAVIGATOR_TO_EDITOR"; + static const std::string LINK_NAVIGATOR_TO_EDITOR; // "LINK_NAVIGATOR_TO_EDITOR"; /** * A named preference for how a new perspective is opened. *

- * Value is of type QString. The possible values are defined + * Value is of type std::string. The possible values are defined * by OPEN_PERSPECTIVE_WINDOW, OPEN_PERSPECTIVE_PAGE and * OPEN_PERSPECTIVE_REPLACE. *

* * @see #OPEN_PERSPECTIVE_WINDOW * @see #OPEN_PERSPECTIVE_PAGE * @see #OPEN_PERSPECTIVE_REPLACE * @see #NO_NEW_PERSPECTIVE */ - static const QString OPEN_NEW_PERSPECTIVE; // "OPEN_NEW_PERSPECTIVE"; + static const std::string OPEN_NEW_PERSPECTIVE; // "OPEN_NEW_PERSPECTIVE"; /** * A preference value indicating that an action should open a new * perspective in a new window. */ - static const QString OPEN_PERSPECTIVE_WINDOW; // "OPEN_PERSPECTIVE_WINDOW"; + static const std::string OPEN_PERSPECTIVE_WINDOW; // "OPEN_PERSPECTIVE_WINDOW"; /** * A preference value indicating that an action should open a new * perspective in a new page. * @deprecated Opening a Perspective in a new page is no longer supported * functionality as of 2.0. */ - static const QString OPEN_PERSPECTIVE_PAGE; // "OPEN_PERSPECTIVE_PAGE"; + static const std::string OPEN_PERSPECTIVE_PAGE; // "OPEN_PERSPECTIVE_PAGE"; /** * A preference value indicating that an action should open a new * perspective by replacing the current perspective. */ - static const QString OPEN_PERSPECTIVE_REPLACE; // "OPEN_PERSPECTIVE_REPLACE"; + static const std::string OPEN_PERSPECTIVE_REPLACE; // "OPEN_PERSPECTIVE_REPLACE"; /** * A preference value indicating that an action should not open a new * perspective. */ - static const QString NO_NEW_PERSPECTIVE; // "NO_NEW_PERSPECTIVE"; + static const std::string NO_NEW_PERSPECTIVE; // "NO_NEW_PERSPECTIVE"; /** * A named preference indicating the default workbench perspective. */ - static const QString DEFAULT_PERSPECTIVE_ID; // "defaultPerspectiveId"; + static const std::string DEFAULT_PERSPECTIVE_ID; // "defaultPerspectiveId"; /** * A named preference indicating the presentation factory to use for the * workbench look and feel. * * @since 3.0 */ - static const QString PRESENTATION_FACTORY_ID; // "presentationFactoryId"; + static const std::string PRESENTATION_FACTORY_ID; // "presentationFactoryId"; /** * A named preference indicating where the perspective bar should be docked. * The default value (when this preference is not set) is * TOP_RIGHT. *

* This preference may be one of the following values: {@link #TOP_RIGHT}, * {@link #TOP_LEFT}, or {@link #LEFT}. *

* * @since 3.0 */ - static const QString DOCK_PERSPECTIVE_BAR; // "DOCK_PERSPECTIVE_BAR"; + static const std::string DOCK_PERSPECTIVE_BAR; // "DOCK_PERSPECTIVE_BAR"; /** * A preference indication the initial size of the perspective bar. The default value is 160. * This preference only works when configurer.setShowPerspectiveBar(true) is set in * WorkbenchWindowAdvisor#preWindowOpen() * * This preference only uses integer values * bug 84603: [RCP] [PerspectiveBar] New API or pref to set default perspective bar size * * @since 3.5 */ - static const QString PERSPECTIVE_BAR_SIZE; // "PERSPECTIVE_BAR_SIZE"; + static const std::string PERSPECTIVE_BAR_SIZE; // "PERSPECTIVE_BAR_SIZE"; /** * A named preference indicating where the fast view bar should be docked in * a fresh workspace. This preference is meaningless after a workspace has * been setup, since the fast view bar state is then persisted in the * workbench. This preference is intended for applications that want the * initial docking location to be somewhere specific. The default value * (when this preference is not set) is the bottom. * * @see #LEFT * @see #BOTTOM * @see #RIGHT * @since 3.0 */ - static const QString INITIAL_FAST_VIEW_BAR_LOCATION; // "initialFastViewBarLocation"; + static const std::string INITIAL_FAST_VIEW_BAR_LOCATION; // "initialFastViewBarLocation"; /** * A named preference indicating the preferred layout direction of parts * inside a sash container. The default value (when this preference is not set) * is LEFT. *

* This preference may be one of the following values: {@link #LEFT} or {@link #RIGHT}. *

*/ - static const QString PREFERRED_SASH_LAYOUT; // "preferredSashLayout"; + static const std::string PREFERRED_SASH_LAYOUT; // "preferredSashLayout"; /** * Constant to be used when referring to the top right of the workbench * window. * * @see #DOCK_PERSPECTIVE_BAR * @since 3.0 */ - static const QString TOP_RIGHT; // "topRight"; + static const std::string TOP_RIGHT; // "topRight"; /** * Constant to be used when referring to the top left of the workbench * window. * * @see #DOCK_PERSPECTIVE_BAR * @since 3.0 */ - static const QString TOP_LEFT; // "topLeft"; + static const std::string TOP_LEFT; // "topLeft"; /** * Constant to be used when referring to the left side of the workbench * window. * * @see #DOCK_PERSPECTIVE_BAR * @see #INITIAL_FAST_VIEW_BAR_LOCATION * @since 3.0 */ - static const QString LEFT; // "left"; + static const std::string LEFT; // "left"; /** * Constant to be used when referring to the bottom of the workbench window. * * @see #INITIAL_FAST_VIEW_BAR_LOCATION * @since 3.0 */ - static const QString BOTTOM; // "bottom"; + static const std::string BOTTOM; // "bottom"; /** * Constant to be used when referring to the right side of the workbench * window. * * @see #INITIAL_FAST_VIEW_BAR_LOCATION * @since 3.0 */ - static const QString RIGHT; // "right"; + static const std::string RIGHT; // "right"; /** * A named preference indicating whether the workbench should show the * introduction component (if available) on startup. * *

* The default value for this preference is: true (show * intro) *

* * @see org.eclipse.ui.application.WorkbenchWindowAdvisor#openIntro() * @since 3.0 */ - static const QString SHOW_INTRO; // "showIntro"; + static const std::string SHOW_INTRO; // "showIntro"; /** * A named preference for whether the workbench should show traditional * style tabs in editors and views. * * Boolean-valued: true if editors and views should use a * traditional style of tab and false if editors should show * new style tab (3.0 style) *

* The default value for this preference is: true *

* * @since 3.0 */ - static const QString SHOW_TRADITIONAL_STYLE_TABS; // "SHOW_TRADITIONAL_STYLE_TABS"; + static const std::string SHOW_TRADITIONAL_STYLE_TABS; // "SHOW_TRADITIONAL_STYLE_TABS"; /** * A named preference for whether the workbench should show text on the * perspective bar. * * Boolean-valued: true, if editors should show text on the * perspective bar, false otherwise. *

* The default value for this preference is: true (show text * on the perspective bar) *

* * @since 3.0 */ - static const QString SHOW_TEXT_ON_PERSPECTIVE_BAR; // "SHOW_TEXT_ON_PERSPECTIVE_BAR"; + static const std::string SHOW_TEXT_ON_PERSPECTIVE_BAR; // "SHOW_TEXT_ON_PERSPECTIVE_BAR"; /** * A named preference for whether the workbench should show the "open * perspective" button on the perspective bar. * * Boolean-valued: true, if editors should show "open * perspective" button on the perspective bar, false * otherwise. *

* The default value for this preference is: true (show "open * perspective" button on the perspective bar) *

* * @since 3.4 */ - static const QString SHOW_OPEN_ON_PERSPECTIVE_BAR; // "SHOW_OPEN_ON_PERSPECTIVE_BAR"; + static const std::string SHOW_OPEN_ON_PERSPECTIVE_BAR; // "SHOW_OPEN_ON_PERSPECTIVE_BAR"; /** * A named preference for whether the workbench should show the "Other..." * menu item in the perspective menu. * * Boolean-valued: true, if editors should show text on the * "Other..." menu item, false otherwise. *

* The default value for this preference is: true (show the * "Other..." menu item in the perspective menu) *

* * @since 3.4 */ - static const QString SHOW_OTHER_IN_PERSPECTIVE_MENU; // "SHOW_OTHER_IN_PERSPECTIVE_MENU"; + static const std::string SHOW_OTHER_IN_PERSPECTIVE_MENU; // "SHOW_OTHER_IN_PERSPECTIVE_MENU"; /** * A named preference for the text of the Help Contents action. * * String-valued. If not specified, "&Help Contents" is used. *

* The default value for this preference is: null *

* * @since 3.0 */ - static const QString HELP_CONTENTS_ACTION_TEXT; // "helpContentsActionText"; + static const std::string HELP_CONTENTS_ACTION_TEXT; // "helpContentsActionText"; /** * A named preference for the text of the Help Search action. * * String-valued. If not specified, "S&earch" is used. *

* The default value for this preference is: null *

* * @since 3.1 */ - static const QString HELP_SEARCH_ACTION_TEXT; // "helpSearchActionText"; + static const std::string HELP_SEARCH_ACTION_TEXT; // "helpSearchActionText"; /** * A named preference for the text of the Dynamic Help action. * * String-valued. If not specified, "&Dynamic Help" is used. *

* The default value for this preference is: null *

* * @since 3.1 */ - static const QString DYNAMIC_HELP_ACTION_TEXT; // "dynamicHelpActionText"; + static const std::string DYNAMIC_HELP_ACTION_TEXT; // "dynamicHelpActionText"; /** * A named preference for enabling animations when a layout transition * occurs *

* The default value for this preference is: true (show * animations when a transition occurs) *

* * @since 3.1 */ - static const QString ENABLE_ANIMATIONS; // "ENABLE_ANIMATIONS"; + static const std::string ENABLE_ANIMATIONS; // "ENABLE_ANIMATIONS"; /** * A named preference that view implementors can used to determine whether * or not they should utilize colored labels. * *

* The default value for this preference is: true (show * colored labels) *

* * @since 3.4 */ - static const QString USE_COLORED_LABELS; // "USE_COLORED_LABELS"; + static const std::string USE_COLORED_LABELS; // "USE_COLORED_LABELS"; /** *

* Workbench preference id for the key configuration identifier to be * treated as the default. *

*

* The default value for this preference is * "org.eclipse.ui.defaultAcceleratorConfiguration". *

* * @since 3.1 */ - static const QString KEY_CONFIGURATION_ID; // "KEY_CONFIGURATION_ID"; + static const std::string KEY_CONFIGURATION_ID; // "KEY_CONFIGURATION_ID"; /** *

* Workbench preference identifier for the minimum width of editor tabs. By * default, Eclipse does not define this value and allows SWT to determine * this constant. We use -1 internally to signify "use * default". *

*

* The default value for this preference is -1. *

* * @since 3.1 */ - static const QString EDITOR_MINIMUM_CHARACTERS; // "EDITOR_MINIMUM_CHARACTERS"; + static const std::string EDITOR_MINIMUM_CHARACTERS; // "EDITOR_MINIMUM_CHARACTERS"; /** *

* Workbench preference identifier for the minimum width of view tabs. *

*

* The default value for this preference is 1. *

* * @since 3.2 */ - static const QString VIEW_MINIMUM_CHARACTERS; // "VIEW_MINIMUM_CHARACTERS"; + static const std::string VIEW_MINIMUM_CHARACTERS; // "VIEW_MINIMUM_CHARACTERS"; /** * Stores whether or not system jobs are being shown. * * @since 3.1 */ - static const QString SHOW_SYSTEM_JOBS; // "SHOW_SYSTEM_JOBS"; + static const std::string SHOW_SYSTEM_JOBS; // "SHOW_SYSTEM_JOBS"; /** * Workbench preference for the current theme. * * @since 3.1 */ - static const QString CURRENT_THEME_ID; // "CURRENT_THEME_ID"; + static const std::string CURRENT_THEME_ID; // "CURRENT_THEME_ID"; /** * A preference value indicating whether editors should be closed before * saving the workbench state when exiting. The default is * false. * * @since 3.1 */ - static const QString CLOSE_EDITORS_ON_EXIT; // "CLOSE_EDITORS_ON_EXIT"; + static const std::string CLOSE_EDITORS_ON_EXIT; // "CLOSE_EDITORS_ON_EXIT"; /** * Stores whether or not to show progress while starting the workbench. The * default is false. * * @since 3.1 */ - static const QString SHOW_PROGRESS_ON_STARTUP; // "SHOW_PROGRESS_ON_STARTUP"; + static const std::string SHOW_PROGRESS_ON_STARTUP; // "SHOW_PROGRESS_ON_STARTUP"; /** * Stores whether or not to show the memory monitor in the workbench window. * * @since 3.1 */ - static const QString SHOW_MEMORY_MONITOR; // "SHOW_MEMORY_MONITOR"; + static const std::string SHOW_MEMORY_MONITOR; // "SHOW_MEMORY_MONITOR"; /** * Stores whether or not to use the window working set as the default * working set for newly created views (without previously stored state). * This is a hint that view implementors should honor. * * @since 3.2 */ - static const QString USE_WINDOW_WORKING_SET_BY_DEFAULT; // "USE_WINDOW_WORKING_SET_BY_DEFAULT"; + static const std::string USE_WINDOW_WORKING_SET_BY_DEFAULT; // "USE_WINDOW_WORKING_SET_BY_DEFAULT"; /** * Stores whether or not to show the text widget that allows type-ahead * search in the case where a FilteredTree is used to display and filter * tree items. * * @since 3.2 */ - static const QString SHOW_FILTERED_TEXTS; // "SHOW_FILTERED_TEXTS"; + static const std::string SHOW_FILTERED_TEXTS; // "SHOW_FILTERED_TEXTS"; /** * Stores whether or not views may be detached. The default is * true. * * @since 3.2 */ - static const QString ENABLE_DETACHED_VIEWS; // "ENABLE_DETACHED_VIEWS"; + static const std::string ENABLE_DETACHED_VIEWS; // "ENABLE_DETACHED_VIEWS"; /** * Stores whether or not the workbench prompts for saving when a dirty * editor or view is closed, but the Saveable objects are still open in * other parts. If * true (default), the user will be prompted. If false, there will be * no prompt. * * @see Saveable * @since 3.2 */ - static const QString PROMPT_WHEN_SAVEABLE_STILL_OPEN; // "PROMPT_WHEN_SAVEABLE_STILL_OPEN"; + static const std::string PROMPT_WHEN_SAVEABLE_STILL_OPEN; // "PROMPT_WHEN_SAVEABLE_STILL_OPEN"; /** * Lists the extra perspectives to show in the perspective bar. The value is * a comma-separated list of perspective ids. The default is the empty * string. * * @since 3.2 */ - static const QString PERSPECTIVE_BAR_EXTRAS; // "PERSPECTIVE_BAR_EXTRAS"; + static const std::string PERSPECTIVE_BAR_EXTRAS; // "PERSPECTIVE_BAR_EXTRAS"; /** * Allows locking the trim to prevent user dragging on startup. The default * is false. * * @since 3.2 */ - static const QString LOCK_TRIM; // "LOCK_TRIM"; + static const std::string LOCK_TRIM; // "LOCK_TRIM"; /** * A named preference for providing the 3.3 presentation's min/max behaviour *

* The default value for this preference is: false; use the * 3.2 behaviour. *

* * @since 3.3 */ - static const QString ENABLE_NEW_MIN_MAX; // "ENABLE_MIN_MAX"; + static const std::string ENABLE_NEW_MIN_MAX; // "ENABLE_MIN_MAX"; /** * A named preference for disabling opening a new fast view from the fast * view bar controls ("Show View as a fast view" button or "New Fast View" * submenu). *

* Value is of type boolean. *

*

* The default is false. *

* * @since 3.3 */ - static const QString DISABLE_NEW_FAST_VIEW; // "disableNewFastView"; + static const std::string DISABLE_NEW_FAST_VIEW; // "disableNewFastView"; /** * A named preference for enabling the 3.2 behavior for closing sticky * views. When not enabled a sticky view is closed in all perspectives when * the view is closed. *

* The default value for this preference is: false; use the * 3.2 behaviour. *

* * @since 3.3 */ - static const QString ENABLE_32_STICKY_CLOSE_BEHAVIOR; // "ENABLE_32_STICKY_CLOSE_BEHAVIOR"; + static const std::string ENABLE_32_STICKY_CLOSE_BEHAVIOR; // "ENABLE_32_STICKY_CLOSE_BEHAVIOR"; /** * An named preference for whether or not tabs are on the top or bottom * for views. Values are either \c SWT.TOP or \c SWT.BOTTOM . *

* The default value for this preference is: SWT.TOP. *

* * @since 3.4 */ - static const QString VIEW_TAB_POSITION; // "VIEW_TAB_POSITION"; + static const std::string VIEW_TAB_POSITION; // "VIEW_TAB_POSITION"; /** * An named preference for whether or not tabs are on the top or bottom * for editors. Values are either \c SWT.TOP or \c SWT.BOTTOM . *

* The default value for this preference is: SWT.TOP. *

* * @since 3.4 */ - static const QString EDITOR_TAB_POSITION; // "EDITOR_TAB_POSITION"; + static const std::string EDITOR_TAB_POSITION; // "EDITOR_TAB_POSITION"; /** * Workbench preference id for whether the workbench should show multiple * editor tabs. * * Boolean-valued: true if editors should show multiple * editor tabs, and false if editors should show a single * editor tab. *

* The default value for this preference is: true *

* * @since 3.4 */ - static const QString SHOW_MULTIPLE_EDITOR_TABS; // "SHOW_MULTIPLE_EDITOR_TABS"; + static const std::string SHOW_MULTIPLE_EDITOR_TABS; // "SHOW_MULTIPLE_EDITOR_TABS"; /** * Workbench preference id for whether the workbench may open editors * in-place. Note that editors will only be opened in-place if this * preference is false and if the current platform supports * in-place editing. * * Boolean-valued: false if editors may be opened in-place, * and true if editors should never be opened in-place. *

* The default value for this preference is: false *

* * @since 3.4 */ - static const QString DISABLE_OPEN_EDITOR_IN_PLACE; // "DISABLE_OPEN_EDITOR_IN_PLACE"; + static const std::string DISABLE_OPEN_EDITOR_IN_PLACE; // "DISABLE_OPEN_EDITOR_IN_PLACE"; }; } #endif /* BERRYWORKBENCHPREFERENCECONSTANTS_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp b/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp index 61515d68e3..8c79c56d6d 100644 --- a/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp +++ b/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp @@ -1,87 +1,87 @@ /*============================================================================ 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 "berryRadioState.h" #include "berryObjectString.h" #include "berryObjectStringMap.h" -#include "berryIPreferences.h" +#include namespace berry { const QString RadioState::STATE_ID = "org.blueberry.ui.commands.radioState"; const QString RadioState::PARAMETER_ID = "org.blueberry.ui.commands.radioStateParameter"; RadioState::RadioState() { SetShouldPersist(true); } void RadioState::SetInitializationData(const SmartPointer& /*config*/, const QString& /*propertyName*/, const Object::Pointer& data) { bool shouldPersist = true; // persist by default if (data.Cast()) { SetValue(data); } else if (ObjectStringMap::Pointer parameters = data.Cast()) { const QString defaultString = parameters->value("default"); if (!defaultString.isNull()) { Object::Pointer value(new ObjectString(defaultString)); SetValue(value); } const QString persistedString = parameters->value("persisted"); if (!persistedString.isNull() && persistedString.compare("false", Qt::CaseInsensitive) == 0) shouldPersist = false; } SetShouldPersist(shouldPersist); } -void RadioState::Load(const SmartPointer& store, const QString& preferenceKey) +void RadioState::Load(const mitk::IPreferences* store, const std::string& preferenceKey) { if (!ShouldPersist()) return; - const QString prefValue = store->Get(preferenceKey, QString()); + const auto prefValue = QString::fromStdString(store->Get(preferenceKey, "")); if (!prefValue.isEmpty()) { Object::Pointer value(new ObjectString(prefValue)); SetValue(value); } } -void RadioState::Save(const SmartPointer& store, const QString& preferenceKey) +void RadioState::Save(mitk::IPreferences* store, const std::string& preferenceKey) { if (!ShouldPersist()) return; const Object::Pointer value = GetValue(); if (ObjectString::Pointer objStr = value.Cast()) { - store->Put(preferenceKey, *objStr); + store->Put(preferenceKey, (*objStr).toStdString()); } } void RadioState::SetValue(const Object::Pointer& value) { if (!(value.Cast())) return; // we set only String values PersistentState::SetValue(value); } } diff --git a/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.h b/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.h index c7d6a7baba..ff4a89c67e 100644 --- a/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.h +++ b/Plugins/org.blueberry.ui.qt/src/handlers/berryRadioState.h @@ -1,71 +1,71 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYRADIOSTATE_H #define BERRYRADIOSTATE_H #include "internal/berryPersistentState.h" #include "berryIExecutableExtension.h" namespace berry { /** * This state supports a radio-button like command, where the value of the * parameterized command is stored as state. The command must define a state * using the {@link #STATE_ID} id and a string commandParameter using the * {@link #PARAMETER_ID} id. Menu contributions supplied by * org.eclipse.ui.menus can then set the {@link #PARAMETER_ID}. *

* When parsing from the registry, this state understands two parameters: * default, which is the default value for this item; and * persisted, which is whether the state should be persisted * between sessions. The default parameter has no default value and * must be specified in one of its forms, and the persisted * parameter defaults to true. If only one parameter is passed * (i.e., using the class name followed by a colon), then it is assumed to be * the default parameter. *

* * @see HandlerUtil#updateRadioState(org.eclipse.core.commands.Command, String) * @see HandlerUtil#matchesRadioState(org.eclipse.core.commands.ExecutionEvent) */ class RadioState : public PersistentState, public IExecutableExtension { public: /** * The state ID for a radio state understood by the system. */ static const QString STATE_ID; // = "org.blueberry.ui.commands.radioState"; /** * The parameter ID for a radio state understood by the system. */ static const QString PARAMETER_ID; // = "org.blueberry.ui.commands.radioStateParameter"; RadioState(); void SetInitializationData(const SmartPointer& config, const QString& propertyName, const Object::Pointer& data) override; - void Load(const SmartPointer& store, const QString& preferenceKey) override; + void Load(const mitk::IPreferences* store, const std::string& preferenceKey) override; - void Save(const SmartPointer& store, const QString& preferenceKey) override; + void Save(mitk::IPreferences* store, const std::string& preferenceKey) override; void SetValue(const Object::Pointer& value) override; }; } #endif // BERRYRADIOSTATE_H diff --git a/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp b/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp index 93a967c972..dd6e53c954 100644 --- a/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp +++ b/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp @@ -1,68 +1,68 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryToggleState.h" #include "berryObjects.h" -#include "berryIPreferences.h" - #include +#include + namespace berry { ToggleState::ToggleState() { Object::Pointer value(new ObjectBool(false)); SetValue(value); } -void ToggleState::Load(const SmartPointer& store, - const QString& preferenceKey) +void ToggleState::Load(const mitk::IPreferences* store, + const std::string& preferenceKey) { bool currentValue = GetValue().Cast()->GetValue(); - //store.setDefault(preferenceKey, currentValue); - if (ShouldPersist() && (store->Keys().contains(preferenceKey))) + const auto keys = store->Keys(); + if (ShouldPersist() && (std::find(keys.begin(), keys.end(), preferenceKey) != keys.end())) { const bool value = store->GetBool(preferenceKey, currentValue); if (value != currentValue) { Object::Pointer newValue(new ObjectBool(value)); SetValue(newValue); } } } -void ToggleState::Save(const SmartPointer& store, - const QString& preferenceKey) +void ToggleState::Save(mitk::IPreferences* store, + const std::string& preferenceKey) { if (ShouldPersist()) { const Object::Pointer value = GetValue(); if (ObjectBool::Pointer boolValue = value.Cast()) { store->PutBool(preferenceKey, boolValue->GetValue()); } } } void ToggleState::SetValue(const Object::Pointer& value) { if (!(value.Cast())) { throw ctkInvalidArgumentException("ToggleState takes a Boolean as a value"); } PersistentState::SetValue(value); } } diff --git a/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.h b/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.h index 6282bb53c5..5301830c23 100644 --- a/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.h +++ b/Plugins/org.blueberry.ui.qt/src/handlers/berryToggleState.h @@ -1,55 +1,55 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYTOGGLESTATE_H #define BERRYTOGGLESTATE_H #include "internal/berryPersistentState.h" namespace berry { /** *

* A piece of state storing a \c bool. *

*

* If this state is registered using \c IMenuStateIds.STYLE , then it will * control the presentation of the command if displayed in the menus, tool bars * or status line. *

*

* Clients may instantiate this class, but must not extend. *

*/ class ToggleState : public PersistentState { public: /** * Constructs a new ToggleState. By default, the toggle is * off (e.g., false). */ ToggleState(); - void Load(const SmartPointer& store, - const QString& preferenceKey) override; + void Load(const mitk::IPreferences* store, + const std::string& preferenceKey) override; - void Save(const SmartPointer& store, - const QString& preferenceKey) override; + void Save(mitk::IPreferences* store, + const std::string& preferenceKey) override; void SetValue(const Object::Pointer& value) override; }; } #endif // BERRYTOGGLESTATE_H diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp index 6c63eb5ac5..b2e87cfab6 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp @@ -1,251 +1,251 @@ /*============================================================================ 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 "berryChangeToPerspectiveMenu.h" #include #include #include #include #include #include #include -#include #include #include #include #include "berryCommandContributionItemParameter.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPreferenceConstants.h" #include "berryPreferenceConstants.h" #include +#include + namespace berry { const QString ChangeToPerspectiveMenu::NO_TARGETS_MSG = ""; bool PerspectiveComparator(const IPerspectiveDescriptor::Pointer& d1, const IPerspectiveDescriptor::Pointer& d2) { return d1->GetLabel() < d2->GetLabel(); } ChangeToPerspectiveMenu::ChangeToPerspectiveMenu(IWorkbenchWindow* window, const QString& id) : ContributionItem(id) , window(window) , reg(window->GetWorkbench()->GetPerspectiveRegistry()) , showActive(true) , dirty(true) { CommandContributionItemParameter::Pointer showDlgItemParms( new CommandContributionItemParameter( window, QString::null, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE, CommandContributionItem::STYLE_PUSH)); showDlgItemParms->label = "&Other..."; showDlgItem = new CommandContributionItem(showDlgItemParms); // indicate that a open perspectives submenu has been created /* if (WorkbenchWindow* window = dynamic_cast(window)) { window->AddSubmenu(WorkbenchWindow::OPEN_PERSPECTIVE_SUBMENU); } */ } void ChangeToPerspectiveMenu::Fill(QMenu* menu, QAction* before) { if (MenuManager* mm = dynamic_cast(GetParent())) { this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); } if (!dirty) { return; } MenuManager::Pointer manager(new MenuManager()); FillMenu(manager.GetPointer()); QList items = manager->GetItems(); if (items.isEmpty()) { auto action = new QAction(NO_TARGETS_MSG, menu); action->setEnabled(false); menu->insertAction(before, action); } else { foreach (IContributionItem::Pointer item, items) { item->Fill(menu, before); } } dirty = false; } bool ChangeToPerspectiveMenu::IsDirty() const { return dirty; } bool ChangeToPerspectiveMenu::IsDynamic() const { return true; } void ChangeToPerspectiveMenu::AboutToShow(IMenuManager* manager) { manager->MarkDirty(); dirty = true; } void ChangeToPerspectiveMenu::FillMenu(IMenuManager* manager) { // Clear out the manager so that we have a blank slate. manager->RemoveAll(); // Collect and sort perspective descriptors. QList persps = GetPerspectiveShortcuts(); qSort(persps.begin(), persps.end(), PerspectiveComparator); /* * Convert the perspective descriptors to command parameters, and filter * using the activity/capability mechanism. */ for (const IPerspectiveDescriptor::Pointer &descriptor : qAsConst(persps)) { CommandContributionItemParameter::Pointer ccip = GetItem(descriptor); // if (WorkbenchActivityHelper.filterItem(ccip)) { // continue; // } CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); manager->Add(item); } - IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); - bool showOther = true; - prefs->GetBool(WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU, showOther); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + bool showOther = prefs->GetBool(WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU, true); if (showOther) { // Add a separator and then "Other..." if (!manager->IsEmpty()) { IContributionItem::Pointer separator(new Separator()); manager->Add(separator); } manager->Add(showDlgItem); } } SmartPointer ChangeToPerspectiveMenu::GetItem(const IPerspectiveDescriptor::Pointer& desc) const { - IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); int mode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = window->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page.IsNotNull()) { persp = page->GetPerspective(); } QString perspId = desc->GetId(); class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution { QString localId; QString pluginId; public: typedef PluginCCIP Self; static const char* GetStaticClassName() { return "PluginCCIP"; } berryObjectTypeInfo(CommandContributionItemParameter, IPluginContribution) PluginCCIP(const IPerspectiveDescriptor::Pointer& v, IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) : CommandContributionItemParameter(serviceLocator, id, commandId, style) { PerspectiveDescriptor::Pointer vd = v.Cast(); localId = vd->GetLocalId(); pluginId = vd->GetPluginId(); } QString GetLocalId() const override { return localId; } QString GetPluginId() const override { return pluginId; } }; CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, window, perspId, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE, CommandContributionItem::STYLE_PUSH)); parms->label = desc->GetLabel(); parms->icon = desc->GetImageDescriptor(); Object::Pointer strId(new ObjectString(perspId)); parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID, strId); // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp.IsNotNull()) { Object::Pointer bNewWnd(new ObjectBool(true)); parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW, bNewWnd); } return parms; } QList > ChangeToPerspectiveMenu::GetPerspectiveShortcuts() const { QList list; IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return list; } QList ids = page->GetPerspectiveShortcuts(); for (int i = 0; i < ids.size(); i++) { IPerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId(ids[i]); if (desc.IsNotNull() && !list.contains(desc)) { /* if (WorkbenchActivityHelper::FilterItem(desc)) { continue; } */ list.push_back(desc); } } return list; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp index be4e617055..34cce02a34 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp @@ -1,397 +1,395 @@ /*============================================================================ 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 "berryCommandPersistence.h" #include "berryHandleObject.h" #include "berryStatus.h" #include "berryICommandService.h" #include "berryIConfigurationElement.h" #include "berryCommandCategory.h" #include "berryCommand.h" #include "berryCommandParameter.h" #include "berryParameterType.h" #include "berryParameterValueConverterProxy.h" #include "berryCommandStateProxy.h" #include "berryIExtensionRegistry.h" #include "berryIExtension.h" #include "berryPlatform.h" #include "berryPlatformUI.h" #include "berryWorkbenchPlugin.h" -#include "berryIPreferencesService.h" -#include "berryIPreferences.h" #include "berryCommandService.h" namespace berry { const int CommandPersistence::INDEX_CATEGORY_DEFINITIONS = 0; const int CommandPersistence::INDEX_COMMAND_DEFINITIONS = 1; const int CommandPersistence::INDEX_PARAMETER_TYPE_DEFINITIONS = 2; const int CommandPersistence::INDEX_SIZE = 3; void CommandPersistence::ReadCategoriesFromRegistry( const QList >& configurationElements, ICommandService* const commandService) { // Undefine all the previous handle objects. const QList handleObjects = commandService->GetDefinedCategories(); foreach (const CommandCategory::Pointer handleObject, handleObjects) { handleObject->Undefine(); } // Define the uncategorized category. commandService->DefineUncategorizedCategory( QObject::tr("Uncategorized"), QObject::tr("Commands that were either auto-generated or have no category")); QList warningsToLog; foreach (const IConfigurationElement::Pointer& configurationElement, configurationElements) { // Read out the category identifier. const QString categoryId = ReadRequired(configurationElement, ATT_ID, warningsToLog, "Categories need an id"); if (categoryId.isNull()) { continue; } // Read out the name. const QString name = ReadRequired(configurationElement, ATT_NAME, warningsToLog, "Categories need a name", categoryId); if (name.isNull()) { continue; } // Read out the description. const QString description = ReadOptional(configurationElement, ATT_DESCRIPTION); const CommandCategory::Pointer category = commandService->GetCategory(categoryId); category->Define(name, description); } // If there were any warnings, then log them now. LogWarnings(warningsToLog, "Warnings while parsing the commands from the 'org.blueberry.ui.commands' and 'org.blueberry.ui.actionDefinitions' extension points."); } void CommandPersistence::ReadCommandsFromRegistry( const QList >& configurationElements, ICommandService* const commandService) { // Undefine all the previous handle objects. const QList handleObjects = commandService->GetDefinedCommands(); foreach (const Command::Pointer& handleObject, handleObjects) { handleObject->Undefine(); } QList warningsToLog; foreach (const IConfigurationElement::Pointer& configurationElement, configurationElements) { // Read out the command identifier. const QString commandId = ReadRequired(configurationElement, ATT_ID, warningsToLog, "Commands need an id"); if (commandId.isNull()) { continue; } // Read out the name. const QString name = ReadRequired(configurationElement, ATT_NAME, warningsToLog, "Commands need a name"); if (name.isNull()) { continue; } // Read out the description. const QString description = ReadOptional(configurationElement, ATT_DESCRIPTION); // Read out the category id. QString categoryId = configurationElement->GetAttribute(ATT_CATEGORY_ID); if (categoryId.isEmpty()) { categoryId = configurationElement->GetAttribute(ATT_CATEGORY); if (categoryId.isEmpty()) { categoryId = QString(); } } // Read out the parameters. const QList parameters = ReadParameters(configurationElement, warningsToLog, commandService); // Read out the returnTypeId. const QString returnTypeId = ReadOptional(configurationElement, ATT_RETURN_TYPE_ID); // Read out the help context identifier. const QString helpContextId = ReadOptional(configurationElement, ATT_HELP_CONTEXT_ID); const Command::Pointer command = commandService->GetCommand(commandId); const CommandCategory::Pointer category = commandService->GetCategory(categoryId); if (!category->IsDefined()) { AddWarning(warningsToLog, "Commands should really have a category", configurationElement, commandId, "categoryId", categoryId); } ParameterType::Pointer returnType; if (!returnTypeId.isNull()) { returnType = commandService->GetParameterType(returnTypeId); } command->Define(name, description, category, parameters, returnType, helpContextId); ReadState(configurationElement, warningsToLog, command); } // If there were any warnings, then log them now. LogWarnings(warningsToLog, "Warnings while parsing the commands from the 'org.blueberry.ui.commands' and 'org.blueberry.ui.actionDefinitions' extension points."); } QList > CommandPersistence::ReadParameters( const SmartPointer& configurationElement, QList >& warningsToLog, ICommandService* const commandService) { const QList parameterElements = configurationElement ->GetChildren(TAG_COMMAND_PARAMETER); if (parameterElements.isEmpty()) { return QList(); } QList parameters; foreach (const IConfigurationElement::Pointer& parameterElement, parameterElements) { // Read out the id const QString id = ReadRequired(parameterElement, ATT_ID, warningsToLog, "Parameters need an id"); if (id.isNull()) { continue; } // Read out the name. const QString name = ReadRequired(parameterElement, ATT_NAME, warningsToLog, "Parameters need a name"); if (name.isNull()) { continue; } /* * The IParameterValues will be initialized lazily as an * IExecutableExtension. */ // Read out the typeId attribute, if present. const QString typeId = ReadOptional(parameterElement, ATT_TYPE_ID); // Read out the optional attribute, if present. const bool optional = ReadBoolean(parameterElement, ATT_OPTIONAL, true); ParameterType::Pointer type; if (!typeId.isNull()) { type = commandService->GetParameterType(typeId); } const IParameter::Pointer parameter(new CommandParameter(id, name, parameterElement, type, optional)); parameters.push_back(parameter); } return parameters; } void CommandPersistence::ReadParameterTypesFromRegistry( const QList >& configurationElements, ICommandService* const commandService) { // Undefine all the previous handle objects. const QList handleObjects = commandService->GetDefinedParameterTypes(); foreach (const ParameterType::Pointer& handleObject, handleObjects) { handleObject->Undefine(); } QList warningsToLog; foreach (const IConfigurationElement::Pointer configurationElement, configurationElements) { // Read out the commandParameterType identifier. const QString parameterTypeId = ReadRequired(configurationElement, ATT_ID, warningsToLog, "Command parameter types need an id"); if (parameterTypeId.isNull()) { continue; } // Read out the type. const QString type = ReadOptional(configurationElement, ATT_TYPE); // Read out the converter. const QString converter = ReadOptional(configurationElement, ATT_CONVERTER); /* * if the converter attribute was given, create a proxy * AbstractParameterValueConverter for the ParameterType, otherwise * null indicates there is no converter */ const QSharedPointer parameterValueConverter( (converter.isNull()) ? nullptr : new ParameterValueConverterProxy(configurationElement)); const ParameterType::Pointer parameterType = commandService->GetParameterType(parameterTypeId); parameterType->Define(type, parameterValueConverter); } // If there were any warnings, then log them now. LogWarnings(warningsToLog, "Warnings while parsing the commandParameterTypes from the 'org.blueberry.ui.commands' extension point."); } void CommandPersistence::ReadState( const SmartPointer& configurationElement, QList >& warningsToLog, const SmartPointer& command) { const QList stateElements = configurationElement ->GetChildren(TAG_STATE); if (stateElements.isEmpty()) { return; } foreach (const IConfigurationElement::Pointer stateElement, stateElements) { const QString id = ReadRequired(stateElement, ATT_ID, warningsToLog, "State needs an id"); if (id.isNull()) { continue; } if (CheckClass(stateElement, warningsToLog, "State must have an associated class", id)) { const State::Pointer state( new CommandStateProxy(stateElement, ATT_CLASS, WorkbenchPlugin::GetDefault()->GetPreferences(), CommandService::CreatePreferenceKey(command, id)) ); command->AddState(id, state); } } } bool CommandPersistence::IsChangeImportant(const QList >& /*extensions*/, RegistryChangeType /*changeType*/) { return false; } bool CommandPersistence::IsChangeImportant(const QList >& /*extensionPoints*/, RegistryChangeType /*changeType*/) { return false; } void CommandPersistence::Read() { RegistryPersistence::Read(); ReRead(); } CommandPersistence::CommandPersistence(ICommandService* const commandService) : commandService(commandService) { if (commandService == nullptr) { throw ctkInvalidArgumentException("The command service cannot be null"); } } bool CommandPersistence::CommandsNeedUpdating(const QList >& extensions) { foreach(const IExtension::Pointer& extension, extensions) { if (extension->GetExtensionPointUniqueIdentifier() == EXTENSION_COMMANDS || extension->GetExtensionPointUniqueIdentifier() == EXTENSION_ACTION_DEFINITIONS) { return true; } } return false; } void CommandPersistence::ReRead() { // Create the extension registry mementos. IExtensionRegistry* const registry = Platform::GetExtensionRegistry(); QList > indexedConfigurationElements; for (int i = 0; i < INDEX_SIZE; ++i) { indexedConfigurationElements.push_back(QList()); } // Sort the commands extension point based on element name. QList commandsExtensionPoint = registry ->GetConfigurationElementsFor(EXTENSION_COMMANDS); foreach (const IConfigurationElement::Pointer& configurationElement, commandsExtensionPoint) { const QString name = configurationElement->GetName(); // Check if it is a binding definition. if (TAG_COMMAND == name) { indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS].push_back(configurationElement); } else if (TAG_CATEGORY == name) { indexedConfigurationElements[INDEX_CATEGORY_DEFINITIONS].push_back(configurationElement); } else if (TAG_COMMAND_PARAMETER_TYPE == name) { indexedConfigurationElements[INDEX_PARAMETER_TYPE_DEFINITIONS].push_back(configurationElement); } } const QList actionDefinitionsExtensionPoint = registry ->GetConfigurationElementsFor(EXTENSION_ACTION_DEFINITIONS); foreach (const IConfigurationElement::Pointer& configurationElement, actionDefinitionsExtensionPoint) { const QString name = configurationElement->GetName(); if (TAG_ACTION_DEFINITION == name) { indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS].push_back(configurationElement); } } ReadCategoriesFromRegistry(indexedConfigurationElements[INDEX_CATEGORY_DEFINITIONS], commandService); ReadCommandsFromRegistry(indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS], commandService); ReadParameterTypesFromRegistry(indexedConfigurationElements[INDEX_PARAMETER_TYPE_DEFINITIONS], commandService); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp index 853b8968fd..f37b522b35 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp @@ -1,314 +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 "berryIPreferences.h" #include #include #include #include #include #include #include namespace berry { -const QString CommandService::PREFERENCE_KEY_PREFIX = "org.blueberry.ui.commands/state"; +const std::string CommandService::PREFERENCE_KEY_PREFIX = "org.blueberry.ui.commands/state"; -const QString CommandService::CreatePreferenceKey(const SmartPointer& command, - const QString& stateId) +std::string CommandService::CreatePreferenceKey(const SmartPointer& command, + const QString& stateId) { - return PREFERENCE_KEY_PREFIX + '/' + command->GetId() + '/' + 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 neeeds 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(); } QStringList CommandService::GetDefinedCommandIds() const { return commandManager->GetDefinedCommandIds().toList(); } QList > CommandService::GetDefinedCommands() const { return commandManager->GetDefinedCommands(); } QStringList CommandService::GetDefinedParameterTypeIds() const { return commandManager->GetDefinedParameterTypeIds().toList(); } 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/berryCommandService.h b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.h index 001b9f0adb..09c7bb3f0b 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.h @@ -1,143 +1,143 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYCOMMANDSERVICE_H #define BERRYCOMMANDSERVICE_H #include - #include "berryCommandPersistence.h" +#include namespace berry { class CommandManager; /** *

* Provides services related to the command architecture within the workbench. * This service can be used to access the set of commands and handlers. *

*/ class CommandService : public ICommandService { private: friend class CommandPersistence; /** * The preference key prefix for all handler state. */ - static const QString PREFERENCE_KEY_PREFIX; + static const std::string PREFERENCE_KEY_PREFIX; /** * Creates a preference key for the given piece of state on the given * command. * * @param command * The command for which the preference key should be created; * must not be null. * @param stateId * The identifier of the state for which the preference key * should be created; must not be null. * @return A suitable preference key; never null. */ - static const QString CreatePreferenceKey(const SmartPointer& command, - const QString& stateId); + static std::string CreatePreferenceKey(const SmartPointer& command, + const QString& stateId); /** * The command manager that supports this service. This value is never * null. */ CommandManager* commandManager; /** * The persistence class for this command service. */ CommandPersistence commandPersistence; /** * This is a map of commandIds to a list containing currently registered * callbacks, in the form of IElementReference. */ QHash > > commandCallbacks; public: /** * Constructs a new instance of CommandService using a * command manager. Takes ownership of the provided CommandManager. * * @param commandManager * The command manager to use; must not be null. */ CommandService( CommandManager* commandManager); ~CommandService() override; void AddExecutionListener(IExecutionListener* listener) override; void DefineUncategorizedCategory(const QString& name, const QString& description) override; SmartPointer Deserialize(const QString& serializedParameterizedCommand) const override; void Dispose() override; SmartPointer GetCategory(const QString& categoryId) const override; SmartPointer GetCommand(const QString& commandId) const override; QList > GetDefinedCategories() const override; QStringList GetDefinedCategoryIds() const override; QStringList GetDefinedCommandIds() const override; QList > GetDefinedCommands() const override; QStringList GetDefinedParameterTypeIds() const override; QList > GetDefinedParameterTypes() const override; QString GetHelpContextId(const SmartPointer& command) const override; QString GetHelpContextId(const QString& commandId) const override; SmartPointer GetParameterType(const QString& parameterTypeId) const override; void ReadRegistry() override; void RemoveExecutionListener(IExecutionListener* listener) override; void SetHelpContextId(const SmartPointer& handler, const QString& helpContextId) override; void RefreshElements(const QString& commandId, const QHash& filter) override; SmartPointer RegisterElementForCommand( const SmartPointer& command, const SmartPointer& element) override; void RegisterElement(const SmartPointer& elementReference) override; void UnregisterElement(const SmartPointer& elementReference) override; const CommandPersistence* GetCommandPersistence() const; }; } #endif // BERRYCOMMANDSERVICE_H diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp index 71958502e8..cd554333a1 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp @@ -1,229 +1,230 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryCommandStateProxy.h" #include "berryIConfigurationElement.h" #include "berryStatus.h" #include "berryPlatformUI.h" #include "berryWorkbenchPlugin.h" -#include "berryIPreferences.h" + +#include namespace berry { CommandStateProxy::CommandStateProxy(const SmartPointer& configurationElement, const QString& stateAttributeName, - const SmartPointer& preferenceStore, - const QString& preferenceKey) + mitk::IPreferences* preferenceStore, + const std::string& preferenceKey) : configurationElement(configurationElement) , preferenceKey(preferenceKey) , preferenceStore(preferenceStore) , stateAttributeName(stateAttributeName) { if (configurationElement.IsNull()) { throw ctkInvalidArgumentException( "The configuration element backing a state proxy cannot be null"); } if (stateAttributeName.isNull()) { throw ctkInvalidArgumentException( "The attribute containing the state class must be known"); } } void CommandStateProxy::AddListener(IStateListener* listener) { if (state.IsNull()) { this->AddListener(listener); } else { state->AddListener(listener); } } CommandStateProxy::~CommandStateProxy() { if (state.IsNotNull()) { if (PersistentState::Pointer persistableState = state.Cast()) { - if (persistableState->ShouldPersist() && preferenceStore.IsNotNull() - && !preferenceKey.isNull()) + if (persistableState->ShouldPersist() && preferenceStore != nullptr + && !preferenceKey.empty()) { persistableState->Save(preferenceStore, preferenceKey); } } } } Object::Pointer CommandStateProxy::GetValue() const { if (const_cast(this)->LoadState()) { return state->GetValue(); } return Object::Pointer(nullptr); } -void CommandStateProxy::Load(const SmartPointer& /*store*/, - const QString& preferenceKey) +void CommandStateProxy::Load(const mitk::IPreferences* /*store*/, + const std::string& preferenceKey) { if (LoadState()) { if (PersistentState::Pointer persistableState = state.Cast()) { - if (persistableState->ShouldPersist() && preferenceStore.IsNotNull() - && !preferenceKey.isNull()) + if (persistableState->ShouldPersist() && preferenceStore != nullptr + && !preferenceKey.empty()) { persistableState->Load(preferenceStore, preferenceKey); } } } } void CommandStateProxy::RemoveListener(IStateListener* listener) { if (state.IsNull()) { this->RemoveListener(listener); } else { state->RemoveListener(listener); } } -void CommandStateProxy::Save(const SmartPointer& store, - const QString& preferenceKey) +void CommandStateProxy::Save(mitk::IPreferences* store, + const std::string& preferenceKey) { if (LoadState()) { if (PersistentState::Pointer persistableState = state.Cast()) { persistableState->Save(store, preferenceKey); } } } void CommandStateProxy::SetId(const QString& id) { PersistentState::SetId(id); if (state.IsNotNull()) { state->SetId(id); } } void CommandStateProxy::SetShouldPersist(bool persisted) { if (LoadState(persisted)) { if (PersistentState::Pointer persistableState = state.Cast()) { persistableState->SetShouldPersist(persisted); } } } void CommandStateProxy::SetValue(const Object::Pointer& value) { if (LoadState()) { state->SetValue(value); } } bool CommandStateProxy::ShouldPersist() { if (LoadState()) { if (PersistentState::Pointer persistableState = state.Cast()) { return persistableState->ShouldPersist(); } } return false; } QString CommandStateProxy::ToString() const { if (state.IsNull()) { return configurationElement->GetAttribute(stateAttributeName); } return state->ToString(); } bool CommandStateProxy::LoadState(bool readPersistence) { if (state.IsNull()) { try { state = configurationElement->CreateExecutableExtension(stateAttributeName); if (state.IsNull()) { const QString message = "The proxied state was the wrong class"; const IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, message, BERRY_STATUS_LOC)); WorkbenchPlugin::Log(message, status); return false; } state->SetId(GetId()); configurationElement = nullptr; // Try to load the persistent state, if possible. if (readPersistence) { if (PersistentState::Pointer persistentState = state.Cast()) { persistentState->SetShouldPersist(true); } } Load(preferenceStore, preferenceKey); // Transfer the local listeners to the real state. typedef IStateListener::Events::StateEvent::ListenerList ListenerListType; const ListenerListType listenerArray = this->stateEvents.stateChanged.GetListeners(); for (auto i = listenerArray.begin(); i != listenerArray.end(); ++i) { state->AddListener(*(*i)); this->RemoveListener(*(*i)); } return true; } catch (const CoreException& e) { const QString message = "The proxied state for '" + configurationElement->GetAttribute(stateAttributeName) + "' could not be loaded"; IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, message, e, BERRY_STATUS_LOC)); WorkbenchPlugin::Log(message, status); return false; } } return true; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h index 5f9784bdeb..5a7854d982 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h @@ -1,147 +1,146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYCOMMANDSTATEPROXY_H #define BERRYCOMMANDSTATEPROXY_H #include "berryPersistentState.h" namespace berry { struct IConfigurationElement; -struct IPreferences; /** *

* A proxy for handler state that has been defined in XML. This delays the class * loading until the state is really asked for information. Asking a proxy for * anything (except disposing, and adding and removing listeners) will cause the * proxy to instantiate the proxied handler. *

*

* Loading the proxied state will automatically cause it to load its value from * the preference store. Disposing of the state will cause it to persist its * value. *

*

* This class is not intended for use outside of the * org.eclipse.ui.workbench plug-in. *

*/ class CommandStateProxy : public PersistentState { public: berryObjectMacro(berry::CommandStateProxy); private: /** * The configuration element from which the state can be created. This value * will exist until the element is converted into a real class -- at which * point this value will be set to null. */ SmartPointer configurationElement; /** * The key in the preference store to locate the persisted state. */ - const QString preferenceKey; + const std::string preferenceKey; /** * The preference store containing the persisted state, if any. */ - const SmartPointer preferenceStore; + mitk::IPreferences* preferenceStore; /** * The real state. This value is null until the proxy is * forced to load the real state. At this point, the configuration element * is converted, nulled out, and this state gains a reference. */ SmartPointer state; /** * The name of the configuration element attribute which contains the * information necessary to instantiate the real state. */ const QString stateAttributeName; public: /** * Constructs a new instance of HandlerState with all the * information it needs to create the real state later. * * @param configurationElement * The configuration element from which the real class can be * loaded at run-time; must not be null. * @param stateAttributeName * The name of the attribute or element containing the state * executable extension; must not be null. * @param preferenceStore * The preference store to which any persistent data should be * written, and from which it should be loaded; may be * null. * @param preferenceKey * The key at which the persistent data is located within the * preference store. */ CommandStateProxy(const SmartPointer& configurationElement, const QString& stateAttributeName, - const SmartPointer& preferenceStore, - const QString& preferenceKey); + mitk::IPreferences* preferenceStore, + const std::string& preferenceKey); void AddListener(IStateListener* listener) override; ~CommandStateProxy() override; Object::Pointer GetValue() const override; - void Load(const SmartPointer& store, - const QString& preferenceKey) override; + void Load(const mitk::IPreferences* store, + const std::string& preferenceKey) override; using State::RemoveListener; void RemoveListener(IStateListener* listener) override; - void Save(const SmartPointer& store, - const QString& preferenceKey) override; + void Save(mitk::IPreferences* store, + const std::string& preferenceKey) override; void SetId(const QString& id) override; void SetShouldPersist(bool persisted) override; void SetValue(const Object::Pointer& value) override; bool ShouldPersist() override; QString ToString() const override; private: /** * Loads the state, if possible. If the state is loaded, then the member * variables are updated accordingly and the state is told to load its value * from the preference store. * * @param readPersistence * Whether the persistent state for this object should be read. * @return true if the state is now non-null; * false otherwise. */ bool LoadState(bool readPersistence = false); }; } #endif // BERRYCOMMANDSTATEPROXY_H diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp index 7a05e26f7c..6a8ec00702 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp @@ -1,1270 +1,1270 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPartSashContainer.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryPartStack.h" #include "berryPageLayout.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryDragUtil.h" #include "berryWorkbenchPlugin.h" -#include "berryIPreferencesService.h" -#include "berryIPreferences.h" #include "berryWorkbenchPreferenceConstants.h" #include "berryGeometry.h" #include "berryPartPane.h" #include "berryQtTracker.h" #include "berryConstants.h" +#include +#include namespace berry { bool PartSashContainer::leftToRight = true; PartSashContainer::ControlListener::ControlListener( PartSashContainer* container) : partSashContainer(container) { } GuiTk::IControlListener::Events::Types PartSashContainer::ControlListener::GetEventTypes() const { return Events::RESIZED; } void PartSashContainer::ControlListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { partSashContainer->ResizeSashes(); } PartSashContainer::SashContainerDropTarget::SashContainerDropTarget( PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) : partSashContainer(partSashContainer) { this->SetTarget(sourcePart, side, cursor, targetPart); } void PartSashContainer::SashContainerDropTarget::SetTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { this->side = side; this->targetPart = targetPart; this->sourcePart = sourcePart; this->cursor = cursor; } void PartSashContainer::SashContainerDropTarget::Drop() { if (side != Constants::NONE) { LayoutPart::Pointer visiblePart = sourcePart.Cast (); if (sourcePart.Cast () != 0) { visiblePart = partSashContainer->GetVisiblePart(sourcePart.Cast< ILayoutContainer> ()); } partSashContainer->DropObject( partSashContainer->GetVisibleParts(sourcePart), visiblePart, targetPart, side); } } void PartSashContainer::DropObject(const QList& toDrop, LayoutPart::Pointer visiblePart, Object::Pointer targetPart, int side) { //getControl().setRedraw(false); // Targetpart is null if there isn't a part under the cursor (all the parts are // hidden or the container is empty). In this case, the actual side doesn't really // since we'll be the only visible container and will fill the entire space. However, // we can't leave it as Constants::CENTER since we can't stack if we don't have something // to stack on. In this case, we pick Constants::BOTTOM -- this will insert the new pane // below any currently-hidden parts. if (targetPart == 0 && side == Constants::CENTER) { side = Constants::BOTTOM; } PartStack::Pointer targetStack = targetPart.Cast (); if (targetStack == 0 && targetPart.Cast() != 0) { targetStack = targetPart.Cast ()->GetStack(); } LayoutPart::Pointer targetLayoutPart = targetStack; // if targetLayoutPart == 0 then we normally got a EditorSashContainer if (targetLayoutPart == 0) targetLayoutPart = targetPart.Cast(); if (side == Constants::CENTER) { if (this->IsStackType(targetStack)) { for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, targetStack); } } } else { PartStack::Pointer newPart = this->CreateStack(); // if the toDrop array has 1 item propagate the stack // appearance if (toDrop.size() == 1 && toDrop[0]->GetStack() != 0) { toDrop[0]->GetStack()->CopyAppearanceProperties(newPart); } for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, newPart); } this->AddEnhanced(newPart, side, this->GetDockingRatio(newPart, targetStack), targetLayoutPart); } if (visiblePart != 0) { this->SetVisiblePart(visiblePart->GetContainer(), visiblePart.Cast ()); } //getControl().setRedraw(true); if (visiblePart != 0) { visiblePart->SetFocus(); } } CursorType PartSashContainer::SashContainerDropTarget::GetCursor() { return QtDragManager::PositionToCursorType(cursor); } QRect PartSashContainer::SashContainerDropTarget::GetSnapRectangle() { QRect targetBounds; if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else { targetBounds = DragUtil::GetDisplayBounds(partSashContainer->GetParent()); } if (side == Constants::CENTER || side == Constants::NONE) { return targetBounds; } int distance = Geometry::GetDimension(targetBounds, !Geometry::IsHorizontal( side)); ILayoutContainer::Pointer stack = targetPart.Cast (); if (stack == 0 && targetPart.Cast () != 0) { stack = targetPart.Cast ()->GetContainer(); } return Geometry::GetExtrudedEdge(targetBounds, (int) (distance * partSashContainer->GetDockingRatio(sourcePart, stack)), side); } PartSashContainer::PartSashContainer(const QString& id, WorkbenchPage* _page, QWidget* _parentWidget) : LayoutPart(id), parentWidget(_parentWidget), parent(nullptr), page(_page), active( false), layoutDirty(false) { resizeListener = new ControlListener(this); - QString layout = WorkbenchPlugin::GetDefault()->GetPreferencesService()-> + auto layout = WorkbenchPlugin::GetDefault()->GetPreferencesService()-> GetSystemPreferences()->Get(WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, WorkbenchPreferenceConstants::LEFT); if (layout == WorkbenchPreferenceConstants::RIGHT) { leftToRight = false; } } QList PartSashContainer::GetVisibleParts( Object::Pointer pane) { QList parts; if (pane.Cast ().IsNotNull()) { parts.push_back(pane.Cast ()); } else if (pane.Cast ().IsNotNull()) { PartStack::Pointer stack = pane.Cast (); QList children = stack->GetChildren(); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () != 0) { parts.push_back(iter->Cast ()); } } } return parts; } PartSashContainer::~PartSashContainer() { } void PartSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { if (root == 0) { return; } LayoutTree::Pointer part = root->Find(pane); if (part == 0) { return; } part->FindSashes(sashes); } void PartSashContainer::Add(LayoutPart::Pointer child) { if (child.IsNull()) { return; } this->AddEnhanced(child, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddPart(LayoutPart::Pointer child) { if (child.IsNull()) { return; } PartStack::Pointer newFolder = this->CreateStack(); newFolder->Add(child); this->AddEnhanced(newFolder, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddEnhanced(LayoutPart::Pointer child, int directionConstant, float ratioForNewPart, LayoutPart::Pointer relative) { int relativePosition = PageLayout::ConstantToLayoutPosition(directionConstant); float ratioForUpperLeftPart; if (relativePosition == IPageLayout::RIGHT || relativePosition == IPageLayout::BOTTOM) { ratioForUpperLeftPart = 1.0f - ratioForNewPart; } else { ratioForUpperLeftPart = ratioForNewPart; } this->Add(child, relativePosition, ratioForUpperLeftPart, relative); } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative) { bool isHorizontal = (relationship == IPageLayout::LEFT || relationship == IPageLayout::RIGHT); LayoutTree::Pointer node; if (root != 0 && relative != 0) { node = root->Find(relative); } QRect bounds; if (this->GetParent() == nullptr) { QWidget* control = this->GetPage()->GetClientComposite(); if (control != nullptr) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(control); } else { bounds = QRect(0, 0, 800, 600); } bounds.setX(0); bounds.setY(0); } else { bounds = this->GetBounds(); } int totalSize = this->MeasureTree(bounds, node, isHorizontal); int left = (int) (totalSize * ratio); int right = totalSize - left; this->Add(child, relationship, left, right, relative); } int PartSashContainer::MeasureTree(const QRect& outerBounds, LayoutTree::ConstPointer toMeasure, bool horizontal) { if (toMeasure == 0) { return Geometry::GetDimension(outerBounds, horizontal); } LayoutTreeNode* parent = toMeasure->GetParent(); if (parent == nullptr) { return Geometry::GetDimension(outerBounds, horizontal); } if (parent->GetSash()->IsHorizontal() == horizontal) { return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } bool isLeft = parent->IsLeftChild(toMeasure); LayoutTree::Pointer otherChild = parent->GetChild(!isLeft); if (otherChild->IsVisible()) { int left = parent->GetSash()->GetLeft(); int right = parent->GetSash()->GetRight(); int childSize = isLeft ? left : right; int bias = parent->GetCompressionBias(); // Normalize bias: 1 = we're fixed, -1 = other child is fixed if (isLeft) { bias = -bias; } if (bias == 1) { // If we're fixed, return the fixed size return childSize; } else if (bias == -1) { // If the other child is fixed, return the size of the parent minus the fixed size of the // other child return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) - (left + right - childSize); } // Else return the size of the parent, scaled appropriately return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) * childSize / (left + right); } return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } void PartSashContainer::AddChild(const RelationshipInfo& info) { LayoutPart::Pointer child = info.part; children.push_back(child); if (root == 0) { root = new LayoutTree(child); } else { //Add the part to the tree. int vertical = (info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::RIGHT) ? Constants::VERTICAL : Constants::HORIZONTAL; bool left = info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::TOP; LayoutPartSash::Pointer sash(new LayoutPartSash(this, vertical)); sash->SetSizes(info.left, info.right); if ((parent != nullptr) && child.Cast ().IsNull()) { sash->CreateControl(parent); } LayoutTree::Pointer newroot = root->Insert(child, left, sash, info.relative); root = newroot; } this->ChildAdded(child); if (active) { child->CreateControl(parent); child->SetVisible(true); child->SetContainer(ILayoutContainer::Pointer(this)); this->ResizeChild(child); } } void PartSashContainer::AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder) { RelationshipInfo newRelationshipInfo; newRelationshipInfo.part = child; if (root != 0) { newRelationshipInfo.relationship = IPageLayout::RIGHT; newRelationshipInfo.relative = root->FindBottomRight(); newRelationshipInfo.left = 200; newRelationshipInfo.right = 200; } // find the relationship info for the placeholder QList relationships = this->ComputeRelation(); for (int i = 0; i < relationships.size(); i++) { RelationshipInfo info = relationships[i]; if (info.part == placeholder) { newRelationshipInfo.left = info.left; newRelationshipInfo.right = info.right; newRelationshipInfo.relationship = info.relationship; newRelationshipInfo.relative = info.relative; } } this->AddChild(newRelationshipInfo); this->FlushLayout(); } bool PartSashContainer::AllowsBorder() { return true; } void PartSashContainer::ChildAdded(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(true); } } void PartSashContainer::ChildRemoved(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(false); } } QList PartSashContainer::ComputeRelation() { LayoutTree::Pointer treeRoot = root; QList list; if (treeRoot == 0) { return QList(); } RelationshipInfo r; r.part = treeRoot->ComputeRelation(list); list.push_front(r); return list; } void PartSashContainer::SetActive(bool isActive) { if (isActive == active) { return; } active = isActive; ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast ().IsNotNull()) { PartStack::Pointer stack = childIter->Cast (); stack->SetActive(isActive); } } if (isActive) { this->CreateControl(parentWidget); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(parent, resizeListener); DragUtil::AddDragTarget(parent, this); DragUtil::AddDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer child = *childIter; child->SetContainer(ILayoutContainer::Pointer(this)); child->SetVisible(true); //zoomedPart == null || child == zoomedPart); if (child.Cast ().IsNull()) { if (root != 0) { LayoutTree::Pointer node = root->Find(child); if (node != 0) { node->FlushCache(); } } } } if (root != 0) { //root.flushChildren(); //if (!isZoomed()) { root->CreateControl(parent); } } this->ResizeSashes(); } else { DragUtil::RemoveDragTarget(parent, this); DragUtil::RemoveDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); // remove all Listeners if (resizeListener != 0 && parent != nullptr) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(parent, resizeListener); } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer child = *iter; child->SetContainer(ILayoutContainer::Pointer(nullptr)); if (child.Cast ().IsNotNull()) { child->SetVisible(false); } } this->DisposeSashes(); //dispose(); } } void PartSashContainer::CreateControl(QWidget* parentWidget) { if (this->parent != nullptr) { return; } parent = this->CreateParent(parentWidget); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->CreateControl(parent); } } void PartSashContainer::Dispose() { if (parent == nullptr) { return; } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { // In PartSashContainer dispose really means deactivate, so we // only dispose PartTabFolders. if (iter->Cast() != 0) { (*iter)->Dispose(); } } this->DisposeParent(); this->parent = nullptr; } void PartSashContainer::DisposeSashes() { if (root != 0) { root->DisposeSashes(); } } void PartSashContainer::SetVisible(bool makeVisible) { if (makeVisible == this->GetVisible()) { return; } //if (!SwtUtil.isDisposed(this.parent)) //{ Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(this->parent, makeVisible); //} LayoutPart::SetVisible(makeVisible); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->SetVisible(makeVisible); // && (zoomedPart == null || child == zoomedPart)); } } LayoutPart::Pointer PartSashContainer::FindBottomRight() { if (root == 0) { return LayoutPart::Pointer(nullptr); } return root->FindBottomRight(); } QRect PartSashContainer::GetBounds() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->parent); } ILayoutContainer::ChildrenType PartSashContainer::GetChildren() const { return children; } QWidget* PartSashContainer::GetControl() { return this->parent; } LayoutTree::Pointer PartSashContainer::GetLayoutTree() { return root; } WorkbenchPage::Pointer PartSashContainer::GetPage() { return WorkbenchPage::Pointer(page); } QWidget* PartSashContainer::GetParent() { return parent; } bool PartSashContainer::IsChild(LayoutPart::Pointer part) { return std::find(children.begin(), children.end(), part) != children.end(); } void PartSashContainer::ResizeChild(LayoutPart::Pointer childThatChanged) { if (root != 0) { LayoutTree::Pointer tree = root->Find(childThatChanged); if (tree != 0) { tree->FlushCache(); } } this->FlushLayout(); } void PartSashContainer::Remove(LayoutPart::Pointer child) { // if (child == getZoomedPart()) // { // childRequestZoomOut(); // } if (!this->IsChild(child)) { return; } children.removeAll(child); if (root != 0) { root = root->Remove(child); } this->ChildRemoved(child); if (active) { child->SetVisible(false); child->SetContainer(ILayoutContainer::Pointer(nullptr)); this->FlushLayout(); } } void PartSashContainer::FlushLayout() { layoutDirty = true; LayoutPart::FlushLayout(); if (layoutDirty) { this->ResizeSashes(); } } void PartSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // if (oldChild == getZoomedPart()) // { // if (newChild.Cast ().IsNotNull()) // { // childRequestZoomOut(); // } // else // { // zoomedPart.setZoomed(false); // zoomedPart = newChild; // zoomedPart.setZoomed(true); // } // } children.erase(std::find(children.begin(), children.end(), oldChild)); children.push_back(newChild); this->ChildAdded(newChild); if (root != 0) { LayoutTree::Pointer leaf; leaf = root->Find(oldChild); if (leaf != 0) { leaf->SetPart(newChild); } } this->ChildRemoved(oldChild); if (active) { oldChild->SetVisible(false); oldChild->SetContainer(ILayoutContainer::Pointer(nullptr)); newChild->CreateControl(parent); newChild->SetContainer(ILayoutContainer::Pointer(this)); newChild->SetVisible(true); //zoomedPart == null || zoomedPart == newChild); this->ResizeChild(newChild); } } void PartSashContainer::ResizeSashes() { layoutDirty = false; if (!active) { return; } // if (isZoomed()) // { // getZoomedPart().setBounds(parent.getClientArea()); // } // else { if (root != 0) { root->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea( parent)); } } } int PartSashContainer::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { // if (isZoomed()) // { // return getZoomedPart().computePreferredSize(width, availableParallel, // availablePerpendicular, preferredParallel); // } if (root != 0) { return root->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } return preferredParallel; } int PartSashContainer::GetSizeFlags(bool width) { // if (isZoomed()) // { // return getZoomedPart().getSizeFlags(width); // } if (root != 0) { return root->GetSizeFlags(width); } return 0; } void PartSashContainer::SetBounds(const QRect& r) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(this->parent, r); } IDropTarget::Pointer PartSashContainer::Drag(QWidget* /*currentControl*/, const Object::Pointer& draggedObject, const QPoint& position, const QRect& /*dragRectangle*/) { if (!(draggedObject.Cast () != 0 || draggedObject.Cast () != 0)) { return IDropTarget::Pointer(nullptr); } PartPane::Pointer sourcePart = draggedObject.Cast (); PartStack::Pointer sourceContainer = draggedObject.Cast (); if (sourceContainer == 0) { sourceContainer = sourcePart->GetStack(); } if (!this->IsStackType(sourceContainer) && !this->IsPaneType(sourcePart)) { return IDropTarget::Pointer(nullptr); } IWorkbenchWindow::Pointer window = sourcePart ? sourcePart->GetWorkbenchWindow() : sourceContainer->GetWorkbenchWindow(); bool differentWindows = window != this->GetWorkbenchWindow(); bool editorDropOK = ((sourceContainer->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) && window->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(nullptr); } QRect containerBounds = DragUtil::GetDisplayBounds(parent); LayoutPart::Pointer targetPart; // If this container has no visible children if (this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) == 0) { return this->CreateDropTarget(draggedObject, Constants::CENTER, Constants::CENTER, Object::Pointer(nullptr)); } if (containerBounds.contains(position)) { if (root != 0) { targetPart = root->FindPart( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(parent, position)); } if (targetPart != 0) { QWidget* targetControl = targetPart->GetControl(); QRect targetBounds = DragUtil::GetDisplayBounds(targetControl); int side = Geometry::GetClosestSide(targetBounds, position); int distance = Geometry::GetDistanceFromEdge(targetBounds, position, side); // is the source coming from a standalone part bool standalone = (this->IsStackType(sourceContainer) && sourceContainer->IsStandalone()) || (this->IsPaneType(sourcePart) && sourcePart->GetStack()->IsStandalone()); // Only allow dropping onto an existing stack from different windows if (differentWindows && targetPart.Cast () != 0 && targetPart.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) { IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); return target; } // Reserve the 5 pixels around the edge of the part for the drop-on-edge cursor if (distance >= 5 && !standalone) { // Otherwise, ask the part if it has any special meaning for this drop location IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); if (target != 0) { return target; } } if (distance > 30 && this->IsStackType(targetPart.Cast ()) && !standalone) { PartStack::Pointer targetContainer = targetPart.Cast (); if (targetContainer->AllowsAdd(sourcePart)) { side = Constants::CENTER; } } // If the part doesn't want to override this drop location then drop on the edge // A "pointless drop" would be one that will put the dragged object back where it started. // Note that it should be perfectly valid to drag an object back to where it came from -- however, // the drop should be ignored. bool pointlessDrop = false; // = isZoomed(); if (!sourcePart && sourceContainer == targetPart) { pointlessDrop = true; } if ((sourceContainer != 0) && (sourceContainer == targetPart) && this->GetVisibleChildrenCount(sourceContainer.Cast()) <= 1) { pointlessDrop = true; } if (side == Constants::CENTER && sourceContainer == targetPart) { pointlessDrop = true; } int cursor = side; if (pointlessDrop) { side = Constants::NONE; cursor = Constants::CENTER; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, targetPart); else return this->CreateDropTarget(sourceContainer, side, cursor, targetPart); } } else { // We only allow dropping into a stack, not creating one if (differentWindows) return IDropTarget::Pointer(nullptr); int side = Geometry::GetClosestSide(containerBounds, position); bool pointlessDrop = false; // = isZoomed(); if (/*(this->IsStackType(sourceContainer) && sourceContainer == this) ||*/ (this->IsPaneType(sourcePart) && this->GetVisibleChildrenCount( sourceContainer.Cast()) <= 1) && sourceContainer->GetContainer() == this) { if (root == 0 || this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) <= 1) { pointlessDrop = true; } } int cursor = Geometry::GetOppositeSide(side); if (pointlessDrop) { side = Constants::NONE; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, Object::Pointer(nullptr)); else return this->CreateDropTarget(sourceContainer, side, cursor, Object::Pointer(nullptr)); } return IDropTarget::Pointer(nullptr); } PartSashContainer::SashContainerDropTarget::Pointer PartSashContainer::CreateDropTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { if (dropTarget == 0) { dropTarget = new SashContainerDropTarget(this, sourcePart, side, cursor, targetPart); } else { dropTarget->SetTarget(sourcePart, side, cursor, targetPart); } return dropTarget; } void PartSashContainer::Stack(LayoutPart::Pointer newPart, ILayoutContainer::Pointer container) { //this->GetControl().setRedraw(false); // Only deref the part if it is being referenced in -this- perspective Perspective::Pointer persp = page->GetActivePerspective(); PerspectiveHelper* pres = (persp != 0) ? persp->GetPresentation() : nullptr; if (pres != nullptr && container.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { IWorkbenchPartReference::Pointer newPartRef = newPart.Cast ()->GetPartReference(); IViewReference::Pointer vRef = newPartRef.Cast (); if (vRef != 0) { LayoutPart::Pointer fpp = pres->FindPart(vRef->GetId(), vRef->GetSecondaryId()); if (fpp != 0) { // Remove the part from old container. this->DerefPart(newPart); } } } else { // Remove the part from old container. this->DerefPart(newPart); } // Reparent part and add it to the workbook newPart->Reparent(this->GetParent()); container->Add(newPart); //getControl().setRedraw(true); } void PartSashContainer::DerefPart(LayoutPart::Pointer sourcePart) { ILayoutContainer::Pointer container = sourcePart->GetContainer(); if (container != 0) { container->Remove(sourcePart); if (this->IsStackType(container) && container.Cast () != 0) { if (container->GetChildren().size() == 0) { LayoutPart::Pointer stack = container.Cast (); this->Remove(stack); stack->Dispose(); } } } } std::size_t PartSashContainer::GetVisibleChildrenCount( ILayoutContainer::Pointer container) { // Treat null as an empty container if (container == 0) { return 0; } ILayoutContainer::ChildrenType children = container->GetChildren(); std::size_t count = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { count++; } } return count; } float PartSashContainer::GetDockingRatio(Object::Pointer /*dragged*/, ILayoutContainer::Pointer /*target*/) { return 0.5f; } void PartSashContainer::DescribeLayout(QString& buf) const { if (root == 0) { return; } // if (isZoomed()) // { // buf.append("zoomed "); //$NON-NLS-1$ // root.describeLayout(buf); // } // else { buf.append("layout "); //$NON-NLS-1$ root->DescribeLayout(buf); } } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative) { if (child == 0) { return; } if (relative != 0 && !this->IsChild(relative)) { return; } if (relationship < IPageLayout::LEFT || relationship > IPageLayout::BOTTOM) { relationship = IPageLayout::LEFT; } // store info about relative positions RelationshipInfo info; info.part = child; info.relationship = relationship; info.left = left; info.right = right; info.relative = relative; this->AddChild(info); } bool PartSashContainer::AllowsAutoFocus() { return true; } void PartSashContainer::StartDeferringEvents() { LayoutPart::StartDeferringEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(true); } } void PartSashContainer::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(false); } } void PartSashContainer::TestInvariants() { LayoutPart::TestInvariants(); // If we have a parent container, ensure that we are displaying the zoomed appearance iff // our parent is zoomed in on us // if (this->GetContainer() != 0) // { // Assert.isTrue((getZoomedPart() != null) == (getContainer().childIsZoomed( // this))); // } ILayoutContainer::ChildrenType childArray = this->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = childArray.begin(); iter != childArray.end(); ++iter) { (*iter)->TestInvariants(); } // If we're zoomed, ensure that we're actually zoomed into one of our children // if (isZoomed()) // { // Assert.isTrue(children.contains(zoomedPart)); // } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPersistentState.h b/Plugins/org.blueberry.ui.qt/src/internal/berryPersistentState.h index 030c8e1a4c..c2db59b189 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPersistentState.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPersistentState.h @@ -1,98 +1,102 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYPERSISTENTSTATE_H #define BERRYPERSISTENTSTATE_H #include "berryState.h" +#include -namespace berry { +namespace mitk +{ + class IPreferences; +} -struct IPreferences; +namespace berry { /** *

* This is a state that can be made persistent. A state is persisted to a * preference store. *

*

* Clients may extend this class. *

* * @since 3.2 */ class PersistentState : public State { public: berryObjectMacro(berry::PersistentState); PersistentState(); /** * Loads this state from the preference store, given the location at which * to look. This method must be symmetric with a call to * {@link #save(IPreferenceStore, String)}. * * @param store * The store from which to read; must not be null. * @param preferenceKey * The key at which the state is stored; must not be * null. */ - virtual void Load(const SmartPointer& store, - const QString& preferenceKey) = 0; + virtual void Load(const mitk::IPreferences* store, + const std::string& preferenceKey) = 0; /** * Saves this state to the preference store, given the location at which to * write. This method must be symmetric with a call to * {@link #load(IPreferenceStore, String)}. * * @param store * The store to which the state should be written; must not be * null. * @param preferenceKey * The key at which the state should be stored; must not be * null. */ - virtual void Save(const SmartPointer& store, - const QString& preferenceKey) = 0; + virtual void Save(mitk::IPreferences* store, + const std::string& preferenceKey) = 0; /** * Sets whether this state should be persisted. * * @param persisted * Whether this state should be persisted. */ virtual void SetShouldPersist(bool persisted); /** * Whether this state should be persisted. Subclasses should check this * method before loading or saving. * * @return true if this state should be persisted; * false otherwise. */ virtual bool ShouldPersist(); private: /** * Whether this state should be persisted. */ bool persisted; }; } #endif // BERRYPERSISTENTSTATE_H diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp index c97d8c4d53..83403abed2 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.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 "berryPerspectiveRegistry.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" #include "berryPreferenceConstants.h" #include "berryPerspective.h" #include "berryPerspectiveRegistryReader.h" #include "berryPlatformUI.h" #include "handlers/berryClosePerspectiveHandler.h" -#include "berryIPreferencesService.h" -#include "berryIBerryPreferences.h" #include "berryIExtension.h" #include "berryIExtensionTracker.h" +#include +#include + namespace berry { const QString PerspectiveRegistry::EXT = "_persp.xml"; const QString PerspectiveRegistry::ID_DEF_PERSP = "PerspectiveRegistry.DEFAULT_PERSP"; const QString PerspectiveRegistry::PERSP = "_persp"; const char PerspectiveRegistry::SPACE_DELIMITER = ' '; class PerspectiveRegistry::PreferenceChangeListener { PerspectiveRegistry* m_Registry; public: PreferenceChangeListener(PerspectiveRegistry* registry) : m_Registry(registry) {} - void PropertyChange(const IBerryPreferences::ChangeEvent& event) + void PropertyChange(const mitk::IPreferences::ChangeEvent& event) { /* * To ensure that no custom perspective definitions are * deleted when preferences are imported, merge old and new * values */ - if (event.GetProperty().endsWith(PERSP)) + if (QString::fromStdString(event.GetProperty()).endsWith(PERSP)) { /* A Perspective is being changed, merge */ this->MergePerspectives(event); } else if (event.GetProperty() == PreferenceConstants::PERSPECTIVES) { /* The list of perpsectives is being changed, merge */ UpdatePreferenceList(event.GetSource()); } } - void MergePerspectives(const IBerryPreferences::ChangeEvent& event) + void MergePerspectives(const mitk::IPreferences::ChangeEvent& event) { - IBerryPreferences* store = event.GetSource(); - if (event.GetNewValue().isNull() || - event.GetNewValue().isEmpty()) + auto* store = event.GetSource(); + if (event.GetNewValue().empty()) { /* * Perpsective is being removed; if the user has deleted or * reverted a custom perspective, let the change pass * through. Otherwise, restore the custom perspective entry */ // Find the matching descriptor in the registry QList perspectiveList = m_Registry->GetPerspectives(); for (int i = 0; i < perspectiveList.size(); i++) { QString id = perspectiveList[i]->GetId(); - if (event.GetProperty() == id + PERSP) + const auto property = QString::fromStdString(event.GetProperty()); + if (property == id + PERSP) { // found // descriptor // see if the perspective has been flagged for // reverting or deleting if (!m_Registry->perspToRemove.contains(id)) { // restore - store->Put(id + PERSP, event.GetOldValue()); + store->Put((id + PERSP).toStdString(), event.GetOldValue()); } else { // remove element from the list m_Registry->perspToRemove.removeAll(id); } } } } - else if ((event.GetOldValue().isNull() || event.GetOldValue().isEmpty())) + else if (event.GetOldValue().empty()) { /* * New perspective is being added, update the * perspectiveRegistry to contain the new custom perspective */ - - QString id = event.GetProperty().left(event.GetProperty().lastIndexOf(PERSP)); + auto property = QString::fromStdString(event.GetProperty()); + QString id = property.left(property.lastIndexOf(PERSP)); if (m_Registry->FindPerspectiveWithId(id).IsNull()) { // perspective does not already exist in registry, add // it PerspectiveDescriptor::Pointer desc(new PerspectiveDescriptor( QString::null, QString::null, PerspectiveDescriptor::Pointer())); std::stringstream reader; - std::string xmlStr = event.GetNewValue().toStdString(); + std::string xmlStr = event.GetNewValue(); reader.str(xmlStr); try { XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(reader); desc->RestoreState(memento); m_Registry->AddPerspective(desc); } catch (const WorkbenchException& e) { //m_Registry->UnableToLoadPerspective(e.getStatus()); m_Registry->UnableToLoadPerspective(e.what()); } } } /* If necessary, add to the list of perspectives */ this->UpdatePreferenceList(store); } - void UpdatePreferenceList(IBerryPreferences* store) + void UpdatePreferenceList(mitk::IPreferences* store) { QList perspectiveList = m_Registry->GetPerspectives(); QStringList perspBuffer; for (int i = 0; i < perspectiveList.size(); i++) { PerspectiveDescriptor::Pointer desc = perspectiveList[i].Cast(); if (m_Registry->HasCustomDefinition(desc)) { perspBuffer.push_back(desc->GetId()); } } - store->Put(PreferenceConstants::PERSPECTIVES, perspBuffer.join(QString(SPACE_DELIMITER))); + store->Put(PreferenceConstants::PERSPECTIVES, perspBuffer.join(QString(SPACE_DELIMITER)).toStdString()); } }; PerspectiveRegistry::PerspectiveRegistry() : preferenceListener(new PreferenceChangeListener(this)) { IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker(); tracker->RegisterHandler(this, QString("org.blueberry.ui.perspectives")); - berry::IBerryPreferences::Pointer prefs = - WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences().Cast(); + mitk::IPreferences* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); prefs->OnPropertyChanged += - berry::MessageDelegate1( + mitk::MessageDelegate1( preferenceListener.data(), &PreferenceChangeListener::PropertyChange); } void PerspectiveRegistry::AddPerspective(PerspectiveDescriptor::Pointer desc) { if (desc == 0) { return; } this->Add(desc); } void PerspectiveRegistry::RevertPerspectives( const QList& perspToRevert) { // indicate that the user is removing these perspectives for (QList::const_iterator iter = perspToRevert.begin(); iter != perspToRevert.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } } void PerspectiveRegistry::DeletePerspectives( const QList& perspToDelete) { for (QList::const_iterator iter = perspToDelete.begin(); iter != perspToDelete.end(); ++iter) { this->DeletePerspective(*iter); } } void PerspectiveRegistry::DeletePerspective(IPerspectiveDescriptor::Pointer in) { PerspectiveDescriptor::Pointer desc = in.Cast(); // Don't delete predefined perspectives if (!desc->IsPredefined()) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } } void PerspectiveRegistry::Load() { // Load the registries. this->LoadPredefined(); this->LoadCustom(); // Get default perspective. // Get it from the R1.0 dialog settings first. Fixes bug 17039 // IDialogSettings dialogSettings = // WorkbenchPlugin.getDefault() .getDialogSettings(); // QString str = dialogSettings.get(ID_DEF_PERSP); // if (str != null && str.length() > 0) // { // this->SetDefaultPerspective(str); // dialogSettings.put(ID_DEF_PERSP, ""); //$NON-NLS-1$ // } this->VerifyDefaultPerspective(); } void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc, XMLMemento* memento) { - IPreferencesService* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); // Save it to the preference store. std::stringstream ss; memento->Save(ss); - prefs->GetSystemPreferences()->Put(desc->GetId() + PERSP, QString::fromStdString(ss.str())); + prefs->GetSystemPreferences()->Put((desc->GetId() + PERSP).toStdString(), ss.str()); } IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& id) { std::stringstream ss; - IPreferencesService* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - std::string xmlString = prefs->GetSystemPreferences()->Get(id + PERSP, QString::null).toStdString(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + const auto xmlString = prefs->GetSystemPreferences()->Get((id + PERSP).toStdString(), ""); if (!xmlString.empty()) { // defined in store ss.str(xmlString); } XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); return memento; } bool PerspectiveRegistry::ValidateLabel(const QString& label) { return !label.trimmed().isEmpty(); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithId(const QString& id) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetId() == id) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return null; // } return desc; } } return IPerspectiveDescriptor::Pointer(nullptr); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithLabel( const QString& label) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetLabel() == label) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return 0; // } return desc; } } return IPerspectiveDescriptor::Pointer(nullptr); } QString PerspectiveRegistry::GetDefaultPerspective() { return defaultPerspID; } QList PerspectiveRegistry::GetPerspectives() { // Collection descs = WorkbenchActivityHelper.restrictCollection(perspectives, // new ArrayList()); // return (IPerspectiveDescriptor[]) descs.toArray( // new IPerspectiveDescriptor[descs.size()]); QList result; for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { result.push_back(iter->Cast()); } return result; } void PerspectiveRegistry::SetDefaultPerspective(const QString& id) { IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { defaultPerspID = id; //TODO Preferences // PrefUtil.getAPIPreferenceStore().setValue( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id); } } IPerspectiveDescriptor::Pointer PerspectiveRegistry::CreatePerspective(const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Sanity check to avoid invalid or duplicate labels. if (!this->ValidateLabel(label)) { return IPerspectiveDescriptor::Pointer(nullptr); } if (this->FindPerspectiveWithLabel(label) != 0) { return IPerspectiveDescriptor::Pointer(nullptr); } // Calculate ID. QString id(label); id = id.replace(' ', '_').trimmed(); // Create descriptor. PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, label, originalDescriptor.Cast())); this->Add(desc); return IPerspectiveDescriptor::Pointer(static_cast(desc.GetPointer())); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Check for invalid labels if (label == "" || label.trimmed().isEmpty()) { throw Poco::InvalidArgumentException(); } // Check for duplicates IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { throw Poco::InvalidArgumentException(); } // Create descriptor. desc = new PerspectiveDescriptor(id, label, originalDescriptor.Cast()); this->Add(desc.Cast()); return desc; } void PerspectiveRegistry::RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) { PerspectiveDescriptor::Pointer desc = perspToRevert.Cast(); perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } PerspectiveRegistry::~PerspectiveRegistry() { // PlatformUI::GetWorkbench()->GetExtensionTracker()->UnregisterHandler(this); // WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences()->RemovePropertyChangeListener( // preferenceListener); } void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc) { // remove the entry from the preference store. - IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - store->GetSystemPreferences()->Remove(desc->GetId() + PERSP); + store->GetSystemPreferences()->Remove((desc->GetId() + PERSP).toStdString()); } bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const { - IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - return store->GetSystemPreferences()->Keys().contains(desc->GetId() + PERSP); + auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + const auto keys = store->GetSystemPreferences()->Keys(); + return std::find(keys.begin(), keys.end(), (desc->GetId() + PERSP).toStdString()) != keys.end(); } void PerspectiveRegistry::Add(PerspectiveDescriptor::Pointer desc) { perspectives.push_back(desc); IConfigurationElement::Pointer element = desc->GetConfigElement(); if (element.IsNotNull()) { PlatformUI::GetWorkbench()->GetExtensionTracker()->RegisterObject( element->GetDeclaringExtension(), desc, IExtensionTracker::REF_WEAK); } } void PerspectiveRegistry::InternalDeletePerspective(PerspectiveDescriptor::Pointer desc) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } void PerspectiveRegistry::LoadCustom() { QScopedPointer reader; /* Get the entries from the Preference store */ - IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - - IPreferences::Pointer prefs = store->GetSystemPreferences(); + auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* prefs = store->GetSystemPreferences(); /* Get the space-delimited list of custom perspective ids */ - QString customPerspectives = prefs->Get(PreferenceConstants::PERSPECTIVES, QString::null); + QString customPerspectives = QString::fromStdString(prefs->Get(PreferenceConstants::PERSPECTIVES, "")); QStringList perspectivesList = customPerspectives.split(' ', QString::SkipEmptyParts); for (int i = 0; i < perspectivesList.size(); i++) { try { - std::string xmlString = prefs->Get(perspectivesList[i] + PERSP, QString::null).toStdString(); + const auto xmlString = prefs->Get((perspectivesList[i] + PERSP).toStdString(), ""); if (!xmlString.empty()) { reader.reset(new std::stringstream(xmlString)); //reader->exceptions(std::ios_base::failbit); } else { throw WorkbenchException(QString("Description of '%1' perspective could not be found.").arg(perspectivesList[i])); } // Restore the layout state. XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(*reader); PerspectiveDescriptor::Pointer newPersp(new PerspectiveDescriptor( QString::null, QString::null, PerspectiveDescriptor::Pointer(nullptr))); newPersp->RestoreState(memento); QString id = newPersp->GetId(); IPerspectiveDescriptor::Pointer oldPersp = FindPerspectiveWithId(id); if (oldPersp.IsNull()) { Add(newPersp); } } catch (const std::ios_base::failure&) { UnableToLoadPerspective(QString::null); } catch (const WorkbenchException& e) { UnableToLoadPerspective(e.message()); } } // // Get the entries from files, if any // // if -data @noDefault specified the state location may not be // // initialized // IPath path = WorkbenchPlugin.getDefault().getDataLocation(); // if (path == null) // { // return; // } // File folder = path.toFile(); // if (folder.isDirectory()) // { // File[] fileList = folder.listFiles(); // int nSize = fileList.length; // for (int nX = 0; nX < nSize; nX++) // { // File file = fileList[nX]; // if (file.getName().endsWith(EXT)) // { // // get the memento // InputStream stream = null; // try // { // stream = new FileInputStream(file); // reader = new BufferedReader(new InputStreamReader(stream, "utf-8")); //$NON-NLS-1$ // // Restore the layout state. // XMLMemento memento = XMLMemento.createReadRoot(reader); // PerspectiveDescriptor newPersp = // new PerspectiveDescriptor(null, null, null); // newPersp.restoreState(memento); // IPerspectiveDescriptor oldPersp = findPerspectiveWithId( // newPersp .getId()); // if (oldPersp == null) // { // add(newPersp); // } // // save to the preference store // saveCustomPersp(newPersp, memento); // // delete the file // file.delete(); // reader.close(); // stream.close(); // } catch (IOException e) // { // unableToLoadPerspective(null); // } catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // } // } } void PerspectiveRegistry::UnableToLoadPerspective(const QString& status) { QString msg = "Unable to load perspective"; if (status == "") { WorkbenchPlugin::Log(msg); //IStatus errStatus = // new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } else { WorkbenchPlugin::Log(status + ": " + msg); //IStatus errStatus = StatusUtil.newStatus(status, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } } void PerspectiveRegistry::LoadPredefined() { PerspectiveRegistryReader reader(this); reader.ReadPerspectives(Platform::GetExtensionRegistry()); } void PerspectiveRegistry::VerifyDefaultPerspective() { // Step 1: Try current defPerspId value. IPerspectiveDescriptor::Pointer desc; if (defaultPerspID != "") { desc = this->FindPerspectiveWithId(defaultPerspID); } if (desc != 0) { return; } // Step 2. Read default value. //TODO Preferences // QString str = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID); // if (str != null && str.length() > 0) // { // desc = this->FindPerspectiveWithId(str); // } // if (desc != 0) // { // defaultPerspID = str; // return; // } // Step 3. Use application-specific default defaultPerspID = Workbench::GetInstance()->GetDefaultPerspectiveId(); } void PerspectiveRegistry::RemoveExtension(const IExtension::Pointer& /*source*/, const QList& objects) { for (int i = 0; i < objects.size(); i++) { if (PerspectiveDescriptor::Pointer desc = objects[i].Cast()) { // close the perspective in all windows QList windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (int w = 0; w < windows.size(); ++w) { IWorkbenchWindow::Pointer window = windows[w]; QList pages = window->GetPages(); for (int p = 0; p < pages.size(); ++p) { WorkbenchPage::Pointer page = pages[p].Cast(); ClosePerspectiveHandler::ClosePerspective(page, page->FindPerspective(desc)); } } // ((Workbench)PlatformUI.getWorkbench()).getPerspectiveHistory().removeItem(desc); this->InternalDeletePerspective(desc); } } } void PerspectiveRegistry::AddExtension(IExtensionTracker* /*tracker*/, const IExtension::Pointer& addedExtension) { QList addedElements = addedExtension->GetConfigurationElements(); for (int i = 0; i < addedElements.size(); i++) { PerspectiveRegistryReader reader(this); reader.ReadElement(addedElements[i]); } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h index 1bf177fa69..9599d8bb08 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h @@ -1,223 +1,218 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYPERSPECTIVEREGISTRY_H_ #define BERRYPERSPECTIVEREGISTRY_H_ #include "berryIPerspectiveRegistry.h" #include "berryIExtensionChangeHandler.h" #include "berryPerspectiveDescriptor.h" #include namespace berry { class XMLMemento; /** * Perspective registry. */ class PerspectiveRegistry : public IPerspectiveRegistry, public IExtensionChangeHandler { friend class PerspectiveDescriptor; private: QString defaultPerspID; static const QString EXT; // = "_persp.xml"; static const QString ID_DEF_PERSP; // = "PerspectiveRegistry.DEFAULT_PERSP"; static const QString PERSP; // = "_persp"; static const char SPACE_DELIMITER; // = ' '; QList perspectives; // keep track of the perspectives the user has selected to remove or revert QList perspToRemove; class PreferenceChangeListener; QScopedPointer preferenceListener; void AddExtension(IExtensionTracker* tracker, const SmartPointer& extension) override; void RemoveExtension(const SmartPointer& extension, const QList >& objects) override; public: /** * Construct a new registry. */ PerspectiveRegistry(); /** * Adds a perspective. This is typically used by the reader. * * @param desc */ void AddPerspective(PerspectiveDescriptor::Pointer desc); /** * Reverts a list of perspectives back to the plugin definition * * @param perspToRevert */ void RevertPerspectives(const QList& perspToRevert); /** * Deletes a list of perspectives * * @param perspToDelete */ void DeletePerspectives(const QList& perspToDelete); /** * Delete a perspective. Has no effect if the perspective is defined in an * extension. * * @param in */ void DeletePerspective(IPerspectiveDescriptor::Pointer in) override; /** * Loads the registry. */ void Load(); /** * Saves a custom perspective definition to the preference store. * * @param desc * the perspective * @param memento * the memento to save to * @throws IOException */ void SaveCustomPersp(PerspectiveDescriptor::Pointer desc, XMLMemento* memento); /** * Gets the Custom perspective definition from the preference store. * * @param id * the id of the perspective to find * @return IMemento a memento containing the perspective description * * @throws WorkbenchException * @throws IOException */ IMemento::Pointer GetCustomPersp(const QString& id); /** * Return true if a label is valid. This checks only the * given label in isolation. It does not check whether the given label is * used by any existing perspectives. * * @param label * the label to test * @return whether the label is valid */ bool ValidateLabel(const QString& label); /** * Dispose the receiver. */ ~PerspectiveRegistry() override; // ---------- IPerspectiveRegistry methods ------------ IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const QString& id) override; IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const QString& label) override; QString GetDefaultPerspective() override; QList GetPerspectives() override; void SetDefaultPerspective(const QString& id) override; IPerspectiveDescriptor::Pointer CreatePerspective(const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) override; IPerspectiveDescriptor::Pointer ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) override; void RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) override; protected: /** * Removes the custom definition of a perspective from the preference store * * @param desc */ void DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc); /** * Method hasCustomDefinition. * * @param desc */ bool HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const; private: - /** - * Initialize the preference change listener. - */ - void InitializePreferenceChangeListener(); - /** * @param desc */ void Add(PerspectiveDescriptor::Pointer desc); /** * Delete a perspective. This will remove perspectives defined in * extensions. * * @param desc * the perspective to delete */ void InternalDeletePerspective(PerspectiveDescriptor::Pointer desc); /** * Read children from the file system. */ void LoadCustom(); /** * @param status */ void UnableToLoadPerspective(const QString& status); /** * Read children from the plugin registry. */ void LoadPredefined(); /** * Verifies the id of the default perspective. If the default perspective is * invalid use the workbench default. */ void VerifyDefaultPerspective(); }; } #endif /* BERRYPERSPECTIVEREGISTRY_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.cpp index aa97f87950..67ef7d1587 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.cpp @@ -1,60 +1,60 @@ /*============================================================================ 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 "berryPreferenceConstants.h" namespace berry { -const QString PreferenceConstants::OPEN_ON_SINGLE_CLICK = "OPEN_ON_SINGLE_CLICK"; -const QString PreferenceConstants::SELECT_ON_HOVER = "SELECT_ON_HOVER"; -const QString PreferenceConstants::OPEN_AFTER_DELAY = "OPEN_AFTER_DELAY"; -const QString PreferenceConstants::COLOR_ICONS = "COLOR_ICONS"; -const QString PreferenceConstants::EDITORS = "editors"; -const QString PreferenceConstants::RESOURCES = "resourcetypes"; -const QString PreferenceConstants::PERSPECTIVES = "perspectives"; -const QString PreferenceConstants::REUSE_EDITORS = "REUSE_OPEN_EDITORS"; -const QString PreferenceConstants::REUSE_DIRTY_EDITORS = "REUSE_DIRTY_EDITORS"; -const QString PreferenceConstants::REUSE_EDITORS_BOOLEAN = "REUSE_OPEN_EDITORS_BOOLEAN"; -const QString PreferenceConstants::RECENT_FILES = "RECENT_FILES"; -const QString PreferenceConstants::OPEN_VIEW_MODE = "OPEN_VIEW_MODE"; +const std::string PreferenceConstants::OPEN_ON_SINGLE_CLICK = "OPEN_ON_SINGLE_CLICK"; +const std::string PreferenceConstants::SELECT_ON_HOVER = "SELECT_ON_HOVER"; +const std::string PreferenceConstants::OPEN_AFTER_DELAY = "OPEN_AFTER_DELAY"; +const std::string PreferenceConstants::COLOR_ICONS = "COLOR_ICONS"; +const std::string PreferenceConstants::EDITORS = "editors"; +const std::string PreferenceConstants::RESOURCES = "resourcetypes"; +const std::string PreferenceConstants::PERSPECTIVES = "perspectives"; +const std::string PreferenceConstants::REUSE_EDITORS = "REUSE_OPEN_EDITORS"; +const std::string PreferenceConstants::REUSE_DIRTY_EDITORS = "REUSE_DIRTY_EDITORS"; +const std::string PreferenceConstants::REUSE_EDITORS_BOOLEAN = "REUSE_OPEN_EDITORS_BOOLEAN"; +const std::string PreferenceConstants::RECENT_FILES = "RECENT_FILES"; +const std::string PreferenceConstants::OPEN_VIEW_MODE = "OPEN_VIEW_MODE"; const int PreferenceConstants::OVM_EMBED = 0; const int PreferenceConstants::OVM_FAST = 1; const int PreferenceConstants::OVM_FLOAT = 2; -const QString PreferenceConstants::OPEN_PERSP_MODE = "OPEN_PERSPECTIVE_MODE"; +const std::string PreferenceConstants::OPEN_PERSP_MODE = "OPEN_PERSPECTIVE_MODE"; const int PreferenceConstants::OPM_ACTIVE_PAGE = 0; const int PreferenceConstants::OPM_NEW_WINDOW = 2; -const QString PreferenceConstants::ENABLED_DECORATORS = "ENABLED_DECORATORS"; -const QString PreferenceConstants::STICKY_CYCLE = "STICKY_CYCLE"; -const QString PreferenceConstants::PLUGINS_NOT_ACTIVATED_ON_STARTUP = "PLUGINS_NOT_ACTIVATED_ON_STARTUP"; +const std::string PreferenceConstants::ENABLED_DECORATORS = "ENABLED_DECORATORS"; +const std::string PreferenceConstants::STICKY_CYCLE = "STICKY_CYCLE"; +const std::string PreferenceConstants::PLUGINS_NOT_ACTIVATED_ON_STARTUP = "PLUGINS_NOT_ACTIVATED_ON_STARTUP"; const char PreferenceConstants::SEPARATOR = ';'; -const QString PreferenceConstants::DEFAULT_EDITORS = "defaultEditors"; -const QString PreferenceConstants::DEFAULT_EDITORS_CACHE = "defaultEditorsCache"; -const QString PreferenceConstants::EDITOR_TAB_WIDTH = "EDITOR_TAB_WIDTH"; -const QString PreferenceConstants::EDITORLIST_PULLDOWN_ACTIVE = "EDITORLIST_PULLDOWN_ACTIVE"; -const QString PreferenceConstants::EDITORLIST_SELECTION_SCOPE = "EDITORLIST_SELECTION_SCOPE"; +const std::string PreferenceConstants::DEFAULT_EDITORS = "defaultEditors"; +const std::string PreferenceConstants::DEFAULT_EDITORS_CACHE = "defaultEditorsCache"; +const std::string PreferenceConstants::EDITOR_TAB_WIDTH = "EDITOR_TAB_WIDTH"; +const std::string PreferenceConstants::EDITORLIST_PULLDOWN_ACTIVE = "EDITORLIST_PULLDOWN_ACTIVE"; +const std::string PreferenceConstants::EDITORLIST_SELECTION_SCOPE = "EDITORLIST_SELECTION_SCOPE"; const int PreferenceConstants::EDITORLIST_SET_WINDOW_SCOPE = 0; const int PreferenceConstants::EDITORLIST_SET_PAGE_SCOPE = 1; const int PreferenceConstants::EDITORLIST_SET_TAB_GROUP_SCOPE = 2; -const QString PreferenceConstants::EDITORLIST_SORT_CRITERIA = "EDITORLIST_SORT_CRITERIA"; +const std::string PreferenceConstants::EDITORLIST_SORT_CRITERIA = "EDITORLIST_SORT_CRITERIA"; const int PreferenceConstants::EDITORLIST_NAME_SORT = 0; const int PreferenceConstants::EDITORLIST_MRU_SORT = 1; -const QString PreferenceConstants::EDITORLIST_DISPLAY_FULL_NAME = "EDITORLIST_DISPLAY_FULL_NAME"; -const QString PreferenceConstants::OVERRIDE_PRESENTATION = "overridepresentation"; //$ -const QString PreferenceConstants::KEYS_PREFERENCE_SELECTED_TAB = "KEYS_PREFERENCE_SELECTED_TAB"; -const QString PreferenceConstants::MULTI_KEY_ASSIST = "MULTI_KEY_ASSIST"; -const QString PreferenceConstants::MULTI_KEY_ASSIST_TIME = "MULTI_KEY_ASSIST_TIME"; -const QString PreferenceConstants::USE_IPERSISTABLE_EDITORS = "USE_IPERSISTABLE_EDITORS"; -const QString PreferenceConstants::RUN_IN_BACKGROUND = "RUN_IN_BACKGROUND"; -const QString PreferenceConstants::SHOULD_PROMPT_FOR_ENABLEMENT = "shouldPromptForEnablement"; +const std::string PreferenceConstants::EDITORLIST_DISPLAY_FULL_NAME = "EDITORLIST_DISPLAY_FULL_NAME"; +const std::string PreferenceConstants::OVERRIDE_PRESENTATION = "overridepresentation"; //$ +const std::string PreferenceConstants::KEYS_PREFERENCE_SELECTED_TAB = "KEYS_PREFERENCE_SELECTED_TAB"; +const std::string PreferenceConstants::MULTI_KEY_ASSIST = "MULTI_KEY_ASSIST"; +const std::string PreferenceConstants::MULTI_KEY_ASSIST_TIME = "MULTI_KEY_ASSIST_TIME"; +const std::string PreferenceConstants::USE_IPERSISTABLE_EDITORS = "USE_IPERSISTABLE_EDITORS"; +const std::string PreferenceConstants::RUN_IN_BACKGROUND = "RUN_IN_BACKGROUND"; +const std::string PreferenceConstants::SHOULD_PROMPT_FOR_ENABLEMENT = "shouldPromptForEnablement"; } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.h b/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.h index 5eba031827..567a50bfa1 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPreferenceConstants.h @@ -1,209 +1,209 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYPREFERENCECONSTANTS_H_ #define BERRYPREFERENCECONSTANTS_H_ -#include +#include namespace berry { /** * The PreferenceConstants are the internal constants used by the Workbench. */ struct PreferenceConstants { public: //Boolean: true; // = single click opens editor; false; // = double click opens it. - static const QString OPEN_ON_SINGLE_CLICK; // = "OPEN_ON_SINGLE_CLICK"; + static const std::string OPEN_ON_SINGLE_CLICK; // = "OPEN_ON_SINGLE_CLICK"; //Boolean: true; // = select on hover; - static const QString SELECT_ON_HOVER; // = "SELECT_ON_HOVER"; + static const std::string SELECT_ON_HOVER; // = "SELECT_ON_HOVER"; //Boolean: true; // = open after delay - static const QString OPEN_AFTER_DELAY; // = "OPEN_AFTER_DELAY"; + static const std::string OPEN_AFTER_DELAY; // = "OPEN_AFTER_DELAY"; //Do we show color icons in toolbars? - static const QString COLOR_ICONS; // = "COLOR_ICONS"; + static const std::string COLOR_ICONS; // = "COLOR_ICONS"; //mappings for type/extension to an editor - const static QString EDITORS; // = "editors"; + const static std::string EDITORS; // = "editors"; - const static QString RESOURCES; // = "resourcetypes"; + const static std::string RESOURCES; // = "resourcetypes"; //saving perspective layouts - const static QString PERSPECTIVES; // = "perspectives"; + const static std::string PERSPECTIVES; // = "perspectives"; // (int) If > 0, an editor will be reused once 'N' editors are opened. - static const QString REUSE_EDITORS; // = "REUSE_OPEN_EDITORS"; + static const std::string REUSE_EDITORS; // = "REUSE_OPEN_EDITORS"; //Boolean: true; // = replace dirty editor if no other editors to reuse // (prompt for save); // false; // = open a new editor if no other editors to resuse - static const QString REUSE_DIRTY_EDITORS; // = "REUSE_DIRTY_EDITORS"; + static const std::string REUSE_DIRTY_EDITORS; // = "REUSE_DIRTY_EDITORS"; //On/Off option for the two preceding options. - static const QString REUSE_EDITORS_BOOLEAN; // = "REUSE_OPEN_EDITORS_BOOLEAN"; + static const std::string REUSE_EDITORS_BOOLEAN; // = "REUSE_OPEN_EDITORS_BOOLEAN"; // (int) N recently viewed files will be listed in the File->Open Recent // menu. - static const QString RECENT_FILES; // = "RECENT_FILES"; + static const std::string RECENT_FILES; // = "RECENT_FILES"; // (integer) Mode for opening a view. - static const QString OPEN_VIEW_MODE; // = "OPEN_VIEW_MODE"; + static const std::string OPEN_VIEW_MODE; // = "OPEN_VIEW_MODE"; static const int OVM_EMBED; // = 0; static const int OVM_FAST; // = 1; static const int OVM_FLOAT; // = 2; // (int) Mode for opening a new perspective - static const QString OPEN_PERSP_MODE; // = "OPEN_PERSPECTIVE_MODE"; + static const std::string OPEN_PERSP_MODE; // = "OPEN_PERSPECTIVE_MODE"; static const int OPM_ACTIVE_PAGE; // = 0; // static const int OPM_NEW_PAGE; // = 1; static const int OPM_NEW_WINDOW; // = 2; //Identifier for enabled decorators - static const QString ENABLED_DECORATORS; // = "ENABLED_DECORATORS"; + static const std::string ENABLED_DECORATORS; // = "ENABLED_DECORATORS"; //Boolean: true; // = keep cycle part dialog open when keys released - static const QString STICKY_CYCLE; // = "STICKY_CYCLE"; + static const std::string STICKY_CYCLE; // = "STICKY_CYCLE"; //List of plugins but that extends "startup" extension point but are // overriden by the user. - //QString of plugin unique ids separated by ";" - static const QString PLUGINS_NOT_ACTIVATED_ON_STARTUP; // = "PLUGINS_NOT_ACTIVATED_ON_STARTUP"; + //std::string of plugin unique ids separated by ";" + static const std::string PLUGINS_NOT_ACTIVATED_ON_STARTUP; // = "PLUGINS_NOT_ACTIVATED_ON_STARTUP"; //Separator for PLUGINS_NOT_ACTIVATED_ON_STARTUP static const char SEPARATOR; // = ';'; //Preference key for default editors - const static QString DEFAULT_EDITORS; // = "defaultEditors"; + const static std::string DEFAULT_EDITORS; // = "defaultEditors"; //Preference key for default editors - const static QString DEFAULT_EDITORS_CACHE; // = "defaultEditorsCache"; + const static std::string DEFAULT_EDITORS_CACHE; // = "defaultEditorsCache"; //Tab width; // = tab height * scalar value - const static QString EDITOR_TAB_WIDTH; // = "EDITOR_TAB_WIDTH"; + const static std::string EDITOR_TAB_WIDTH; // = "EDITOR_TAB_WIDTH"; //Boolean: true; // = show Editors drop down button on CTabFolder - static const QString EDITORLIST_PULLDOWN_ACTIVE; // = "EDITORLIST_PULLDOWN_ACTIVE"; + static const std::string EDITORLIST_PULLDOWN_ACTIVE; // = "EDITORLIST_PULLDOWN_ACTIVE"; // Selection scope for EditorList - static const QString EDITORLIST_SELECTION_SCOPE; // = "EDITORLIST_SELECTION_SCOPE"; + static const std::string EDITORLIST_SELECTION_SCOPE; // = "EDITORLIST_SELECTION_SCOPE"; static const int EDITORLIST_SET_WINDOW_SCOPE; // = 0; static const int EDITORLIST_SET_PAGE_SCOPE; // = 1; static const int EDITORLIST_SET_TAB_GROUP_SCOPE; // = 2; // Sort criteria for EditorList - static const QString EDITORLIST_SORT_CRITERIA; // = "EDITORLIST_SORT_CRITERIA"; + static const std::string EDITORLIST_SORT_CRITERIA; // = "EDITORLIST_SORT_CRITERIA"; static const int EDITORLIST_NAME_SORT; // = 0; static const int EDITORLIST_MRU_SORT; // = 1; /** * Boolean; true; // = EditorList displays full path */ - static const QString EDITORLIST_DISPLAY_FULL_NAME; // = "EDITORLIST_DISPLAY_FULL_NAME"; + static const std::string EDITORLIST_DISPLAY_FULL_NAME; // = "EDITORLIST_DISPLAY_FULL_NAME"; /** * Workbench preference id for determining whether the user has chosen to * override some of the settings in the current presentation. *

* The default value for this preference is: false (prompt) *

* */ - static const QString OVERRIDE_PRESENTATION; // = "overridepresentation"; //$ + static const std::string OVERRIDE_PRESENTATION; // = "overridepresentation"; //$ /** *

* The key for the preference indicating which tab is selected in the keys * preference page when last okay was pressed. This value should never * really be directly edited by a user. *

*

* This preference is an int value. The default value is * 0. *

* */ - static const QString KEYS_PREFERENCE_SELECTED_TAB; // = "KEYS_PREFERENCE_SELECTED_TAB"; + static const std::string KEYS_PREFERENCE_SELECTED_TAB; // = "KEYS_PREFERENCE_SELECTED_TAB"; /** *

* The key for the preference indicating whether multi-stroke key sequences * should provide assistance to the user. This means that if the user pauses * after pressing the first key, a window will open showing the possible * completions. *

*

* This preference is a boolean value. The default value is * false. *

* */ - static const QString MULTI_KEY_ASSIST; // = "MULTI_KEY_ASSIST"; + static const std::string MULTI_KEY_ASSIST; // = "MULTI_KEY_ASSIST"; /** *

* The key for the preference indicating how long the assist window should * wait before opening. This is a value in milliseconds -- from the time the * first key in a multi-key is received by the system, to the time the * assist window should appear. *

*

* This preference is an int value. The default value is * 1000. *

*/ - static const QString MULTI_KEY_ASSIST_TIME; // = "MULTI_KEY_ASSIST_TIME"; + static const std::string MULTI_KEY_ASSIST_TIME; // = "MULTI_KEY_ASSIST_TIME"; /** * Workbench preference to use the new IPersistableEditor interface * throughout the workbench new editor/open editor calls. */ - static const QString USE_IPERSISTABLE_EDITORS; // = "USE_IPERSISTABLE_EDITORS"; + static const std::string USE_IPERSISTABLE_EDITORS; // = "USE_IPERSISTABLE_EDITORS"; /** * Preference to show user jobs in a dialog. */ - static const QString RUN_IN_BACKGROUND; // = "RUN_IN_BACKGROUND"; + static const std::string RUN_IN_BACKGROUND; // = "RUN_IN_BACKGROUND"; /** * Workbench preference id for determining whether the user will be prompted * for activity enablement. If this is false then activities are enabled * automatically. If it is true, then the user is only prompted for * activities that they have not already declared a disinterest in via the * prompt dialog. *

* The default value for this preference is: true (prompt) *

*/ - static const QString SHOULD_PROMPT_FOR_ENABLEMENT; // = "shouldPromptForEnablement"; + static const std::string SHOULD_PROMPT_FOR_ENABLEMENT; // = "shouldPromptForEnablement"; }; } #endif /* BERRYPREFERENCECONSTANTS_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp index ae564734bc..bf38e33d11 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp @@ -1,327 +1,328 @@ /*============================================================================ 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 "berryQtShowViewDialog.h" #include -#include #include #include "berryWorkbenchPlugin.h" #include "berryXMLMemento.h" #include #include +#include + namespace berry { static const QString TAG_SHOWVIEWDIALOG = "ShowViewDialog"; static const QString TAG_CATEGORY = "category"; static const QString TAG_SELECTION = "selection"; static const QString TAG_GEOMETRY = "geometry"; class ViewFilterProxyModel : public QSortFilterProxyModel { public: ViewFilterProxyModel(QObject* parent = nullptr) : QSortFilterProxyModel(parent) , m_FilterOnKeywords(true) { this->setFilterCaseSensitivity(Qt::CaseInsensitive); } bool filterOnKeywords() const { return m_FilterOnKeywords; } void setFilterOnKeywords(bool filterOnKeywords) { if (m_FilterOnKeywords != filterOnKeywords) { m_FilterOnKeywords = filterOnKeywords; this->filterChanged(); } } protected: bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override { QRegExp regExp = filterRegExp(); if (!regExp.isValid() || regExp.isEmpty()) return true; QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent); QStringList keywords; if (m_FilterOnKeywords) { keywords = sourceModel()->data(sourceIndex, ViewTreeModel::Keywords).toStringList(); } else { if (sourceModel()->hasChildren(sourceIndex)) { // this is a category item int numChildren = sourceModel()->rowCount(sourceIndex); for (int i = 0; i < numChildren; ++i) { keywords.push_back(sourceModel()->data(sourceIndex.child(i, 0)).toString()); } } else { // this is a view item keywords.push_back(sourceModel()->data(sourceIndex).toString()); } } for(auto& keyword : keywords) { if (keyword.contains(regExp)) return true; } return false; } private: bool m_FilterOnKeywords; }; QtShowViewDialog::QtShowViewDialog(const IWorkbenchWindow* window, IViewRegistry* registry, QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) , m_Window(window) , m_ViewReg(registry) , m_FilterModel(nullptr) { m_UserInterface.setupUi(this); m_UserInterface.m_TreeView->header()->setVisible(false); m_UserInterface.m_TreeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_FilterModel = new ViewFilterProxyModel(this); auto sourceModel = new ViewTreeModel(window, m_FilterModel); m_FilterModel->setSourceModel(sourceModel); m_UserInterface.m_TreeView->setModel(m_FilterModel); connect(m_UserInterface.m_Filter, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString))); connect(m_UserInterface.m_TreeView, SIGNAL(clicked(QModelIndex)), this, SLOT(setDescription(QModelIndex))); connect(m_UserInterface.m_TreeView, SIGNAL(collapsed(QModelIndex)), this, SLOT(categoryCollapsed(QModelIndex))); connect(m_UserInterface.m_TreeView, SIGNAL(expanded(QModelIndex)), this, SLOT(categoryExpanded(QModelIndex))); connect(m_UserInterface.m_TreeView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); connect(m_UserInterface.m_TreeView, SIGNAL(activated(QModelIndex)), this, SLOT(accept())); connect(m_UserInterface.m_TreeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection))); connect(m_UserInterface.m_KeywordFilter, SIGNAL(clicked(bool)), this, SLOT(enableKeywordFilter(bool))); this->RestoreState(); m_UserInterface.m_Filter->selectAll(); this->UpdateButtons(); } void QtShowViewDialog::setDescription(const QModelIndex& index) { QString description = m_UserInterface.m_TreeView->model()->data(index, Qt::WhatsThisRole).toString(); m_UserInterface.m_Description->setText(description); } void QtShowViewDialog::enableKeywordFilter(bool enable) { m_FilterModel->setFilterOnKeywords(enable); this->RestoreExpandedState(); } void QtShowViewDialog::setFilter(const QString& filter) { m_FilterModel->setFilterWildcard(filter); this->RestoreExpandedState(); } void QtShowViewDialog::categoryCollapsed(const QModelIndex& index) { m_ExpandedCategories.removeAll(m_FilterModel->mapToSource(index)); } void QtShowViewDialog::categoryExpanded(const QModelIndex& index) { m_ExpandedCategories.push_back(m_FilterModel->mapToSource(index)); } void QtShowViewDialog::selectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { UpdateButtons(); } void QtShowViewDialog::RestoreExpandedState() { int rowCount = m_FilterModel->rowCount(); for (int i = 0; i < rowCount; ++i) { QModelIndex index = m_FilterModel->index(i, 0); if (m_ExpandedCategories.contains(m_FilterModel->mapToSource(index))) { m_UserInterface.m_TreeView->expand(index); } } } void QtShowViewDialog::UpdateButtons() { QPushButton* okBtn = m_UserInterface.m_ButtonBox->button(QDialogButtonBox::Ok); if (okBtn) { okBtn->setEnabled(!m_UserInterface.m_TreeView->selectionModel()->selection().isEmpty()); } } void QtShowViewDialog::RestoreState() { - IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); - QString str = prefs->Get(TAG_SHOWVIEWDIALOG, QString::null); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + auto str = QString::fromStdString(prefs->Get(TAG_SHOWVIEWDIALOG.toStdString(), "")); if (str.isEmpty()) return; std::stringstream ss(str.toStdString()); XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); bool keywordFilter = false; if (memento->GetBoolean("keywordFilter", keywordFilter)) { m_UserInterface.m_KeywordFilter->setChecked(keywordFilter); m_FilterModel->setFilterOnKeywords(keywordFilter); } QString filter; if (memento->GetString("filter", filter)) { m_UserInterface.m_Filter->setText(filter); } IMemento::Pointer geomChild = memento->GetChild(TAG_GEOMETRY); if (geomChild.IsNotNull()) { QString geom = geomChild->GetTextData(); if (!geom.isEmpty()) { QByteArray ba = QByteArray::fromBase64(geom.toLatin1()); this->restoreGeometry(ba); } } QHash rootIndices; int rowCount = m_FilterModel->sourceModel()->rowCount(); for (int i = 0; i < rowCount; ++i) { QModelIndex sourceIndex = m_FilterModel->sourceModel()->index(i, 0); QString id = sourceIndex.data(ViewTreeModel::Id).toString(); if (!id.isEmpty()) { rootIndices[id] = sourceIndex; } } for (const IMemento::Pointer &categoryChild : memento->GetChildren(TAG_CATEGORY)) { QString id = categoryChild->GetID(); if (!id.isEmpty()) { if (rootIndices.contains(id)) { m_ExpandedCategories.push_back(rootIndices[id]); } } } this->RestoreExpandedState(); QItemSelection itemSelection; for (const IMemento::Pointer &selectionChild : memento->GetChildren(TAG_SELECTION)) { QString id = selectionChild->GetID(); if (!id.isEmpty()) { QModelIndexList indexList = m_FilterModel->match(m_FilterModel->index(0, 0), ViewTreeModel::Id, QVariant::fromValue(id), 1, Qt::MatchExactly | Qt::MatchRecursive); if (!indexList.isEmpty()) { QItemSelection subSelection(indexList.front(), indexList.front()); itemSelection.merge(subSelection, QItemSelectionModel::SelectCurrent); } } } m_UserInterface.m_TreeView->selectionModel()->select(itemSelection, QItemSelectionModel::ClearAndSelect); } void QtShowViewDialog::SaveState() { XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot(TAG_SHOWVIEWDIALOG); memento->PutString("filter", m_UserInterface.m_Filter->text()); memento->PutBoolean("keywordFilter", m_UserInterface.m_KeywordFilter->isChecked()); // dialog geometry QByteArray geom = this->saveGeometry(); IMemento::Pointer geomChild = memento->CreateChild(TAG_GEOMETRY); geomChild->PutTextData(geom.toBase64().constData()); // expanded categories for (const QPersistentModelIndex &index : qAsConst(m_ExpandedCategories)) { if (index.isValid()) { QString id = index.data(ViewTreeModel::Id).toString(); if (!id.isEmpty()) { memento->CreateChild(TAG_CATEGORY, id); } } } // we only record a single selected item. restoring a multi-selection might be // confusing for the user QModelIndexList selectedIndices = m_UserInterface.m_TreeView->selectionModel()->selectedIndexes(); if (!selectedIndices.isEmpty()) { QString id = selectedIndices.back().data(ViewTreeModel::Id).toString(); if (!id.isEmpty()) { memento->CreateChild(TAG_SELECTION, id); } } std::stringstream ss; memento->Save(ss); - IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); - prefs->Put(TAG_SHOWVIEWDIALOG, QString::fromStdString(ss.str())); - prefs->Sync(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + prefs->Put(TAG_SHOWVIEWDIALOG.toStdString(), ss.str()); + prefs->Flush(); } void QtShowViewDialog::done(int r) { this->SaveState(); QDialog::done(r); } QList QtShowViewDialog::GetSelection() const { QList selected; QModelIndexList indices = m_UserInterface.m_TreeView->selectionModel()->selectedIndexes(); for(QModelIndex index : qAsConst(indices)) { QString id = m_FilterModel->data(index, ViewTreeModel::Id).toString(); selected.push_back(id); } return selected; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp index cf73d47ec1..cd166d9ac2 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp @@ -1,267 +1,265 @@ /*============================================================================ 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 "berryQtStylePreferencePage.h" -#include -#include - #include "berryWorkbenchPlugin.h" +#include #include #include #include +#include +#include + namespace berry { QtStylePreferencePage::QtStylePreferencePage() { } void QtStylePreferencePage::Init(IWorkbench::Pointer ) { } void QtStylePreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); - berry::IPreferencesService* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext(); ctkServiceReference styleManagerRef = context->getServiceReference(); if (styleManagerRef) { styleManager = context->getService(styleManagerRef); } m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); Update(); connect(controls.m_StylesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(StyleChanged(int))); connect(controls.m_FontComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(FontChanged(int))); connect(controls.m_FontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(FontChanged(int))); connect(controls.m_PathList, SIGNAL(itemSelectionChanged()), this, SLOT(UpdatePathListButtons())); connect(controls.m_AddButton, SIGNAL(clicked(bool)), this, SLOT(AddPathClicked(bool))); connect(controls.m_EditButton, SIGNAL(clicked(bool)), this, SLOT(EditPathClicked(bool))); connect(controls.m_RemoveButton, SIGNAL(clicked(bool)), this, SLOT(RemovePathClicked(bool))); } void QtStylePreferencePage::FillStyleCombo(const berry::IQtStyleManager::Style& currentStyle) { controls.m_StylesCombo->clear(); styles.clear(); styleManager->GetStyles(styles); qSort(styles); for (int i = 0; i < styles.size(); ++i) { controls.m_StylesCombo->addItem(styles.at(i).name, QVariant(styles.at(i).fileName)); } controls.m_StylesCombo->setCurrentIndex(styles.indexOf(currentStyle)); } void QtStylePreferencePage::FillFontCombo(const QString& currentFont) { controls.m_FontComboBox->clear(); QStringList fonts; styleManager->GetFonts(fonts); for (int i = 0; i < fonts.size(); ++i) { controls.m_FontComboBox->addItem(fonts.at(i)); } controls.m_FontComboBox->setCurrentIndex(fonts.indexOf(currentFont)); if (currentFont == QString("<>")) { controls.m_FontSizeSpinBox->setEnabled(false); } else { controls.m_FontSizeSpinBox->setEnabled(true); } } void QtStylePreferencePage::AddPath(const QString& path, bool updateCombo) { if (!controls.m_PathList->findItems(path, Qt::MatchCaseSensitive).isEmpty()) return; new QListWidgetItem(path, controls.m_PathList); styleManager->AddStyles(path); if (updateCombo) FillStyleCombo(oldStyle); } void QtStylePreferencePage::StyleChanged(int /*index*/) { QString fileName = controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString(); styleManager->SetStyle(fileName); } void QtStylePreferencePage::FontChanged(int /*index*/) { QString fontName = controls.m_FontComboBox->currentText(); int fontSize = controls.m_FontSizeSpinBox->value(); if (fontName == QString("<>")) { controls.m_FontSizeSpinBox->setEnabled(false); } else { controls.m_FontSizeSpinBox->setEnabled(true); } styleManager->SetFont(fontName); styleManager->SetFontSize(fontSize); styleManager->UpdateWorkbenchFont(); } void QtStylePreferencePage::AddPathClicked(bool /*checked*/) { QListWidgetItem* item = controls.m_PathList->currentItem(); QString initialDir; if (item) initialDir = item->text(); QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir); if (!dir.isEmpty()) this->AddPath(dir, true); } void QtStylePreferencePage::RemovePathClicked(bool /*checked*/) { QList selection = controls.m_PathList->selectedItems(); QListIterator it(selection); while (it.hasNext()) { QListWidgetItem* item = it.next(); QString dir = item->text(); controls.m_PathList->takeItem(controls.m_PathList->row(item)); delete item; styleManager->RemoveStyles(dir); } if (!styleManager->Contains(oldStyle.fileName)) { oldStyle = styleManager->GetDefaultStyle(); } FillStyleCombo(oldStyle); } void QtStylePreferencePage::EditPathClicked(bool checked) { QListWidgetItem* item = controls.m_PathList->currentItem(); QString initialDir = item->text(); QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir); if (!dir.isEmpty()) { this->RemovePathClicked(checked); this->AddPath(dir, true); } } void QtStylePreferencePage::UpdatePathListButtons() { int s = controls.m_PathList->selectedItems().size(); if (s == 0) { controls.m_EditButton->setEnabled(false); controls.m_RemoveButton->setEnabled(false); } else if (s == 1) { controls.m_EditButton->setEnabled(true); controls.m_RemoveButton->setEnabled(true); } else { controls.m_EditButton->setEnabled(false); controls.m_RemoveButton->setEnabled(true); } } QWidget* QtStylePreferencePage::GetQtControl() const { return mainWidget; } bool QtStylePreferencePage::PerformOk() { - m_StylePref->Put(berry::QtPreferences::QT_STYLE_NAME, - controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString()); + m_StylePref->Put(berry::QtPreferences::QT_STYLE_NAME, controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString().toStdString()); QString paths; for (int i = 0; i < controls.m_PathList->count(); ++i) { QString path = controls.m_PathList->item(i)->text() + ";"; paths += path; } - m_StylePref->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths); - m_StylePref->Put(berry::QtPreferences::QT_FONT_NAME, - controls.m_FontComboBox->currentText()); - m_StylePref->Put(berry::QtPreferences::QT_FONT_SIZE, - QString::number(controls.m_FontSizeSpinBox->value())); + m_StylePref->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths.toStdString()); + m_StylePref->Put(berry::QtPreferences::QT_FONT_NAME, controls.m_FontComboBox->currentText().toStdString()); + m_StylePref->Put(berry::QtPreferences::QT_FONT_SIZE, std::to_string(controls.m_FontSizeSpinBox->value())); m_StylePref->PutBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, controls.m_ToolbarCategoryCheckBox->isChecked()); return true; } void QtStylePreferencePage::PerformCancel() { Update(); } void QtStylePreferencePage::Update() { styleManager->RemoveStyles(); - QString paths = m_StylePref->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, ""); + auto paths = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, "")); QStringList pathList = paths.split(";", QString::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddPath(it.next(), false); } - QString styleName = m_StylePref->Get(berry::QtPreferences::QT_STYLE_NAME, ""); + auto styleName = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_STYLE_NAME, "")); styleManager->SetStyle(styleName); oldStyle = styleManager->GetStyle(); FillStyleCombo(oldStyle); - QString fontName = m_StylePref->Get(berry::QtPreferences::QT_FONT_NAME, "Open Sans"); + auto fontName = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_FONT_NAME, "Open Sans")); styleManager->SetFont(fontName); - int fontSize = m_StylePref->Get(berry::QtPreferences::QT_FONT_SIZE, "9").toInt(); + auto fontSize = std::stoi(m_StylePref->Get(berry::QtPreferences::QT_FONT_SIZE, "9")); styleManager->SetFontSize(fontSize); controls.m_FontSizeSpinBox->setValue(fontSize); styleManager->UpdateWorkbenchFont(); FillFontCombo(styleManager->GetFont()); controls.m_ToolbarCategoryCheckBox->setChecked( m_StylePref->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true)); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h index 872008cfc7..c0253f57d7 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h @@ -1,77 +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. ============================================================================*/ #ifndef BERRYQTSTYLEPREFERENCEPAGE_H_ #define BERRYQTSTYLEPREFERENCEPAGE_H_ #include #include -#include #include #include +namespace mitk +{ + class IPreferences; +} + namespace berry { class QtStylePreferencePage : public QObject, public IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QtStylePreferencePage(); void Init(IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; protected: void AddPath(const QString& path, bool updateCombo); void FillStyleCombo(const berry::IQtStyleManager::Style& currentStyle); void FillFontCombo(const QString& currentFont); protected slots: void StyleChanged(int /*index*/); void FontChanged(int /*index*/); void AddPathClicked(bool /*checked*/); void RemovePathClicked(bool /*checked*/); void EditPathClicked(bool checked); void UpdatePathListButtons(); private: berry::IQtStyleManager* styleManager; Ui::QtStylePreferencePageUI controls; - berry::IPreferences::Pointer m_StylePref; + mitk::IPreferences* m_StylePref; berry::IQtStyleManager::Style oldStyle; berry::IQtStyleManager::StyleList styles; QWidget* mainWidget; }; } #endif /* BERRYQTSTYLEPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp index 8309f352a7..38bd69cefb 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp @@ -1,299 +1,300 @@ /*============================================================================ 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 "berryReopenEditorMenu.h" -#include #include #include #include #include #include "berryEditorHistory.h" #include "berryEditorHistoryItem.h" #include "berryWorkbench.h" #include "berryWorkbenchPlugin.h" #include "berryPreferenceConstants.h" #include #include #include +#include + namespace berry { ReopenEditorMenu::ReopenEditorMenu(IWorkbenchWindow* window, const QString& id, bool showSeparator) : ContributionItem(id) , window(window) , history(nullptr) , showSeparator(showSeparator) , dirty(true) { IWorkbench* workbench = window->GetWorkbench(); if (Workbench* w = dynamic_cast(workbench)) { history = w->GetEditorHistory(); } } QString ReopenEditorMenu::CalcText(int index, const QString& name, const QString& toolTip, bool rtl) { QString sb; int mnemonic = index + 1; QString nm = QString::number(mnemonic); if (mnemonic <= MAX_MNEMONIC_SIZE) { nm.prepend('&'); } QString fileName = name; QString pathName = toolTip; if (pathName == fileName) { // tool tip text isn't necessarily a path; // sometimes it's the same as name, so it shouldn't be treated as a path then pathName.clear(); } QFileInfo path(pathName); // if last segment in path is the fileName, remove it if (path.fileName() == fileName) { path.setFile(path.path()); pathName = path.absoluteFilePath(); } if ((fileName.size() + pathName.size()) <= (MAX_TEXT_LENGTH - 4)) { // entire item name fits within maximum length sb += fileName; if (!pathName.isEmpty()) { sb += " [" + pathName + "]"; } } else { // need to shorten the item name int length = fileName.size(); if (length > MAX_TEXT_LENGTH) { // file name does not fit within length, truncate it sb += fileName.leftRef(MAX_TEXT_LENGTH - 3); sb += "..."; } else if (length > MAX_TEXT_LENGTH - 7) { sb += fileName; } else { sb += fileName; QStringList pathSegments = path.absoluteFilePath().split('/', QString::SkipEmptyParts); int segmentCount = pathSegments.size(); if (segmentCount > 0) { length += 7; // 7 chars are taken for " [...]" sb += " ["; // Add first n segments that fit int i = 0; while (i < segmentCount && length < MAX_TEXT_LENGTH) { const QString& segment = pathSegments[i]; if (length + segment.size() < MAX_TEXT_LENGTH) { sb += segment + QDir::separator(); length += segment.size() + 1; i++; } else if (i == 0) { // append at least part of the first segment sb += segment.leftRef(MAX_TEXT_LENGTH - length); length = MAX_TEXT_LENGTH; break; } else { break; } } sb += "..."; i = segmentCount - 1; // Add last n segments that fit while (i > 0 && length < MAX_TEXT_LENGTH) { const QString& segment = pathSegments[i]; if (length + segment.size() < MAX_TEXT_LENGTH) { sb += QDir::separator(); sb += segment; length += segment.size() + 1; i--; } else { break; } } sb.append("]"); } } } QString process; if (rtl) { process = sb + " " + nm; } else { process = nm + " " + sb; } //return TextProcessor.process(process, TextProcessor.getDefaultDelimiters() + "[]"); return process; } void ReopenEditorMenu::Fill(QMenu* menu, QAction* before) { if (window->GetActivePage() == nullptr || window->GetActivePage()->GetPerspective().IsNull()) { return; } if (MenuManager* mm = dynamic_cast(this->GetParent())) { mm->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), this, SLOT(MenuAboutToShow(IMenuManager*))); } int itemsToShow = WorkbenchPlugin::GetDefault()->GetPreferences()->GetInt(PreferenceConstants::RECENT_FILES, 6); if (itemsToShow == 0 || history == nullptr) { return; } // Get items. QList historyItems = history->GetItems(); int n = std::min(itemsToShow, historyItems.size()); if (n <= 0) { return; } if (showSeparator) { menu->addSeparator(); } struct _SafeRunnable : public ISafeRunnable { QMenu* menu; QAction* before; EditorHistoryItem::Pointer item; const int historyIndex; _SafeRunnable(QMenu* menu, QAction* before, EditorHistoryItem::Pointer item, int index) : menu(menu), before(before), item(item), historyIndex(index) {} void Run() override { QString text = ReopenEditorMenu::CalcText(historyIndex, item); auto mi = new QAction(text, nullptr); menu->insertAction(before, mi); mi->setData(QVariant::fromValue(item)); } void HandleException(const ctkException& e) override { // just skip the item if there's an error, // e.g. in the calculation of the shortened name WorkbenchPlugin::Log(this->GetClassName(), "Fill", e); } }; for (int i = 0; i < n; i++) { EditorHistoryItem::Pointer item = historyItems[i]; ISafeRunnable::Pointer runnable(new _SafeRunnable(menu, before, item, i)); SafeRunner::Run(runnable); } dirty = false; } bool ReopenEditorMenu::IsDirty() const { return dirty; } bool ReopenEditorMenu::IsDynamic() const { return true; } void ReopenEditorMenu::Open(const EditorHistoryItem::Pointer& item) { IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNotNull()) { try { QString itemName = item->GetName(); if (!item->IsRestored()) { item->RestoreState(); } IEditorInput::Pointer input = item->GetInput(); IEditorDescriptor::Pointer desc = item->GetDescriptor(); if (!input || !desc) { QString title = "Problems opening editor"; QString msg = QString("Unable to open %1.").arg(itemName); QMessageBox::warning(window->GetShell()->GetControl(), title, msg); history->Remove(item); } else { page->OpenEditor(input, desc->GetId()); } } catch (const PartInitException& e2) { QString title = "Problems opening editor"; QMessageBox::warning(window->GetShell()->GetControl(), title, e2.what()); history->Remove(item); } } } QString ReopenEditorMenu::CalcText(int index, const EditorHistoryItem::Pointer& item) { // IMPORTANT: avoid accessing the item's input since // this can require activating plugins. // Instead, ask the item for the info, which can // consult its memento if it is not restored yet. return CalcText(index, item->GetName(), item->GetToolTipText(), false); // Window::GetDefaultOrientation() == SWT.RIGHT_TO_LEFT); } void ReopenEditorMenu::MenuAboutToShow(IMenuManager* manager) { manager->MarkDirty(); dirty = true; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp index 30ae706448..5eb5443c39 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp @@ -1,1977 +1,1978 @@ /*============================================================================ 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 "berryLog.h" #include "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbench.h" #include #include "berryPolicy.h" #include "berrySaveablesList.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryEditorHistory.h" #include "berryEditorHistoryItem.h" #include "berryServiceLocatorCreator.h" #include "berryWorkbenchPage.h" #include "berryPerspective.h" #include "berryPreferenceConstants.h" #include "berryUIExtensionTracker.h" #include "berryWorkbenchWindow.h" #include "berryDisplay.h" #include "services/berryIServiceFactory.h" #include "util/berrySafeRunnable.h" #include "berryWorkbenchServiceRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchMenuService.h" #include "berryEvaluationService.h" #include "berryCommandService.h" #include "berryCommandManager.h" #include "berryMenuManager.h" #include "berryParameterType.h" #include "berryQActionProperties.h" #include "berrySourceProviderService.h" #include "berryWorkbenchLocationService.h" #include #include #include #include #include -#include -#include #include #include #include #include #include #include #include +#include +#include + namespace berry { Workbench* Workbench::instance = nullptr; WorkbenchTestable::Pointer Workbench::testableObject; const unsigned int Workbench::VERSION_STRING_COUNT = 1; const QString Workbench::VERSION_STRING[Workbench::VERSION_STRING_COUNT] = { "1.0" }; const QString Workbench::DEFAULT_WORKBENCH_STATE_FILENAME = "workbench.xml"; class RestoreStateRunnable: public SafeRunnable { private: Workbench* workbench; Poco::File stateFile; bool& result; public: RestoreStateRunnable(Workbench* workbench, const QString& stateFile, bool& result) : SafeRunnable( "Unable to read workbench state. Workbench UI layout will be reset."), workbench(workbench), stateFile(stateFile.toStdString()), result(result) { } void Run() override { Poco::FileInputStream input(stateFile.path()); IMemento::Pointer memento = XMLMemento::CreateReadRoot(input); // Validate known version format QString version; memento->GetString(WorkbenchConstants::TAG_VERSION, version); bool valid = false; for (auto & elem : Workbench::VERSION_STRING) { if (elem == version) { valid = true; break; } } if (!valid) { input.close(); QString msg = "Invalid workbench state version. workbench.xml will be deleted"; QMessageBox::critical(nullptr, "Restoring Problems", msg); stateFile.remove(); // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result = false; return; } // // Validate compatible version format // // We no longer support the release 1.0 format // if (VERSION_STRING[0].equals(version)) // { // reader.close(); // QString msg = "The saved user interface layout is in an " // "obsolete format and cannot be preserved. Your projects and files " // "will not be affected. Press OK to convert to the new format. Press " // "Cancel to exit with no changes."; // QList dlgLabels; // dlgLabels.push_back("Ok"); // dlgLabels.push_back("Cancel"); // IDialog::Pointer dlg = MessageDialog::CreateDialog(Shell::Pointer(0), // "Cannot Preserve Layout", 0, msg, IDialog::WARNING, dlgLabels, 0); // IDialog::ReturnCode ignoreSavedState = dlg->Open(); // // OK is the default // if (ignoreSavedState == IDialog::OK) // { // stateFile.remove(); // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, // // null); // result = false; // } // else // { // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_EXIT, msg, // // null); // result = false; // } // return; // } // Restore the saved state //final IStatus restoreResult = restoreState(memento); /*bool restoreResult =*/ workbench->RestoreState(memento); input.close(); // if (restoreResult.getSeverity() == IStatus.ERROR) { // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // StatusManager.getManager().handle(restoreResult, StatusManager.LOG); // } // }); // // } } void HandleException(const ctkException& e) override { //StartupThreading.runWithoutExceptions(new StartupRunnable() { //public void runWithException() { Handle(e); // QString msg = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$ // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, e); result = false; stateFile.remove(); // }}); } private: void Handle(const ctkException& e) { SafeRunnable::HandleException(e); } }; int Workbench::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { // create the workbench instance Workbench workbench(display, advisor); // run the workbench event loop int returnCode = workbench.RunUI(); return returnCode; } Display* Workbench::CreateDisplay() { // create the display Display* newDisplay = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDisplay(); // workaround for 1GEZ9UR and 1GF07HN //newDisplay.setWarnings(false); // Set the priority higher than normal so as to be higher // than the JobManager. //Poco::Thread::current()->setPriority(Poco::Thread::PRIO_HIGH); //initializeImages(); return newDisplay; } Workbench::ServiceLocatorOwner::ServiceLocatorOwner(Workbench* wb) : workbench(wb) { } void Workbench::ServiceLocatorOwner::Dispose() { QMessageBox::information( nullptr, "Restart needed", "A required plug-in is no longer available and the Workbench needs " "to be restarted. You will be prompted to save if there is any unsaved work."); workbench->Close(PlatformUI::RETURN_RESTART, true); } Workbench::Workbench(Display* display, WorkbenchAdvisor* advisor) : commandManager(nullptr), progressCount(-1) , serviceLocatorOwner(new ServiceLocatorOwner(this)) , largeUpdates(0), introManager(nullptr), isStarting(true), isClosing(false) , activeWorkbenchWindow(nullptr) { poco_check_ptr(display) ; poco_check_ptr(advisor); // the reference count to the one and only workbench instance // is increased, so that temporary smart pointer to the workbench // do not delete it this->Register(); this->display = display; this->advisor = advisor; Workbench::instance = this; serviceLocatorCreator.reset(new ServiceLocatorCreator()); serviceLocatorCreator->Register(); this->serviceLocator = serviceLocatorCreator->CreateServiceLocator( nullptr, nullptr, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); serviceLocator->RegisterService(serviceLocatorCreator.data()); workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WORKBENCH_SCOPE, this, nullptr, nullptr, 0)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); returnCode = PlatformUI::RETURN_UNSTARTABLE; } Display* Workbench::GetDisplay() const { return display; } Workbench* Workbench::GetInstance() { return instance; } WorkbenchTestable::Pointer Workbench::GetWorkbenchTestable() { if (!testableObject) { testableObject = new WorkbenchTestable(); } return testableObject; } Workbench::~Workbench() { this->instance = nullptr; this->UnRegister(false); } Object* Workbench::GetService(const QString& key) { return serviceLocator->GetService(key); } bool Workbench::HasService(const QString& key) const { return serviceLocator->HasService(key); } bool Workbench::Init() { // // setup debug mode if required. // if (WorkbenchPlugin.getDefault().isDebugging()) { // WorkbenchPlugin.DEBUG = true; // ModalContext.setDebugMode(true); // } bool bail = false; // create workbench window manager //windowManager = new WindowManager(); IIntroRegistry* introRegistry = WorkbenchPlugin::GetDefault()->GetIntroRegistry(); if (introRegistry->GetIntroCount() > 0) { IProduct::Pointer product = Platform::GetProduct(); if (product.IsNotNull()) { introDescriptor = introRegistry->GetIntroForProduct(product->GetId()).Cast(); } } // TODO Correctly order service initialization // there needs to be some serious consideration given to // the services, and hooking them up in the correct order evaluationService.reset(new EvaluationService()); evaluationService->Register(); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { serviceLocator->RegisterService(evaluationService.data()); // } // }); // Initialize the activity support. //workbenchActivitySupport = new WorkbenchActivitySupport(); //activityHelper = ActivityPersistanceHelper.getInstance(); this->InitializeDefaultServices(); // initializeFonts(); // initializeColors(); // initializeApplicationColors(); // now that the workbench is sufficiently initialized, let the advisor // have a turn. advisor->InternalBasicInitialize(this->GetWorkbenchConfigurer()); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { StartSourceProviders(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // activateWorkbenchContext(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // createApplicationMenu(); // } // }); // attempt to restore a previous workbench state advisor->PreStartup(); if (!advisor->OpenWindows()) { bail = true; } if (bail) return false; //forceOpenPerspective(); return true; } bool Workbench::RestoreState() { //return false; if (!GetWorkbenchConfigurer()->GetSaveAndRestore()) { // QString msg = "This application does not save and restore previously saved state."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // Read the workbench state file. QString stateFile = GetWorkbenchStateFile(); // If there is no state file cause one to open. if (stateFile.isEmpty() || !QFile::exists(stateFile)) { // QString msg = "No previously saved state to restore."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // final IStatus result[] = { new Status(IStatus.OK, // WorkbenchPlugin.PI_WORKBENCH, IStatus.OK, "", null) }; //$NON-NLS-1$ bool result = true; ISafeRunnable::Pointer runnable(new RestoreStateRunnable(this, stateFile, result)); SafeRunner::Run(runnable); // ensure at least one window was opened //if (result[0].isOK() && windowManager.getWindows().length == 0) if (result && windowManager.GetWindowCount() == 0) { QString msg = "No windows restored."; // result[0] = new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result &= false; } return result; } bool Workbench::RestoreState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.Workbench_problemsRestoring, null); bool result = true; const bool showProgress = false; //TODO restore state progress // final boolean showProgress = PrefUtil.getAPIPreferenceStore() // .getBoolean( // IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); try { /* * Restored windows will be set in the createdWindows field to be * used by the openWindowsAfterRestore() method */ if (!showProgress) { DoRestoreState(memento, result); } else { // Retrieve how many plug-ins were loaded while restoring the // workbench int lastProgressCount = -1; memento->GetInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, lastProgressCount); // If we don't know how many plug-ins were loaded last time, // assume we are loading half of the installed plug-ins. /*const std::size_t expectedProgressCount = std::max(1, lastProgressCount == -1 ? WorkbenchPlugin::GetDefault()->GetBundleCount() / 2 : lastProgressCount);*/ //TODO restore state progress // RunStartupWithProgress(expectedProgressCount, new Runnable() { // public void Run() { // DoRestoreState(memento, result); // } // }); } } catch (...) { OpenWindowsAfterRestore(); throw; } OpenWindowsAfterRestore(); return result; } void Workbench::DoRestoreState(IMemento::Pointer memento, bool& status) // final MultiStatus status) { IMemento::Pointer childMem; try { // UIStats.start(UIStats.RESTORE_WORKBENCH, "MRUList"); //$NON-NLS-1$ IMemento::Pointer mruMemento = memento ->GetChild(WorkbenchConstants::TAG_MRU_LIST); if (mruMemento) { // TODO restore editor history //status.add(getEditorHistory().restoreState(mruMemento)); } //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ } catch (...) { //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ throw; } // Restore advisor state. IMemento::Pointer advisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); if (advisorState) { //status.add(getAdvisor().restoreState(advisorState)); status &= GetAdvisor()->RestoreState(advisorState); } // Get the child windows. QList children = memento ->GetChildren(WorkbenchConstants::TAG_WINDOW); createdWindows.clear(); // Read the workbench windows. for (int i = 0; i < children.size(); i++) { childMem = children[i]; WorkbenchWindow::Pointer newWindow; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow = NewWorkbenchWindow(); newWindow->Create(); // }}); createdWindows.push_back(newWindow); // allow the application to specify an initial perspective to open // @issue temporary workaround for ignoring initial perspective // String initialPerspectiveId = // getAdvisor().getInitialWindowPerspectiveId(); // if (initialPerspectiveId != null) { // IPerspectiveDescriptor desc = // getPerspectiveRegistry().findPerspectiveWithId(initialPerspectiveId); // result.merge(newWindow.restoreState(childMem, desc)); // } // add the window so that any work done in newWindow.restoreState // that relies on Workbench methods has windows to work with windowManager.Add(newWindow); // now that we've added it to the window manager we need to listen // for any exception that might hose us before we get a chance to // open it. If one occurs, remove the new window from the manager. // Assume that the new window is a phantom for now try { //status.merge(newWindow[0].restoreState(childMem, null)); status &= newWindow->RestoreState(childMem, IPerspectiveDescriptor::Pointer(nullptr)); try { newWindow->FireWindowRestored(); } catch (const WorkbenchException& /*e*/) { //status.add(e.getStatus()); status &= false; } // everything worked so far, don't close now } catch (...) { // null the window in newWindowHolder so that it won't be // opened later on createdWindows[i] = nullptr; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newWindow->Close(); // }}); } } } void Workbench::OpenWindowsAfterRestore() { if (createdWindows.empty()) { return; } // now open the windows (except the ones that were nulled because we // closed them above) for (int i = 0; i < createdWindows.size(); i++) { if (createdWindows[i]) { WorkbenchWindow::Pointer myWindow = createdWindows[i]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { try { myWindow->Open(); } catch (...) { myWindow->Close(); throw; } // }}); } } createdWindows.clear(); } void Workbench::InitializeDefaultServices() { // final IContributionService contributionService = new ContributionService( // getAdvisor()); // serviceLocator.registerService(IContributionService.class, // contributionService); // // // TODO Correctly order service initialization // // there needs to be some serious consideration given to // // the services, and hooking them up in the correct order // // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { saveablesList.reset(new SaveablesList()); saveablesList->Register(); serviceLocator->RegisterService(saveablesList.data()); // }}); // /* * Phase 1 of the initialization of commands. When this phase completes, * all the services and managers will exist, and be accessible via the * getService(Object) method. */ // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { Command::DEBUG_COMMAND_EXECUTION = Policy::DEBUG_COMMANDS(); Command::DEBUG_HANDLERS = Policy::DEBUG_HANDLERS_VERBOSE(); Command::DEBUG_HANDLERS_COMMAND_ID = Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID(); commandManager.reset(new CommandManager()); // }}); // // final CommandService [] commandService = new CommandService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { commandService.reset(new CommandService(commandManager.data())); commandService->Register(); commandService->ReadRegistry(); serviceLocator->RegisterService(commandService.data()); // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // ContextManager.DEBUG = Policy.DEBUG_CONTEXTS; // contextManager = new ContextManager(); // }}); // // final IContextService contextService = new ContextService( // contextManager); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // contextService.readRegistry(); // }}); // // serviceLocator.registerService(IContextService.class, contextService); // // // final IBindingService [] bindingService = new BindingService[1]; // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // BindingManager.DEBUG = Policy.DEBUG_KEY_BINDINGS; // bindingManager = new BindingManager(contextManager, commandManager); // bindingService[0] = new BindingService( // bindingManager, commandService[0], Workbench.this); // // }}); // // bindingService[0].readRegistryAndPreferences(commandService[0]); // serviceLocator.registerService(IBindingService.class, bindingService[0]); // // final CommandImageManager commandImageManager = new CommandImageManager(); // final CommandImageService commandImageService = new CommandImageService( // commandImageManager, commandService[0]); // commandImageService.readRegistry(); // serviceLocator.registerService(ICommandImageService.class, // commandImageService); auto wms = new WorkbenchMenuService(serviceLocator.GetPointer()); menuService.reset(wms); menuService->Register(); serviceLocator->RegisterService(menuService.data()); // the service must be registered before it is initialized - its // initialization uses the service locator to address a dependency on // the menu service //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { wms->ReadRegistry(); // }}); // the source providers are now initialized in phase 3, but source // priorities have to be set before handler initialization // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { InitializeSourcePriorities(); // } // }); /* * Phase 2 of the initialization of commands. This handles the creation * of wrappers for legacy APIs. By the time this phase completes, any * code trying to access commands through legacy APIs should work. */ //IHandlerService* handlerService = nullptr; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { /*handlerService = */serviceLocator->GetService(); // } // }); // workbenchContextSupport = new WorkbenchContextSupport(this, // contextManager); // workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, // commandManager, contextManager, handlerService[0]); // initializeCommandResolver(); this->AddWindowListener(this); // bindingManager.addBindingManagerListener(bindingManagerListener); // serviceLocator.registerService(ISelectionConversionService.class, // new SelectionConversionService()); } int Workbench::RunUI() { // initialize workbench and restore or open one window bool initOK = this->Init(); // let the advisor run its start up code if (initOK) { advisor->PostStartup(); // may trigger a close/restart } //TODO start eager plug-ins //startPlugins(); //addStartupRegistryListener(); isStarting = false; BERRY_INFO << "BlueBerry Workbench ready"; this->GetWorkbenchTestable()->Init(Display::GetDefault(), this); // spin event loop return display->RunEventLoop(); } QString Workbench::GetDefaultPerspectiveId() const { return this->GetAdvisor()->GetInitialWindowPerspectiveId(); } IAdaptable* Workbench::GetDefaultPageInput() const { return this->GetAdvisor()->GetDefaultPageInput(); } QString Workbench::GetPresentationId() const { if (factoryID != "") { return factoryID; } //factoryID = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID); // Workaround for bug 58975 - New preference mechanism does not properly // initialize defaults // Ensure that the UI plugin has started too. factoryID = WorkbenchConstants::DEFAULT_PRESENTATION_ID; return factoryID; } IElementFactory* Workbench::GetElementFactory(const QString& factoryId) const { return WorkbenchPlugin::GetDefault()->GetElementFactory(factoryId); } void Workbench::UpdateTheme() { WorkbenchPlugin::GetDefault()->GetPresentationFactory()->UpdateTheme(); } void Workbench::LargeUpdateStart() { if (largeUpdates++ == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(false); // workbenchContextSupport.setProcessing(false); QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateStart(); } } } } void Workbench::LargeUpdateEnd() { if (--largeUpdates == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(true); // workbenchContextSupport.setProcessing(true); // Perform window-specific blocking. QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateEnd(); } } } } IExtensionTracker*Workbench::GetExtensionTracker() const { if (tracker.isNull()) { tracker.reset(new UIExtensionTracker(this->GetDisplay())); } return tracker.data(); } void Workbench::OpenFirstTimeWindow() { try { IAdaptable* input; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { input = this->GetDefaultPageInput(); // }}); this->BusyOpenWorkbenchWindow(this->GetPerspectiveRegistry()->GetDefaultPerspective(), input); } catch (WorkbenchException& e) { // Don't use the window's shell as the dialog parent, // as the window is not open yet (bug 76724). //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Problems_Opening_Page, e.getMessage(), e // .getStatus()); // }}); BERRY_ERROR << "Error: Problems opening page. " << e.what() << std::endl; } } WorkbenchConfigurer::Pointer Workbench::GetWorkbenchConfigurer() { if (workbenchConfigurer.IsNull()) { workbenchConfigurer = new WorkbenchConfigurer(); } return workbenchConfigurer; } WorkbenchAdvisor* Workbench::GetAdvisor() const { return advisor; } IViewRegistry* Workbench::GetViewRegistry() const { return WorkbenchPlugin::GetDefault()->GetViewRegistry(); } IEditorRegistry* Workbench::GetEditorRegistry() const { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } EditorHistory* Workbench::GetEditorHistory() const { if (editorHistory.isNull()) { editorHistory.reset(new EditorHistory()); } return editorHistory.data(); } IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() const { return WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry(); } bool Workbench::Close() { return this->Close(PlatformUI::RETURN_OK, false); } bool Workbench::Close(int returnCode, bool force) { BERRY_INFO << "Closing workbench..."; this->returnCode = returnCode; bool ret; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(force); // } //}); return ret; } /** * Closes the workbench. Assumes that the busy cursor is active. * * @param force * true if the close is mandatory, and false if the close is * allowed to fail * @return true if the close succeeded, and false otherwise */ bool Workbench::BusyClose(bool force) { // notify the advisor of preShutdown and allow it to veto if not forced isClosing = advisor->PreShutdown(); if (!force && !isClosing) { return false; } // notify regular workbench clients of preShutdown and allow them to // veto if not forced isClosing = this->FirePreShutdown(force); if (!force && !isClosing) { return false; } // save any open editors if they are dirty isClosing = this->SaveAllEditors(!force); if (!force && !isClosing) { return false; } bool closeEditors = !force && false; // false is the default for the not yet implemented preference below // && PrefUtil.getAPIPreferenceStore().getBoolean( // IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT); if (closeEditors) { // SafeRunner.run(new SafeRunnable() { // public void run() { QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchPage::Pointer page = windows[i]->GetActivePage(); if (page) isClosing = isClosing && page->CloseAllEditors(false); } // } //}); if (!force && !isClosing) { return false; } } if (this->GetWorkbenchConfigurer()->GetSaveAndRestore()) { try { // SafeRunner.run(new SafeRunnable() { // public void run() { XMLMemento::Pointer mem = RecordWorkbenchState(); // Save the IMemento to a file. SaveMementoToFile(mem); // } } catch(const ctkException& e) { // public void handleException(Throwable e) { QString message; if (e.what() == nullptr) { message = "An error has occurred. See error log for more details. Do you want to exit?"; } else { message = QString("An error has occurred: ") + e.what() + ". See error log for more details. Do you want to exit?"; } if (QMessageBox::question(nullptr, "Error", message) != QMessageBox::Yes) { isClosing = false; } } // } // }); } if (!force && !isClosing) { return false; } //SafeRunner.run(new SafeRunnable(WorkbenchMessages.ErrorClosing) { // public void run() { if (isClosing || force) { isClosing = windowManager.Close(); } // } //}); if (!force && !isClosing) { return false; } this->Shutdown(); display->ExitEventLoop(0); return true; } QString Workbench::GetWorkbenchStateFile() const { QString path = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (path.isNull()) { return QString(); } return QDir::cleanPath(path + "/" + DEFAULT_WORKBENCH_STATE_FILENAME); } /* * Save the workbench UI in a persistence file. */ bool Workbench::SaveMementoToFile(XMLMemento::Pointer memento) { // Save it to a file. // XXX: nobody currently checks the return value of this method. QString stateFile = GetWorkbenchStateFile(); if (stateFile.isNull()) { return false; } //BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; try { Poco::FileOutputStream stream(stateFile.toStdString()); memento->Save(stream); } catch (const Poco::IOException& /*e*/) { QFile::remove(stateFile); QMessageBox::critical(nullptr, "Saving Problems", "Unable to store workbench state."); return false; } // Success ! return true; } IWorkbenchWindow::Pointer Workbench::GetActiveWorkbenchWindow() const { // Look for the window that was last known being // the active one WorkbenchWindow::Pointer win = this->GetActivatedWindow(); return win; } std::size_t Workbench::GetWorkbenchWindowCount() const { return windowManager.GetWindowCount(); } QList Workbench::GetWorkbenchWindows() const { QList windows = windowManager.GetWindows(); QList result; for (QList::iterator iter = windows.begin(); iter != windows.end(); ++iter) { result.push_back(iter->Cast()); } return result; } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Run op in busy cursor. //final Object[] result = new Object[1]; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { return this->BusyOpenWorkbenchWindow(perspID, input); // } catch (WorkbenchException e) { // result[0] = e; // } // } //}); } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow(IAdaptable* input) { return this->OpenWorkbenchWindow(this->GetPerspectiveRegistry() ->GetDefaultPerspective(), input); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& perspectiveId, IWorkbenchWindow::Pointer window) { // If the specified window has the requested perspective open, then the // window // is given focus and the perspective is shown. The page's input is // ignored. WorkbenchWindow::Pointer win = window.Cast (); if (win) { IWorkbenchPage::Pointer page = win->GetActivePage(); if (page) { QList perspectives(page ->GetOpenPerspectives()); for (int i = 0; i < perspectives.size(); i++) { IPerspectiveDescriptor::Pointer persp = perspectives[i]; if (perspectiveId == persp->GetId()) { win->MakeVisible(); page->SetPerspective(persp); return page; } } } } // If another window that has the workspace root as input and the // requested // perpective open and active, then the window is given focus. IAdaptable* input = GetDefaultPageInput(); QList windows(GetWorkbenchWindows()); for (int i = 0; i < windows.size(); i++) { win = windows[i].Cast(); if (window != win) { WorkbenchPage::Pointer page = win->GetActivePage().Cast(); if (page) { bool inputSame = false; if (input == nullptr) { inputSame = (page->GetInput() == nullptr); } else { inputSame = input == page->GetInput(); } if (inputSame) { Perspective::Pointer persp = page->GetActivePerspective(); if (persp) { IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc) { if (perspectiveId == desc->GetId()) { Shell::Pointer shell = win->GetShell(); shell->Open(); if (shell->GetMinimized()) { shell->SetMinimized(false); } return page; } } } } } } } // Otherwise the requested perspective is opened and shown in the // specified // window or in a new window depending on the current user preference // for opening // perspectives, and that window is given focus. win = window.Cast(); if (win) { - IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); int mode = store->GetSystemPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = win->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page) { persp = page->GetPerspective(); } // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp) { IWorkbenchWindow::Pointer newWindow = OpenWorkbenchWindow(perspectiveId, input); return newWindow->GetActivePage(); } IPerspectiveDescriptor::Pointer desc = GetPerspectiveRegistry() ->FindPerspectiveWithId(perspectiveId); if (desc == 0) { throw WorkbenchException( "Unable to create perspective \"" + perspectiveId + "\". There is no corresponding perspective extension."); } win->GetShell()->Open(); if (page == 0) { page = win->OpenPage(perspectiveId, input); } else { page->SetPerspective(desc); } return page; } // Just throw an exception.... throw WorkbenchException("Problems opening perspective \"" + perspectiveId + "\""); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& /*perspectiveId*/, IWorkbenchWindow::Pointer /*window*/, IAdaptable* /*input*/) { return IWorkbenchPage::Pointer(nullptr); // // If the specified window has the requested perspective open and the // // same requested // // input, then the window is given focus and the perspective is shown. // bool inputSameAsWindow = false; // WorkbenchWindow::Pointer win = window.Cast(); // if (win.IsNotNull()) { // WorkbenchPage::Pointer page = win->GetActiveWorkbenchPage(); // if (page.IsNotNull()) { // bool inputSame = false; // if (input == 0) { // inputSame = (page->GetInput() == 0); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // inputSameAsWindow = true; // IPerspectiveDescriptor perspectives[] = page // .getOpenPerspectives(); // for (int i = 0; i < perspectives.length; i++) { // IPerspectiveDescriptor persp = perspectives[i]; // if (perspectiveId.equals(persp.getId())) { // win.makeVisible(); // page.setPerspective(persp); // return page; // } // } // } // } // } // // // If another window has the requested input and the requested // // perpective open and active, then that window is given focus. // IWorkbenchWindow[] windows = getWorkbenchWindows(); // for (int i = 0; i < windows.length; i++) { // win = (WorkbenchWindow) windows[i]; // if (window != win) { // WorkbenchPage page = win.getActiveWorkbenchPage(); // if (page != null) { // boolean inputSame = false; // if (input == null) { // inputSame = (page.getInput() == null); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // Perspective persp = page.getActivePerspective(); // if (persp != null) { // IPerspectiveDescriptor desc = persp.getDesc(); // if (desc != null) { // if (perspectiveId.equals(desc.getId())) { // win.getShell().open(); // return page; // } // } // } // } // } // } // } // // // If the specified window has the same requested input but not the // // requested // // perspective, then the window is given focus and the perspective is // // opened and shown // // on condition that the user preference is not to open perspectives in // // a new window. // win = (WorkbenchWindow) window; // if (inputSameAsWindow && win != null) { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int mode = store.getInt(IPreferenceConstants.OPEN_PERSP_MODE); // // if (IPreferenceConstants.OPM_NEW_WINDOW != mode) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // If the specified window has no active perspective, then open the // // requested perspective and show the specified window. // if (win != null) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor persp = null; // if (page != null) { // persp = page.getPerspective(); // } // if (persp == null) { // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // Otherwise the requested perspective is opened and shown in a new // // window, and the // // window is given focus. // IWorkbenchWindow newWindow = openWorkbenchWindow(perspectiveId, input); // return newWindow.getActivePage(); } bool Workbench::SaveAllEditors(bool /*confirm*/) { return true; } IIntroManager* Workbench::GetIntroManager() const { return GetWorkbenchIntroManager(); } WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() const { if (introManager.isNull()) { introManager.reset(new WorkbenchIntroManager(const_cast(this))); } return introManager.data(); } IntroDescriptor::Pointer Workbench::GetIntroDescriptor() const { return introDescriptor; } void Workbench::SetIntroDescriptor(IntroDescriptor::Pointer descriptor) { if (GetIntroManager()->GetIntro()) { GetIntroManager()->CloseIntro(GetIntroManager()->GetIntro()); } introDescriptor = descriptor; } bool Workbench::IsRunning() const { return Tweaklets::Get(WorkbenchTweaklet::KEY)->IsRunning(); } bool Workbench::IsStarting() const { return isStarting; } bool Workbench::IsClosing() const { return isClosing; } WorkbenchWindow::Pointer Workbench::GetActivatedWindow() const { return activatedWindow; } /* * Sets the workbench window which was last known being the active one, or * null . */ void Workbench::SetActivatedWindow(WorkbenchWindow::Pointer window) { activatedWindow = window; } WorkbenchWindow::Pointer Workbench::NewWorkbenchWindow() { WorkbenchWindow::Pointer wbw(new WorkbenchWindow(this->GetNewWindowNumber())); return wbw; } int Workbench::GetNewWindowNumber() { // Get window list. QList windows = windowManager.GetWindows(); int count = static_cast(windows.size()); // Create an array of booleans (size = window count). // Cross off every number found in the window list. auto checkArray = new bool[count]; for (int nX = 0; nX < count; ++nX) { if (windows[nX].Cast ().IsNotNull()) { WorkbenchWindow::Pointer ww = windows[nX].Cast (); int index = ww->GetNumber() - 1; if (index >= 0 && index < count) { checkArray[index] = true; } } } // Return first index which is not used. // If no empty index was found then every slot is full. // Return next index. for (int index = 0; index < count; index++) { if (!checkArray[index]) { delete[] checkArray; return index + 1; } } delete[] checkArray; return static_cast(count + 1); } IWorkbenchWindow::Pointer Workbench::BusyOpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Create a workbench window (becomes active window) //final WorkbenchWindow newWindowArray[] = new WorkbenchWindow[1]; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { // newWindowArray[0] = newWorkbenchWindow(); WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); // } //}); //final WorkbenchWindow newWindow = newWindowArray[0]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Create(); // must be created before adding to window // manager // } //}); windowManager.Add(newWindow); //final WorkbenchException [] exceptions = new WorkbenchException[1]; // Create the initial page. if (perspID != "") { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { try { newWindow->BusyOpenPage(perspID, input); } catch (WorkbenchException& e) { windowManager.Remove(newWindow); throw e; } } // Open window after opening page, to avoid flicker. //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Open(); // } //}); return newWindow; } bool Workbench::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Workbench_problemsSaving, null); bool result = true; // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING[0]); // Save how many plug-ins were loaded while restoring the workbench if (progressCount != -1) { memento->PutInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, progressCount); } // Save the advisor state. IMemento::Pointer advisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); //result.add(getAdvisor().saveState(advisorState)); result &= GetAdvisor()->SaveState(advisorState); // Save the workbench windows. QList windows(GetWorkbenchWindows()); for (int nX = 0; nX < windows.size(); nX++) { WorkbenchWindow::Pointer window = windows[nX].Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_WINDOW); //result.merge(window.saveState(childMem)); result &= window->SaveState(childMem); } // result.add(getEditorHistory().saveState( // memento.createChild(IWorkbenchConstants.TAG_MRU_LIST))); return result; } XMLMemento::Pointer Workbench::RecordWorkbenchState() { XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_WORKBENCH); //final IStatus status = saveState(memento); bool status = SaveState(memento); //if (status.getSeverity() != IStatus.OK) { if (!status) { // // don't use newWindow as parent because it has not yet been opened // // (bug 76724) // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Workbench_problemsSaving, // WorkbenchMessages.Workbench_problemsSavingMsg, status); // }}); } return memento; } void Workbench::AddWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.AddListener(listener); } void Workbench::RemoveWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.RemoveListener(listener); } IWorkbenchListener::Events& Workbench::GetWorkbenchEvents() { return workbenchEvents; } void Workbench::AddWindowListener(IWindowListener* l) { windowEvents.AddListener(l); } void Workbench::RemoveWindowListener(IWindowListener* l) { windowEvents.RemoveListener(l); } IWindowListener::Events& Workbench::GetWindowEvents() { return windowEvents; } bool Workbench::FirePreShutdown(bool forced) { //SafeRunnable.run(new SafeRunnable() { // public void run() { typedef IWorkbenchListener::Events::PreShutdownEvent::ListenerList ListenerList; const ListenerList& listeners = workbenchEvents.preShutdown.GetListeners(); for ( auto iter = listeners.begin(); iter != listeners.end(); ++iter ) { // notify each listener if (! (*iter)->Execute(dynamic_cast(this), forced)) return false; } // } return true; } /** * Fire workbench postShutdown event. * * @since 3.2 */ void Workbench::FirePostShutdown() { // SafeRunnable.run(new SafeRunnable() { // public void run() { workbenchEvents.postShutdown(this); // } } void Workbench::FireWindowOpened(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowOpened(window); // } } void Workbench::FireWindowClosed(IWorkbenchWindow::Pointer window) { if (activatedWindow == window) { // Do not hang onto it so it can be GC'ed activatedWindow = nullptr; } // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowClosed(window); // } } void Workbench::FireWindowActivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowActivated(window); // } } void Workbench::FireWindowDeactivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowDeactivated(window); // } } IWorkbenchWindow::Pointer Workbench::RestoreWorkbenchWindow(IMemento::Pointer memento) { WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); //newWindow.create(); windowManager.Add(newWindow); // whether the window was opened bool opened = false; try { newWindow->RestoreState(memento, IPerspectiveDescriptor::Pointer(nullptr)); newWindow->FireWindowRestored(); newWindow->Open(); opened = true; } catch (...) { if (!opened) { newWindow->Close(); } } return newWindow; } void Workbench::Shutdown() { // shutdown application-specific portions first advisor->PostShutdown(); // notify regular workbench clients of shutdown, and clear the list when // done this->FirePostShutdown(); //workbenchListeners.clear(); //cancelEarlyStartup(); // for dynamic UI // Platform.getExtensionRegistry().removeRegistryChangeListener( // extensionEventHandler); // Platform.getExtensionRegistry().removeRegistryChangeListener( // startupRegistryListener); // ((GrabFocus) Tweaklets.get(GrabFocus.KEY)).dispose(); // Bring down all of the services. serviceLocator->Dispose(); // workbenchActivitySupport.dispose(); // WorkbenchHelpSystem.disposeIfNecessary(); // shutdown the rest of the workbench // WorkbenchColors.shutdown(); // activityHelper.shutdown(); // uninitializeImages(); // if (WorkbenchPlugin.getDefault() != null) { // WorkbenchPlugin.getDefault().reset(); // } // WorkbenchThemeManager.getInstance().dispose(); // PropertyPageContributorManager.getManager().dispose(); // ObjectActionContributorManager.getManager().dispose(); // if (tracker != null) { // tracker.close(); // } Tweaklets::Clear(); } void Workbench::InitializeSourcePriorities() { WorkbenchServiceRegistry::GetRegistry()->InitializeSourcePriorities(); } void Workbench::StartSourceProviders() { /* * Phase 3 of the initialization of commands. The source providers that * the workbench provides are creating and registered with the above * services. These source providers notify the services when particular * pieces of workbench state change. */ IEvaluationService* const evaluationService = serviceLocator->GetService(); //IContextService* const contextService = serviceLocator->GetService(); auto sps = new SourceProviderService(serviceLocator.GetPointer()); sourceProviderService.reset(sps); sourceProviderService->Register(); serviceLocator->RegisterService(sourceProviderService.data()); struct SafeSourceProviderRunnable : public ISafeRunnable { SafeSourceProviderRunnable(SourceProviderService* sps, IEvaluationService* es) : sps(sps), es(es) {} void Run() override { // this currently instantiates all players ... sigh sps->ReadRegistry(); QList sp = sps->GetSourceProviders(); for (int i = 0; i < sp.size(); i++) { es->AddSourceProvider(sp[i]); //if (!(sp[i] instanceof ActiveContextSourceProvider)) //{ // contextService.addSourceProvider(sp[i]); //} } } void HandleException(const ctkException& exception) override { WorkbenchPlugin::Log("Failed to initialize a source provider", exception); } private: SourceProviderService* sps; IEvaluationService* es; }; ISafeRunnable::Pointer sourceProviderRunnable( new SafeSourceProviderRunnable(sps, evaluationService)); SafeRunner::Run(sourceProviderRunnable); // SafeRunner.run(new ISafeRunnable() { // public void run() throws Exception { // // these guys are need to provide the variables they say // // they source // actionSetSourceProvider = (ActionSetSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_ACTION_SETS_NAME); // FocusControlSourceProvider focusControl = (FocusControlSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_FOCUS_CONTROL_ID_NAME); // serviceLocator.registerService(IFocusService.class, focusControl); // menuSourceProvider = (MenuSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_MENU_NAME); // } // public void handleException(Throwable exception) { // WorkbenchPlugin.log("Failed to initialize a source provider", exception); //$NON-NLS-1$ // } // }); } void Workbench::UpdateActiveWorkbenchWindowMenuManager(bool textOnly) { if (activeWorkbenchWindow != nullptr) { // if (actionSetSourceProvider != null) // { // activeWorkbenchWindow->RemoveActionSetsListener(actionSetSourceProvider); // } activeWorkbenchWindow = nullptr; } //bool actionSetsUpdated = false; IWorkbenchWindow::Pointer workbenchWindow = GetActiveWorkbenchWindow(); if (WorkbenchWindow::Pointer wbWnd = workbenchWindow.Cast()) { activeWorkbenchWindow = wbWnd.GetPointer(); if (activeWorkbenchWindow->IsClosing()) { return; } // Update the action sets. // Shell::Pointer windowShell = activeWorkbenchWindow->GetShell(); // Shell::Pointer activeShell = GetDisplay()->GetActiveShell(); // IContextService* service = GetService(); // if ((Util.equals(windowShell, activeShell) || service.getShellType(activeShell) == IContextService.TYPE_WINDOW) // && actionSetSourceProvider != null) // { // activeWorkbenchWindow->AddActionSetsListener(actionSetSourceProvider); // final WorkbenchPage page = activeWorkbenchWindow.getActiveWorkbenchPage(); // final IActionSetDescriptor[] newActionSets; // if (page != null) // { // newActionSets = page.getActionSets(); // final ActionSetsEvent event = new ActionSetsEvent(newActionSets); // actionSetSourceProvider.actionSetsChanged(event); // actionSetsUpdated = true; // } // } MenuManager* menuManager = activeWorkbenchWindow->GetMenuManager(); if (textOnly) { menuManager->Update(QActionProperties::TEXT); } else { menuManager->Update(true); } } // if (!actionSetsUpdated && actionSetSourceProvider != null) // { // ActionSetsEvent event = new ActionSetsEvent(null); // actionSetSourceProvider.actionSetsChanged(event); // } } void Workbench::WindowActivated(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } void Workbench::WindowDeactivated(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } void Workbench::WindowClosed(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } void Workbench::WindowOpened(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp b/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp index 49adf8fbdf..28e535bb9c 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp @@ -1,266 +1,265 @@ /*============================================================================ 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 "berryNativeTabFolder.h" #include "berryNativeTabItem.h" #include "berryQCTabBar.h" #include #include #include #include #include -#include #include #include #include #include #include namespace berry { AbstractTabItem* NativeTabFolder::GetTab(int index) { return tabControl->getTab(index); } void NativeTabFolder::TabSelectionChanged(int index) { this->FireEvent(TabFolderEvent::EVENT_TAB_SELECTED, tabControl->getTab(index)); } void NativeTabFolder::DragStarted(const QPoint& location) { this->HandleDragStarted(location); } void NativeTabFolder::ViewFormDestroyed(QObject*) { viewForm = nullptr; content = nullptr; } NativeTabFolder::NativeTabFolder(QWidget* parent) : QObject(parent) { content = nullptr; viewForm = new QtControlWidget(parent, nullptr); viewForm->setObjectName("ViewForm"); viewForm->installEventFilter(this); auto layout = new QVBoxLayout; layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); viewForm->setLayout(layout); connect(viewForm, SIGNAL(destroyed(QObject*)), this, SLOT(ViewFormDestroyed(QObject*))); tabControl = new QCTabBar; tabControl->installEventFilter(this); tabControl->setMinimumSize(0, 27); tabControl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred); layout->addWidget(tabControl); contentFrame = new QFrame(viewForm); contentFrame->setObjectName("ViewFormContentFrame"); contentFrame->installEventFilter(this); contentFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); auto contentFrameLayout = new QVBoxLayout(contentFrame); contentFrameLayout->setContentsMargins(0, 0, 0, 0); contentFrameLayout->setSpacing(0); layout->addWidget(contentFrame); this->connect(tabControl, SIGNAL(currentChanged(int)), this, SLOT(TabSelectionChanged(int))); this->connect(tabControl, SIGNAL(dragStarted(const QPoint&)), this, SLOT(DragStarted(const QPoint&))); ctkServiceReference serviceRef = WorkbenchPlugin::GetDefault()->GetPluginContext()->getServiceReference(); if (serviceRef) { skinManager = WorkbenchPlugin::GetDefault()->GetPluginContext()->getService(serviceRef); } } NativeTabFolder::~NativeTabFolder() { if (!PlatformUI::GetWorkbench()->IsClosing()) { BERRY_DEBUG << "Deleting viewForm"; if (content != nullptr) { content->setParent(nullptr); } viewForm->deleteLater(); } } bool NativeTabFolder::eventFilter(QObject* watched, QEvent* event) { if (event->type() == QEvent::MouseButtonPress) { QMouseEvent* mouseEvent = static_cast(event); this->HandleMousePress(mouseEvent->pos()); } return QObject::eventFilter(watched, event); } void NativeTabFolder::SetActive(int activeState) { AbstractTabFolder::SetActive(activeState); this->UpdateColors(); } void NativeTabFolder::UpdateColors() { viewForm->setStyleSheet(1 == this->GetActive() ? skinManager->GetActiveTabStylesheet() : skinManager->GetTabStylesheet()); } void NativeTabFolder::CloseButtonClicked(AbstractTabItem* item) { this->FireEvent(TabFolderEvent::EVENT_CLOSE, item); } QSize NativeTabFolder::ComputeSize(int /*widthHint*/, int /*heightHint*/) { return QSize(50,50); } AbstractTabItem* NativeTabFolder::Add(int index, int flags) { auto item = new NativeTabItem(this, index, flags); return item; } void NativeTabFolder::Move(int from, int to) { int tabCount = tabControl->count(); if (to > tabCount) to = tabCount; tabControl->moveAbstractTab(from, to); } void NativeTabFolder::Layout(bool flushCache) { AbstractTabFolder::Layout(flushCache); } QPoint NativeTabFolder::GetPaneMenuLocation() { return AbstractTabFolder::GetPaneMenuLocation(); } void NativeTabFolder::SetState(int state) { AbstractTabFolder::SetState(state); } QRect NativeTabFolder::GetClientArea() { if (content == nullptr) { return QRect(); } return content->geometry(); } QList NativeTabFolder::GetItems() { return tabControl->getTabs(); } void NativeTabFolder::SetSelection(AbstractTabItem* toSelect) { if (toSelect == nullptr) { return; } tabControl->setCurrentTab(toSelect); } void NativeTabFolder::SetSelectedInfo(const PartInfo&) { } QRect NativeTabFolder::GetTabArea() { return tabControl->geometry(); } QWidget* NativeTabFolder::GetControl() { return viewForm; } bool NativeTabFolder::IsOnBorder(const QPoint& ) { return false; } AbstractTabItem* NativeTabFolder::GetSelection() { return tabControl->getCurrentTab(); } QWidget* NativeTabFolder::GetContentParent() { return contentFrame; } void NativeTabFolder::SetContent(QWidget* newContent) { if (content != nullptr) { contentFrame->layout()->removeWidget(content); disconnect(content); } content = newContent; content->installEventFilter(this); contentFrame->layout()->addWidget(content); } QCTabBar* NativeTabFolder::GetTabFolder() { return tabControl; } void NativeTabFolder::SetSelectedTitle(const QString&) { } void NativeTabFolder::SetSelectedImage(const QPixmap*) { } AbstractTabItem* NativeTabFolder::GetItem(const QPoint& toFind) { QPoint localPoint = tabControl->mapFromGlobal(toFind); int index = tabControl->tabAt(localPoint); if (index < 0) return nullptr; return tabControl->getTab(index); } void NativeTabFolder::EnablePaneMenu(bool) { } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp index b1050da66d..0713959c31 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp @@ -1,284 +1,285 @@ /*============================================================================ 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 "berryPerspectivesPreferencePage.h" #include "ui_berryPerspectivesPreferencePage.h" -#include -#include #include #include "internal/berryPerspective.h" #include "internal/berryPerspectiveRegistry.h" #include "internal/berryPreferenceConstants.h" #include "internal/berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" #include #include +#include +#include + namespace berry { bool PerspectiveComparator(const PerspectiveDescriptor::Pointer& p1, const PerspectiveDescriptor::Pointer& p2) { return p1->GetLabel() < p2->GetLabel(); } PerspectivesPreferencePage::PerspectivesPreferencePage() : ui(nullptr) , pageWidget(nullptr) , workbench(nullptr) , perspRegistry(nullptr) { } PerspectivesPreferencePage::~PerspectivesPreferencePage() { delete ui; } void PerspectivesPreferencePage::Init(berry::IWorkbench::Pointer workbench) { ui = new Ui::PerspectivesPreferencePage; this->workbench = workbench.GetPointer(); perspRegistry = dynamic_cast(workbench->GetPerspectiveRegistry()); } void PerspectivesPreferencePage::CreateQtControl(QWidget* parent) { pageWidget = new QWidget(parent); ui->setupUi(pageWidget); ui->perspectivesListWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->perspectivesListWidget->setIconSize(QSize(16, 16)); connect(ui->sameWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInSameWindow())); connect(ui->newWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInNewWindow())); connect(ui->perspectivesListWidget, SIGNAL(itemSelectionChanged()), this, SLOT(PerspectiveSelectionChanged())); connect(ui->revertButton, SIGNAL(clicked()), this, SLOT(RevertPerspective())); connect(ui->makeDefaultButton, SIGNAL(clicked()), this, SLOT(MakeDefaultPerspective())); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(DeletePerspective())); this->Update(); } QWidget* PerspectivesPreferencePage::GetQtControl() const { return pageWidget; } bool PerspectivesPreferencePage::PerformOk() { // Set the default perspective if (defaultPerspectiveId != perspRegistry->GetDefaultPerspective()) { perspRegistry->SetDefaultPerspective(defaultPerspectiveId); } //Delete the perspective if(perspectives.size() < perspRegistry->GetPerspectives().size()) { QList windows = workbench->GetWorkbenchWindows(); // close any perspectives that are about to be deleted for (int i = 0; i < windows.size(); i++) { QList pages = windows[i]->GetPages(); for (int j = 0; j < pages.size(); j++) { WorkbenchPage::Pointer page = pages[j].Cast(); for (int k = 0; k < perspToDelete.size(); k++) { IPerspectiveDescriptor::Pointer desc(perspToDelete[k].GetPointer()); if (page->FindPerspective(desc).IsNotNull()) { page->ClosePerspective(desc, true, true); } } } } perspRegistry->DeletePerspectives(perspToDelete); } // Revert the perspectives perspRegistry->RevertPerspectives(perspToRevert); // store the open perspective mode setting preferences->PutInt(PreferenceConstants::OPEN_PERSP_MODE, openPerspMode); return true; } void PerspectivesPreferencePage::PerformCancel() { } void PerspectivesPreferencePage::Update() { preferences = WorkbenchPlugin::GetDefault()->GetPreferences(); openPerspMode = preferences->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); ui->sameWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_ACTIVE_PAGE); ui->newWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_NEW_WINDOW); // Populate the perspectivesTable perspectives.clear(); perspToRevert.clear(); perspToDelete.clear(); QList persps = perspRegistry->GetPerspectives(); for (int i = 0; i < persps.size(); i++) { perspectives.push_back(persps[i].Cast()); } qSort(perspectives.begin(), perspectives.end(), PerspectiveComparator); defaultPerspectiveId = perspRegistry->GetDefaultPerspective(); UpdatePerspectivesTable(); } void PerspectivesPreferencePage::OpenPerspInSameWindow() { openPerspMode = PreferenceConstants::OPM_ACTIVE_PAGE; } void PerspectivesPreferencePage::OpenPerspInNewWindow() { openPerspMode = PreferenceConstants::OPM_NEW_WINDOW; } void PerspectivesPreferencePage::PerspectiveSelectionChanged() { UpdateButtons(); } void PerspectivesPreferencePage::RevertPerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToRevert.contains(desc)) { perspToRevert.push_back(desc); } UpdateButtons(); } void PerspectivesPreferencePage::DeletePerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToDelete.contains(desc)) { if (!FindOpenInstance(desc)) { perspToDelete.push_back(desc); perspToRevert.removeAll(desc); perspectives.removeAll(desc); UpdatePerspectivesTable(); } } UpdateButtons(); } void PerspectivesPreferencePage::MakeDefaultPerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToDelete.contains(desc)) { int row = perspectives.indexOf(desc); defaultPerspectiveId = desc->GetId(); UpdatePerspectivesTable(); ui->perspectivesListWidget->item(row)->setSelected(true); } UpdateButtons(); } void PerspectivesPreferencePage::UpdateButtons() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc) { ui->revertButton->setEnabled(desc->IsPredefined() && desc->HasCustomDefinition() && !perspToRevert.contains(desc)); ui->deleteButton->setEnabled(!desc->IsPredefined()); ui->makeDefaultButton->setEnabled(true); } else { ui->revertButton->setEnabled(false); ui->deleteButton->setEnabled(false); ui->makeDefaultButton->setEnabled(false); } } void PerspectivesPreferencePage::UpdatePerspectivesTable() { ui->perspectivesListWidget->clear(); for (const PerspectiveDescriptor::Pointer &desc : qAsConst(perspectives)) { NewPerspectivesTableItem(desc); } } void PerspectivesPreferencePage::NewPerspectivesTableItem(const SmartPointer& desc) { QString label = desc->GetLabel(); if (desc->GetId() == defaultPerspectiveId) { label += " (default)"; } new QListWidgetItem(desc->GetImageDescriptor(), label, ui->perspectivesListWidget); } bool PerspectivesPreferencePage::FindOpenInstance(const PerspectiveDescriptor::Pointer& desc) { QList windows = workbench->GetWorkbenchWindows(); //find all active perspectives currently for (int i = 0; i < windows.size(); i++) { QList pages = windows[i]->GetPages(); for (int j = 0; j < pages.size(); j++) { WorkbenchPage::Pointer page = pages[j].Cast(); if (page->FindPerspective(desc).IsNotNull()) { QMessageBox::StandardButton returnCode = QMessageBox::question(workbench->GetActiveWorkbenchWindow()->GetShell()->GetControl(), "Delete Perspective", QString("Are you sure you want to delete the \"%1\" perspective? It has open instances.").arg(desc->GetLabel()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); return (returnCode != QMessageBox::Yes); } } } return false; } SmartPointer PerspectivesPreferencePage::GetSelectedPerspective() const { PerspectiveDescriptor::Pointer desc; QList selection = ui->perspectivesListWidget->selectedItems(); if (!selection.isEmpty()) { int row = ui->perspectivesListWidget->row(selection.back()); if (row > -1) { desc = perspectives.at(row); } } return desc; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h index b3b3991761..630920adda 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h @@ -1,81 +1,86 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYPERSPECTIVESPREFERENCEPAGE_H #define BERRYPERSPECTIVESPREFERENCEPAGE_H #include +namespace mitk +{ + class IPreferences; +} + namespace Ui { class PerspectivesPreferencePage; } namespace berry { class PerspectiveDescriptor; class PerspectiveRegistry; class PerspectivesPreferencePage : public QObject, public IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: PerspectivesPreferencePage(); ~PerspectivesPreferencePage() override; void Init(IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; private: Q_SLOT void OpenPerspInSameWindow(); Q_SLOT void OpenPerspInNewWindow(); Q_SLOT void PerspectiveSelectionChanged(); Q_SLOT void RevertPerspective(); Q_SLOT void DeletePerspective(); Q_SLOT void MakeDefaultPerspective(); void UpdateButtons(); void UpdatePerspectivesTable(); void NewPerspectivesTableItem(const SmartPointer& desc); bool FindOpenInstance(const SmartPointer& desc); SmartPointer GetSelectedPerspective() const; Ui::PerspectivesPreferencePage* ui; QWidget* pageWidget; int openPerspMode; - SmartPointer preferences; + mitk::IPreferences* preferences; IWorkbench* workbench; PerspectiveRegistry* perspRegistry; QString defaultPerspectiveId; QList > perspectives; QList > perspToRevert; QList > perspToDelete; }; } #endif // BERRYPERSPECTIVESPREFERENCEPAGE_H diff --git a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp index fd441126b0..3d44bd4a04 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp @@ -1,137 +1,138 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryShowPerspectiveHandler.h" -#include #include #include #include #include #include "internal/berryPreferenceConstants.h" #include "internal/berryQtShowPerspectiveDialog.h" #include "internal/berryWorkbench.h" #include "berryWorkbenchPlugin.h" #include +#include + namespace berry { Object::Pointer ShowPerspectiveHandler::Execute(const ExecutionEvent::ConstPointer& event) { IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); // Get the perspective identifier, if any. const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); auto idParam = parameters.find(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID); auto newWindowParam = parameters.find(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW); if (idParam == parameters.end() || idParam.value().isEmpty()) { OpenOther(window.GetPointer()); } else { if (newWindowParam == parameters.end() || newWindowParam.value().compare("false", Qt::CaseInsensitive) == 0) { OpenPerspective(idParam.value(), window.GetPointer()); } else { OpenNewWindowPerspective(idParam.value(), window.GetPointer()); } } return Object::Pointer(); } void ShowPerspectiveHandler::OpenNewWindowPerspective(const QString& perspectiveId, const IWorkbenchWindow* activeWorkbenchWindow) { IWorkbench* workbench = activeWorkbenchWindow->GetWorkbench(); try { IAdaptable* input = dynamic_cast(workbench)->GetDefaultPageInput(); workbench->OpenWorkbenchWindow(perspectiveId, input); } catch (const WorkbenchException& e) { QMessageBox::critical(activeWorkbenchWindow->GetShell()->GetControl(), "Problems Changing Perspective", e.message()); // ErrorDialog.openError(activeWorkbenchWindow.getShell(), // WorkbenchMessages.ChangeToPerspectiveMenu_errorTitle, e // .getMessage(), e.getStatus()); } } void ShowPerspectiveHandler::OpenOther(IWorkbenchWindow* activeWorkbenchWindow) { QtShowPerspectiveDialog dialog(activeWorkbenchWindow->GetWorkbench()->GetPerspectiveRegistry(), activeWorkbenchWindow->GetShell()->GetControl()); int returnCode = dialog.exec(); if (returnCode == QDialog::Rejected) { return; } QString perspectiveId = dialog.GetSelection(); if (!perspectiveId.isEmpty()) { int openPerspMode = WorkbenchPlugin::GetDefault()->GetPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage(); IPerspectiveDescriptor::Pointer persp = page == nullptr ? IPerspectiveDescriptor::Pointer() : page->GetPerspective(); // only open it in a new window if the preference is set and the // current workbench page doesn't have an active perspective if (PreferenceConstants::OPM_NEW_WINDOW == openPerspMode && persp.IsNotNull()) { OpenNewWindowPerspective(perspectiveId, activeWorkbenchWindow); } else { OpenPerspective(perspectiveId, activeWorkbenchWindow); } } } void ShowPerspectiveHandler::OpenPerspective(const QString& perspectiveId, IWorkbenchWindow* activeWorkbenchWindow) { IWorkbench* workbench = activeWorkbenchWindow->GetWorkbench(); IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); IPerspectiveDescriptor::Pointer desc = workbench->GetPerspectiveRegistry()->FindPerspectiveWithId(perspectiveId); if (desc.IsNull()) { throw ExecutionException(QString("Perspective ") + perspectiveId + " cannot be found."); } try { if (activePage.IsNotNull()) { activePage->SetPerspective(desc); } else { IAdaptable* input = dynamic_cast(workbench)->GetDefaultPageInput(); activeWorkbenchWindow->OpenPage(perspectiveId, input); } } catch (const WorkbenchException& e) { throw ExecutionException("Perspective could not be opened.", e); } } } diff --git a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp index 0c5b39723a..6f00d0b756 100644 --- a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp +++ b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp @@ -1,72 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkCoreExtActivator.h" #include "mitkCoreExtConstants.h" #include "mitkLogMacros.h" -#include -#include -#include - #include +#include +#include +#include + +#include + +US_INITIALIZE_MODULE + namespace mitk { void CoreExtActivator::start(ctkPluginContext* context) { Q_UNUSED(context) this->StartInputDeviceModules(context); } void CoreExtActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } void CoreExtActivator::StartInputDeviceModules(ctkPluginContext* context) { m_InputDeviceRegistry.reset(new InputDeviceRegistry()); context->registerService(m_InputDeviceRegistry.data()); - // Gets the last setting of the preferences; if a device was selected, - // it will still be activated after a restart - ctkServiceReference prefServiceRef = context->getServiceReference(); - if (!prefServiceRef) - { - MITK_WARN << "Preferences service not available"; - return; - } - berry::IPreferencesService* prefService = context->getService(prefServiceRef); - berry::IPreferences::Pointer extPreferencesNode = - prefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* extPreferencesNode = prefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES.toStdString()); // Initializes the modules QList descriptors(m_InputDeviceRegistry->GetInputDevices()); for (QList::const_iterator it = descriptors.begin(); it != descriptors.end(); ++it) { - if (extPreferencesNode->GetBool((*it)->GetID(), false)) + if (extPreferencesNode->GetBool((*it)->GetID().toStdString(), false)) { IInputDevice::Pointer temp = (*it)->CreateInputDevice(); temp->RegisterInputDevice(); } } } CoreExtActivator::~CoreExtActivator() { } } // end namespace mitk diff --git a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp index cd308e32cf..29c65ebc75 100644 --- a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp @@ -1,473 +1,465 @@ /*============================================================================ 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 "mitkWorkbenchUtil.h" -#include #include #include #include -#include -#include #include "mitkIDataStorageService.h" #include "mitkDataStorageEditorInput.h" #include "mitkRenderingManager.h" #include "mitkIRenderingManager.h" #include "mitkProperties.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkCoreObjectFactory.h" +#include +#include +#include #include "QmitkIOUtil.h" #include #include #include #include "internal/org_mitk_gui_common_Activator.h" namespace mitk { struct WorkbenchUtilPrivate { /** * Get the editor descriptor for a given name using the editorDescriptor * passed in as a default as a starting point. * * @param name * The name of the element to open. * @param editorReg * The editor registry to do the lookups from. * @param defaultDescriptor * IEditorDescriptor or null * @return IEditorDescriptor * @throws PartInitException * if no valid editor can be found */ static berry::IEditorDescriptor::Pointer GetEditorDescriptor(const QString& name, berry::IEditorRegistry* editorReg, berry::IEditorDescriptor::Pointer defaultDescriptor) { if (defaultDescriptor.IsNotNull()) { return defaultDescriptor; } berry::IEditorDescriptor::Pointer editorDesc = defaultDescriptor; // next check the OS for in-place editor (OLE on Win32) if (editorReg->IsSystemInPlaceEditorAvailable(name)) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_INPLACE_EDITOR_ID); } // next check with the OS for an external editor if (editorDesc.IsNull() && editorReg->IsSystemExternalEditorAvailable(name)) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } // if no valid editor found, bail out if (editorDesc.IsNull()) { throw berry::PartInitException("No editor found"); } return editorDesc; } static mitk::IDataStorageReference::Pointer GetDataStorageReference() { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = nullptr; ctkServiceReference dsRef = context->getServiceReference(); if (dsRef) { dss = context->getService(dsRef); } if (nullptr == dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return mitk::IDataStorageReference::Pointer(nullptr); } // Get the active data storage (or the default one, if none is active) mitk::IDataStorageReference::Pointer dataStorageRef = dss->GetDataStorage(); context->ungetService(dsRef); return dataStorageRef; } }; // end struct WorkbenchUtilPrivate //! [UtilLoadFiles] void WorkbenchUtil::LoadFiles(const QStringList &fileNames, berry::IWorkbenchWindow::Pointer window, bool openEditor) //! [UtilLoadFiles] { if (fileNames.empty()) { return; } mitk::IDataStorageReference::Pointer dataStorageReference = WorkbenchUtilPrivate::GetDataStorageReference(); if (nullptr == dataStorageReference) { return; } mitk::DataStorage::Pointer dataStorage = dataStorageReference->GetDataStorage(); // Turn off ASSERT #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) int lastCrtReportType = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); #endif // Do the actual work of loading the data into the data storage DataStorage::SetOfObjects::Pointer data; try { data = QmitkIOUtil::Load(fileNames, *dataStorage); } catch (const mitk::Exception& e) { MITK_INFO << e; return; } const bool dsmodified = !data->empty(); // Set ASSERT status back to previous status. #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) if (lastCrtReportType) _CrtSetReportMode(_CRT_ASSERT, lastCrtReportType); #endif // Check if there is an open perspective. If not, open the default perspective. if (window->GetActivePage().IsNull()) { QString defaultPerspId = window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); window->GetWorkbench()->ShowPerspective(defaultPerspId, window); } bool globalReinitOnNodeAdded = true; - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); if (prefService != nullptr) { - berry::IPreferences::Pointer prefs - = prefService->GetSystemPreferences()->Node("org.mitk.views.datamanager"); - if (prefs.IsNotNull()) - { + auto* prefs = prefService->GetSystemPreferences()->Node("org.mitk.views.datamanager"); + + if (prefs != nullptr) globalReinitOnNodeAdded = prefs->GetBool("Call global reinit if node is added", true); - } } if (openEditor && globalReinitOnNodeAdded) { try { // Activate the editor using the same data storage or open the default editor mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(dataStorageReference)); berry::IEditorPart::Pointer editor = mitk::WorkbenchUtil::OpenEditor(window->GetActivePage(), input, true); mitk::IRenderWindowPart* renderEditor = dynamic_cast(editor.GetPointer()); mitk::IRenderingManager* renderingManager = renderEditor == nullptr ? nullptr : renderEditor->GetRenderingManager(); if (dsmodified && renderingManager) { mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } } catch (const berry::PartInitException& e) { QString msg = "An error occurred when displaying the file(s): %1"; QMessageBox::warning(QApplication::activeWindow(), "Error displaying file", msg.arg(e.message())); } } } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, berry::IEditorInput::Pointer input, const QString &editorId, bool activate) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be nullptr"); } // open the editor on the input return page->OpenEditor(input, editorId, activate); } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, mitk::DataStorageEditorInput::Pointer input, bool activate, bool determineContentType) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be nullptr"); } // open the editor on the data storage QString name = input->GetName() + ".mitk"; berry::IEditorDescriptor::Pointer editorDesc = WorkbenchUtilPrivate::GetEditorDescriptor(name, berry::PlatformUI::GetWorkbench()->GetEditorRegistry(), GetDefaultEditor(name, determineContentType)); return page->OpenEditor(input, editorDesc->GetId(), activate); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetEditorDescriptor(const QString& name, bool /*inferContentType*/) { if (name.isEmpty()) { throw std::invalid_argument("name argument must not be empty"); } // no used for now //IContentType contentType = inferContentType ? Platform // .getContentTypeManager().findContentTypeFor(name) : null; berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); return WorkbenchUtilPrivate::GetEditorDescriptor(name, editorReg, editorReg->GetDefaultEditor(name /*, contentType*/)); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetDefaultEditor(const QString& name, bool /*determineContentType*/) { // Try file specific editor. berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); try { QString editorID; // = file.getPersistentProperty(EDITOR_KEY); if (!editorID.isEmpty()) { berry::IEditorDescriptor::Pointer desc = editorReg->FindEditor(editorID); if (desc.IsNotNull()) { return desc; } } } catch (const berry::CoreException&) { // do nothing } // IContentType contentType = null; // if (determineContentType) // { // contentType = getContentType(file); // } // Try lookup with filename return editorReg->GetDefaultEditor(name); //, contentType); } mitk::IRenderWindowPart* WorkbenchUtil::GetRenderWindowPart(berry::IWorkbenchPage::Pointer page, IRenderWindowPartStrategies strategies) { // Return the active editor if it implements mitk::IRenderWindowPart mitk::IRenderWindowPart* renderWindowPart = dynamic_cast(page->GetActiveEditor().GetPointer()); if (renderWindowPart) { return renderWindowPart; } // No suitable active editor found, check visible editors QList editors = page->GetEditorReferences(); for (QList::iterator i = editors.begin(); i != editors.end(); ++i) { berry::IWorkbenchPart::Pointer part = (*i)->GetPart(false); if (page->IsPartVisible(part)) { renderWindowPart = dynamic_cast(part.GetPointer()); if (renderWindowPart) { return renderWindowPart; } } } // No suitable visible editor found, check visible views QList views = page->GetViewReferences(); for (QList::iterator i = views.begin(); i != views.end(); ++i) { berry::IWorkbenchPart::Pointer part = (*i)->GetPart(false); if (page->IsPartVisible(part)) { renderWindowPart = dynamic_cast(part.GetPointer()); if (renderWindowPart) { return renderWindowPart; } } } // No strategies given if (strategies == NONE) { return nullptr; } mitk::IDataStorageReference::Pointer dataStorageReference = WorkbenchUtilPrivate::GetDataStorageReference(); if (nullptr == dataStorageReference) { return nullptr; } mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(dataStorageReference)); bool activate = false; if (strategies & ACTIVATE) { activate = true; } berry::IEditorPart::Pointer editorPart; if (strategies & OPEN) { // This will create a default editor for the given input. If an editor // with that input is already open, the editor is brought to the front. try { editorPart = mitk::WorkbenchUtil::OpenEditor(page, input, activate); } catch (const berry::PartInitException&) { // There is no editor registered which can handle the given input. } } else if (activate || (strategies & BRING_TO_FRONT)) { // check if a suitable editor is already opened editorPart = page->FindEditor(input); if (editorPart) { if (activate) { page->Activate(editorPart); } else { page->BringToTop(editorPart); } } } return dynamic_cast(editorPart.GetPointer()); } mitk::IRenderWindowPart* WorkbenchUtil::OpenRenderWindowPart(berry::IWorkbenchPage::Pointer page, bool activatedEditor/* = true*/) { if (activatedEditor) { return GetRenderWindowPart(page, ACTIVATE | OPEN); } else { return GetRenderWindowPart(page, BRING_TO_FRONT | OPEN); } } bool WorkbenchUtil::SetDepartmentLogoPreference(const QString &logoResource, ctkPluginContext *context) { if (context == nullptr) { BERRY_WARN << "Plugin context invalid, unable to set custom logo."; return false; } // The logo must be available in the local filesystem. We check if we have not already extracted the // logo from the plug-in or if this plug-ins timestamp is newer then the already extracted logo timestamp. // If one of the conditions is true, extract it and write it to the plug-in specific storage location. const QString logoFileName = logoResource.mid(logoResource.lastIndexOf('/') + 1); if (logoFileName.isEmpty()) { BERRY_WARN << "Logo file name empty, unable to set custom logo."; return false; } const QString logoPath = context->getDataFile("").absoluteFilePath(); bool extractLogo = true; QFileInfo logoFileInfo(logoPath + "/" + logoFileName); if (logoFileInfo.exists()) { // The logo has been extracted previously. Check if the plugin timestamp is newer, which // means it might contain an updated logo. QString pluginLocation = QUrl(context->getPlugin()->getLocation()).toLocalFile(); if (!pluginLocation.isEmpty()) { QFileInfo pluginFileInfo(pluginLocation); if (logoFileInfo.lastModified() > pluginFileInfo.lastModified()) { extractLogo = false; } } } if (extractLogo) { // Extract the logo from the shared library and write it to disk. QFile logo(logoResource); if (!logo.exists()) { BERRY_WARN << "Custom logo '" << logoResource << "' does not exist."; return false; } if (logo.open(QIODevice::ReadOnly)) { QFile localLogo(logoPath + "/" + logoFileName); if (localLogo.open(QIODevice::WriteOnly)) { localLogo.write(logo.readAll()); localLogo.flush(); } } } logoFileInfo.refresh(); if (logoFileInfo.exists()) { - // Get the preferences service - ctkServiceReference prefServiceRef = context->getServiceReference(); - berry::IPreferencesService* prefService = nullptr; - if (prefServiceRef) - { - prefService = context->getService(prefServiceRef); - } + auto* prefService = mitk::CoreServices::GetPreferencesService(); - if (prefService) + if (prefService != nullptr) { prefService->GetSystemPreferences()->Put("DepartmentLogo", qPrintable(logoFileInfo.absoluteFilePath())); } else { BERRY_WARN << "Preferences service not available, unable to set custom logo."; return false; } } else { BERRY_WARN << "Custom logo at '" << logoFileInfo.absoluteFilePath().toStdString() << "' does not exist."; return false; } return true; } } // namespace mitk diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeRemoveAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeRemoveAction.cpp index d27dc9c17a..864d1adf92 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeRemoveAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeRemoveAction.cpp @@ -1,118 +1,116 @@ /*============================================================================ 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 // qt #include -// berry -#include -#include -#include +#include +#include +#include namespace RemoveAction { void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, mitk::DataStorage::Pointer dataStorage, const QList& selectedNodes, QWidget* parent /* = nullptr*/) { if (selectedNodes.empty()) { return; } QString question("Do you really want to remove "); for (auto& dataNode : selectedNodes) { if (nullptr == dataNode) { continue; } question.append(QString::fromStdString(dataNode->GetName())); question.append(", "); } // remove the last two characters = ", " question = question.remove(question.size() - 2, 2); question.append(" from data storage?"); QMessageBox::StandardButton answerButton = QMessageBox::question(parent, "DataManager", question, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (answerButton == QMessageBox::Yes) { for (auto& dataNode : selectedNodes) { if (nullptr == dataNode) { continue; } dataStorage->Remove(dataNode); } - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer preferencesNode = - prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* preferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID.toStdString()); bool globalReinit = preferencesNode->GetBool("Call global reinit if node is deleted", true); if (globalReinit) { GlobalReinitAction::Run(workbenchPartSite, dataStorage); } } } } QmitkDataNodeRemoveAction::QmitkDataNodeRemoveAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite) : QAction(parent) , QmitkAbstractDataNodeAction(workbenchpartSite) { setText(tr("Remove")); m_Parent = parent; InitializeAction(); } QmitkDataNodeRemoveAction::QmitkDataNodeRemoveAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite) : QAction(parent) , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite)) { setText(tr("Remove")); m_Parent = parent; InitializeAction(); } void QmitkDataNodeRemoveAction::InitializeAction() { connect(this, &QmitkDataNodeRemoveAction::triggered, this, &QmitkDataNodeRemoveAction::OnActionTriggered); } void QmitkDataNodeRemoveAction::OnActionTriggered(bool /*checked*/) { auto workbenchPartSite = m_WorkbenchPartSite.Lock(); if (workbenchPartSite.IsNull()) { return; } auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) { return; } auto selectedNodes = GetSelectedNodes(); RemoveAction::Run(workbenchPartSite, dataStorage, selectedNodes, m_Parent); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp index a3eb2dc0ab..d5aa7de5b4 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp @@ -1,103 +1,102 @@ /*============================================================================ 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 // mitk core #include -// berry -#include -#include -#include +#include +#include +#include // namespace that contains the concrete action namespace ToggleVisibilityAction { void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, mitk::DataStorage::Pointer dataStorage, const QList& selectedNodes /*= QList()*/, mitk::BaseRenderer* baseRenderer /*= nullptr*/) { bool isVisible; for (auto& node : selectedNodes) { if (node.IsNotNull()) { isVisible = false; node->GetBoolProperty("visible", isVisible, baseRenderer); node->SetVisibility(!isVisible, baseRenderer); } } - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - berry::IPreferences::Pointer preferences = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID); + auto* preferences = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID.toStdString()); bool globalReinit = preferences->GetBool("Call global reinit if node visibility is changed", false); if (globalReinit) { GlobalReinitAction::Run(workbenchPartSite, dataStorage); } else { if (nullptr == baseRenderer) { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } else { mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow()); } } } } QmitkDataNodeToggleVisibilityAction::QmitkDataNodeToggleVisibilityAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite) : QAction(parent) , QmitkAbstractDataNodeAction(workbenchpartSite) { setText(tr("Toggle visibility")); InitializeAction(); } QmitkDataNodeToggleVisibilityAction::QmitkDataNodeToggleVisibilityAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite) : QAction(parent) , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite)) { setText(tr("Toggle visibility")); InitializeAction(); } void QmitkDataNodeToggleVisibilityAction::InitializeAction() { connect(this, &QmitkDataNodeToggleVisibilityAction::triggered, this, &QmitkDataNodeToggleVisibilityAction::OnActionTriggered); } void QmitkDataNodeToggleVisibilityAction::OnActionTriggered(bool /*checked*/) { auto workbenchPartSite = m_WorkbenchPartSite.Lock(); if (workbenchPartSite.IsNull()) { return; } auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) { return; } mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer(); auto dataNodes = GetSelectedNodes(); ToggleVisibilityAction::Run(workbenchPartSite, dataStorage, dataNodes, baseRenderer); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp index b7cb403835..bbd6a6cde0 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp @@ -1,88 +1,86 @@ /*============================================================================ 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 "QmitkDefaultDropTargetListener.h" #include #include #include #include #include #include "internal/org_mitk_gui_qt_application_Activator.h" -#include -#include #include #include +#include +#include class QmitkDefaultDropTargetListenerPrivate { public: - berry::IPreferences::Pointer GetPreferences() const + mitk::IPreferences* GetPreferences() const { - berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); - if (prefService) - { - return prefService->GetSystemPreferences()->Node("/General"); - } - return berry::IPreferences::Pointer(nullptr); + auto* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); + + return prefService != nullptr + ? prefService->GetSystemPreferences()->Node("/General") + : nullptr; } bool GetOpenEditor() const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if(prefs.IsNotNull()) - { - return prefs->GetBool("OpenEditor", true); - } - return true; + auto* prefs = GetPreferences(); + + return prefs != nullptr + ? prefs->GetBool("OpenEditor", true) + : true; } }; QmitkDefaultDropTargetListener::QmitkDefaultDropTargetListener() : berry::IDropTargetListener(), d(new QmitkDefaultDropTargetListenerPrivate()) { } QmitkDefaultDropTargetListener::~QmitkDefaultDropTargetListener() { } berry::IDropTargetListener::Events::Types QmitkDefaultDropTargetListener::GetDropTargetEventTypes() const { return Events::DROP; } void QmitkDefaultDropTargetListener::DropEvent(QDropEvent *event) { qDebug() << event->mimeData()->formats(); qDebug() << event->mimeData()->text(); QList fileNames = event->mimeData()->urls(); if (fileNames.empty()) return; QStringList fileNames2; foreach(QUrl url, fileNames) { fileNames2.push_back(url.toLocalFile()); } mitk::WorkbenchUtil::LoadFiles(fileNames2, berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), d->GetOpenEditor()); event->accept(); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp index 7ce48eaa8a..0887b43a98 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp @@ -1,191 +1,188 @@ /*============================================================================ 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 "QmitkFileOpenAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include +#include +#include #include -#include - #include namespace { mitk::DataStorage::Pointer GetDataStorage() { auto context = mitk::org_mitk_gui_qt_application_Activator::GetContext(); if (nullptr == context) return nullptr; auto dataStorageServiceReference = context->getServiceReference(); if (!dataStorageServiceReference) return nullptr; auto dataStorageService = context->getService(dataStorageServiceReference); if (nullptr == dataStorageService) return nullptr; auto dataStorageReference = dataStorageService->GetDataStorage(); if (dataStorageReference.IsNull()) return nullptr; return dataStorageReference->GetDataStorage(); } mitk::DataNode::Pointer GetFirstSelectedNode() { auto dataStorage = GetDataStorage(); if (dataStorage.IsNull()) return nullptr; auto selectedNodes = dataStorage->GetSubset(mitk::NodePredicateProperty::New("selected", mitk::BoolProperty::New(true))); if (selectedNodes->empty()) return nullptr; return selectedNodes->front(); } QString GetPathOfFirstSelectedNode() { auto firstSelectedNode = GetFirstSelectedNode(); if (firstSelectedNode.IsNull()) return ""; auto data = firstSelectedNode->GetData(); if (nullptr == data) return ""; auto pathProperty = data->GetConstProperty("path"); if (pathProperty.IsNull()) return ""; return QFileInfo(QString::fromStdString(pathProperty->GetValueAsString())).canonicalPath(); } } class QmitkFileOpenActionPrivate { public: void Init(berry::IWorkbenchWindow* window, QmitkFileOpenAction* action) { m_Window = window; action->setText("&Open File..."); action->setToolTip("Open data files (images, surfaces,...)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } - berry::IPreferences::Pointer GetPreferences() const + mitk::IPreferences* GetPreferences() const { - berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); - if (prefService != nullptr) - { - return prefService->GetSystemPreferences()->Node("/General"); - } - return berry::IPreferences::Pointer(nullptr); + auto* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); + + return prefService != nullptr + ? prefService->GetSystemPreferences()->Node("/General") + : nullptr; } QString GetLastFileOpenPath() const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if (prefs.IsNotNull()) - { - return prefs->Get("LastFileOpenPath", ""); - } - return QString(); + auto* prefs = GetPreferences(); + + return prefs != nullptr + ? QString::fromStdString(prefs->Get("LastFileOpenPath", "")) + : QString(); } void SetLastFileOpenPath(const QString& path) const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if (prefs.IsNotNull()) + auto* prefs = GetPreferences(); + if (prefs != nullptr) { - prefs->Put("LastFileOpenPath", path); + prefs->Put("LastFileOpenPath", path.toStdString()); prefs->Flush(); } } bool GetOpenEditor() const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if (prefs.IsNotNull()) - { - return prefs->GetBool("OpenEditor", true); - } - return true; + auto* prefs = GetPreferences(); + + return prefs != nullptr + ? prefs->GetBool("OpenEditor", true) + : true; } berry::IWorkbenchWindow* m_Window; }; QmitkFileOpenAction::QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) , d(new QmitkFileOpenActionPrivate) { d->Init(window.GetPointer(), this); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) , d(new QmitkFileOpenActionPrivate) { d->Init(window.GetPointer(), this); setIcon(icon); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon& icon, berry::IWorkbenchWindow* window) : QAction(nullptr), d(new QmitkFileOpenActionPrivate) { d->Init(window, this); setIcon(icon); } QmitkFileOpenAction::~QmitkFileOpenAction() { } void QmitkFileOpenAction::Run() { auto path = GetPathOfFirstSelectedNode(); if (path.isEmpty()) path = d->GetLastFileOpenPath(); // Ask the user for a list of files to open QStringList fileNames = QFileDialog::getOpenFileNames(nullptr, "Open", path, QmitkIOUtil::GetFileOpenFilterString()); if (fileNames.empty()) { return; } d->SetLastFileOpenPath(fileNames.front()); mitk::WorkbenchUtil::LoadFiles(fileNames, berry::IWorkbenchWindow::Pointer(d->m_Window), d->GetOpenEditor()); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp index d945baac54..24aba232fb 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp @@ -1,275 +1,274 @@ /*============================================================================ 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 "QmitkFileSaveAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include +#include +#include #include #include -#include #include #include #include namespace { mitk::DataStorage::Pointer GetDataStorage() { auto context = mitk::org_mitk_gui_qt_application_Activator::GetContext(); if (nullptr == context) return nullptr; auto dataStorageServiceReference = context->getServiceReference(); if (!dataStorageServiceReference) return nullptr; auto dataStorageService = context->getService(dataStorageServiceReference); if (nullptr == dataStorageService) return nullptr; auto dataStorageReference = dataStorageService->GetDataStorage(); if (dataStorageReference.IsNull()) return nullptr; return dataStorageReference->GetDataStorage(); } QString GetParentPath(mitk::DataNode::Pointer dataNode) { if (dataNode.IsNull()) return ""; auto dataStorage = GetDataStorage(); if (dataStorage.IsNull()) return ""; auto sources = dataStorage->GetSources(dataNode); if (sources.IsNull() || sources->empty()) return ""; const auto &parentNode = sources->front(); if (parentNode.IsNull()) return ""; auto data = parentNode->GetData(); if (nullptr != data) { auto pathProperty = data->GetConstProperty("path"); if (pathProperty.IsNotNull()) return QFileInfo(QString::fromStdString(pathProperty->GetValueAsString())).canonicalPath(); } return GetParentPath(parentNode); } } class QmitkFileSaveActionPrivate { private: void HandleSelectionChanged(const berry::IWorkbenchPart::Pointer& /*part*/, const berry::ISelection::ConstPointer& selection) { this->SetEnabled(selection); } QScopedPointer m_SelectionListener; public: QmitkFileSaveActionPrivate() : m_SelectionListener(new berry::NullSelectionChangedAdapter( this, &QmitkFileSaveActionPrivate::HandleSelectionChanged)) { } ~QmitkFileSaveActionPrivate() { auto window = m_Window.Lock(); if (window.IsNotNull()) { window->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data()); } } void Init(berry::IWorkbenchWindow* window, QAction* action) { m_Window = berry::IWorkbenchWindow::Pointer(window); m_Action = action; m_Action->setText("&Save..."); m_Action->setToolTip("Save data objects (images, surfaces,...)"); berry::ISelectionService* selectionService = m_Window.Lock()->GetSelectionService(); SetEnabled(selectionService->GetSelection()); selectionService->AddSelectionListener(m_SelectionListener.data()); QObject::connect(m_Action, SIGNAL(triggered(bool)), m_Action, SLOT(Run())); } - berry::IPreferences::Pointer GetPreferences() const + mitk::IPreferences* GetPreferences() const { - berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); - if (prefService != nullptr) - { - return prefService->GetSystemPreferences()->Node("/General"); - } - return berry::IPreferences::Pointer(nullptr); + auto* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); + + return prefService != nullptr + ? prefService->GetSystemPreferences()->Node("/General") + : nullptr; } QString GetLastFileSavePath() const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if (prefs.IsNotNull()) - { - return prefs->Get("LastFileSavePath", ""); - } - return QString(); + auto* prefs = GetPreferences(); + + return prefs != nullptr + ? QString::fromStdString(prefs->Get("LastFileSavePath", "")) + : QString(); } void SetLastFileSavePath(const QString& path) const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if (prefs.IsNotNull()) + auto* prefs = GetPreferences(); + if (prefs != nullptr) { - prefs->Put("LastFileSavePath", path); + prefs->Put("LastFileSavePath", path.toStdString()); prefs->Flush(); } } void SetEnabled(berry::ISelection::ConstPointer selection) { mitk::DataNodeSelection::ConstPointer nodeSelection = selection.Cast(); if (nodeSelection.IsNotNull() && !selection->IsEmpty()) { bool enable = false; std::list dataNodes = nodeSelection->GetSelectedDataNodes(); for (std::list::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { if ((*nodeIter)->GetData() != nullptr) { enable = true; break; } } m_Action->setEnabled(enable); } else { m_Action->setEnabled(false); } } berry::IWorkbenchWindow::WeakPtr m_Window; QAction* m_Action; }; QmitkFileSaveAction::QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window) : QAction(tr("Save...")) , d(new QmitkFileSaveActionPrivate) { d->Init(window.GetPointer(), this); } QmitkFileSaveAction::QmitkFileSaveAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(tr("Save...")) , d(new QmitkFileSaveActionPrivate) { d->Init(window.GetPointer(), this); setIcon(icon); } QmitkFileSaveAction::QmitkFileSaveAction(const QIcon& icon, berry::IWorkbenchWindow* window) : QAction(tr("Save...")) , d(new QmitkFileSaveActionPrivate) { d->Init(window, this); setIcon(icon); } QmitkFileSaveAction::~QmitkFileSaveAction() { } void QmitkFileSaveAction::Run() { // get the list of selected base data objects mitk::DataNodeSelection::ConstPointer selection = d->m_Window.Lock()->GetSelectionService()->GetSelection().Cast(); if (selection.IsNull() || selection->IsEmpty()) { MITK_ERROR << "Assertion failed: data node selection is nullptr or empty"; return; } std::list dataNodes = selection->GetSelectedDataNodes(); std::vector data; QStringList names; for (std::list::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { data.push_back((*nodeIter)->GetData()); std::string name; (*nodeIter)->GetStringProperty("name", name); names.push_back(QString::fromStdString(name)); } QString path; if (1 == data.size()) { if (nullptr != data[0]) { auto pathProperty = data[0]->GetConstProperty("path"); if (pathProperty.IsNotNull()) path = QFileInfo(QString::fromStdString(pathProperty->GetValueAsString())).canonicalPath(); } if (path.isEmpty()) path = GetParentPath(dataNodes.front()); } if (path.isEmpty()) path = d->GetLastFileSavePath(); try { auto setPathProperty = true; auto fileNames = QmitkIOUtil::Save(data, names, path, d->m_Action->parentWidget(), setPathProperty); if (!fileNames.empty()) d->SetLastFileSavePath(QFileInfo(fileNames.back()).absolutePath()); } catch (const mitk::Exception& e) { MITK_INFO << e; return; } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp index c033a7d94f..52593cb3cd 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp @@ -1,485 +1,385 @@ /*============================================================================ 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 "QmitkPreferencesDialog.h" #include "berryPlatform.h" #include "berryPlatformUI.h" #include "berryIWorkbench.h" #include "berryIConfigurationElement.h" #include "berryIExtensionRegistry.h" #include "berryIExtension.h" -#include #include #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include #include #include +#include +#include +#include using namespace std; static std::vector splitString(const std::string &s, char delim=' ') { std::vector < std::string > elems; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } class QmitkPreferencesDialogPrivate : public Ui::QmitkPreferencesDialog { public: /// /// Just a stub class for holding information on prefpages (metadata) /// struct PrefPage { PrefPage(QString _id, QString _name, QString _category , QString _className, QString _keywords, berry::IConfigurationElement::Pointer _confElem) : id(_id), name(_name), category(_category), className(_className), keywords(_keywords), prefPage(nullptr), confElem(_confElem), treeWidgetItem(nullptr) {} bool operator==(const PrefPage& other) { return id == other.id; } bool operator<(const PrefPage& other) { return name < other.name; } QString id; QString name; QString category; QString className; QString keywords; berry::IQtPreferencePage* prefPage; berry::IConfigurationElement::Pointer confElem; QTreeWidgetItem* treeWidgetItem; }; QmitkPreferencesDialogPrivate() : m_CurrentPage(0) { berry::IExtensionRegistry* xpService = berry::Platform::GetExtensionRegistry(); // m_PrefPages QList prefPages(xpService->GetConfigurationElementsFor("org.blueberry.ui.preferencePages")); QList keywordExts(xpService->GetConfigurationElementsFor("org.blueberry.ui.keywords")); QList::iterator prefPagesIt; QList::iterator keywordRefsIt; for (prefPagesIt = prefPages.begin(); prefPagesIt != prefPages.end(); ++prefPagesIt) { QString id = (*prefPagesIt)->GetAttribute("id"); QString name = (*prefPagesIt)->GetAttribute("name"); QString className = (*prefPagesIt)->GetAttribute("class"); if(!id.isEmpty() && !name.isEmpty() && !className.isEmpty()) { QString keywordLabels; QString category = (*prefPagesIt)->GetAttribute("category"); //# collect keywords QList keywordRefs = (*prefPagesIt)->GetChildren("keywordreference"); // get all keyword references for (keywordRefsIt = keywordRefs.begin() ; keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { QString keywordRefId = (*keywordRefsIt)->GetAttribute("id"); // get referenced id for (QList::iterator keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) // iterate over all keywords { QString keywordId = (*keywordExtsIt)->GetAttribute("id"); // get keyword id if(keywordId == keywordRefId) // if referenced id is equals the current keyword id { //# collect all keywords from label attribute with a tokenizer QString currLabel = (*keywordExtsIt)->GetAttribute("label"); currLabel = currLabel.toLower(); if (!currLabel.isEmpty()) keywordLabels += QString(" ") + currLabel; //break; // break here; possibly search for other referenced keywords } } } // add information as PrefPage m_PrefPages.push_back(PrefPage(id, name, category, className, keywordLabels, berry::IConfigurationElement::Pointer(*prefPagesIt))); } } } /// /// Saves all treewidgetitems in a map, the key is the id of the preferencepage. /// QList m_PrefPages; int m_CurrentPage; }; QmitkPreferencesDialog::QmitkPreferencesDialog(QWidget * parent, Qt::WindowFlags f) : QDialog(parent, f), d(new QmitkPreferencesDialogPrivate) { d->setupUi(this); QObject::connect(d->m_Keyword, SIGNAL(editingFinished()), this, SLOT(OnKeywordEditingFinished())); QObject::connect(d->m_Keyword, SIGNAL(textChanged(QString)), this, SLOT(OnKeywordTextChanged(QString))); QObject::connect(d->m_PreferencesTree, SIGNAL(itemSelectionChanged()), this, SLOT(OnPreferencesTreeItemSelectionChanged())); - QPushButton* importButton = d->buttonBox->addButton("Import...", QDialogButtonBox::ActionRole); - QObject::connect(importButton, SIGNAL(clicked()), this, SLOT(OnImportButtonClicked())); - - QPushButton* exportButton = d->buttonBox->addButton("Export...", QDialogButtonBox::ActionRole); - QObject::connect(exportButton, SIGNAL(clicked()), this, SLOT(OnExportButtonClicked())); - QObject::connect(this, SIGNAL(accepted()), this, SLOT(OnDialogAccepted())); QObject::connect(this, SIGNAL(rejected()), this, SLOT(OnDialogRejected())); this->UpdateTree(); } QmitkPreferencesDialog::~QmitkPreferencesDialog() { } void QmitkPreferencesDialog::SetSelectedPage(const QString& id) { for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { if(it->id == id) { d->m_PreferencesTree->setCurrentItem(it->treeWidgetItem); break; } } } -void QmitkPreferencesDialog::OnImportButtonClicked() -{ - int answer = QMessageBox::question(this, "Importing Preferences" - , "All existing preferences will be overwritten!\nAre you sure that you want to import other preferences?", QMessageBox::Yes | QMessageBox::No ); - if(answer == QMessageBox::No) - return; - - try - { - berry::IBerryPreferencesService* berryPrefService = - dynamic_cast(berry::Platform::GetPreferencesService()); - if(berryPrefService != nullptr) - { - static QString importDir = ""; - QString fileName = QFileDialog::getOpenFileName(this, tr("Choose file to import preferences"), - importDir, tr("XML files (*.xml)")); - - if(!fileName.isEmpty()) - { - importDir = QFileInfo(fileName).absoluteDir().path(); - berryPrefService->ImportPreferences(fileName, ""); - berry::IQtPreferencePage* prefPage = d->m_PrefPages[d->m_CurrentPage].prefPage; - if(prefPage) - prefPage->Update(); - - MITK_INFO("QmitkPreferencesDialog") << "Preferences successfully imported from " << fileName; - } - } - } - catch (Poco::Exception& pe) - { - QMessageBox::critical(this, "Error Importing", pe.message().c_str()); - MITK_ERROR("QmitkPreferencesDialog") << pe.what(); - } - catch (std::exception& e) - { - QMessageBox::critical(this, "Error Importing", e.what()); - MITK_ERROR("QmitkPreferencesDialog") << e.what(); - } -} - -void QmitkPreferencesDialog::OnExportButtonClicked() -{ - try - { - berry::IBerryPreferencesService* berryPrefService = - dynamic_cast(berry::Platform::GetPreferencesService()); - if(berryPrefService != nullptr) - { - SavePreferences(); - static QString exportDir = ""; - QString fileName = QFileDialog::getSaveFileName(this, tr("Choose file to export preferences"), - exportDir, tr("XML files (*.xml)")); - - if(!fileName.isEmpty()) - { - if(QFileInfo(fileName).suffix() != ".xml") - { - fileName += ".xml"; - } - exportDir = QFileInfo(fileName).absoluteDir().path(); - berryPrefService->ExportPreferences(fileName, ""); - MITK_INFO("QmitkPreferencesDialog") << "Preferences successfully exported to " << fileName; - } - } - } - catch (Poco::Exception& pe) - { - QMessageBox::critical(this, "Error Exporting", pe.message().c_str()); - MITK_ERROR("QmitkPreferencesDialog") << pe.what(); - } - catch (std::exception& e) - { - QMessageBox::critical(this, "Error Exporting", e.what()); - MITK_ERROR("QmitkPreferencesDialog") << e.what(); - } -} - void QmitkPreferencesDialog::SavePreferences() { berry::IQtPreferencePage* prefPage = nullptr; for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { prefPage = it->prefPage; if(prefPage) { prefPage->PerformOk(); } } /** * Every preference page has its own preferences, which should stay the same after a system restart.
* Therefore this method flushes all the preferences, every time a change in the preferences is
* performed and confirmed. * */ - berry::Platform::GetPreferencesService()->GetSystemPreferences()->Flush(); + mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Flush(); } void QmitkPreferencesDialog::OnDialogAccepted() { this->SavePreferences(); } void QmitkPreferencesDialog::OnDialogRejected() { berry::IQtPreferencePage* prefPage = d->m_PrefPages[d->m_CurrentPage].prefPage; if(prefPage) prefPage->PerformCancel(); } void QmitkPreferencesDialog::OnKeywordTextChanged(const QString & /*s*/) { // search for text this->UpdateTree(); } void QmitkPreferencesDialog::OnKeywordEditingFinished() { } -//bool QmitkPreferencesDialog::eventFilter( QObject *obj, QEvent *event ) -//{ -// if(obj == d->m_Keyword) -// { -// if(event->type() == QEvent::FocusIn && d->m_Keyword->text() == "search ...") -// { -// d->m_Keyword->setText(""); -// d->m_Keyword->setStyleSheet("color: black;"); -// } -// else if(event->type() == QEvent::FocusOut && d->m_Keyword->text() == "") -// { -// d->m_Keyword->setText("search ..."); -// d->m_Keyword->setStyleSheet("color: gray;"); -// } -// } -// return true; -//} - void QmitkPreferencesDialog::OnPreferencesTreeItemSelectionChanged() { if(d->m_PreferencesTree == nullptr) return; // TODO: create page and show it QList selectedItems = d->m_PreferencesTree->selectedItems(); if(selectedItems.size()>0) { d->m_CurrentPage = 0; berry::IWorkbench* workbench = berry::PlatformUI::GetWorkbench(); for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it, ++d->m_CurrentPage) { if(it->treeWidgetItem == selectedItems.at(0)) { d->m_Headline->setText(it->name); if(it->prefPage == nullptr) { berry::IPreferencePage* page = it->confElem->CreateExecutableExtension("class"); it->prefPage = dynamic_cast(page); it->prefPage->Init(berry::IWorkbench::Pointer(workbench)); it->prefPage->CreateQtControl(d->m_PreferencesPanel); d->m_PreferencesPanel->addWidget(it->prefPage->GetQtControl()); } d->m_PreferencesPanel->setCurrentWidget(it->prefPage->GetQtControl()); break; } } } } void QmitkPreferencesDialog::UpdateTree() { if(d->m_PreferencesTree == nullptr) return; d->m_PreferencesTree->sortByColumn(0, Qt::AscendingOrder); //m_PreferencesTree->clear(); QString keyword = d->m_Keyword->text().toLower(); map items; std::list< QList::iterator > deferredItems; for (QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { if (it->treeWidgetItem == nullptr) { if (it->category.isEmpty()) { it->treeWidgetItem = new QTreeWidgetItem(d->m_PreferencesTree); it->treeWidgetItem->setText(0, it->name); items[it->id] = it->treeWidgetItem; } else { // the parent might not be created yet deferredItems.push_back(it); } } } // deal with deferred items. We do not know how many levels // of parents need to be created auto currentItem = deferredItems.begin(); while (currentItem != deferredItems.end()) { auto currentItemContent = *currentItem; if (items[currentItemContent->category] != nullptr) { currentItemContent->treeWidgetItem = new QTreeWidgetItem(items[currentItemContent->category]); currentItemContent->treeWidgetItem->setText(0, currentItemContent->name); items[currentItemContent->id] = currentItemContent->treeWidgetItem; deferredItems.erase(currentItem); currentItem = deferredItems.begin(); } else { ++currentItem; } } if (!deferredItems.empty()) { MITK_ERROR << "Unknown preference category. They are added top-level."; for (const auto ¤tItemContent : deferredItems) { currentItemContent->treeWidgetItem = new QTreeWidgetItem(d->m_PreferencesTree); currentItemContent->treeWidgetItem->setText(0, currentItemContent->name); items[currentItemContent->id] = currentItemContent->treeWidgetItem; } } //First, set all pages to hidden to avoid prolems //when iterating over the child page first which contains a specific keyword //and sets the parent to visible //but after this the parent is searched for the keyword. However, the keyword might not be available //so the parent and all of its children will be set to hidden. if(!keyword.isEmpty()) { for (QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { it->treeWidgetItem->setHidden(true); } } // we have to iterate over the list a second time, as only // now all parents and items are guaranteed to be created for (QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { // hide treeWidgetItem if keyword not matches if(!keyword.isEmpty()) { //Split text of search box into multiple single strings vector keywordsAvailable = splitString(keyword.toUtf8().constData()); bool foundAll = true; //perform an AND-search for(unsigned int i = 0; i < keywordsAvailable.size(); i++) { if (it->keywords.indexOf(QString::fromStdString(keywordsAvailable[i])) == -1) { foundAll = false; break; } } if(foundAll) { //#make the whole branch visible QTreeWidgetItem* treeWidgetParent = it->treeWidgetItem->parent(); while(treeWidgetParent!=nullptr) { treeWidgetParent->setHidden(false); treeWidgetParent->setExpanded(true); treeWidgetParent = treeWidgetParent->parent(); } it->treeWidgetItem->setHidden(false); QFont f = it->treeWidgetItem->font(0); f.setBold(true); it->treeWidgetItem->setFont(0, f); } } else { QFont f = it->treeWidgetItem->font(0); f.setBold(false); it->treeWidgetItem->setFont(0, f); it->treeWidgetItem->setHidden(false); } } if(d->m_PrefPages.size()>0) { if(d->m_PrefPages.front().treeWidgetItem != nullptr) d->m_PrefPages.front().treeWidgetItem->setSelected(true); } d->m_PreferencesTree->expandAll(); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h index 0f97f83659..22716812db 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h @@ -1,64 +1,62 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYQMITKPREFERENCESDIALOG_H_ #define BERRYQMITKPREFERENCESDIALOG_H_ #include #include #include class QmitkPreferencesDialogPrivate; /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkPreferencesDialog : public QDialog { Q_OBJECT public: QmitkPreferencesDialog(QWidget * parent = nullptr, Qt::WindowFlags f = nullptr); ~QmitkPreferencesDialog() override; void SetSelectedPage(const QString& id); protected slots: - void OnImportButtonClicked(); - void OnExportButtonClicked(); void OnDialogAccepted(); void OnDialogRejected(); void OnKeywordTextChanged(const QString & s); void OnKeywordEditingFinished(); void OnPreferencesTreeItemSelectionChanged(); protected: //bool eventFilter(QObject *obj, QEvent *event); void UpdateTree(); /// /// Saves all preferencepages. /// void SavePreferences(); QScopedPointer d; }; #endif /* BERRYQMITKPREFERENCESDIALOG_H_ */ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkRedoAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkRedoAction.cpp index cd85eba203..5d2c5dab9b 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkRedoAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkRedoAction.cpp @@ -1,84 +1,82 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRedoAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include -#include - class QmitkRedoActionPrivate { public: void init ( berry::IWorkbenchWindow* window, QmitkRedoAction* action ) { m_Window = window; action->setText("&Redo"); action->setToolTip("execute the last action that was undone again (not supported by all modules)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IWorkbenchWindow* m_Window; }; QmitkRedoAction::QmitkRedoAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr), d(new QmitkRedoActionPrivate) { d->init(window.GetPointer(), this); } QmitkRedoAction::QmitkRedoAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr), d(new QmitkRedoActionPrivate) { d->init(window.GetPointer(), this); this->setIcon(icon); } QmitkRedoAction::QmitkRedoAction(const QIcon& icon, berry::IWorkbenchWindow* window) : QAction(nullptr), d(new QmitkRedoActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkRedoAction::~QmitkRedoAction() { } void QmitkRedoAction::Run() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkUndoAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkUndoAction.cpp index d43c6aa19b..87a2d5e748 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkUndoAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkUndoAction.cpp @@ -1,84 +1,82 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkUndoAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include -#include - class QmitkUndoActionPrivate { public: void init ( berry::IWorkbenchWindow* window, QmitkUndoAction* action ) { m_Window = window; action->setText("&Undo"); action->setToolTip("Undo the last action (not supported by all modules)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IWorkbenchWindow* m_Window; }; QmitkUndoAction::QmitkUndoAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr), d(new QmitkUndoActionPrivate) { d->init(window.GetPointer(), this); } QmitkUndoAction::QmitkUndoAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr), d(new QmitkUndoActionPrivate) { d->init(window.GetPointer(), this); this->setIcon(icon); } QmitkUndoAction::QmitkUndoAction(const QIcon& icon, berry::IWorkbenchWindow* window) : QAction(nullptr), d(new QmitkUndoActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkUndoAction::~QmitkUndoAction() { } void QmitkUndoAction::Run() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h index 43e79726cd..ee799b7b48 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h @@ -1,70 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKEDITORSPREFERENCEPAGE_H_ #define QMITKEDITORSPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" -#include class QWidget; class QmitkEditorsPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: /** * Default constructor */ QmitkEditorsPreferencePage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench) override; /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget) override; /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const override; /** * @see berry::IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @see berry::IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @see berry::IPreferencePage::Update() */ void Update() override; protected: QWidget* m_MainControl; }; #endif /* QMITKEDITORSPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp index 3d282cdf42..5a648390b6 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp @@ -1,74 +1,75 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkGeneralPreferencePage.h" #include "QmitkDataNodeGlobalReinitAction.h" #include #include -#include -#include +#include +#include +#include QmitkGeneralPreferencePage::QmitkGeneralPreferencePage() : m_MainControl(nullptr) { // nothing here } void QmitkGeneralPreferencePage::Init(berry::IWorkbench::Pointer) { // nothing here } void QmitkGeneralPreferencePage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID.toStdString()); m_MainControl = new QWidget(parent); m_GlobalReinitOnNodeDelete = new QCheckBox; m_GlobalReinitOnNodeVisibilityChanged = new QCheckBox; auto formLayout = new QFormLayout; formLayout->addRow("&Call global reinit if node is deleted", m_GlobalReinitOnNodeDelete); formLayout->addRow("&Call global reinit if node visibility is changed", m_GlobalReinitOnNodeVisibilityChanged); m_MainControl->setLayout(formLayout); Update(); } QWidget* QmitkGeneralPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkGeneralPreferencePage::PerformOk() { m_GeneralPreferencesNode->PutBool("Call global reinit if node is deleted", m_GlobalReinitOnNodeDelete->isChecked()); m_GeneralPreferencesNode->PutBool("Call global reinit if node visibility is changed", m_GlobalReinitOnNodeVisibilityChanged->isChecked()); return true; } void QmitkGeneralPreferencePage::PerformCancel() { // nothing here } void QmitkGeneralPreferencePage::Update() { m_GlobalReinitOnNodeDelete->setChecked(m_GeneralPreferencesNode->GetBool("Call global reinit if node is deleted", true)); m_GlobalReinitOnNodeVisibilityChanged->setChecked(m_GeneralPreferencesNode->GetBool("Call global reinit if node visibility is changed", false)); } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h index 4c9af6f890..214837be68 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h @@ -1,71 +1,75 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKGENERALPREFERENCEPAGE_H #define QMITKGENERALPREFERENCEPAGE_H #include "berryIQtPreferencePage.h" -#include class QWidget; class QCheckBox; +namespace mitk +{ + class IPreferences; +} + class QmitkGeneralPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkGeneralPreferencePage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench) override; /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget) override; /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const override; /** * @see berry::IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @see berry::IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @see berry::IPreferencePage::Update() */ void Update() override; protected: QWidget* m_MainControl; QCheckBox* m_GlobalReinitOnNodeDelete; QCheckBox* m_GlobalReinitOnNodeVisibilityChanged; - berry::IPreferences::Pointer m_GeneralPreferencesNode; + mitk::IPreferences* m_GeneralPreferencesNode; }; #endif // QMITKGENERALPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp index e8061f172f..d34efacf4d 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp @@ -1,68 +1,69 @@ /*============================================================================ 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 "org_mitk_gui_qt_application_Activator.h" +#include + #include "QmitkGeneralPreferencePage.h" #include "QmitkEditorsPreferencePage.h" #include #include "QmitkShowPreferencePageHandler.h" +#include + +US_INITIALIZE_MODULE + namespace mitk { org_mitk_gui_qt_application_Activator* org_mitk_gui_qt_application_Activator::m_Instance = nullptr; ctkPluginContext* org_mitk_gui_qt_application_Activator::m_Context = nullptr; void org_mitk_gui_qt_application_Activator::start(ctkPluginContext* context) { this->m_Instance = this; this->m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkGeneralPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkEditorsPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkShowPreferencePageHandler, context) QmitkRegisterClasses(); - - this->m_PrefServiceTracker.reset(new ctkServiceTracker(context)); - this->m_PrefServiceTracker->open(); } void org_mitk_gui_qt_application_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) - this->m_PrefServiceTracker.reset(); - this->m_Context = nullptr; this->m_Instance = nullptr; } ctkPluginContext* org_mitk_gui_qt_application_Activator::GetContext() { return m_Context; } org_mitk_gui_qt_application_Activator *org_mitk_gui_qt_application_Activator::GetInstance() { return m_Instance; } - berry::IPreferencesService* org_mitk_gui_qt_application_Activator::GetPreferencesService() + mitk::IPreferencesService* org_mitk_gui_qt_application_Activator::GetPreferencesService() { - return m_PrefServiceTracker->getService(); + return mitk::CoreServices::GetPreferencesService(); } } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h index f566d7c236..cb4d6d4948 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h @@ -1,55 +1,50 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include -#include - -#include - namespace mitk { +class IPreferencesService; + class org_mitk_gui_qt_application_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_application") Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context) override; void stop(ctkPluginContext* context) override; static ctkPluginContext* GetContext(); static org_mitk_gui_qt_application_Activator* GetInstance(); - berry::IPreferencesService* GetPreferencesService(); + mitk::IPreferencesService* GetPreferencesService(); private: static org_mitk_gui_qt_application_Activator* m_Instance; static ctkPluginContext* m_Context; - - QScopedPointer > m_PrefServiceTracker; - }; // org_mitk_gui_common_Activator typedef org_mitk_gui_qt_application_Activator PluginActivator; } #endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp index 6f5b9ee3a5..0b26b41e8f 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp @@ -1,257 +1,259 @@ /*============================================================================ 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 "CommandLineModulesPreferencesPage.h" #include "CommandLineModulesViewConstants.h" +#include +#include +#include + #include #include #include #include #include #include #include #include #include #include -#include -#include #include "QmitkDirectoryListWidget.h" #include "QmitkFileListWidget.h" //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::CommandLineModulesPreferencesPage() : m_MainControl(nullptr) , m_DebugOutput(nullptr) , m_ShowAdvancedWidgets(nullptr) , m_OutputDirectory(nullptr) , m_TemporaryDirectory(nullptr) , m_ModulesDirectories(nullptr) , m_ModulesFiles(nullptr) , m_GridLayoutForLoadCheckboxes(nullptr) , m_LoadFromHomeDir(nullptr) , m_LoadFromHomeDirCliModules(nullptr) , m_LoadFromCurrentDir(nullptr) , m_LoadFromCurrentDirCliModules(nullptr) , m_LoadFromApplicationDir(nullptr) , m_LoadFromApplicationDirCliModules(nullptr) , m_LoadFromAutoLoadPathDir(nullptr) , m_ValidationMode(nullptr) , m_MaximumNumberProcesses(nullptr) , m_CLIPreferencesNode(nullptr) { } //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::~CommandLineModulesPreferencesPage() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); - QString id = "/" + CommandLineModulesViewConstants::VIEW_ID; + const auto id = "/" + CommandLineModulesViewConstants::VIEW_ID; m_CLIPreferencesNode = prefService->GetSystemPreferences()->Node(id); m_MainControl = new QWidget(parent); m_TemporaryDirectory = new ctkDirectoryButton(m_MainControl); m_TemporaryDirectory->setCaption("Select a directory for temporary files ... "); m_OutputDirectory = new ctkDirectoryButton(m_MainControl); m_OutputDirectory->setCaption("Select a default directory for output files ... "); m_ModulesDirectories = new QmitkDirectoryListWidget(m_MainControl); m_ModulesDirectories->m_Label->setText("Select directories to scan:"); m_ModulesFiles = new QmitkFileListWidget(m_MainControl); m_ModulesFiles->m_Label->setText("Select additional executables:"); m_DebugOutput = new QCheckBox(m_MainControl); m_DebugOutput->setToolTip("Output debugging information to the console."); m_ShowAdvancedWidgets = new QCheckBox(m_MainControl); m_ShowAdvancedWidgets->setToolTip("If selected, additional widgets appear\nin front-end for advanced users."); m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl); m_LoadFromAutoLoadPathDir->setText("CTK_MODULE_LOAD_PATH"); m_LoadFromAutoLoadPathDir->setToolTip("Scan the directory specified by\nthe environment variable CTK_MODULE_LOAD_PATH."); m_LoadFromAutoLoadPathDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDir = new QCheckBox(m_MainControl); m_LoadFromApplicationDir->setText("install dir"); m_LoadFromApplicationDir->setToolTip("Scan the directory where\nthe application is installed."); m_LoadFromApplicationDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDirCliModules = new QCheckBox(m_MainControl); m_LoadFromApplicationDirCliModules->setText("install dir/cli-modules"); m_LoadFromApplicationDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the installation directory."); m_LoadFromApplicationDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDir = new QCheckBox(m_MainControl); m_LoadFromHomeDir->setText("home dir"); m_LoadFromHomeDir->setToolTip("Scan the users home directory."); m_LoadFromHomeDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDirCliModules = new QCheckBox(m_MainControl); m_LoadFromHomeDirCliModules->setText("home dir/cli-modules"); m_LoadFromHomeDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the users home directory."); m_LoadFromHomeDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDir = new QCheckBox(m_MainControl); m_LoadFromCurrentDir->setText("current dir"); m_LoadFromCurrentDir->setToolTip("Scan the current working directory\nfrom where the application was launched."); m_LoadFromCurrentDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDirCliModules = new QCheckBox(m_MainControl); m_LoadFromCurrentDirCliModules->setText("current dir/cli-modules"); m_LoadFromCurrentDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the current working directory \n from where the application was launched."); m_LoadFromCurrentDirCliModules->setLayoutDirection(Qt::RightToLeft); m_GridLayoutForLoadCheckboxes = new QGridLayout; m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDir, 0, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDirCliModules, 0, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDir, 1, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDirCliModules, 1, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDir, 2, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDirCliModules, 2, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromAutoLoadPathDir, 3, 1); m_ValidationMode = new QComboBox(m_MainControl); m_ValidationMode->addItem("strict", ctkCmdLineModuleManager::STRICT_VALIDATION); m_ValidationMode->addItem("none", ctkCmdLineModuleManager::SKIP_VALIDATION); m_ValidationMode->addItem("weak", ctkCmdLineModuleManager::WEAK_VALIDATION); m_ValidationMode->setCurrentIndex(0); m_MaximumNumberProcesses = new QSpinBox(m_MainControl); m_MaximumNumberProcesses->setMinimum(1); m_MaximumNumberProcesses->setMaximum(1000000); m_XmlTimeoutInSeconds = new QSpinBox(m_MainControl); m_XmlTimeoutInSeconds->setMinimum(1); m_XmlTimeoutInSeconds->setMaximum(3600); auto formLayout = new QFormLayout; formLayout->addRow("show debug output:", m_DebugOutput); formLayout->addRow("show advanced widgets:", m_ShowAdvancedWidgets); formLayout->addRow("XML time-out (secs):", m_XmlTimeoutInSeconds); formLayout->addRow("XML validation mode:", m_ValidationMode); formLayout->addRow("max. concurrent processes:", m_MaximumNumberProcesses); formLayout->addRow("scan:", m_GridLayoutForLoadCheckboxes); formLayout->addRow("additional module directories:", m_ModulesDirectories); formLayout->addRow("additional modules:", m_ModulesFiles); formLayout->addRow("temporary directory:", m_TemporaryDirectory); formLayout->addRow("default output directory:", m_OutputDirectory); m_MainControl->setLayout(formLayout); this->Update(); } //----------------------------------------------------------------------------- QWidget* CommandLineModulesPreferencesPage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- std::string CommandLineModulesPreferencesPage::ConvertToStdString(const QStringList& list) { std::string output; for (int i = 0; i < list.count(); i++) { QString path = list[i] + ";"; output += path.toStdString(); } return output; } //----------------------------------------------------------------------------- bool CommandLineModulesPreferencesPage::PerformOk() { - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory()); - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory()); + m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory().toStdString()); + m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory().toStdString()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, m_ShowAdvancedWidgets->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, m_LoadFromApplicationDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, m_LoadFromHomeDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, m_LoadFromCurrentDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); - QString paths = m_ModulesDirectories->directories().join(";"); + const auto paths = m_ModulesDirectories->directories().join(";").toStdString(); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, paths); - QString modules = m_ModulesFiles->files().join(";"); + const auto modules = m_ModulesFiles->files().join(";").toStdString(); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, modules); int currentValidationMode = m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2); if (currentValidationMode != m_ValidationMode->currentIndex()) { QMessageBox msgBox; msgBox.setText("Changing the XML validation mode will require a restart of the application."); msgBox.exec(); } m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, m_ValidationMode->currentIndex()); m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, m_XmlTimeoutInSeconds->value()); m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::MAX_CONCURRENT, m_MaximumNumberProcesses->value()); return true; } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::PerformCancel() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Update() { - QString fallbackTmpDir = QDir::tempPath(); - m_TemporaryDirectory->setDirectory(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir)); + const auto fallbackTmpDir = QDir::tempPath().toStdString(); + m_TemporaryDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir))); - QString fallbackOutputDir = QDir::homePath(); - m_OutputDirectory->setDirectory(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir)); + const auto fallbackOutputDir = QDir::homePath().toStdString(); + m_OutputDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir))); m_ShowAdvancedWidgets->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); m_DebugOutput->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false)); m_LoadFromApplicationDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false)); m_LoadFromApplicationDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true)); m_LoadFromHomeDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false)); m_LoadFromHomeDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false)); m_LoadFromCurrentDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false)); m_LoadFromCurrentDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false)); m_LoadFromAutoLoadPathDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); - QString paths = m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, ""); + const auto paths = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); QStringList directoryList = paths.split(";", QString::SkipEmptyParts); m_ModulesDirectories->setDirectories(directoryList); - QString files = m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, ""); + const auto files = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); QStringList fileList = files.split(";", QString::SkipEmptyParts); m_ModulesFiles->setFiles(fileList); m_ValidationMode->setCurrentIndex(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2)); m_XmlTimeoutInSeconds->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30)); // 30 secs = QProcess default timeout m_MaximumNumberProcesses->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4)); } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h index 91e5e1eb9f..6fe94807f4 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h @@ -1,108 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef COMMANDLINEMODULESPREFERENCESPAGE_H #define COMMANDLINEMODULESPREFERENCESPAGE_H #include "berryIQtPreferencePage.h" -#include "berryIPreferences.h" #include class QWidget; class QGridLayout; class QCheckBox; class QComboBox; class QSpinBox; class QmitkDirectoryListWidget; class QmitkFileListWidget; class ctkDirectoryButton; +namespace mitk +{ + class IPreferences; +} + /** * \class CommandLineModulesPreferencesPage * \brief Preference page for CommandLineModulesView * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ class CommandLineModulesPreferencesPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: CommandLineModulesPreferencesPage(); ~CommandLineModulesPreferencesPage() override; /** * \brief Called by framework to initialise this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: protected: QWidget *m_MainControl; QCheckBox *m_DebugOutput; QCheckBox *m_ShowAdvancedWidgets; ctkDirectoryButton *m_OutputDirectory; ctkDirectoryButton *m_TemporaryDirectory; QmitkDirectoryListWidget *m_ModulesDirectories; QmitkFileListWidget *m_ModulesFiles; QGridLayout *m_GridLayoutForLoadCheckboxes; QCheckBox *m_LoadFromHomeDir; QCheckBox *m_LoadFromHomeDirCliModules; QCheckBox *m_LoadFromCurrentDir; QCheckBox *m_LoadFromCurrentDirCliModules; QCheckBox *m_LoadFromApplicationDir; QCheckBox *m_LoadFromApplicationDirCliModules; QCheckBox *m_LoadFromAutoLoadPathDir; QComboBox *m_ValidationMode; QSpinBox *m_XmlTimeoutInSeconds; QSpinBox *m_MaximumNumberProcesses; - berry::IPreferences::Pointer m_CLIPreferencesNode; + mitk::IPreferences* m_CLIPreferencesNode; private: std::string ConvertToStdString(const QStringList& list); }; #endif // COMMANDLINEMODULESPREFERENCESPAGE_H diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp index deccce88e0..87eb17ff3a 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp @@ -1,547 +1,532 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ - -// Blueberry -#include -#include -#include -#include +#include +#include +#include // Qmitk #include "CommandLineModulesView.h" #include "CommandLineModulesViewConstants.h" #include "CommandLineModulesViewControls.h" #include "CommandLineModulesPreferencesPage.h" #include "QmitkCmdLineModuleFactoryGui.h" #include "QmitkCmdLineModuleGui.h" #include "QmitkCmdLineModuleRunner.h" // Qt #include #include #include #include #include #include #include #include // CTK #include #include #include #include #include #include #include #include #include #include //----------------------------------------------------------------------------- CommandLineModulesView::CommandLineModulesView() : m_Controls(nullptr) , m_Parent(nullptr) , m_Layout(nullptr) , m_ModuleManager(nullptr) , m_ModuleBackend(nullptr) , m_DirectoryWatcher(nullptr) , m_TemporaryDirectoryName("") , m_MaximumConcurrentProcesses(4) , m_CurrentlyRunningProcesses(0) , m_DebugOutput(false) , m_XmlTimeoutSeconds(30) // 30 seconds = QProcess default timeout. { } //----------------------------------------------------------------------------- CommandLineModulesView::~CommandLineModulesView() { if (m_ModuleManager != nullptr) { delete m_ModuleManager; } if (m_ModuleBackend != nullptr) { delete m_ModuleBackend; } if (m_DirectoryWatcher != nullptr) { delete m_DirectoryWatcher; } if (m_Layout != nullptr) { delete m_Layout; } for (int i = 0; i < m_ListOfModules.size(); i++) { delete m_ListOfModules[i]; } } //----------------------------------------------------------------------------- void CommandLineModulesView::SetFocus() { this->m_Controls->m_ComboBox->setFocus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::CreateQtPartControl( QWidget *parent ) { m_Parent = parent; if (!m_Controls) { // We create CommandLineModulesViewControls, which derives from the Qt generated class. m_Controls = new CommandLineModulesViewControls(parent); // Create a layout to contain a display of QmitkCmdLineModuleRunner. m_Layout = new QVBoxLayout(m_Controls->m_RunningWidgets); m_Layout->setContentsMargins(0,0,0,0); m_Layout->setSpacing(0); // This must be done independent of other preferences, as we need it before // we create the ctkCmdLineModuleManager to initialise the Cache. this->RetrieveAndStoreTemporaryDirectoryPreferenceValues(); this->RetrieveAndStoreValidationMode(); // Start to create the command line module infrastructure. m_ModuleBackend = new ctkCmdLineModuleBackendLocalProcess(); m_ModuleManager = new ctkCmdLineModuleManager(m_ValidationMode, m_TemporaryDirectoryName); // Set the main object, the ctkCmdLineModuleManager onto all the objects that need it. m_Controls->m_ComboBox->SetManager(m_ModuleManager); m_DirectoryWatcher = new ctkCmdLineModuleDirectoryWatcher(m_ModuleManager); connect(this->m_DirectoryWatcher, SIGNAL(errorDetected(QString)), this, SLOT(OnDirectoryWatcherErrorsDetected(QString))); m_ModuleManager->registerBackend(m_ModuleBackend); // Setup the remaining preferences. this->RetrieveAndStorePreferenceValues(); // Connect signals to slots after we have set up GUI. connect(this->m_Controls->m_RunButton, SIGNAL(pressed()), this, SLOT(OnRunButtonPressed())); connect(this->m_Controls->m_RestoreDefaults, SIGNAL(pressed()), this, SLOT(OnRestoreButtonPressed())); connect(this->m_Controls->m_ComboBox, SIGNAL(actionChanged(QAction*)), this, SLOT(OnActionChanged(QAction*))); connect(this->m_Controls->m_TabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(OnTabCloseRequested(int))); connect(this->m_Controls->m_ClearXMLCache, SIGNAL(pressed()), this, SLOT(OnClearCache())); connect(this->m_Controls->m_ReloadModules, SIGNAL(pressed()), this, SLOT(OnReloadModules())); this->UpdateRunButtonEnabledStatus(); } } //----------------------------------------------------------------------------- -berry::IBerryPreferences::Pointer CommandLineModulesView::RetrievePreferences() +mitk::IPreferences* CommandLineModulesView::RetrievePreferences() const { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - assert( prefService ); - - QString id = "/" + CommandLineModulesViewConstants::VIEW_ID; - berry::IBerryPreferences::Pointer prefs - = (prefService->GetSystemPreferences()->Node(id)) - .Cast(); - - assert( prefs ); - - return prefs; + return mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStoreTemporaryDirectoryPreferenceValues() { - berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); + auto* prefs = this->RetrievePreferences(); - QString fallbackTmpDir = QDir::tempPath(); - m_TemporaryDirectoryName = - prefs->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir); + const auto fallbackTmpDir = QDir::tempPath().toStdString(); + m_TemporaryDirectoryName = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir)); } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStoreValidationMode() { - berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); + auto* prefs = this->RetrievePreferences(); int value = prefs->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2); if (value == 0) { m_ValidationMode = ctkCmdLineModuleManager::STRICT_VALIDATION; } else if (value == 1) { m_ValidationMode = ctkCmdLineModuleManager::SKIP_VALIDATION; } else { m_ValidationMode = ctkCmdLineModuleManager::WEAK_VALIDATION; } } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStorePreferenceValues() { - berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); + auto* prefs = this->RetrievePreferences(); - QString fallbackHomeDir = QDir::homePath(); - m_OutputDirectoryName = - prefs->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackHomeDir); + const auto fallbackHomeDir = QDir::homePath().toStdString(); + m_OutputDirectoryName = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackHomeDir)); m_MaximumConcurrentProcesses = prefs->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4); m_XmlTimeoutSeconds = prefs->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30); m_ModuleManager->setTimeOutForXMLRetrieval(m_XmlTimeoutSeconds * 1000); // preference is in seconds, underlying CTK library in milliseconds. // Get the flag for debug output, useful when parsing all the XML. m_DebugOutput = prefs->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false); m_DirectoryWatcher->setDebug(m_DebugOutput); // Show/Hide the advanced widgets this->m_Controls->SetAdvancedWidgetsVisible(prefs->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); bool loadApplicationDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false); bool loadApplicationDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true); bool loadHomeDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false); bool loadHomeDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false); bool loadCurrentDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false); bool loadCurrentDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false); bool loadAutoLoadDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false); // Get some default application paths. // Here we can use the preferences to set up the builder, ctkCmdLineModuleDefaultPathBuilder builder; if (loadApplicationDir) builder.addApplicationDir(); if (loadApplicationDirCliModules) builder.addApplicationDir("cli-modules"); if (loadHomeDir) builder.addHomeDir(); if (loadHomeDirCliModules) builder.addHomeDir("cli-modules"); if (loadCurrentDir) builder.addCurrentDir(); if (loadCurrentDirCliModules) builder.addCurrentDir("cli-modules"); if (loadAutoLoadDir) builder.addCtkModuleLoadPath(); // and then we ask the builder to set up the paths. QStringList defaultPaths = builder.getDirectoryList(); // We get additional directory paths from preferences. - QString pathString = prefs->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, ""); + const auto pathString = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); QStringList additionalPaths = pathString.split(";", QString::SkipEmptyParts); // Combine the sets of directory paths. QStringList totalPaths; totalPaths << defaultPaths; totalPaths << additionalPaths; - QString additionalModulesString = prefs->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, ""); + const auto additionalModulesString = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); QStringList additionalModules = additionalModulesString.split(";", QString::SkipEmptyParts); // OnPreferencesChanged can be called for each preference in a dialog box, so // when you hit "OK", it is called repeatedly, whereas we want to only call these only once. if (m_DirectoryPaths != totalPaths) { m_DirectoryPaths = totalPaths; m_DirectoryWatcher->setDirectories(totalPaths); } if (m_ModulePaths != additionalModules) { m_ModulePaths = additionalModules; m_DirectoryWatcher->setAdditionalModules(additionalModules); } } //----------------------------------------------------------------------------- -void CommandLineModulesView::OnPreferencesChanged(const berry::IBerryPreferences* /*prefs*/) +void CommandLineModulesView::OnPreferencesChanged(const mitk::IPreferences* /*prefs*/) { this->RetrieveAndStoreTemporaryDirectoryPreferenceValues(); this->RetrieveAndStoreValidationMode(); this->RetrieveAndStorePreferenceValues(); } //----------------------------------------------------------------------------- ctkCmdLineModuleReference CommandLineModulesView::GetReferenceByFullName(QString fullName) { ctkCmdLineModuleReference result; QList references = this->m_ModuleManager->moduleReferences(); ctkCmdLineModuleReference ref; foreach(ref, references) { QString name = ref.description().categoryDotTitle(); if (name == fullName) { result = ref; } } return result; } //----------------------------------------------------------------------------- void CommandLineModulesView::OnActionChanged(QAction* action) { QString fullName = action->objectName(); ctkCmdLineModuleReference ref = this->GetReferenceByFullName(fullName); // ref should never be invalid, as the menu was generated from each ctkCmdLineModuleReference. // But just to be sure ... if invalid, don't do anything. if (ref) { // Check if we already have the reference. int tabIndex = -1; for (int i = 0; i < m_ListOfModules.size(); i++) { ctkCmdLineModuleReference tabsReference = m_ListOfModules[i]->moduleReference(); if (ref.location() == tabsReference.location()) { tabIndex = i; break; } } // i.e. we found a matching tab, so just switch to it. if (tabIndex != -1) { m_Controls->m_TabWidget->setCurrentIndex(tabIndex); } else // i.e. we did not find a matching tab { // In this case, we need to create a new tab, and give // it a GUI for the user to setup the parameters with. QmitkCmdLineModuleFactoryGui factory(this->GetDataStorage()); ctkCmdLineModuleFrontend *frontEnd = factory.create(ref); QmitkCmdLineModuleGui *theGui = dynamic_cast(frontEnd); // Add to list and tab wigdget m_ListOfModules.push_back(frontEnd); int tabIndex = m_Controls->m_TabWidget->addTab(theGui->getGui(), ref.description().title()); m_Controls->m_TabWidget->setTabToolTip(tabIndex, ref.description().title() + ":" + ref.xmlValidationErrorString()); // Here lies a small caveat. // // The XML may specify a default output file name. // However, this will probably have no file path, so we should probably add one. // Otherwise you will likely be trying to write in the application installation folder // eg. C:/Program Files (Windows) or /Applications/ (Mac) // // Also, we may find that 3rd party apps crash when they can't write. // So lets plan for the worst and hope for the best :-) QString parameterName; QList parameters; parameters = frontEnd->parameters("image", ctkCmdLineModuleFrontend::Output); parameters << frontEnd->parameters("file", ctkCmdLineModuleFrontend::Output); parameters << frontEnd->parameters("geometry", ctkCmdLineModuleFrontend::Output); foreach (ctkCmdLineModuleParameter parameter, parameters) { parameterName = parameter.name(); QString outputFileName = frontEnd->value(parameterName, ctkCmdLineModuleFrontend::DisplayRole).toString(); QFileInfo outputFileInfo(outputFileName); if (outputFileInfo.absoluteFilePath() != outputFileName) { QDir defaultOutputDir(m_OutputDirectoryName); QFileInfo replacementFileInfo(defaultOutputDir, outputFileName); frontEnd->setValue(parameterName, replacementFileInfo.absoluteFilePath(), ctkCmdLineModuleFrontend::DisplayRole); } } } } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnTabCloseRequested(int tabNumber) { ctkCmdLineModuleFrontend *frontEnd = m_ListOfModules[tabNumber]; m_Controls->m_TabWidget->removeTab(tabNumber); m_ListOfModules.removeAt(tabNumber); delete frontEnd; } //----------------------------------------------------------------------------- void CommandLineModulesView::AskUserToSelectAModule() const { QMessageBox msgBox; msgBox.setText("Please select a module!"); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnRestoreButtonPressed() { int tabNumber = m_Controls->m_TabWidget->currentIndex(); if (tabNumber >= 0) { ctkCmdLineModuleFrontend *frontEnd = m_ListOfModules[tabNumber]; frontEnd->resetValues(); } else { this->AskUserToSelectAModule(); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnRunButtonPressed() { int tabNumber = m_Controls->m_TabWidget->currentIndex(); if (tabNumber >= 0) { // 1. Create a new QmitkCmdLineModuleRunner to represent the running widget. auto widget = new QmitkCmdLineModuleRunner(m_Controls->m_RunningWidgets); widget->SetDataStorage(this->GetDataStorage()); widget->SetManager(m_ModuleManager); widget->SetOutputDirectory(m_OutputDirectoryName); // 2. Create a new front end. QmitkCmdLineModuleFactoryGui factory(this->GetDataStorage()); ctkCmdLineModuleFrontend *frontEndOnCurrentTab = m_ListOfModules[tabNumber]; QmitkCmdLineModuleGui *frontEndGuiOnCurrentTab = dynamic_cast(frontEndOnCurrentTab); ctkCmdLineModuleReference currentTabFrontendReferences = frontEndGuiOnCurrentTab->moduleReference(); ctkCmdLineModuleFrontend *newFrontEnd = factory.create(currentTabFrontendReferences); QmitkCmdLineModuleGui *newFrontEndGui = dynamic_cast(newFrontEnd); widget->SetFrontend(newFrontEndGui); m_Layout->insertWidget(0, widget); // 3. Copy parameters. This MUST come after widget->SetFrontEnd newFrontEndGui->copyParameters(*frontEndGuiOnCurrentTab); newFrontEndGui->setParameterContainerEnabled(false); // 4. Connect widget signals to here, to count how many jobs running. connect(widget, SIGNAL(started()), this, SLOT(OnJobStarted())); connect(widget, SIGNAL(finished()), this, SLOT(OnJobFinished())); // 5. GO. widget->Run(); } else { this->AskUserToSelectAModule(); } } //----------------------------------------------------------------------------- void CommandLineModulesView::UpdateRunButtonEnabledStatus() { if (m_CurrentlyRunningProcesses >= m_MaximumConcurrentProcesses) { m_Controls->m_RunButton->setEnabled(false); } else { m_Controls->m_RunButton->setEnabled(true); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnJobStarted() { m_CurrentlyRunningProcesses++; this->UpdateRunButtonEnabledStatus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnJobFinished() { m_CurrentlyRunningProcesses--; this->UpdateRunButtonEnabledStatus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnDirectoryWatcherErrorsDetected(const QString& errorMsg) { ctkCmdLineModuleUtils::messageBoxForModuleRegistration(errorMsg); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnClearCache() { if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnClearCache(): starting"; } m_ModuleManager->clearCache(); if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnClearCache(): finishing"; } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnReloadModules() { QList urls; QList moduleRefs = m_ModuleManager->moduleReferences(); foreach (ctkCmdLineModuleReference ref, moduleRefs) { urls.push_back(ref.location()); } if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnReloadModules(): unloading:" << urls; } foreach (ctkCmdLineModuleReference ref, moduleRefs) { m_ModuleManager->unregisterModule(ref); } if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnReloadModules(): reloading."; } QList refResults = QtConcurrent::blockingMapped(urls, ctkCmdLineModuleConcurrentRegister(m_ModuleManager, m_DebugOutput)); if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnReloadModules(): finished."; } QString errorMessages = ctkCmdLineModuleUtils::errorMessagesFromModuleRegistration(refResults, m_ModuleManager->validationMode()); ctkCmdLineModuleUtils::messageBoxForModuleRegistration(errorMessages); } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h index 4207c1781d..25be8da301 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h @@ -1,252 +1,249 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef CommandLineModulesView_h #define CommandLineModulesView_h #include -#include -#include -#include #include #include #include class ctkCmdLineModuleBackendLocalProcess; class ctkCmdLineModuleDirectoryWatcher; class CommandLineModulesViewControls; class QmitkCmdLineModuleRunner; class QAction; class QVBoxLayout; -namespace berry +namespace mitk { - struct IBerryPreferences; + class IPreferences; } /*! * \class CommandLineModulesView * \brief Provides basic GUI interface to the CTK command line modules. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal * \sa QmitkAbstractView */ class CommandLineModulesView : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: CommandLineModulesView(); ~CommandLineModulesView() override; /** * \brief Main method, called by framework to create the GUI at the right time. * \param parent The parent QWidget, as this class itself is not a QWidget subclass. */ void CreateQtPartControl(QWidget *parent) override; /** * \brief Called by the framework to indicate that the preferences have changed. * \param prefs not used, as we call RetrievePreferenceValues(). */ - void OnPreferencesChanged(const berry::IBerryPreferences* prefs) override; + void OnPreferencesChanged(const mitk::IPreferences* prefs) override; protected Q_SLOTS: /** * \brief Called when the ctkMenuComboBox has the menu selection changed, * and causes the corresponding GUI to be displayed. */ void OnActionChanged(QAction*); /** * \brief Slot that is called when the restore defaults button is pressed, * to reset the current GUI form to the default values, if the XML specifies defaults. */ void OnRestoreButtonPressed(); /** * \brief Slot that is called when the Run button is pressed to run the current module. */ void OnRunButtonPressed(); /** * \brief Alerts the user of any errors comming out of the directory watcher. */ void OnDirectoryWatcherErrorsDetected(const QString&); protected: /** * \brief Called by framework to set the focus on the right widget * when this view has focus, so currently, thats the ctkMenuCombo box. */ void SetFocus() override; private slots: /** * \brief Called when the user clicks to close a tab, and removes the front end from m_ListOfModules */ void OnTabCloseRequested(int tabNumber); /** * \brief Called from QmitkCmdLineModuleProgressWidget to indicate a job has started. */ void OnJobStarted(); /** * \brief Called from QmitkCmdLineModuleProgressWidget to indicate a job has finished. */ void OnJobFinished(); /** * \brief Called when the user hits the 'clear XML cache' button. */ void OnClearCache(); /** * \brief Called when the user hits the 'reload modules' button. */ void OnReloadModules(); private: /** * \brief Called on startup and by OnPreferencesChanged to load all * preferences except the temporary folder into member variables. */ void RetrieveAndStorePreferenceValues(); /** * \brief Called on startup and by OnPreferencesChanged to load the temporary folder * preference into member variable m_TemporaryDirectoryName. */ void RetrieveAndStoreTemporaryDirectoryPreferenceValues(); /** * \brief Called on startup and by OnPreferencesChanged to set the validation mode, but will require a restart. */ void RetrieveAndStoreValidationMode(); /** * \brief Called to get hold of the actual preferences node. */ - berry::IBerryPreferences::Pointer RetrievePreferences(); + mitk::IPreferences* RetrievePreferences() const; /** * \brief Search all modules for the one matching the given identifier. * \param fullName The "fullName" is the . from the XML. * \return ctkCmdLineModuleReference the reference corresponding to the fullName, or an invalid reference if non found. */ ctkCmdLineModuleReference GetReferenceByFullName(QString fullName); /** * \brief Raises a message box asking the user to select a module first. */ void AskUserToSelectAModule() const; /** * \brief Enables or Disables the Run Button. */ void UpdateRunButtonEnabledStatus(); /** * \brief The GUI controls contain a reset and run button, and a QWidget container, and the GUI component * for each command line module is added to the QWidget dynamically at run time. */ CommandLineModulesViewControls *m_Controls; /** * \brief We store the parent, passed in via CommandLineModulesView::CreateQtPartControl, * as this class itself is not a QWidget. */ QWidget *m_Parent; /** * \brief We keep a local layout, and arrange a display of QmitkCmdLineModuleProgressWidget, * where each QmitkCmdLineModuleProgressWidget represents a single running job. */ QVBoxLayout *m_Layout; /** * \brief The manager is responsible for loading and instantiating command line modules. */ ctkCmdLineModuleManager *m_ModuleManager; /** * \brief We are using a back-end that runs locally installed command line programs. */ ctkCmdLineModuleBackendLocalProcess *m_ModuleBackend; /** * \brief The ctkCmdLineModuleDirectoryWatcher maintains the list of directories * we are using to load modules, to provide automatic updates. */ ctkCmdLineModuleDirectoryWatcher *m_DirectoryWatcher; /** * \brief We store a temporary folder name, accessible via user preferences. */ QString m_TemporaryDirectoryName; /** * \brief We store an output folder name, accessible via user preferences for when * the file specified in a default output path is not within a writable directory. */ QString m_OutputDirectoryName; /** * \brief Cache the list of directory paths locally to avoid repeatedly trying to update Directory Watcher. */ QStringList m_DirectoryPaths; /** * \brief Cache the list of module/executable paths locally to avoid repeatedly trying to update Directory Watcher. */ QStringList m_ModulePaths; /** * \brief We store the validation mode, accessisble via user preferences. */ ctkCmdLineModuleManager::ValidationMode m_ValidationMode; /** * \brief We store the maximum number of concurrent processes, and disable the run button accordingly. */ int m_MaximumConcurrentProcesses; /** * \brief Counts the number of currently running processes. */ int m_CurrentlyRunningProcesses; /** * \brief Member variable, taken from preference page. */ bool m_DebugOutput; /** * \brief Member variable, taken from preferences page. */ int m_XmlTimeoutSeconds; /** * \brief We keep a list of front ends to match the m_TabWidget. */ QList<ctkCmdLineModuleFrontend*> m_ListOfModules; }; #endif // CommandLineModulesView_h diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp index 6b63d6c35e..e36d3eb42e 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp @@ -1,31 +1,31 @@ /*============================================================================ 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 "CommandLineModulesViewConstants.h" -const QString CommandLineModulesViewConstants::VIEW_ID = "org.mitk.views.cmdlinemodules"; -const QString CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME = "temporary directory"; -const QString CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME = "output directory"; -const QString CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME = "module directories"; -const QString CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME = "module files"; -const QString CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME = "debug output"; -const QString CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR = "load from application dir"; -const QString CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR = "load from home dir"; -const QString CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR = "load from current dir"; -const QString CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR = "load from auto-load dir"; -const QString CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES = "load from application dir/cli-modules"; -const QString CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES = "load from home dir/cli-modules"; -const QString CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES = "load from current dir/cli-modules"; -const QString CommandLineModulesViewConstants::XML_VALIDATION_MODE = "xml validation mode"; -const QString CommandLineModulesViewConstants::XML_TIMEOUT_SECS = "xml time-out"; -const QString CommandLineModulesViewConstants::MAX_CONCURRENT = "max concurrent processes"; -const QString CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME = "show advanced widgets"; +const std::string CommandLineModulesViewConstants::VIEW_ID = "org.mitk.views.cmdlinemodules"; +const std::string CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME = "temporary directory"; +const std::string CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME = "output directory"; +const std::string CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME = "module directories"; +const std::string CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME = "module files"; +const std::string CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME = "debug output"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR = "load from application dir"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR = "load from home dir"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR = "load from current dir"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR = "load from auto-load dir"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES = "load from application dir/cli-modules"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES = "load from home dir/cli-modules"; +const std::string CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES = "load from current dir/cli-modules"; +const std::string CommandLineModulesViewConstants::XML_VALIDATION_MODE = "xml validation mode"; +const std::string CommandLineModulesViewConstants::XML_TIMEOUT_SECS = "xml time-out"; +const std::string CommandLineModulesViewConstants::MAX_CONCURRENT = "max concurrent processes"; +const std::string CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME = "show advanced widgets"; diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h index 4fedb1104e..48a230b399 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h @@ -1,121 +1,121 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef CommandLineModulesViewConstants_h #define CommandLineModulesViewConstants_h #include <QString> /** * \class CommandLineModulesViewConstants * \brief Structure to define a namespace for constants used privately within this view. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ struct CommandLineModulesViewConstants { /** * \brief The name of the preferences node containing the temporary directory. */ - static const QString TEMPORARY_DIRECTORY_NODE_NAME; + static const std::string TEMPORARY_DIRECTORY_NODE_NAME; /** * \brief The name of the preferences node containing the output directory. */ - static const QString OUTPUT_DIRECTORY_NODE_NAME; + static const std::string OUTPUT_DIRECTORY_NODE_NAME; /** * \brief The name of the preferences node containing the list of directories to scan. */ - static const QString MODULE_DIRECTORIES_NODE_NAME; + static const std::string MODULE_DIRECTORIES_NODE_NAME; /** * \brief The name of the preferences node containing the additional files to add to the module list. */ - static const QString MODULE_FILES_NODE_NAME; + static const std::string MODULE_FILES_NODE_NAME; /** * \brief The name of the preferences node containing whether we are producing debug output. */ - static const QString DEBUG_OUTPUT_NODE_NAME; + static const std::string DEBUG_OUTPUT_NODE_NAME; /** * \brief The name of the preferences node containing whether we are displaying advanced widgets. */ - static const QString SHOW_ADVANCED_WIDGETS_NAME; + static const std::string SHOW_ADVANCED_WIDGETS_NAME; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the application directory. */ - static const QString LOAD_FROM_APPLICATION_DIR; + static const std::string LOAD_FROM_APPLICATION_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the "application directory/cli-modules". */ - static const QString LOAD_FROM_APPLICATION_DIR_CLI_MODULES; + static const std::string LOAD_FROM_APPLICATION_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the users home directory. */ - static const QString LOAD_FROM_HOME_DIR; + static const std::string LOAD_FROM_HOME_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the users "home directory/cli-modules". */ - static const QString LOAD_FROM_HOME_DIR_CLI_MODULES; + static const std::string LOAD_FROM_HOME_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the applications current working directory. */ - static const QString LOAD_FROM_CURRENT_DIR; + static const std::string LOAD_FROM_CURRENT_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the applications "current working directory/cli-modules". */ - static const QString LOAD_FROM_CURRENT_DIR_CLI_MODULES; + static const std::string LOAD_FROM_CURRENT_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the directory specified in CTK_MODULE_LOAD_PATH. */ - static const QString LOAD_FROM_AUTO_LOAD_DIR; + static const std::string LOAD_FROM_AUTO_LOAD_DIR; /** * \brief The name of the preferences node containing the validation mode. */ - static const QString XML_VALIDATION_MODE; + static const std::string XML_VALIDATION_MODE; /** * \brief The name of the preferences node containing the timeout in seconds for XML retrieval. */ - static const QString XML_TIMEOUT_SECS; + static const std::string XML_TIMEOUT_SECS; /** * \brief The name of the preferences node containing the maximum number of concurrent processes. */ - static const QString MAX_CONCURRENT; + static const std::string MAX_CONCURRENT; /** * \brief The View ID = org.mitk.gui.qt.cmdlinemodules, and should match that in plugin.xml. */ - static const QString VIEW_ID; + static const std::string VIEW_ID; }; #endif // CommandLineModulesViewConstants_h diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/org_mitk_gui_qt_cmdlinemodules_Activator.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/org_mitk_gui_qt_cmdlinemodules_Activator.cpp index f6213a83dc..a99aea6a9f 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/org_mitk_gui_qt_cmdlinemodules_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/org_mitk_gui_qt_cmdlinemodules_Activator.cpp @@ -1,31 +1,35 @@ /*============================================================================ 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 "org_mitk_gui_qt_cmdlinemodules_Activator.h" #include "CommandLineModulesView.h" #include "CommandLineModulesPreferencesPage.h" +#include <usModuleInitialization.h> + +US_INITIALIZE_MODULE + namespace mitk { void org_mitk_gui_qt_cmdlinemodules_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(CommandLineModulesView, context) BERRY_REGISTER_EXTENSION_CLASS(CommandLineModulesPreferencesPage, context) } void org_mitk_gui_qt_cmdlinemodules_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp index 3c76c856b0..dd6b34f1af 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp @@ -1,152 +1,145 @@ /*============================================================================ 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 "QmitkAbstractRenderEditor.h" #include "internal/QmitkCommonActivator.h" #include <mitkDataStorageEditorInput.h> #include <mitkIRenderingManager.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> -#include <berryIPreferencesService.h> #include <berryUIException.h> -#include <ctkServiceTracker.h> - class QmitkAbstractRenderEditorPrivate { public: QmitkAbstractRenderEditorPrivate() : m_RenderingManagerInterface(mitk::MakeRenderingManagerInterface(mitk::RenderingManager::GetInstance())) - , m_PrefServiceTracker(QmitkCommonActivator::GetContext()) { - m_PrefServiceTracker.open(); } ~QmitkAbstractRenderEditorPrivate() { delete m_RenderingManagerInterface; } mitk::IRenderingManager* m_RenderingManagerInterface; - ctkServiceTracker<berry::IPreferencesService*> m_PrefServiceTracker; - berry::IBerryPreferences::Pointer m_Prefs; + mitk::IPreferences* m_Prefs; }; QmitkAbstractRenderEditor::QmitkAbstractRenderEditor() : d(new QmitkAbstractRenderEditorPrivate) { } QmitkAbstractRenderEditor::~QmitkAbstractRenderEditor() { - if (d->m_Prefs.IsNotNull()) + if (d->m_Prefs != nullptr) { - d->m_Prefs->OnChanged.RemoveListener(berry::MessageDelegate1<QmitkAbstractRenderEditor, const berry::IBerryPreferences*> + d->m_Prefs->OnChanged.RemoveListener(mitk::MessageDelegate1<QmitkAbstractRenderEditor, const mitk::IPreferences*> (this, &QmitkAbstractRenderEditor::OnPreferencesChanged ) ); } } void QmitkAbstractRenderEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { if (input.Cast<mitk::DataStorageEditorInput>().IsNull()) throw berry::PartInitException("Invalid Input: Must be mitk::DataStorageEditorInput"); this->SetSite(site); this->SetInput(input); - d->m_Prefs = this->GetPreferences().Cast<berry::IBerryPreferences>(); - if (d->m_Prefs.IsNotNull()) + d->m_Prefs = this->GetPreferences(); + if (d->m_Prefs != nullptr) { - d->m_Prefs->OnChanged.AddListener(berry::MessageDelegate1<QmitkAbstractRenderEditor, const berry::IBerryPreferences*> + d->m_Prefs->OnChanged.AddListener(mitk::MessageDelegate1<QmitkAbstractRenderEditor, const mitk::IPreferences*> (this, &QmitkAbstractRenderEditor::OnPreferencesChanged ) ); } } mitk::IDataStorageReference::Pointer QmitkAbstractRenderEditor::GetDataStorageReference() const { mitk::DataStorageEditorInput::Pointer input = this->GetEditorInput().Cast<mitk::DataStorageEditorInput>(); if (input.IsNotNull()) { return input->GetDataStorageReference(); } return mitk::IDataStorageReference::Pointer(nullptr); } mitk::DataStorage::Pointer QmitkAbstractRenderEditor::GetDataStorage() const { mitk::IDataStorageReference::Pointer ref = this->GetDataStorageReference(); if (ref.IsNotNull()) return ref->GetDataStorage(); return mitk::DataStorage::Pointer(nullptr); } -berry::IPreferences::Pointer QmitkAbstractRenderEditor::GetPreferences() const +mitk::IPreferences* QmitkAbstractRenderEditor::GetPreferences() const { - berry::IPreferencesService* prefService = d->m_PrefServiceTracker.getService(); - if (prefService != nullptr) - { - return prefService->GetSystemPreferences()->Node(this->GetSite()->GetId()); - } - return berry::IPreferences::Pointer(nullptr); + mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); + return prefService->GetSystemPreferences()->Node(this->GetSite()->GetId().toStdString()); } mitk::IRenderingManager* QmitkAbstractRenderEditor::GetRenderingManager() const { // we use the global rendering manager here. This should maybe replaced // by a local one, managing only the render windows specific for the editor return d->m_RenderingManagerInterface; } void QmitkAbstractRenderEditor::RequestUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->RequestUpdateAll(requestType); } void QmitkAbstractRenderEditor::ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->ForceImmediateUpdateAll(requestType); } mitk::SliceNavigationController* QmitkAbstractRenderEditor::GetTimeNavigationController() const { if (GetRenderingManager()) return GetRenderingManager()->GetTimeNavigationController(); return nullptr; } -void QmitkAbstractRenderEditor::OnPreferencesChanged(const berry::IBerryPreferences *) +void QmitkAbstractRenderEditor::OnPreferencesChanged(const mitk::IPreferences *) {} void QmitkAbstractRenderEditor::DoSave() {} void QmitkAbstractRenderEditor::DoSaveAs() {} bool QmitkAbstractRenderEditor::IsDirty() const { return false; } bool QmitkAbstractRenderEditor::IsSaveAsAllowed() const { return false; } mitk::TimePointType QmitkAbstractRenderEditor::GetSelectedTimePoint(const QString& /*id*/) const { auto timeNavigator = this->GetTimeNavigationController(); if (nullptr != timeNavigator) { return timeNavigator->GetSelectedTimePoint(); } return 0; } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h index 5ce38bc3ad..65cf964bc3 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h @@ -1,162 +1,166 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKABSTRACTRENDEREDITOR_H #define QMITKABSTRACTRENDEREDITOR_H #include <berryQtEditorPart.h> -#include <berryIBerryPreferences.h> #include "mitkIRenderWindowPart.h" #include <mitkIDataStorageReference.h> #include <mitkDataStorage.h> #include <org_mitk_gui_qt_common_Export.h> class QmitkAbstractRenderEditorPrivate; +namespace mitk +{ + class IPreferences; +} + /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK render window BlueBerry Editors. * * QmitkAbstractRenderEditor provides several convenience methods that ease the introduction of * a new editor for rendering a MITK DataStorage: * * <ol> * <li> Access to the DataStorage (~ the shared data repository) * <li> Access to and update notification for the editor's preferences * <li> Default implementation of some mitk::IRenderWindowPart methods * </ol> * * When inheriting from QmitkAbstractRenderEditor, you must implement the following methods: * <ul> * <li>void CreateQtPartControl(QWidget* parent) * <li>void SetFocus() * </ul> * * You may reimplement the following private virtual methods to be notified about certain changes: * <ul> - * <li>void OnPreferencesChanged(const berry::IBerryPreferences*) + * <li>void OnPreferencesChanged(const mitk::IPreferences*) * </ul> * * \see IRenderWindowPart * \see ILinkedRenderWindowPart */ class MITK_QT_COMMON QmitkAbstractRenderEditor : public berry::QtEditorPart, public virtual mitk::IRenderWindowPart { Q_OBJECT Q_INTERFACES(mitk::IRenderWindowPart) public: berryObjectMacro(QmitkAbstractRenderEditor, QtEditorPart, mitk::IRenderWindowPart); /** * \see mitk::IRenderWindowPart::GetSelectedTimePoint() This default implementation assumes that all renderer use the same TimeNavigationControl provided by this class (GetTimeNavigationControl()). */ mitk::TimePointType GetSelectedTimePoint(const QString& id = QString()) const override; QmitkAbstractRenderEditor(); ~QmitkAbstractRenderEditor() override; protected: /** * Initializes this editor by checking for a valid mitk::DataStorageEditorInput as <code>input</code>. * * \see berry::IEditorPart::Init */ void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) override; /** * Get a reference to the DataStorage set by the editor input. */ virtual mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Get the DataStorage set by the editor input. */ virtual mitk::DataStorage::Pointer GetDataStorage() const; /** * Get the preferences for this editor. */ - virtual berry::IPreferences::Pointer GetPreferences() const; + virtual mitk::IPreferences* GetPreferences() const; /** * Get the RenderingManager used by this editor. This default implementation uses the * global MITK RenderingManager provided by mitk::RenderingManager::GetInstance(). * * \see mitk::IRenderWindowPart::GetRenderingManager */ mitk::IRenderingManager* GetRenderingManager() const override; /** * Request an update of this editor's render windows. * This implementation calls mitk::IRenderingManager::RequestUpdate on the rendering * manager interface returned by GetRenderingManager(); * * \param requestType The type of render windows for which an update is requested. * * \see mitk::IRenderWindowPart::RequestUpdate */ void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) override; /** * Force an immediate update of this editor's render windows. * This implementation calls mitk::IRenderingManager::ForceImmediateUpdate() on the rendering * manager interface returned by GetRenderingManager(); * * \param requestType The type of render windows for which an immedate update is forced. * * \see mitk::IRenderWindowPart::ForceImmediateUpdate */ void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) override; /** * Get the time navigation controller for this editor. * This implementation returns the SliceNavigationController returned by the mitk::IRenderingManager::GetTimeNavigationController() * method of the interface implementation returned by GetRenderingManager(). * * \see mitk::IRenderingManager::GetTimeNavigationController */ mitk::SliceNavigationController* GetTimeNavigationController() const override; /** \see berry::IEditorPart::DoSave */ void DoSave() override; /** \see berry::IEditorPart::DoSaveAs */ void DoSaveAs() override; /** \see berry::IEditorPart::IsDirty */ bool IsDirty() const override; /** \see berry::IEditorPart::IsSaveAsAllowed */ bool IsSaveAsAllowed() const override; private: - virtual void OnPreferencesChanged(const berry::IBerryPreferences*); + virtual void OnPreferencesChanged(const mitk::IPreferences*); private: QScopedPointer<QmitkAbstractRenderEditorPrivate> d; }; #endif // QMITKABSTRACTRENDEREDITOR_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp index 9dbad4d3e8..caefe8515f 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp @@ -1,522 +1,521 @@ /*============================================================================ 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 <mitkLogMacros.h> +#include <mitkCoreServices.h> +#include <mitkIPreferences.h> +#include <mitkIPreferencesService.h> #include <mitkIDataStorageService.h> #include <mitkDataStorageEditorInput.h> #include <mitkDataNodeObject.h> #include <mitkIRenderingManager.h> // berry Includes #include <berryIWorkbenchPage.h> -#include <berryIBerryPreferences.h> #include <berryIEditorPart.h> #include <berryINullSelectionListener.h> #include <berryUIException.h> // CTK Includes #include <ctkServiceTracker.h> // Qt Includes #include <QItemSelectionModel> #include <QApplication> #include <QMessageBox> #include <QScrollArea> #include <QVBoxLayout> class QmitkAbstractViewPrivate { public: QmitkAbstractViewPrivate(QmitkAbstractView* qq) : q(qq) - , m_PrefServiceTracker(QmitkCommonActivator::GetContext()) , m_DataStorageServiceTracker(QmitkCommonActivator::GetContext()) , m_Parent(nullptr) , m_DataNodeItemModel(new QmitkDataNodeItemModel) , m_DataNodeSelectionModel(new QItemSelectionModel(m_DataNodeItemModel)) , m_InDataStorageChanged(false) { - m_PrefServiceTracker.open(); m_DataStorageServiceTracker.open(); } ~QmitkAbstractViewPrivate() { delete m_DataNodeSelectionModel; delete m_DataNodeItemModel; - m_PrefServiceTracker.close(); m_DataStorageServiceTracker.close(); } /** * Called when a DataStorage Add Event was thrown. Sets * m_InDataStorageChanged to true and calls NodeAdded afterwards. * \see m_InDataStorageChanged */ void NodeAddedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeAdded(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage remove event was thrown. Sets * m_InDataStorageChanged to true and calls NodeRemoved afterwards. * \see m_InDataStorageChanged */ void NodeRemovedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeRemoved(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage changed event was thrown. Sets * m_InDataStorageChanged to true and calls NodeChanged afterwards. * \see m_InDataStorageChanged */ void NodeChangedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeChanged(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * reactions to selection events from views */ void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection) { if(sourcepart.IsNull() || sourcepart.GetPointer() == static_cast<berry::IWorkbenchPart*>(q)) return; if(selection.IsNull()) { q->OnNullSelection(sourcepart); return; } mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast<const mitk::DataNodeSelection>(); q->OnSelectionChanged(sourcepart, this->DataNodeSelectionToQList(_DataNodeSelection)); } /** * Converts a mitk::DataNodeSelection to a QList<mitk::DataNode::Pointer> (possibly empty) */ QList<mitk::DataNode::Pointer> DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const; QmitkAbstractView* const q; - ctkServiceTracker<berry::IPreferencesService*> m_PrefServiceTracker; - ctkServiceTracker<mitk::IDataStorageService*> 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<berry::ISelectionListener> 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<QWidget*>(parent); auto parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkAbstractView::AfterCreateQtPartControl() { this->SetSelectionProvider(); // REGISTER DATASTORAGE LISTENER this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*> ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*> ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*> ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER - berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast<berry::IBerryPreferences>(); - if(prefs.IsNotNull()) - prefs->OnChanged.AddListener( - berry::MessageDelegate1<QmitkAbstractView, const berry::IBerryPreferences*>(this, - &QmitkAbstractView::OnPreferencesChanged)); + auto* prefs = this->GetPreferences(); + + if (prefs != nullptr) + prefs->OnChanged.AddListener(mitk::MessageDelegate1<QmitkAbstractView, const mitk::IPreferences*>(this, &QmitkAbstractView::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS d->m_BlueBerrySelectionListener.reset(new berry::NullSelectionChangedAdapter<QmitkAbstractViewPrivate>( d.data(), &QmitkAbstractViewPrivate::BlueBerrySelectionChanged)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(d->m_BlueBerrySelectionListener.data()); // EMULATE INITIAL SELECTION EVENTS // send the current selection berry::IWorkbenchPart::Pointer activePart = this->GetSite()->GetPage()->GetActivePart(); if (activePart.IsNotNull()) { this->OnSelectionChanged(activePart, this->GetCurrentSelection()); } // send preferences changed event - this->OnPreferencesChanged(this->GetPreferences().Cast<berry::IBerryPreferences>().GetPointer()); + this->OnPreferencesChanged(this->GetPreferences()); } QmitkAbstractView::~QmitkAbstractView() { this->Register(); this->GetDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*> ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*> ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy) ); this->GetDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*> ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); - berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast<berry::IBerryPreferences>(); - if(prefs.IsNotNull()) - { - prefs->OnChanged.RemoveListener( - berry::MessageDelegate1<QmitkAbstractView, const berry::IBerryPreferences*>(this, - &QmitkAbstractView::OnPreferencesChanged)); - // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) - // prefs->Flush(); - } + auto* prefs = this->GetPreferences(); + + if(prefs != nullptr) + prefs->OnChanged.RemoveListener(mitk::MessageDelegate1<QmitkAbstractView, const mitk::IPreferences*>(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 berry::IBerryPreferences* ) +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(); } -berry::IPreferences::Pointer QmitkAbstractView::GetPreferences() const +mitk::IPreferences* QmitkAbstractView::GetPreferences() const { - berry::IPreferencesService* prefService = d->m_PrefServiceTracker.getService(); - // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const - QString id = "/" + (const_cast<QmitkAbstractView*>(this))->GetViewSite()->GetId(); - return prefService ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(nullptr); + mitk::CoreServicePointer prefsService(mitk::CoreServices::GetPreferencesService()); + auto* prefs = prefsService->GetSystemPreferences(); + + if (prefs != nullptr) + { + auto viewSite = const_cast<QmitkAbstractView*>(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<mitk::DataNode::Pointer> QmitkAbstractView::GetCurrentSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection()); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast<const mitk::DataNodeSelection>(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsCurrentSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); } QList<mitk::DataNode::Pointer> QmitkAbstractView::GetDataManagerSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast<const mitk::DataNodeSelection>(); 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<berry::QtSelectionProvider>()->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<mitk::DataNode::Pointer>& /*nodes*/) { } void QmitkAbstractView::OnNullSelection(berry::IWorkbenchPart::Pointer /*part*/) { } QList<mitk::DataNode::Pointer> QmitkAbstractViewPrivate::DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const { if (currentSelection.IsNull()) return QList<mitk::DataNode::Pointer>(); return QList<mitk::DataNode::Pointer>::fromStdList(currentSelection->GetSelectedDataNodes()); } void QmitkAbstractView::NodeAdded( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeRemoved( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeChanged( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::FireNodeSelected( mitk::DataNode::Pointer node ) { QList<mitk::DataNode::Pointer> nodes; nodes << node; this->FireNodesSelected(nodes); } void QmitkAbstractView::FireNodesSelected( const QList<mitk::DataNode::Pointer>& nodes ) { // if this is the first call to FireNodesSelected and the selection provider has no QItemSelectiomMode // yet, set our helper model if (d->m_SelectionProvider->GetItemSelectionModel() == nullptr) { d->m_SelectionProvider->SetItemSelectionModel(d->m_DataNodeSelectionModel); } else if (d->m_SelectionProvider->GetItemSelectionModel() != d->m_DataNodeSelectionModel) { MITK_WARN << "A custom data node selection model has been set. Ignoring call to FireNodesSelected()."; return; } if (nodes.empty()) { d->m_DataNodeSelectionModel->clearSelection(); d->m_DataNodeItemModel->clear(); } else { // The helper data node model is just used for sending selection events. // We add the to be selected nodes and set the selection range to everything. d->m_DataNodeItemModel->clear(); foreach(mitk::DataNode::Pointer node, nodes) { d->m_DataNodeItemModel->AddDataNode(node); } d->m_DataNodeSelectionModel->select(QItemSelection(d->m_DataNodeItemModel->index(0,0), d->m_DataNodeItemModel->index(nodes.size()-1, 0)), QItemSelectionModel::ClearAndSelect); } } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h index 9217ba2cfe..599e5cde50 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h @@ -1,362 +1,356 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKABSTRACTVIEW_H_ #define QMITKABSTRACTVIEW_H_ //# blueberry stuff #include <berryQtViewPart.h> -#include <berryIPreferencesService.h> #include <berryISelectionListener.h> -#include <berryIPreferences.h> - //# mitk stuff #include <org_mitk_gui_qt_common_Export.h> #include "mitkDataNodeSelection.h" #include "mitkIRenderWindowPart.h" #include <mitkWorkbenchUtil.h> #include <mitkDataStorage.h> #include <mitkRenderingManager.h> #include <mitkIDataStorageReference.h> #include <QItemSelectionModel> namespace mitk { class DataNode; -} - -namespace berry { - struct IBerryPreferences; + class IPreferences; } class QmitkAbstractViewPrivate; class QmitkAbstractViewSelectionProvider; /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK related BlueBerry Views. * * QmitkAbstractView provides several convenience methods that ease the introduction of a new view: * * <ol> * <li> Access to the DataStorage (~ the shared data repository) * <li> Access to the active IRenderWindowPart * <li> Access to and update notification for the view's preferences * <li> Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService * <li> Access to and update notification for DataNode events (added/removed/modified) * <li> Methods to send DataNode selections through the SelectionService * <li> Some minor important convenience methods (like changing the mouse cursor/exception handling) * </ol> * * Usually all MITK Views inherit from QmitkAbstractView to achieve a consistent Workbench behavior. * * When inheriting from QmitkAbstractView, you must implement the following methods: * <ul> * <li>void CreateQtPartControl(QWidget* parent) * <li>void SetFocus() * </ul> * * You may reimplement the following private virtual methods to customize your View's behavior: * <ul> * <li>void SetSelectionProvider() * <li>QItemSelectionModel* GetDataNodeSelectionModel() const * </ul> * * You may reimplement the following private virtual methods to be notified about certain changes: * <ul> * <li>void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList<mitk::DataNode::Pointer> &nodes) * <li>void OnNullSelection(berry::IWorkbenchPart::Pointer part) - * <li>void OnPreferencesChanged(const berry::IBerryPreferences*) + * <li>void OnPreferencesChanged(const mitk::IPreferences*) * <li>void NodeAdded(const mitk::DataNode* node) * <li>void NodeChanged(const mitk::DataNode* node) * <li>void NodeRemoved(const mitk::DataNode* node) * <li>void DataStorageModified() * <li>void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef) * </ul> * * \see mitk::ILifecycleAwarePart * \see mitk::IZombieViewPart * \see mitk::IRenderWindowPartListener */ class MITK_QT_COMMON QmitkAbstractView : public berry::QtViewPart { public: /** * Creates smartpointer typedefs */ berryObjectMacro(QmitkAbstractView); /** * Nothing to do in the standard ctor. <b>Initiliaze your GUI in CreateQtPartControl(QWidget*)</b> * \see berry::QtViewPart::CreateQtPartControl(QWidget*) */ QmitkAbstractView(); /** * Disconnects all standard event listeners */ ~QmitkAbstractView() override; protected: /** * Informs other parts of the workbench that node is selected via the blueberry selection service. * * \note This method should not be used if you have set your own selection provider via * SetSelectionProvider() or your own QItemSelectionModel via GetDataNodeSelectionModel(). */ void FireNodeSelected(mitk::DataNode::Pointer node); /** * Informs other parts of the workbench that the nodes are selected via the blueberry selection service. * * \note This method should not be used if you have set your own selection provider via * SetSelectionProvider() or your own QItemSelectionModel via GetDataNodeSelectionModel(). */ virtual void FireNodesSelected(const QList<mitk::DataNode::Pointer>& nodes); /** * \return The selection of the currently active part of the workbench or an empty list * if there is no selection or if it is empty. * * \see IsCurrentSelectionValid */ QList<mitk::DataNode::Pointer> GetCurrentSelection() const; /** * Queries the state of the current selection. * * \return If the current selection is <code>nullptr</code>, this method returns * <code>false</code> and <code>true</code> otherwise. */ bool IsCurrentSelectionValid() const; /** * Returns the current selection made in the datamanager bundle or an empty list * if there is no selection or if it is empty. * * \see IsDataManagerSelectionValid */ QList<mitk::DataNode::Pointer> GetDataManagerSelection() const; /** * Queries the state of the current selection of the data manager view. * * \return If the current data manager selection is <code>nullptr</code>, this method returns * <code>false</code> and <code>true</code> otherwise. */ bool IsDataManagerSelectionValid() const; /** * Sets the selection of the data manager view if available. * * \param selection The new selection for the data manager. * \param flags The Qt selection flags for controlling the way how the selection is updated. */ void SetDataManagerSelection(const berry::ISelection::ConstPointer& selection, QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect) const; /** * Takes the current selection and sets it on the data manager. Only matching nodes in the * data manager view will be selected. */ void SynchronizeDataManagerSelection() const; /** * Returns the Preferences object for this View. * <b>Important</b>: When refering to this preferences, e.g. in a PreferencePage: The ID * for this preferences object is "/<VIEW-ID>", e.g. "/org.mitk.views.datamanager" */ - berry::IPreferences::Pointer GetPreferences() const; + mitk::IPreferences* GetPreferences() const; /** * Returns a reference to the currently active DataStorage. */ mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Returns the currently active DataStorage. */ mitk::DataStorage::Pointer GetDataStorage() const; /** * Returns the currently active mitk::IRenderWindowPart. * * \param strategies Strategies for returning a mitk::IRenderWindowPart instance if there * is currently no active one. * \return The active mitk::IRenderWindowPart. */ mitk::IRenderWindowPart* GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategies strategies = mitk::WorkbenchUtil::NONE) const; /** * Request an update of all render windows of the currently active IRenderWindowPart. * * \param requestType Specifies the type of render windows for which an update will be requested. */ void RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Outputs an error message to the console and displays a message box containing * the exception description. * \param e the exception which should be handled * \param parent * \param showDialog controls, whether additionally a message box should be * displayed to inform the user that something went wrong */ void HandleException( std::exception& e, QWidget* parent = nullptr, bool showDialog = true ) const; /** * Calls HandleException ( std::exception&, QWidget*, bool ) internally * \see HandleException ( std::exception&, QWidget*, bool ) */ void HandleException( const char* str, QWidget* parent = nullptr, bool showDialog = true ) const; /** * Convenient method to set and reset a wait cursor ("hourglass") */ void WaitCursorOn(); /** * Convenient method to restore the standard cursor */ void WaitCursorOff(); /** * Convenient method to set and reset a busy cursor */ void BusyCursorOn(); /** * Convenient method to restore the standard cursor */ void BusyCursorOff(); /** * Convenient method to restore the standard cursor */ void RestoreOverrideCursor(); private: /** * Reimplement this method to set a custom selection provider. This method is * called once after CreateQtPartControl(). * * The default implementation registers a QmitkDataNodeSelectionProvider with * a QItemSelectionModel returned by GetDataNodeSelectionModel(). */ virtual void SetSelectionProvider(); /** * Reimplement this method to supply a custom Qt selection model. The custom * model will be used with the default selection provider QmitkDataNodeSelectionProvider * to inform the MITK Workbench about selection changes. * * If you reimplement this method, the methods FireNodeSelected() and FireNodesSelected() * will have no effect. Use your custom selection model to notify the MITK Workbench * about selection changes. * * The Qt item model used with the custom selection model must return mitk::DataNode::Pointer * objects for model indexes when the role is QmitkDataNodeRole. */ virtual QItemSelectionModel* GetDataNodeSelectionModel() const; /** * Called when the selection in the workbench changed. * May be reimplemented by deriving classes. * * \param part The source part responsible for the selection change. * \param nodes A list of selected nodes. * * \see OnNullSelection */ virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList<mitk::DataNode::Pointer> &nodes); /** * Called when a <code>nullptr</code> selection occurs. * * \param part The source part responsible for the selection change. */ virtual void OnNullSelection(berry::IWorkbenchPart::Pointer part); /** * Called when the preferences object of this view changed. * May be reimplemented by deriving classes. * * \see GetPreferences() */ - virtual void OnPreferencesChanged(const berry::IBerryPreferences*); + virtual void OnPreferencesChanged(const mitk::IPreferences*); /** * Called when a DataStorage Add event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeAdded(const mitk::DataNode* node); /** * Called when a DataStorage Changed event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeChanged(const mitk::DataNode* node); /** * Called when a DataStorage Remove event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeRemoved(const mitk::DataNode* node); /** * Called when a DataStorage add *or* remove *or* change event from the currently active * data storage is thrown. * * May be reimplemented by deriving classes. */ virtual void DataStorageModified(); /** * Called when the currently active DataStorage changed. * May be reimplemented by deriving classes. * * \param dsRef A reference to the new active DataStorage. */ virtual void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef); /** * Creates a scroll area for this view and calls CreateQtPartControl then */ void CreatePartControl(QWidget* parent) override; /** * Called immediately after CreateQtPartControl(). * Here standard event listeners for a QmitkAbstractView are registered */ void AfterCreateQtPartControl(); private: friend class QmitkAbstractViewPrivate; friend class QmitkViewCoordinator; Q_DISABLE_COPY(QmitkAbstractView) const QScopedPointer<QmitkAbstractViewPrivate> d; }; #endif /*QMITKABSTRACTVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp index f48338737f..33d6fd0ae0 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp @@ -1,85 +1,84 @@ /*============================================================================ 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 <QmitkDnDFrameWidget.h> -#include <berryIPreferencesService.h> -#include <berryIPreferences.h> #include <berryPlatformUI.h> #include "internal/QmitkCommonActivator.h" #include <mitkWorkbenchUtil.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <QDragEnterEvent> #include <QMimeData> class QmitkDnDFrameWidgetPrivate { public: - berry::IPreferences::Pointer GetPreferences() const + mitk::IPreferences* GetPreferences() const { - berry::IPreferencesService* prefService = QmitkCommonActivator::GetInstance()->GetPreferencesService(); - if (prefService) - { - return prefService->GetSystemPreferences()->Node("/General"); - } - return berry::IPreferences::Pointer(nullptr); + auto* prefService = QmitkCommonActivator::GetInstance()->GetPreferencesService(); + + return prefService != nullptr + ? prefService->GetSystemPreferences()->Node("/General") + : nullptr; } bool GetOpenEditor() const { - berry::IPreferences::Pointer prefs = GetPreferences(); - if(prefs.IsNotNull()) + auto* prefs = GetPreferences(); + if(prefs != nullptr) { return prefs->GetBool("OpenEditor", true); } return true; } }; QmitkDnDFrameWidget::QmitkDnDFrameWidget(QWidget *parent) : QWidget(parent), d(new QmitkDnDFrameWidgetPrivate()) { setAcceptDrops(true); } QmitkDnDFrameWidget::~QmitkDnDFrameWidget() { } void QmitkDnDFrameWidget::dragEnterEvent( QDragEnterEvent *event ) { // accept drags event->acceptProposedAction(); } void QmitkDnDFrameWidget::dropEvent( QDropEvent * event ) { //open dragged files QList<QUrl> fileNames = event->mimeData()->urls(); if (fileNames.empty()) return; QStringList fileNames2; foreach(QUrl url, fileNames) { fileNames2.push_back(url.toLocalFile()); } mitk::WorkbenchUtil::LoadFiles(fileNames2, berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), d->GetOpenEditor()); event->accept(); } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.cpp index d301680b15..13fca49e37 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.cpp @@ -1,463 +1,465 @@ /*============================================================================ 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 "QmitkMultiWidgetDecorationManager.h" +#include <mitkIPreferences.h> + // org mitk gui common plugin #include <mitkIRenderWindowPart.h> // mitk annotation module #include <mitkManualPlacementAnnotationRenderer.h> // mitk qt widgets module #include <QmitkRenderWindowWidget.h> // vtk #include <vtkQImageToImageSource.h> // qt #include <QColor> QmitkMultiWidgetDecorationManager::QmitkMultiWidgetDecorationManager(QmitkAbstractMultiWidget* multiWidget) : m_MultiWidget(multiWidget) , m_LogoAnnotation(mitk::LogoAnnotation::New()) { // nothing here } -void QmitkMultiWidgetDecorationManager::DecorationPreferencesChanged(const berry::IBerryPreferences* preferences) +void QmitkMultiWidgetDecorationManager::DecorationPreferencesChanged(const mitk::IPreferences* preferences) { // Enable change of logo. If no DepartmentLogo was set explicitly, MBILogo is used. // Set new department logo by prefs->Set("DepartmentLogo", "PathToImage"); // If no logo was set for this plug-in specifically, walk the parent preference nodes // and lookup a logo value there. // Disable the logo first, otherwise setting a new logo will have no effect due to how mitkManufacturerLogo works ShowLogo(false); SetupLogo(qPrintable(":/org.mitk.gui.qt.stdmultiwidgeteditor/defaultWatermark.png")); ShowLogo(true); - const berry::IPreferences* currentNode = preferences; + const auto* currentNode = preferences; while (currentNode) { bool logoFound = false; - foreach(const QString& key, currentNode->Keys()) + for(const auto& key : currentNode->Keys()) { if (key == "DepartmentLogo") { ShowLogo(false); - QString departmentLogoLocation = currentNode->Get("DepartmentLogo", ""); - if (!departmentLogoLocation.isEmpty()) + auto departmentLogoLocation = currentNode->Get("DepartmentLogo", ""); + if (!departmentLogoLocation.empty()) { - SetupLogo(qPrintable(departmentLogoLocation)); + SetupLogo(departmentLogoLocation.c_str()); ShowLogo(true); } logoFound = true; break; } } if (logoFound) { break; } - currentNode = currentNode->Parent().GetPointer(); + currentNode = currentNode->Parent(); } /* QmitkMultiWidgetDecorationManager::Colormap colormap = static_cast<QmitkMultiWidgetDecorationManager::Colormap>(preferences->GetInt("Render window widget colormap", 0)); SetColormap(colormap); */ // show colored rectangle ShowAllColoredRectangles(true); // show all gradient background ShowAllGradientBackgrounds(true); // show corner annotations ShowAllCornerAnnotations(true); } void QmitkMultiWidgetDecorationManager::ShowDecorations(bool show, const QStringList& decorations) { if (nullptr == m_MultiWidget) { return; } if (decorations.isEmpty() || decorations.contains(mitk::IRenderWindowPart::DECORATION_BORDER)) { ShowAllColoredRectangles(show); } if (decorations.isEmpty() || decorations.contains(mitk::IRenderWindowPart::DECORATION_LOGO)) { ShowLogo(show); } if (decorations.isEmpty() || decorations.contains(mitk::IRenderWindowPart::DECORATION_MENU)) { //m_MultiWidget->ActivateAllRenderWindowMenus(show); } if (decorations.isEmpty() || decorations.contains(mitk::IRenderWindowPart::DECORATION_BACKGROUND)) { ShowAllGradientBackgrounds(show); } if (decorations.isEmpty() || decorations.contains(mitk::IRenderWindowPart::DECORATION_CORNER_ANNOTATION)) { ShowAllCornerAnnotations(show); } } bool QmitkMultiWidgetDecorationManager::IsDecorationVisible(const QString& decoration) const { if (mitk::IRenderWindowPart::DECORATION_BORDER == decoration) { return AreAllColoredRectanglesVisible(); } else if (mitk::IRenderWindowPart::DECORATION_LOGO == decoration) { return IsLogoVisible(); } else if (mitk::IRenderWindowPart::DECORATION_MENU == decoration) { //return IsMenuWidgetEnabled(); } else if (mitk::IRenderWindowPart::DECORATION_BACKGROUND == decoration) { return AreAllGradientBackgroundsOn(); } else if (mitk::IRenderWindowPart::DECORATION_CORNER_ANNOTATION == decoration) { return AreAllCornerAnnotationsVisible(); } return false; } QStringList QmitkMultiWidgetDecorationManager::GetDecorations() const { QStringList decorations; decorations << mitk::IRenderWindowPart::DECORATION_BORDER << mitk::IRenderWindowPart::DECORATION_LOGO << mitk::IRenderWindowPart::DECORATION_MENU << mitk::IRenderWindowPart::DECORATION_BACKGROUND << mitk::IRenderWindowPart::DECORATION_CORNER_ANNOTATION; return decorations; } void QmitkMultiWidgetDecorationManager::SetupLogo(const char* path) { m_LogoAnnotation->SetOpacity(0.5); mitk::Point2D offset; offset.Fill(0.03); m_LogoAnnotation->SetOffsetVector(offset); m_LogoAnnotation->SetRelativeSize(0.25); m_LogoAnnotation->SetCornerPosition(1); vtkSmartPointer<vtkImageData> vtkLogo = GetVtkLogo(path); SetLogo(vtkLogo); } void QmitkMultiWidgetDecorationManager::ShowLogo(bool show) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetLastRenderWindowWidget(); if (nullptr != renderWindowWidget) { m_LogoAnnotation->SetVisibility(show); renderWindowWidget->RequestUpdate(); return; } MITK_ERROR << "Logo can not be shown for an unknown widget."; } bool QmitkMultiWidgetDecorationManager::IsLogoVisible() const { return m_LogoAnnotation->IsVisible(); } void QmitkMultiWidgetDecorationManager::SetColormap(QmitkMultiWidgetDecorationManager::Colormap colormap) { switch (colormap) { case Colormap::BlackAndWhite: { FillAllGradientBackgroundColorsWithBlack(); float white[3] = { 1.0f, 1.0f, 1.0f }; SetAllDecorationColors(white); break; } } } void QmitkMultiWidgetDecorationManager::SetDecorationColor(const QString& widgetID, const mitk::Color& color) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { renderWindowWidget->SetDecorationColor(color); return; } MITK_ERROR << "Decoration color can not be set for an unknown widget."; } void QmitkMultiWidgetDecorationManager::SetAllDecorationColors(const mitk::Color& color) { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->SetDecorationColor(color); } } mitk::Color QmitkMultiWidgetDecorationManager::GetDecorationColor(const QString& widgetID) const { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { return renderWindowWidget->GetDecorationColor(); } MITK_ERROR << "Decoration color can not be retrieved for an unknown widget. Returning black color!"; float black[3] = { 0.0f, 0.0f, 0.0f }; return mitk::Color(black); } void QmitkMultiWidgetDecorationManager::ShowColoredRectangle(const QString& widgetID, bool show) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { renderWindowWidget->ShowColoredRectangle(show); return; } MITK_ERROR << "Colored rectangle can not be set for an unknown widget."; } void QmitkMultiWidgetDecorationManager::ShowAllColoredRectangles(bool show) { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->ShowColoredRectangle(show); } } bool QmitkMultiWidgetDecorationManager::IsColoredRectangleVisible(const QString& widgetID) const { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { return renderWindowWidget->IsColoredRectangleVisible(); } MITK_ERROR << "Colored rectangle visibility can not be retrieved for an unknown widget. Returning 'false'."; return false; } bool QmitkMultiWidgetDecorationManager::AreAllColoredRectanglesVisible() const { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); bool allTrue = true; for (const auto& renderWindowWidget : renderWindowWidgets) { allTrue = allTrue && renderWindowWidget.second->IsColoredRectangleVisible(); } return allTrue; } void QmitkMultiWidgetDecorationManager::SetGradientBackgroundColors(const mitk::Color& upper, const mitk::Color& lower, const QString& widgetID) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { renderWindowWidget->SetGradientBackgroundColors(upper, lower); return; } MITK_ERROR << "Background color gradient can not be set for an unknown widget."; } void QmitkMultiWidgetDecorationManager::SetAllGradientBackgroundColors(const mitk::Color& upper, const mitk::Color& lower) { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->SetGradientBackgroundColors(upper, lower); } } void QmitkMultiWidgetDecorationManager::FillAllGradientBackgroundColorsWithBlack() { float black[3] = { 0.0f, 0.0f, 0.0f }; SetAllGradientBackgroundColors(black, black); } void QmitkMultiWidgetDecorationManager::ShowGradientBackground(const QString& widgetID, bool show) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { renderWindowWidget->ShowGradientBackground(show); return; } MITK_ERROR << "Background color gradient can not be shown for an unknown widget."; } void QmitkMultiWidgetDecorationManager::ShowAllGradientBackgrounds(bool show) { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->ShowGradientBackground(show); } } std::pair<mitk::Color, mitk::Color> QmitkMultiWidgetDecorationManager::GetGradientBackgroundColors(const QString& widgetID) const { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { return renderWindowWidget->GetGradientBackgroundColors(); } MITK_ERROR << "Background color gradient can not be retrieved for an unknown widget. Returning black color pair."; float black[3] = { 0.0f, 0.0f, 0.0f }; return std::make_pair(mitk::Color(black), mitk::Color(black)); } bool QmitkMultiWidgetDecorationManager::IsGradientBackgroundOn(const QString& widgetID) const { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { return renderWindowWidget->IsGradientBackgroundOn(); } MITK_ERROR << "Background color gradient flag can not be retrieved for an unknown widget. Returning 'false'."; return false; } bool QmitkMultiWidgetDecorationManager::AreAllGradientBackgroundsOn() const { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); bool allTrue = true; for (const auto& renderWindowWidget : renderWindowWidgets) { allTrue = allTrue && renderWindowWidget.second->IsGradientBackgroundOn(); } return allTrue; } void QmitkMultiWidgetDecorationManager::SetCornerAnnotationText(const QString& widgetID, const std::string& cornerAnnotation) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { renderWindowWidget->SetCornerAnnotationText(cornerAnnotation); return; } MITK_ERROR << "Corner annotation text can not be retrieved for an unknown widget."; } std::string QmitkMultiWidgetDecorationManager::GetCornerAnnotationText(const QString& widgetID) const { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { return renderWindowWidget->GetCornerAnnotationText(); } MITK_ERROR << "Corner annotation text can not be retrieved for an unknown widget."; return ""; } void QmitkMultiWidgetDecorationManager::ShowCornerAnnotation(const QString& widgetID, bool show) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { renderWindowWidget->ShowCornerAnnotation(show); return; } MITK_ERROR << "Corner annotation can not be set for an unknown widget."; } void QmitkMultiWidgetDecorationManager::ShowAllCornerAnnotations(bool show) { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); for (const auto& renderWindowWidget : renderWindowWidgets) { renderWindowWidget.second->ShowCornerAnnotation(show); } } bool QmitkMultiWidgetDecorationManager::IsCornerAnnotationVisible(const QString& widgetID) const { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(widgetID); if (nullptr != renderWindowWidget) { return renderWindowWidget->IsCornerAnnotationVisible(); } MITK_ERROR << "Corner annotation visibility can not be retrieved for an unknown widget. Returning 'false'."; return false; } bool QmitkMultiWidgetDecorationManager::AreAllCornerAnnotationsVisible() const { QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets(); bool allTrue = true; for (const auto& renderWindowWidget : renderWindowWidgets) { allTrue = allTrue && renderWindowWidget.second->IsCornerAnnotationVisible(); } return allTrue; } ////////////////////////////////////////////////////////////////////////// // PRIVATE ////////////////////////////////////////////////////////////////////////// vtkSmartPointer<vtkImageData> QmitkMultiWidgetDecorationManager::GetVtkLogo(const char* path) { QImage* qimage = new QImage(path); vtkSmartPointer<vtkQImageToImageSource> qImageToVtk; qImageToVtk = vtkSmartPointer<vtkQImageToImageSource>::New(); qImageToVtk->SetQImage(qimage); qImageToVtk->Update(); vtkSmartPointer<vtkImageData> vtkLogo = qImageToVtk->GetOutput(); return vtkLogo; } void QmitkMultiWidgetDecorationManager::SetLogo(vtkSmartPointer<vtkImageData> vtkLogo) { std::shared_ptr<QmitkRenderWindowWidget> renderWindowWidget = m_MultiWidget->GetLastRenderWindowWidget(); if (nullptr != renderWindowWidget && m_LogoAnnotation.IsNotNull()) { mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_LogoAnnotation.GetPointer(), renderWindowWidget->GetRenderWindow()->GetRenderer()); m_LogoAnnotation->SetLogoImage(vtkLogo); mitk::BaseRenderer *renderer = mitk::BaseRenderer::GetInstance(renderWindowWidget->GetRenderWindow()->GetVtkRenderWindow()); m_LogoAnnotation->Update(renderer); renderWindowWidget->RequestUpdate(); return; } MITK_ERROR << "Logo can not be set for an unknown widget."; } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.h b/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.h index 7b42bbe25a..3cfe458af1 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkMultiWidgetDecorationManager.h @@ -1,140 +1,142 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKMULTIWIDGETDECORATIONMANAGER_H #define QMITKMULTIWIDGETDECORATIONMANAGER_H #include <org_mitk_gui_qt_common_Export.h> // mitk core #include <mitkColorProperty.h> // mitk annotation #include <mitkLogoAnnotation.h> // mitk qt widgets #include <QmitkAbstractMultiWidget.h> -// berry -#include <berryIBerryPreferences.h> - // vtk #include <vtkImageData.h> #include <vtkSmartPointer.h> // qt #include <QString> #include <QStringList> +namespace mitk +{ + class IPreferences; +} + /** * @brief * * */ class MITK_QT_COMMON QmitkMultiWidgetDecorationManager { public: QmitkMultiWidgetDecorationManager(QmitkAbstractMultiWidget* multiWidget); enum class Colormap { BlackAndWhite = 0 // black background, white decoration }; - void DecorationPreferencesChanged(const berry::IBerryPreferences* preferences); + void DecorationPreferencesChanged(const mitk::IPreferences* preferences); /** * @brief Show or hide decorations like like colored borders or background, logos, menu widgets, logos and * text annotations. * * \@par Show the decorations specified in decorations if true. Hide them, if not. * \@par A list of decoration names. If empty, all supported decorations are affected. */ void ShowDecorations(bool show, const QStringList& decorations); /** * @brief Return if a specific decoration is visible. * * \return True, if the specified decoration is shown, false if not. */ bool IsDecorationVisible(const QString &decoration) const; QStringList GetDecorations() const; void SetupLogo(const char* path); void ShowLogo(bool show); bool IsLogoVisible() const; void SetColormap(Colormap colormap); void SetDecorationColor(const QString& widgetID, const mitk::Color& color); void SetAllDecorationColors(const mitk::Color& color); mitk::Color GetDecorationColor(const QString& widgetID) const; void ShowColoredRectangle(const QString& widgetID, bool show); void ShowAllColoredRectangles(bool show); bool IsColoredRectangleVisible(const QString& widgetID) const; bool AreAllColoredRectanglesVisible() const; /** * @brief Set a background color gradient for a specific render window. * * If two different input colors are used, a gradient background is generated. * * @param upper The color of the gradient background. * @param lower The color of the gradient background. * @param widgetID The widget identifier. */ void SetGradientBackgroundColors(const mitk::Color& upper, const mitk::Color& lower, const QString& widgetID); /** * @brief Set a background color gradient for all available render windows. * * If two different input colors are used, a gradient background is generated. * * @param upper The color of the gradient background. * @param lower The color of the gradient background. */ void SetAllGradientBackgroundColors(const mitk::Color& upper, const mitk::Color& lower); void FillAllGradientBackgroundColorsWithBlack(); void ShowGradientBackground(const QString& widgetID, bool show); void ShowAllGradientBackgrounds(bool show); /** * @brief Return a render window (widget) specific background color gradient * * @param widgetID The widget identifier. * * @return A color gradient as a pair of colors. * First entry: upper color value * Second entry: lower color value */ std::pair<mitk::Color, mitk::Color> GetGradientBackgroundColors(const QString& widgetID) const; bool IsGradientBackgroundOn(const QString& widgetID) const; bool AreAllGradientBackgroundsOn() const; void SetCornerAnnotationText(const QString& widgetID, const std::string& cornerAnnotation); std::string GetCornerAnnotationText(const QString& widgetID) const; void ShowCornerAnnotation(const QString& widgetID, bool show); void ShowAllCornerAnnotations(bool show); bool IsCornerAnnotationVisible(const QString& widgetID) const; bool AreAllCornerAnnotationsVisible() const; private: vtkSmartPointer<vtkImageData> GetVtkLogo(const char* path); void SetLogo(vtkSmartPointer<vtkImageData> vtkLogo); QmitkAbstractMultiWidget* m_MultiWidget; mitk::LogoAnnotation::Pointer m_LogoAnnotation; }; #endif // QMITKMULTIWIDGETDECORATIONMANAGER_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp index f80d85e67f..df4a7c5920 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp @@ -1,191 +1,158 @@ /*============================================================================ 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 "QmitkNodeSelectionPreferenceHelper.h" #include <internal/QmitkNodeSelectionConstants.h> -#include <berryIPreferencesService.h> - -#include <berryIPreferences.h> -#include <berryIPreferencesService.h> -#include <berryPlatform.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <QmitkDataStorageSelectionHistoryInspector.h> #include <QmitkDataStorageFavoriteNodesInspector.h> #include "mitkExceptionMacro.h" #include "mitkDataStorageInspectorGenerator.h" void mitk::PutVisibleDataStorageInspectors(const VisibleDataStorageInspectorMapType &inspectors) { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); - berry::IPreferences::Pointer visNode = - prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID.c_str()); - - visNode->RemoveNode(); - prefNode->Flush(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); + auto* visNode = prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID); - // new empty preset node - visNode = prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID.c_str()); + visNode->Clear(); // store map in new node for (const auto &inspector : inspectors) { std::ostringstream sstr; sstr << inspector.first; - berry::IPreferences::Pointer aNode = visNode->Node(QString::fromStdString(sstr.str())); + auto* aNode = visNode->Node(sstr.str()); - aNode->Put(mitk::NodeSelectionConstants::VISIBLE_INSPECTOR_ID.c_str(), inspector.second.c_str()); - aNode->Flush(); + aNode->Put(mitk::NodeSelectionConstants::VISIBLE_INSPECTOR_ID, inspector.second); } visNode->Flush(); } mitk::VisibleDataStorageInspectorMapType mitk::GetVisibleDataStorageInspectors() { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); - berry::IPreferences::Pointer visNode = - prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID.c_str()); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); + auto* visNode = prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID); - typedef QStringList NamesType; + using NamesType = std::vector<std::string>; NamesType names = visNode->ChildrenNames(); VisibleDataStorageInspectorMapType visMap; if (!names.empty()) { - for (NamesType::const_iterator pos = names.begin(); pos != names.end(); ++pos) + for (const auto& name : names) { - berry::IPreferences::Pointer aNode = visNode->Node(*pos); + auto* aNode = visNode->Node(name); - if (aNode.IsNull()) - { - mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " - << (*pos).toStdString(); - } + if (aNode == nullptr) + mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << name; - std::istringstream isstr(pos->toStdString()); + std::istringstream isstr(name); unsigned int order = 0; isstr >> order; - auto id = aNode->Get(mitk::NodeSelectionConstants::VISIBLE_INSPECTOR_ID.c_str(), ""); - if (id.isEmpty()) - { - mitkThrow() << "Error in preference interface. ID of visible inspector is not set. Inspector position: " - << order; - } + auto id = aNode->Get(mitk::NodeSelectionConstants::VISIBLE_INSPECTOR_ID, ""); - visMap.insert(std::make_pair(order, id.toStdString())); + if (id.empty()) + mitkThrow() << "Error in preference interface. ID of visible inspector is not set. Inspector position: " << order; + + visMap.insert(std::make_pair(order, id)); } } if (visMap.empty()) { //no visibility preferences set. Generate default auto allProviders = mitk::DataStorageInspectorGenerator::GetProviders(); //fill inspector list unsigned int pos = 0; for (const auto& iter : allProviders) { if (iter.first != QmitkDataStorageFavoriteNodesInspector::INSPECTOR_ID() && iter.first != QmitkDataStorageSelectionHistoryInspector::INSPECTOR_ID()) { visMap.insert(std::make_pair(pos, iter.first)); ++pos; } } } return visMap; } mitk::DataStorageInspectorIDType mitk::GetPreferredDataStorageInspector() { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); + auto id = prefNode->Get(mitk::NodeSelectionConstants::PREFERRED_INSPECTOR_ID, ""); - auto id = prefNode->Get(mitk::NodeSelectionConstants::PREFERRED_INSPECTOR_ID.c_str(), ""); - - mitk::DataStorageInspectorIDType result = id.toStdString(); - - if (result.empty()) + if (id.empty()) { //nothing set, deduce default preferred inspector auto visibleInspectors = GetVisibleDataStorageInspectors(); if (!visibleInspectors.empty()) - { - result = visibleInspectors.begin()->second; - } + id = visibleInspectors.begin()->second; } - return result; + return id; } void mitk::PutPreferredDataStorageInspector(const DataStorageInspectorIDType &id) { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); - prefNode->Put(mitk::NodeSelectionConstants::PREFERRED_INSPECTOR_ID.c_str(), id.c_str()); + prefNode->Put(mitk::NodeSelectionConstants::PREFERRED_INSPECTOR_ID, id); prefNode->Flush(); } void mitk::PutShowFavoritesInspector(bool show) { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); - - prefNode->PutBool(mitk::NodeSelectionConstants::SHOW_FAVORITE_INSPECTOR.c_str(), show); + prefNode->PutBool(mitk::NodeSelectionConstants::SHOW_FAVORITE_INSPECTOR, show); prefNode->Flush(); } bool mitk::GetShowFavoritesInspector() { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); - return prefNode->GetBool(mitk::NodeSelectionConstants::SHOW_FAVORITE_INSPECTOR.c_str(), true); + return prefNode->GetBool(mitk::NodeSelectionConstants::SHOW_FAVORITE_INSPECTOR, true); } void mitk::PutShowHistoryInspector(bool show) { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); - - prefNode->PutBool(mitk::NodeSelectionConstants::SHOW_HISTORY_INSPECTOR.c_str(), show); + prefNode->PutBool(mitk::NodeSelectionConstants::SHOW_HISTORY_INSPECTOR, show); prefNode->Flush(); } bool mitk::GetShowHistoryInspector() { - berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = - prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID); - return prefNode->GetBool(mitk::NodeSelectionConstants::SHOW_HISTORY_INSPECTOR.c_str(), true); + return prefNode->GetBool(mitk::NodeSelectionConstants::SHOW_HISTORY_INSPECTOR, true); } diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp index bf8b062bb7..b925ff44dd 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp @@ -1,69 +1,71 @@ /*============================================================================ 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 "QmitkCommonActivator.h" #include <berryPlatformUI.h> #include <mitkLogMacros.h> +#include <mitkCoreServices.h> #include "QmitkNodeSelectionPreferencePage.h" +#include <usModuleInitialization.h> + +US_INITIALIZE_MODULE + QmitkCommonActivator* QmitkCommonActivator::m_Instance = nullptr; ctkPluginContext* QmitkCommonActivator::m_Context = nullptr; ctkPluginContext* QmitkCommonActivator::GetContext() { return m_Context; } QmitkCommonActivator* QmitkCommonActivator::GetInstance() { return m_Instance; } -berry::IPreferencesService* QmitkCommonActivator::GetPreferencesService() +mitk::IPreferencesService* QmitkCommonActivator::GetPreferencesService() { - return m_PrefServiceTracker->getService(); + return mitk::CoreServices::GetPreferencesService(); } void QmitkCommonActivator::start(ctkPluginContext* context) { this->m_Instance = this; this->m_Context = context; - this->m_PrefServiceTracker.reset(new ctkServiceTracker<berry::IPreferencesService*>(context)); if(berry::PlatformUI::IsWorkbenchRunning()) { m_ViewCoordinator.reset(new QmitkViewCoordinator); m_ViewCoordinator->Start(); } else { MITK_ERROR << "BlueBerry Workbench not running!"; } BERRY_REGISTER_EXTENSION_CLASS(QmitkNodeSelectionPreferencePage, context) } void QmitkCommonActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_ViewCoordinator->Stop(); m_ViewCoordinator.reset(); - this->m_PrefServiceTracker.reset(); - this->m_Context = nullptr; this->m_Instance = nullptr; } diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h index 9b6e2138cc..a148075749 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h @@ -1,62 +1,61 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKCOMMONACTIVATOR_H_ #define QMITKCOMMONACTIVATOR_H_ #include <ctkPluginActivator.h> -#include <ctkServiceTracker.h> - -#include <berryIPreferencesService.h> - #include "QmitkViewCoordinator.h" +namespace mitk +{ + class IPreferencesService; +} + /** * \ingroup org_mitk_gui_qt_common_internal * * \brief The plug-in activator for the StateMachine * * When the plug-in is started by the framework, it initializes StateMachine * specific things. */ class QmitkCommonActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_common") Q_INTERFACES(ctkPluginActivator) public: static ctkPluginContext* GetContext(); static QmitkCommonActivator* GetInstance(); - berry::IPreferencesService* GetPreferencesService(); + mitk::IPreferencesService* GetPreferencesService(); /** * Sets default StateMachine to EventMapper. */ void start(ctkPluginContext* context) override; void stop(ctkPluginContext* context) override; private: static QmitkCommonActivator* m_Instance; static ctkPluginContext* m_Context; QScopedPointer<QmitkViewCoordinator> m_ViewCoordinator; - QScopedPointer<ctkServiceTracker<berry::IPreferencesService*> > m_PrefServiceTracker; - }; #endif /* QMITKCOMMONACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkNodeSelectionPreferencePage.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkNodeSelectionPreferencePage.h index 679b365b07..33ab662032 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkNodeSelectionPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkNodeSelectionPreferencePage.h @@ -1,87 +1,86 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __QMITK_NODE_SELECTION_PREFERENCE_PAGE_H #define __QMITK_NODE_SELECTION_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" -#include "berryIPreferences.h" #include "mitkDataStorageInspectorGenerator.h" #include "ui_QmitkNodeSelectionPreferencePage.h" class QWidget; /** * \class QmitkNodeSelectionPreferencePage * \brief Preference page for general node selection settings. */ class QmitkNodeSelectionPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkNodeSelectionPreferencePage(); ~QmitkNodeSelectionPreferencePage() override; /** * \brief Called by framework to initialize this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; protected slots: void UpdateWidgets(); void MoveDown(); void MoveUp(); protected: QWidget *m_MainControl; Ui::QmitkNodeSelectionPreferencePage* m_Controls; mitk::DataStorageInspectorGenerator::ProviderMapType m_Providers; }; #endif diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp index 7f1ac11d7a..f291ef224b 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp @@ -1,139 +1,136 @@ /*============================================================================ 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 "QmitkDataManagerHotkeysPrefPage.h" // mitk qt widgets ext module #include <QmitkHotkeyLineEdit.h> // berry -#include <berryIPreferencesService.h> -#include <berryPlatform.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> // qt #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> QmitkDataManagerHotkeysPrefPage::QmitkDataManagerHotkeysPrefPage() : m_MainControl(nullptr) { } void QmitkDataManagerHotkeysPrefPage::Init(berry::IWorkbench::Pointer) { } void QmitkDataManagerHotkeysPrefPage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer dataManagerHotkeysPreferencesNode = prefService->GetSystemPreferences()->Node("/DataManager/Hotkeys"); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* dataManagerHotkeysPreferencesNode = prefService->GetSystemPreferences()->Node("/DataManager/Hotkeys"); m_DataManagerHotkeysPreferencesNode = dataManagerHotkeysPreferencesNode; m_HotkeyEditors["Make all nodes invisible"] = new QmitkHotkeyLineEdit("Ctrl+V"); m_HotkeyEditors["Toggle visibility of selected nodes"] = new QmitkHotkeyLineEdit("V"); m_HotkeyEditors["Delete selected nodes"] = new QmitkHotkeyLineEdit("Del"); m_HotkeyEditors["Reinit selected nodes"] = new QmitkHotkeyLineEdit("R"); m_HotkeyEditors["Global reinit"] = new QmitkHotkeyLineEdit("Ctrl+R"); m_HotkeyEditors["Show node information"] = new QmitkHotkeyLineEdit("Ctrl+I"); m_MainControl = new QWidget(parent); auto layout = new QGridLayout; int i = 0; for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) { layout->addWidget(new QLabel(it->first), i, 0); layout->addWidget(it->second, i, 1); layout->setRowStretch(i, 0); ++i; } layout->setRowStretch(i + 1, 10); m_MainControl->setLayout(layout); Update(); } QWidget* QmitkDataManagerHotkeysPrefPage::GetQtControl() const { return m_MainControl; } bool QmitkDataManagerHotkeysPrefPage::PerformOk() { - berry::IPreferences::Pointer dataManagerHotkeysPreferencesNode = m_DataManagerHotkeysPreferencesNode.Lock(); - if (dataManagerHotkeysPreferencesNode.IsNotNull()) + if (m_DataManagerHotkeysPreferencesNode != nullptr) { QString keyString; QString errString; for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) { keyString = it->second->GetKeySequenceAsString(); if (keyString.isEmpty()) { errString = QString("No valid key sequence for \"%1\"").arg(it->first); } if (errString.isEmpty()) { std::map<QString, QmitkHotkeyLineEdit*>::iterator it2; // search for duplicated key for (it2 = m_HotkeyEditors.begin(); it2 != m_HotkeyEditors.end(); ++it2) { if (it->first != it2->first && keyString == it2->second->GetKeySequenceAsString()) { errString = QString("Duplicate hot key for \"%1\" and \"%2\"").arg(it->first).arg(it2->first); break; } } } if (!errString.isEmpty()) { QMessageBox::critical(QApplication::activeWindow(), "Error", errString); return false; } } // no errors -> save all values and flush to file for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) { QString keySequence = it->second->GetKeySequenceAsString(); - dataManagerHotkeysPreferencesNode->Put(it->first, it->second->GetKeySequenceAsString()); + m_DataManagerHotkeysPreferencesNode->Put(it->first.toStdString(), it->second->GetKeySequenceAsString().toStdString()); } - dataManagerHotkeysPreferencesNode->Flush(); + m_DataManagerHotkeysPreferencesNode->Flush(); return true; } return false; } void QmitkDataManagerHotkeysPrefPage::PerformCancel() { } void QmitkDataManagerHotkeysPrefPage::Update() { - berry::IPreferences::Pointer dataManagerHotkeysPreferencesNode = m_DataManagerHotkeysPreferencesNode.Lock(); - if (dataManagerHotkeysPreferencesNode.IsNotNull()) + if (m_DataManagerHotkeysPreferencesNode != nullptr) { for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) - { - it->second->setText(dataManagerHotkeysPreferencesNode->Get(it->first, it->second->text())); - } + it->second->setText(QString::fromStdString(m_DataManagerHotkeysPreferencesNode->Get(it->first.toStdString(), it->second->text().toStdString()))); } } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h index ea2f5d3efc..586c5cff0a 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h @@ -1,73 +1,78 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERHOTKEYSPREFPAGE_H #define QMITKDATAMANAGERHOTKEYSPREFPAGE_H #include <org_mitk_gui_qt_datamanager_Export.h> // blueberry ui qt plugin #include <berryIQtPreferencePage.h> // qt #include <QWidget> // c++ #include <map> +namespace mitk +{ + class IPreferences; +} + class QmitkHotkeyLineEdit; struct MITK_QT_DATAMANAGER QmitkDataManagerHotkeysPrefPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDataManagerHotkeysPrefPage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; /** * @brief \see IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @brief \see IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @brief \see IPreferencePage::Update() */ void Update() override; protected: /** * @brief The node from which the properties are taken (will be catched from the preferences service in ctor) * * */ - berry::IPreferences::WeakPtr m_DataManagerHotkeysPreferencesNode; + mitk::IPreferences* m_DataManagerHotkeysPreferencesNode; /** * @brief Maps a label to hotkey lineedit, e.g. "Toggle Visibility of selected nodes" => QmitkHotkeyLineEdit * * */ std::map<QString, QmitkHotkeyLineEdit*> m_HotkeyEditors; QWidget* m_MainControl; }; #endif // QMITKDATAMANAGERHOTKEYSPREFPAGE_H diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp index 0e65d3117c..9db87ead55 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp @@ -1,88 +1,89 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDataManagerPreferencePage.h" #include "QmitkDataManagerView.h" #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QCheckBox> -#include <berryIPreferencesService.h> -#include <berryPlatform.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> QmitkDataManagerPreferencePage::QmitkDataManagerPreferencePage() : m_MainControl(nullptr) { // nothing here } void QmitkDataManagerPreferencePage::Init(berry::IWorkbench::Pointer ) { // nothing here } void QmitkDataManagerPreferencePage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_DataManagerPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataManagerView::VIEW_ID); + m_DataManagerPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataManagerView::VIEW_ID.toStdString()); m_MainControl = new QWidget(parent); m_EnableSingleEditing = new QCheckBox; m_PlaceNewNodesOnTop = new QCheckBox; m_ShowHelperObjects = new QCheckBox; m_ShowNodesContainingNoData = new QCheckBox; m_AllowParentChange = new QCheckBox; auto formLayout = new QFormLayout; formLayout->addRow("&Single click property editing:", m_EnableSingleEditing); formLayout->addRow("&Place new nodes on top:", m_PlaceNewNodesOnTop); formLayout->addRow("&Show helper objects:", m_ShowHelperObjects); formLayout->addRow("&Show nodes containing no data", m_ShowNodesContainingNoData); formLayout->addRow("&Allow changing of parent node:", m_AllowParentChange); m_MainControl->setLayout(formLayout); Update(); } QWidget* QmitkDataManagerPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkDataManagerPreferencePage::PerformOk() { m_DataManagerPreferencesNode->PutBool("Single click property editing", m_EnableSingleEditing->isChecked()); m_DataManagerPreferencesNode->PutBool("Place new nodes on top", m_PlaceNewNodesOnTop->isChecked()); m_DataManagerPreferencesNode->PutBool("Show helper objects", m_ShowHelperObjects->isChecked()); m_DataManagerPreferencesNode->PutBool("Show nodes containing no data", m_ShowNodesContainingNoData->isChecked()); m_DataManagerPreferencesNode->PutBool("Allow changing of parent node", m_AllowParentChange->isChecked()); return true; } void QmitkDataManagerPreferencePage::PerformCancel() { // nothing here } void QmitkDataManagerPreferencePage::Update() { m_EnableSingleEditing->setChecked(m_DataManagerPreferencesNode->GetBool("Single click property editing", true)); m_PlaceNewNodesOnTop->setChecked(m_DataManagerPreferencesNode->GetBool("Place new nodes on top", true)); m_ShowHelperObjects->setChecked(m_DataManagerPreferencesNode->GetBool("Show helper objects", false)); m_ShowNodesContainingNoData->setChecked(m_DataManagerPreferencesNode->GetBool("Show nodes containing no data", false)); m_AllowParentChange->setChecked(m_DataManagerPreferencesNode->GetBool("Allow changing of parent node", false)); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h index f0c478a463..6f3d31983c 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h @@ -1,63 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERPREFERENCEPAGE_H_ #define QMITKDATAMANAGERPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include <org_mitk_gui_qt_datamanager_Export.h> -#include <berryIPreferences.h> class QWidget; class QCheckBox; +namespace mitk +{ + class IPreferences; +} + struct MITK_QT_DATAMANAGER QmitkDataManagerPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDataManagerPreferencePage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected: QWidget* m_MainControl; QCheckBox* m_EnableSingleEditing; QCheckBox* m_PlaceNewNodesOnTop; QCheckBox* m_ShowHelperObjects; QCheckBox* m_ShowNodesContainingNoData; QCheckBox* m_AllowParentChange; - berry::IPreferences::Pointer m_DataManagerPreferencesNode; + mitk::IPreferences* m_DataManagerPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp index 09fad8822f..7adc044f6d 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp @@ -1,230 +1,231 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDataManagerView.h" // mitk gui qt datamanager #include "internal/QmitkDataManagerItemDelegate.h" #include "internal/QmitkNodeTableViewKeyFilter.h" // mitk core #include <mitkCommon.h> #include <mitkCoreObjectFactory.h> #include <mitkEnumerationProperty.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkLookupTableProperty.h> #include <mitkNodePredicateAnd.h> #include <mitkNodePredicateData.h> #include <mitkNodePredicateDataType.h> #include <mitkNodePredicateNot.h> #include <mitkNodePredicateOr.h> #include <mitkNodePredicateProperty.h> #include <mitkProperties.h> #include <mitkRenderingModeProperty.h> +#include <mitkIPreferences.h> // qt widgets module #include <QmitkCustomVariants.h> #include <QmitkDataStorageFilterProxyModel.h> #include <QmitkDataStorageTreeModel.h> #include <QmitkIOUtil.h> #include <QmitkNodeDescriptorManager.h> // mitk core services plugin #include <mitkIDataStorageReference.h> #include <mitkIDataStorageService.h> // mitk gui common plugin #include <mitkDataNodeObject.h> // mitk gui qt application plugin #include <QmitkDataNodeGlobalReinitAction.h> #include <QmitkDataNodeToggleVisibilityAction.h> // mitk gui qt common plugin #include <QmitkDnDFrameWidget.h> // qt #include <QGridLayout> #include <QVBoxLayout> #include <QTreeView> const QString QmitkDataManagerView::VIEW_ID = "org.mitk.views.datamanager"; QmitkDataManagerView::QmitkDataManagerView() : m_ItemDelegate(nullptr) { } QmitkDataManagerView::~QmitkDataManagerView() { // nothing here } void QmitkDataManagerView::CreateQtPartControl(QWidget* parent) { m_CurrentRowCount = 0; m_Parent = parent; - berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast<berry::IBerryPreferences>(); - assert(prefs); + auto* prefs = this->GetPreferences(); + assert(prefs != nullptr); m_NodeTreeModel = new QmitkDataStorageTreeModel(GetDataStorage(), prefs->GetBool("Place new nodes on top", true)); m_NodeTreeModel->setParent(parent); m_NodeTreeModel->SetAllowHierarchyChange(prefs->GetBool("Allow changing of parent node", false)); // Prepare filters m_HelperObjectFilterPredicate = mitk::NodePredicateOr::New( mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true)), mitk::NodePredicateProperty::New("hidden object", mitk::BoolProperty::New(true))); m_NodeWithNoDataFilterPredicate = mitk::NodePredicateData::New(nullptr); m_FilterModel = new QmitkDataStorageFilterProxyModel(); m_FilterModel->setSourceModel(m_NodeTreeModel); m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate); m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate); m_NodeTreeView = new QTreeView; m_NodeTreeView->setHeaderHidden(true); m_NodeTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_NodeTreeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_NodeTreeView->setAlternatingRowColors(true); m_NodeTreeView->setDragEnabled(true); m_NodeTreeView->setDropIndicatorShown(true); m_NodeTreeView->setAcceptDrops(true); m_NodeTreeView->setContextMenuPolicy(Qt::CustomContextMenu); m_NodeTreeView->setModel(m_FilterModel); m_NodeTreeView->setTextElideMode(Qt::ElideMiddle); m_NodeTreeView->installEventFilter(new QmitkNodeTableViewKeyFilter(this, GetDataStorage())); m_ItemDelegate = new QmitkDataManagerItemDelegate(m_NodeTreeView); m_NodeTreeView->setItemDelegate(m_ItemDelegate); connect(m_NodeTreeModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(NodeTreeViewRowsInserted(const QModelIndex&, int, int))); connect(m_NodeTreeModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(NodeTreeViewRowsRemoved(const QModelIndex&, int, int))); connect(m_NodeTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(NodeSelectionChanged(const QItemSelection &, const QItemSelection &))); connect(m_NodeTreeModel, &QmitkDataStorageTreeModel::nodeVisibilityChanged, this, &QmitkDataManagerView::OnNodeVisibilityChanged); // data node context menu and menu actions m_DataNodeContextMenu = new QmitkDataNodeContextMenu(GetSite(), m_NodeTreeView); m_DataNodeContextMenu->SetDataStorage(GetDataStorage()); connect(m_NodeTreeView, SIGNAL(customContextMenuRequested(const QPoint&)), m_DataNodeContextMenu, SLOT(OnContextMenuRequested(const QPoint&))); QGridLayout* dndFrameWidgetLayout = new QGridLayout; dndFrameWidgetLayout->addWidget(m_NodeTreeView, 0, 0); dndFrameWidgetLayout->setContentsMargins(0, 0, 0, 0); m_DnDFrameWidget = new QmitkDnDFrameWidget(m_Parent); m_DnDFrameWidget->setLayout(dndFrameWidgetLayout); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DnDFrameWidget); layout->setContentsMargins(0, 0, 0, 0); m_Parent->setLayout(layout); } void QmitkDataManagerView::SetFocus() { } ////////////////////////////////////////////////////////////////////////// // Node tree modification ////////////////////////////////////////////////////////////////////////// void QmitkDataManagerView::NodeTreeViewRowsInserted(const QModelIndex& parent, int /*start*/, int /*end*/) { QModelIndex viewIndex = m_FilterModel->mapFromSource(parent); m_NodeTreeView->setExpanded(viewIndex, true); // a new row was inserted if (m_CurrentRowCount == 0 && m_NodeTreeModel->rowCount() == 1) { mitk::WorkbenchUtil::OpenRenderWindowPart(GetSite()->GetPage()); m_CurrentRowCount = m_NodeTreeModel->rowCount(); } } void QmitkDataManagerView::NodeTreeViewRowsRemoved(const QModelIndex& /*parent*/, int /*start*/, int /*end*/) { m_CurrentRowCount = m_NodeTreeModel->rowCount(); } void QmitkDataManagerView::NodeSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { auto selectedNodes = GetCurrentSelection(); auto nodeSet = m_NodeTreeModel->GetNodeSet(); for (auto node : qAsConst(nodeSet)) { if (node.IsNotNull()) { node->SetSelected(selectedNodes.contains(node)); } } m_DataNodeContextMenu->SetSelectedNodes(selectedNodes); } void QmitkDataManagerView::OnNodeVisibilityChanged() { ToggleVisibilityAction::Run(GetSite(), GetDataStorage(), QList<mitk::DataNode::Pointer>()); } void QmitkDataManagerView::NodeChanged(const mitk::DataNode* /*node*/) { // m_FilterModel->invalidate(); // fix as proposed by R. Khlebnikov in the mitk-users mail from 02.09.2014 QMetaObject::invokeMethod(m_FilterModel, "invalidate", Qt::QueuedConnection); } -void QmitkDataManagerView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) +void QmitkDataManagerView::OnPreferencesChanged(const mitk::IPreferences* prefs) { if (m_NodeTreeModel->GetPlaceNewNodesOnTopFlag() != prefs->GetBool("Place new nodes on top", true)) { m_NodeTreeModel->SetPlaceNewNodesOnTop(!m_NodeTreeModel->GetPlaceNewNodesOnTopFlag()); } bool hideHelperObjects = !prefs->GetBool("Show helper objects", false); if (m_FilterModel->HasFilterPredicate(m_HelperObjectFilterPredicate) != hideHelperObjects) { if (hideHelperObjects) { m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate); } else { m_FilterModel->RemoveFilterPredicate(m_HelperObjectFilterPredicate); } } bool hideNodesWithNoData = !prefs->GetBool("Show nodes containing no data", false); if (m_FilterModel->HasFilterPredicate(m_NodeWithNoDataFilterPredicate) != hideNodesWithNoData) { if (hideNodesWithNoData) { m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate); } else { m_FilterModel->RemoveFilterPredicate(m_NodeWithNoDataFilterPredicate); } } m_NodeTreeView->expandAll(); m_NodeTreeModel->SetAllowHierarchyChange(prefs->GetBool("Allow changing of parent node", false)); GlobalReinitAction::Run(GetSite(), GetDataStorage()); } QItemSelectionModel* QmitkDataManagerView::GetDataNodeSelectionModel() const { return m_NodeTreeView->selectionModel(); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h index 4258ce4e39..abecc6d05b 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h @@ -1,123 +1,117 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERVIEW_H #define QMITKDATAMANAGERVIEW_H #include <org_mitk_gui_qt_datamanager_Export.h> // mitk core #include <mitkNodePredicateBase.h> -// berry plugin -#include <berryIBerryPreferences.h> - // mitk gui qt common plugin #include <QmitkAbstractView.h> // mitk gui qt application #include <QmitkDataNodeContextMenu.h> // qt #include <QItemSelection> // forward declarations class QModelIndex; class QTreeView; class QmitkDnDFrameWidget; class QmitkDataStorageTreeModel; class QmitkDataManagerItemDelegate; class QmitkDataStorageFilterProxyModel; /** * @brief A view that shows all data nodes of the data storage in a qt tree view. * */ class MITK_QT_DATAMANAGER QmitkDataManagerView : public QmitkAbstractView { Q_OBJECT public: static const QString VIEW_ID; // = "org.mitk.views.datamanager" QmitkDataManagerView(); ~QmitkDataManagerView() override; public Q_SLOTS: // invoked when the berry preferences were changed - void OnPreferencesChanged(const berry::IBerryPreferences* prefs) override; + void OnPreferencesChanged(const mitk::IPreferences* prefs) override; ////////////////////////////////////////////////////////////////////////// // Slots for Qt node tree signals ////////////////////////////////////////////////////////////////////////// /// When rows are inserted auto expand them void NodeTreeViewRowsInserted(const QModelIndex& parent, int start, int end); /// will setup m_CurrentRowCount void NodeTreeViewRowsRemoved(const QModelIndex& parent, int start, int end); /// Whenever the selection changes set the "selected" property respectively void NodeSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); void OnNodeVisibilityChanged(); protected: void CreateQtPartControl(QWidget* parent) override; void SetFocus() override; /// /// React to node changes. Overridden from QmitkAbstractView. /// void NodeChanged(const mitk::DataNode* node) override; protected: QWidget* m_Parent; QmitkDnDFrameWidget* m_DnDFrameWidget; /// /// \brief A plain widget as the base pane. /// QmitkDataStorageTreeModel* m_NodeTreeModel; QmitkDataStorageFilterProxyModel* m_FilterModel; mitk::NodePredicateBase::Pointer m_HelperObjectFilterPredicate; mitk::NodePredicateBase::Pointer m_NodeWithNoDataFilterPredicate; - /// - /// Holds the preferences for the data manager. - /// - berry::IBerryPreferences::Pointer m_DataManagerPreferencesNode; + /// /// \brief The Table view to show the selected nodes. /// QTreeView* m_NodeTreeView; /// /// \brief The context menu that shows up when right clicking on a node. /// QmitkDataNodeContextMenu* m_DataNodeContextMenu; /// saves the current amount of rows shown in the data manager size_t m_CurrentRowCount; QmitkDataManagerItemDelegate* m_ItemDelegate; private: QItemSelectionModel* GetDataNodeSelectionModel() const override; }; #endif // QMITKDATAMANAGERVIEW_H diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp index 59568929bb..01aec2ee1e 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp @@ -1,116 +1,114 @@ /*============================================================================ 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 "QmitkNodeTableViewKeyFilter.h" #include "../QmitkDataManagerView.h" // mitk gui qt application plugin #include <QmitkDataNodeGlobalReinitAction.h> #include <QmitkDataNodeHideAllAction.h> #include <QmitkDataNodeReinitAction.h> #include <QmitkDataNodeRemoveAction.h> #include <QmitkDataNodeShowDetailsAction.h> #include <QmitkDataNodeToggleVisibilityAction.h> -#include "berryIPreferencesService.h" -#include "berryPlatform.h" +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> // qt #include <QKeyEvent> #include <QKeySequence> QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter(QObject *dataManagerView, mitk::DataStorage *dataStorage) : QObject(dataManagerView), m_DataStorage(dataStorage) { - m_PreferencesService = berry::Platform::GetPreferencesService(); + m_Preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/DataManager/Hotkeys"); } bool QmitkNodeTableViewKeyFilter::eventFilter(QObject *obj, QEvent *event) { auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) { // standard event processing return QObject::eventFilter(obj, event); } QmitkDataManagerView *dataManagerView = qobject_cast<QmitkDataManagerView *>(this->parent()); if (event->type() == QEvent::KeyPress && dataManagerView) { - berry::IPreferences::Pointer nodeTableKeyPrefs = - m_PreferencesService->GetSystemPreferences()->Node("/DataManager/Hotkeys"); - - QKeySequence makeAllInvisible = QKeySequence(nodeTableKeyPrefs->Get("Make all nodes invisible", "Ctrl+V")); - QKeySequence toggleVisibility = QKeySequence(nodeTableKeyPrefs->Get("Toggle visibility of selected nodes", "V")); - QKeySequence deleteSelectedNodes = QKeySequence(nodeTableKeyPrefs->Get("Delete selected nodes", "Del")); - QKeySequence reinit = QKeySequence(nodeTableKeyPrefs->Get("Reinit selected nodes", "R")); - QKeySequence globalReinit = QKeySequence(nodeTableKeyPrefs->Get("Global reinit", "Ctrl+R")); - QKeySequence showInfo = QKeySequence(nodeTableKeyPrefs->Get("Show node information", "Ctrl+I")); + QKeySequence makeAllInvisible = QKeySequence(QString::fromStdString(m_Preferences->Get("Make all nodes invisible", "Ctrl+V"))); + QKeySequence toggleVisibility = QKeySequence(QString::fromStdString(m_Preferences->Get("Toggle visibility of selected nodes", "V"))); + QKeySequence deleteSelectedNodes = QKeySequence(QString::fromStdString(m_Preferences->Get("Delete selected nodes", "Del"))); + QKeySequence reinit = QKeySequence(QString::fromStdString(m_Preferences->Get("Reinit selected nodes", "R"))); + QKeySequence globalReinit = QKeySequence(QString::fromStdString(m_Preferences->Get("Global reinit", "Ctrl+R"))); + QKeySequence showInfo = QKeySequence(QString::fromStdString(m_Preferences->Get("Show node information", "Ctrl+I"))); QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); QKeySequence keySequence = QKeySequence(keyEvent->modifiers() + keyEvent->key()); // if no modifier was pressed the sequence is now empty if (keySequence.isEmpty()) { keySequence = QKeySequence(keyEvent->key()); } auto selectedNodes = AbstractDataNodeAction::GetSelectedNodes(dataManagerView->GetSite()); if (keySequence == makeAllInvisible) { if (selectedNodes.empty()) { // if no nodes are selected, hide all nodes of the data storage auto nodeset = dataStorage->GetAll(); for (auto it = nodeset->Begin(); it != nodeset->End(); ++it) { mitk::DataNode* node = it->Value(); if (nullptr != node) { selectedNodes.push_back(node); } } } HideAllAction::Run(selectedNodes); return true; } if (keySequence == deleteSelectedNodes) { RemoveAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes); return true; } if (keySequence == toggleVisibility) { ToggleVisibilityAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes); return true; } if (keySequence == reinit) { ReinitAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes); return true; } if (keySequence == globalReinit) { GlobalReinitAction::Run(dataManagerView->GetSite(), dataStorage); return true; } if (keySequence == showInfo) { ShowDetailsAction::Run(selectedNodes); return true; } } // standard event processing return QObject::eventFilter(obj, event); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h index 8c3c619dda..4caf9db86a 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h @@ -1,49 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKNODETABLEVIEWKEYFILTER_H #define QMITKNODETABLEVIEWKEYFILTER_H // mitk core #include <mitkDataStorage.h> #include <mitkWeakPointer.h> #include <QObject> -namespace berry +namespace mitk { - struct IPreferencesService; + class IPreferences; } /** * @brief A small class which receives key-pressed events on the node table. */ class QmitkNodeTableViewKeyFilter : public QObject { Q_OBJECT public: QmitkNodeTableViewKeyFilter(QObject *dataManagerView, mitk::DataStorage *dataStorage); protected: bool eventFilter(QObject *obj, QEvent *event) override; - /** - * @brief The Preferences Service to retrieve and store preferences. - */ - berry::IPreferencesService *m_PreferencesService; + + mitk::IPreferences* m_Preferences; mitk::WeakPointer<mitk::DataStorage> m_DataStorage; }; #endif // QMITKNODETABLEVIEWKEYFILTER_H diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/mitkPluginActivator.cpp index c4608ab12a..bd0faae70c 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/mitkPluginActivator.cpp @@ -1,31 +1,35 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "../QmitkDataManagerHotkeysPrefPage.h" #include "../QmitkDataManagerPreferencePage.h" #include "../QmitkDataManagerView.h" +#include <usModuleInitialization.h> + +US_INITIALIZE_MODULE + namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkDataManagerView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDataManagerPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDataManagerHotkeysPrefPage, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/DicomEventHandler.cpp b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/DicomEventHandler.cpp index a33ad356bd..c5292db40d 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/DicomEventHandler.cpp +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/DicomEventHandler.cpp @@ -1,258 +1,256 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "DicomEventHandler.h" #include <service/event/ctkEventConstants.h> #include <ctkDictionary.h> #include <mitkLogMacros.h> #include <mitkDataNode.h> #include <mitkIDataStorageService.h> #include <service/event/ctkEventAdmin.h> #include <ctkServiceReference.h> #include <mitkRenderingManager.h> #include <QVector> #include "mitkImage.h" #include <mitkContourModelSet.h> #include <mitkFileReaderRegistry.h> #include <mitkDICOMRTMimeTypes.h> #include <mitkDICOMFileReaderSelector.h> #include <mitkDICOMDCMTKTagScanner.h> #include <mitkDICOMEnums.h> #include <mitkDICOMTagsOfInterestHelper.h> #include <mitkDICOMProperty.h> #include <mitkPropertyNameHelper.h> #include "mitkBaseDICOMReaderService.h" #include <mitkRTConstants.h> #include <mitkIsoDoseLevelCollections.h> #include <mitkIsoDoseLevelSetProperty.h> #include <mitkIsoDoseLevelVectorProperty.h> #include <mitkDoseImageVtkMapper2D.h> #include <mitkRTUIConstants.h> #include <mitkIsoLevelsGenerator.h> #include <mitkDoseNodeHelper.h> #include <vtkSmartPointer.h> #include <vtkMath.h> #include <mitkTransferFunction.h> #include <mitkTransferFunctionProperty.h> #include <mitkRenderingModeProperty.h> #include <mitkLocaleSwitch.h> #include <mitkIOUtil.h> -#include <berryIPreferencesService.h> -#include <berryIPreferences.h> -#include <berryPlatform.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <ImporterUtil.h> namespace { mitk::IFileReader* GetReader(mitk::FileReaderRegistry& readerRegistry, const mitk::CustomMimeType& mimeType) { try { return readerRegistry.GetReaders(mitk::MimeType(mimeType, -1, -1)).at(0); } catch (const std::out_of_range&) { mitkThrow() << "Cannot find " << mimeType.GetCategory() << " " << mimeType.GetComment() << " file reader."; } } } DicomEventHandler::DicomEventHandler() { } DicomEventHandler::~DicomEventHandler() { } void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent) { QStringList listOfFilesForSeries; listOfFilesForSeries = ctkEvent.getProperty("FilesForSeries").toStringList(); if (!listOfFilesForSeries.isEmpty()) { //for rt data, if the modality tag isn't defined or is "CT" the image is handled like before if(ctkEvent.containsProperty("Modality") && (ctkEvent.getProperty("Modality").toString().compare("RTDOSE",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTSTRUCT",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTPLAN", Qt::CaseInsensitive) == 0)) { QString modality = ctkEvent.getProperty("Modality").toString(); mitk::FileReaderRegistry readerRegistry; if(modality.compare("RTDOSE",Qt::CaseInsensitive) == 0) { auto doseReader = GetReader(readerRegistry, mitk::DICOMRTMimeTypes::DICOMRT_DOSE_MIMETYPE()); doseReader->SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = doseReader->Read(); if (!readerOutput.empty()){ mitk::Image::Pointer doseImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer doseImageNode = mitk::DataNode::New(); doseImageNode->SetData(doseImage); doseImageNode->SetName("RTDose"); if (doseImage != nullptr) { std::string sopUID; if (mitk::GetBackwardsCompatibleDICOMProperty(0x0008, 0x0016, "dicomseriesreader.SOPClassUID", doseImage->GetPropertyList(), sopUID)) { doseImageNode->SetName(sopUID); }; - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - if (prefNode.IsNull()) - { - mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << prefNode->ToString().toStdString(); - } + if (prefNode == nullptr) + mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << prefNode; //set some specific colorwash and isoline properties - bool showColorWashGlobal = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(), true); + bool showColorWashGlobal = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID, true); //Set reference dose property - double referenceDose = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE); + double referenceDose = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID, mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE); mitk::ConfigureNodeAsDoseNode(doseImageNode, mitk::GenerateIsoLevels_Virtuos(), referenceDose, showColorWashGlobal); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(doseImageNode); mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } }//END DOSE } else if(modality.compare("RTSTRUCT",Qt::CaseInsensitive) == 0) { auto structReader = GetReader(readerRegistry, mitk::DICOMRTMimeTypes::DICOMRT_STRUCT_MIMETYPE()); structReader->SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = structReader->Read(); if (readerOutput.empty()){ MITK_ERROR << "No structure sets were created" << endl; } else { std::vector<mitk::DataNode::Pointer> modelVector; ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); for (const auto& aStruct : readerOutput){ mitk::ContourModelSet::Pointer countourModelSet = dynamic_cast<mitk::ContourModelSet*>(aStruct.GetPointer()); mitk::DataNode::Pointer structNode = mitk::DataNode::New(); structNode->SetData(countourModelSet); structNode->SetProperty("name", aStruct->GetProperty("name")); structNode->SetProperty("color", aStruct->GetProperty("contour.color")); structNode->SetProperty("contour.color", aStruct->GetProperty("contour.color")); structNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); dataStorage->Add(structNode); } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } } else if (modality.compare("RTPLAN", Qt::CaseInsensitive) == 0) { auto planReader = GetReader(readerRegistry, mitk::DICOMRTMimeTypes::DICOMRT_PLAN_MIMETYPE()); planReader->SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = planReader->Read(); if (!readerOutput.empty()){ //there is no image, only the properties are interesting mitk::Image::Pointer planDummyImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer planImageNode = mitk::DataNode::New(); planImageNode->SetData(planDummyImage); planImageNode->SetName("RTPlan"); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(planImageNode); } } } else { mitk::StringList seriesToLoad; QStringListIterator it(listOfFilesForSeries); while (it.hasNext()) { seriesToLoad.push_back(ImporterUtil::getUTF8String(it.next())); } //Get Reference for default data storage. ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); std::vector<mitk::BaseData::Pointer> baseDatas = mitk::IOUtil::Load(seriesToLoad.front()); for (const auto &data : baseDatas) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(data); std::string nodeName = mitk::DataNode::NO_NAME_VALUE(); auto nameDataProp = data->GetProperty("name"); if (nameDataProp.IsNotNull()) { //if data has a name property set by reader, use this name nodeName = nameDataProp->GetValueAsString(); } else { //reader didn't specify a name, generate one. nodeName = mitk::GenerateNameFromDICOMProperties(node); } node->SetName(nodeName); dataStorage->Add(node); } } } else { MITK_INFO << "There are no files for the current series"; } } void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& /*ctkEvent*/) { } void DicomEventHandler::SubscribeSlots() { ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref); ctkDictionary properties; properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD"; eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties); properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED"; eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties); } } diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.cpp b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.cpp index b139f22536..a0503a8d1d 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.cpp +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.cpp @@ -1,193 +1,193 @@ /*============================================================================ 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. ============================================================================*/ // Qmitk #include "QmitkDicomBrowser.h" + #include "mitkPluginActivator.h" +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include "berryIQtPreferencePage.h" -#include <berryIPreferences.h> -#include <berryIPreferencesService.h> -#include <berryIBerryPreferences.h> -#include <berryPlatform.h> const std::string QmitkDicomBrowser::EDITOR_ID = "org.mitk.editors.dicombrowser"; const QString QmitkDicomBrowser::TEMP_DICOM_FOLDER_SUFFIX="TmpDicomFolder"; QmitkDicomBrowser::QmitkDicomBrowser() : m_DicomDirectoryListener(new QmitkDicomDirectoryListener()) , m_StoreSCPLauncher(new QmitkStoreSCPLauncher(&m_Builder)) , m_Publisher(new QmitkDicomDataEventPublisher()) { } QmitkDicomBrowser::~QmitkDicomBrowser() { delete m_DicomDirectoryListener; delete m_StoreSCPLauncher; delete m_Handler; delete m_Publisher; } void QmitkDicomBrowser::CreateQtPartControl(QWidget *parent ) { m_Controls.setupUi( parent ); m_Controls.StoreSCPStatusLabel->setTextFormat(Qt::RichText); m_Controls.StoreSCPStatusLabel->setText("<img src=':/org.mitk.gui.qt.dicombrowser/network-offline_16.png'>"); TestHandler(); OnPreferencesChanged(nullptr); CreateTemporaryDirectory(); StartDicomDirectoryListener(); m_Controls.m_ctkDICOMQueryRetrieveWidget->useProgressDialog(true); connect(m_Controls.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int))); connect(m_Controls.externalDataWidget,SIGNAL(SignalStartDicomImport(const QStringList&)), m_Controls.internalDataWidget,SLOT(OnStartDicomImport(const QStringList&))); connect(m_Controls.externalDataWidget,SIGNAL(SignalDicomToDataManager(const QHash<QString,QVariant>&)), this,SLOT(OnViewButtonAddToDataManager(const QHash<QString,QVariant>&))); connect(m_Controls.internalDataWidget,SIGNAL(SignalFinishedImport()),this, SLOT(OnDicomImportFinished())); connect(m_Controls.internalDataWidget,SIGNAL(SignalDicomToDataManager(const QHash<QString,QVariant>&)), this,SLOT(OnViewButtonAddToDataManager(const QHash<QString,QVariant>&))); } void QmitkDicomBrowser::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { this->SetSite(site); this->SetInput(input); } void QmitkDicomBrowser::SetFocus() { } berry::IPartListener::Events::Types QmitkDicomBrowser::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void QmitkDicomBrowser::OnTabChanged(int page) { if (page == 2)//Query/Retrieve is selected { QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString(); QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString(); if(!((m_Builder.GetAETitle()->compare(storageAET,Qt::CaseSensitive)==0)&& (m_Builder.GetPort()->compare(storagePort,Qt::CaseSensitive)==0))) { StopStoreSCP(); StartStoreSCP(); } } } void QmitkDicomBrowser::OnDicomImportFinished() { m_Controls.tabWidget->setCurrentIndex(0); } void QmitkDicomBrowser::StartDicomDirectoryListener() { m_DicomDirectoryListener->SetDicomListenerDirectory(m_TempDirectory); m_DicomDirectoryListener->SetDicomFolderSuffix(TEMP_DICOM_FOLDER_SUFFIX); connect(m_DicomDirectoryListener, SIGNAL(SignalStartDicomImport(const QStringList&)), m_Controls.internalDataWidget, SLOT(OnStartDicomImport(const QStringList&)), Qt::DirectConnection); } void QmitkDicomBrowser::TestHandler() { m_Handler = new DicomEventHandler(); m_Handler->SubscribeSlots(); } void QmitkDicomBrowser::OnViewButtonAddToDataManager(QHash<QString, QVariant> eventProperties) { ctkDictionary properties; // properties["PatientName"] = eventProperties["PatientName"]; // properties["StudyUID"] = eventProperties["StudyUID"]; // properties["StudyName"] = eventProperties["StudyName"]; // properties["SeriesUID"] = eventProperties["SeriesUID"]; // properties["SeriesName"] = eventProperties["SeriesName"]; properties["FilesForSeries"] = eventProperties["FilesForSeries"]; if(eventProperties.contains("Modality")) { properties["Modality"] = eventProperties["Modality"]; } m_Publisher->PublishSignals(mitk::PluginActivator::getContext()); m_Publisher->AddSeriesToDataManagerEvent(properties); } void QmitkDicomBrowser::StartStoreSCP() { QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString(); QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString(); m_Builder.AddPort(storagePort)->AddAETitle(storageAET)->AddTransferSyntax()->AddOtherNetworkOptions()->AddMode()->AddOutputDirectory(m_TempDirectory); m_StoreSCPLauncher = new QmitkStoreSCPLauncher(&m_Builder); connect(m_StoreSCPLauncher, SIGNAL(SignalStatusOfStoreSCP(const QString&)), this, SLOT(OnStoreSCPStatusChanged(const QString&))); connect(m_StoreSCPLauncher ,SIGNAL(SignalStartImport(const QStringList&)),m_Controls.internalDataWidget,SLOT(OnStartDicomImport(const QStringList&))); connect(m_StoreSCPLauncher ,SIGNAL(SignalStoreSCPError(const QString&)),m_DicomDirectoryListener,SLOT(OnDicomNetworkError(const QString&)),Qt::DirectConnection); connect(m_StoreSCPLauncher ,SIGNAL(SignalStoreSCPError(const QString&)),this,SLOT(OnDicomNetworkError(const QString&)),Qt::DirectConnection); m_StoreSCPLauncher->StartStoreSCP(); } void QmitkDicomBrowser::OnStoreSCPStatusChanged(const QString& status) { m_Controls.StoreSCPStatusLabel->setText("<img src=':/org.mitk.gui.qt.dicombrowser/network-idle_16.png'> "+status); } void QmitkDicomBrowser::OnDicomNetworkError(const QString& status) { m_Controls.StoreSCPStatusLabel->setText("<img src=':/org.mitk.gui.qt.dicombrowser/network-error_16.png'> "+status); } void QmitkDicomBrowser::StopStoreSCP() { delete m_StoreSCPLauncher; } void QmitkDicomBrowser::SetPluginDirectory() { m_PluginDirectory = mitk::PluginActivator::getContext()->getDataFile("").absolutePath(); m_PluginDirectory.append("/database"); } void QmitkDicomBrowser::CreateTemporaryDirectory() { QDir tmp; QString tmpPath = QDir::tempPath(); m_TempDirectory.clear(); m_TempDirectory.append(tmpPath); m_TempDirectory.append(QString("/")); m_TempDirectory.append(TEMP_DICOM_FOLDER_SUFFIX); m_TempDirectory.append(QString(".")); m_TempDirectory.append(QTime::currentTime().toString("hhmmsszzz")); m_TempDirectory.append(QString::number(QCoreApplication::applicationPid())); tmp.mkdir(QDir::toNativeSeparators( m_TempDirectory )); } -void QmitkDicomBrowser::OnPreferencesChanged(const berry::IBerryPreferences*) +void QmitkDicomBrowser::OnPreferencesChanged(const mitk::IPreferences*) { SetPluginDirectory(); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - m_DatabaseDirectory = prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader")->Get("default dicom path", m_PluginDirectory); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + m_DatabaseDirectory = QString::fromStdString(prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader")->Get("default dicom path", m_PluginDirectory.toStdString())); m_Controls.internalDataWidget->SetDatabaseDirectory(m_DatabaseDirectory); } diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.h b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.h index 9dbcc2d139..e8a5d5e799 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.h +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomBrowser.h @@ -1,145 +1,149 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkDicomBrowser_h #define QmitkDicomBrowser_h // Blueberry #include <berryIPartListener.h> -#include <berryIBerryPreferences.h> #include <berryISelectionListener.h> #include <berryQtEditorPart.h> // MITK #include "DicomEventHandler.h" #include "QmitkDicomDataEventPublisher.h" #include "QmitkDicomDirectoryListener.h" #include "QmitkStoreSCPLauncher.h" #include "QmitkStoreSCPLauncherBuilder.h" #include "ui_QmitkDicomBrowserControls.h" #include <org_mitk_gui_qt_dicombrowser_Export.h> // Qt #include <QObject> #include <QString> #include <QStringList> #include <QThread> #include <QVariant> +namespace mitk +{ + class IPreferences; +} + /** * \brief QmitkDicomBrowser is an editor providing functionality for dicom storage and import and query retrieve functionality. * * \sa berry::IPartListener * \ingroup ${plugin_target}_internal */ class DICOM_EXPORT QmitkDicomBrowser : public berry::QtEditorPart, virtual public berry::IPartListener { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: berryObjectMacro(QmitkDicomBrowser); static const std::string EDITOR_ID; static const QString TEMP_DICOM_FOLDER_SUFFIX; /** * \brief QmitkDicomBrowser constructor. */ QmitkDicomBrowser(); /** * \brief QmitkDicomBrowser destructor. */ ~QmitkDicomBrowser() override; /** * \brief Init initialize the editor. */ void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) override; void SetFocus() override; void DoSave() override {} void DoSaveAs() override {} bool IsDirty() const override { return false; } bool IsSaveAsAllowed() const override { return false; } - virtual void OnPreferencesChanged(const berry::IBerryPreferences* prefs); + virtual void OnPreferencesChanged(const mitk::IPreferences* prefs); signals: /** * \brief SignalStartDicomImport is enitted when dicom directory for import was selected. */ void SignalStartDicomImport(const QString&); protected slots: /// \brief Called when import is finished. void OnDicomImportFinished(); /// \brief Called when Query Retrieve or Import Folder was clicked. void OnTabChanged(int); /// \brief Called when view button is clicked. Sends out an event for adding the current selected file to the mitkDataStorage. void OnViewButtonAddToDataManager(QHash<QString, QVariant> eventProperties); /// \brief Called when status of dicom storage provider changes. void OnStoreSCPStatusChanged(const QString& status); /// \brief Called when dicom storage provider emits a network error. void OnDicomNetworkError(const QString& status); protected: /// \brief StartStoreSCP starts dicom storage provider. void StartStoreSCP(); /// \brief StopStoreSCP stops dicom storage provider. void StopStoreSCP(); /// \brief TestHandler initializes event handler. void TestHandler(); /// \brief CreateTemporaryDirectory creates temporary directory in which temorary dicom objects are stored. void CreateTemporaryDirectory(); /// \brief StartDicomDirectoryListener starts dicom directory listener. void StartDicomDirectoryListener(); /** * \brief CreateQtPartControl(QWidget *parent) sets the view objects from ui_QmitkDicomBrowserControls.h. * * \param parent is a pointer to the parent widget */ void CreateQtPartControl(QWidget *parent) override; /// \brief SetPluginDirectory Sets plugin directory. void SetPluginDirectory(); Events::Types GetPartEventTypes() const override; ctkFileDialog* m_ImportDialog; Ui::QmitkDicomBrowserControls m_Controls; QmitkDicomDirectoryListener* m_DicomDirectoryListener; QmitkStoreSCPLauncherBuilder m_Builder; QmitkStoreSCPLauncher* m_StoreSCPLauncher; DicomEventHandler* m_Handler; QmitkDicomDataEventPublisher* m_Publisher; QString m_PluginDirectory; QString m_TempDirectory; QString m_DatabaseDirectory; }; #endif // QmitkDicomBrowser_h diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp index 8bd55f2042..b26e541db8 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp @@ -1,115 +1,114 @@ /*============================================================================ 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 "QmitkDicomPreferencePage.h" -#include <berryIPreferencesService.h> -#include <berryIBerryPreferences.h> -#include <berryPlatform.h> #include "mitkPluginActivator.h" +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QCheckBox> #include <QGroupBox> #include <QRadioButton> #include <QMessageBox> #include <QDoubleSpinBox> #include <QLineEdit> #include <QFileDialog> static QString CreateDefaultPath() { QString path = mitk::PluginActivator::getContext()->getDataFile("").absolutePath(); path.append("/database"); return path; } QmitkDicomPreferencePage::QmitkDicomPreferencePage() : m_MainControl(nullptr) { } QmitkDicomPreferencePage::~QmitkDicomPreferencePage() { } void QmitkDicomPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkDicomPreferencePage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - + auto* prefService = mitk::CoreServices::GetPreferencesService(); m_DicomPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader"); m_MainControl = new QWidget(parent); auto formLayout = new QFormLayout; formLayout->setHorizontalSpacing(8); formLayout->setVerticalSpacing(24); auto displayOptionsLayout = new QHBoxLayout; m_PathEdit = new QLineEdit(m_MainControl); displayOptionsLayout->addWidget(m_PathEdit); m_PathSelect = new QPushButton("Select Path",m_MainControl); displayOptionsLayout->addWidget(m_PathSelect); m_PathDefault = new QPushButton("Default",m_MainControl); displayOptionsLayout->addWidget(m_PathDefault); formLayout->addRow("Local database path:",displayOptionsLayout); m_MainControl->setLayout(formLayout); connect(m_PathDefault, SIGNAL(clicked()), this, SLOT(DefaultButtonPushed())); connect(m_PathSelect, SIGNAL(clicked()), this, SLOT(PathSelectButtonPushed())); this->Update(); } QWidget* QmitkDicomPreferencePage::GetQtControl() const { return m_MainControl; } void QmitkDicomPreferencePage::PerformCancel() { } bool QmitkDicomPreferencePage::PerformOk() { - m_DicomPreferencesNode->Put("default dicom path",m_PathEdit->text()); + m_DicomPreferencesNode->Put("default dicom path",m_PathEdit->text().toStdString()); return true; } void QmitkDicomPreferencePage::Update() { - QString path = m_DicomPreferencesNode->Get("default dicom path", CreateDefaultPath()); + const auto path = QString::fromStdString(m_DicomPreferencesNode->Get("default dicom path", CreateDefaultPath().toStdString())); m_PathEdit->setText(path); } void QmitkDicomPreferencePage::DefaultButtonPushed() { m_PathEdit->setText(CreateDefaultPath()); } void QmitkDicomPreferencePage::PathSelectButtonPushed() { QString path = QFileDialog::getExistingDirectory(m_MainControl,"Folder for Dicom directory","dir"); if (!path.isEmpty()) { m_PathEdit->setText(path); } } diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h index e8d151975f..06d9e4e697 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h @@ -1,71 +1,75 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkDicomPreferencePage_h #define QmitkDicomPreferencePage_h #include <QString> #include <QStringList> #include "berryIQtPreferencePage.h" #include <org_mitk_gui_qt_dicombrowser_Export.h> -#include <berryIPreferences.h> + +namespace mitk +{ + class IPreferences; +} class QWidget; class QCheckBox; class QLineEdit; class QPushButton; class DICOM_EXPORT QmitkDicomPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDicomPreferencePage(); ~QmitkDicomPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected: QWidget* m_MainControl; - berry::IPreferences::Pointer m_DicomPreferencesNode; + mitk::IPreferences* m_DicomPreferencesNode; QLineEdit* m_PathEdit; QPushButton* m_PathSelect; QPushButton* m_PathDefault; protected slots: void DefaultButtonPushed(); void PathSelectButtonPushed(); }; #endif // QmitkQmitkDicomPreferencePage_h diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp index a17bf074c2..a7f6081662 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp @@ -1,387 +1,388 @@ /*============================================================================ 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 "DoseVisualizationPreferencePage.h" #include "mitkRTUIConstants.h" #include <QWidget> #include <QMessageBox> #include <QInputDialog> #include <QMenu> -#include <berryIPreferencesService.h> -#include <berryPlatform.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <QmitkDoseColorDelegate.h> #include <QmitkDoseValueDelegate.h> #include <QmitkDoseVisualStyleDelegate.h> #include <QmitkIsoDoseLevelSetModel.h> #include "mitkIsoLevelsGenerator.h" #include "org_mitk_gui_qt_dosevisualization_Activator.h" DoseVisualizationPreferencePage::DoseVisualizationPreferencePage() : m_MainControl(nullptr), m_Controls(nullptr), m_referenceDoseChanged(false), m_presetMapChanged(false), m_globalVisChanged(false) { } DoseVisualizationPreferencePage::~DoseVisualizationPreferencePage() { delete m_LevelSetModel; delete m_DoseColorDelegate; delete m_DoseValueDelegate; delete m_DoseVisualDelegate; delete m_Controls; } void DoseVisualizationPreferencePage::Init(berry::IWorkbench::Pointer ) { } void DoseVisualizationPreferencePage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_DoseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + m_DoseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); m_LevelSetModel = new QmitkIsoDoseLevelSetModel(this); m_DoseColorDelegate = new QmitkDoseColorDelegate(this); m_DoseValueDelegate = new QmitkDoseValueDelegate(this); m_DoseVisualDelegate = new QmitkDoseVisualStyleDelegate(this); m_MainControl = new QWidget(parent); m_Controls = new Ui::DoseVisualizationPreferencePageControls; m_Controls->setupUi( m_MainControl ); this->m_Controls->isoLevelSetView->setModel(m_LevelSetModel); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(0,m_DoseColorDelegate); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(1,m_DoseValueDelegate); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(2,m_DoseVisualDelegate); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(3,m_DoseVisualDelegate); this->m_Controls->isoLevelSetView->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_Controls->spinReferenceDose, SIGNAL(valueChanged(double)), m_LevelSetModel, SLOT(setReferenceDose(double))); connect(m_Controls->spinReferenceDose, SIGNAL(valueChanged(double)), this, SLOT(OnReferenceDoseChanged(double))); connect(m_Controls->checkGlobalSync, SIGNAL(toggled(bool)), m_Controls->spinReferenceDose, SLOT(setEnabled(bool))); connect(m_Controls->radioAbsDose, SIGNAL(toggled(bool)), m_LevelSetModel, SLOT(setShowAbsoluteDose(bool))); connect(m_Controls->isoLevelSetView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(OnShowContextMenuIsoSet(const QPoint&))); connect(m_Controls->listPresets, SIGNAL(currentItemChanged ( QListWidgetItem *, QListWidgetItem *)), this, SLOT(OnCurrentItemChanged ( QListWidgetItem *, QListWidgetItem *))); connect(m_Controls->btnAddPreset, SIGNAL(clicked(bool)), this, SLOT(OnAddPresetClicked(bool))); connect(m_Controls->btnDelPreset, SIGNAL(clicked(bool)), this, SLOT(OnDelPresetClicked(bool))); connect(m_Controls->btnResetPreset, SIGNAL(clicked(bool)), this, SLOT(OnResetPresetClicked(bool))); connect(m_Controls->btnDelLevel, SIGNAL(clicked(bool)), this, SLOT(OnDelLevelClicked(bool))); connect(m_Controls->btnAddLevel, SIGNAL(clicked(bool)), this, SLOT(OnAddLevelClicked(bool))); connect(m_Controls->checkGlobalVisColorWash, SIGNAL(toggled(bool)), this, SLOT(OnGlobalVisChanged(bool))); connect(m_Controls->checkGlobalVisIsoLine, SIGNAL(toggled(bool)), this, SLOT(OnGlobalVisChanged(bool))); this->Update(); } QWidget* DoseVisualizationPreferencePage::GetQtControl() const { return m_MainControl; } bool DoseVisualizationPreferencePage::PerformOk() { - m_DoseVisNode->PutBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID.c_str(),m_Controls->radioAbsDose->isChecked()); - m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(),m_Controls->checkGlobalVisColorWash->isChecked()); - m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID.c_str(),m_Controls->checkGlobalVisIsoLine->isChecked()); - m_DoseVisNode->PutDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(),m_Controls->spinReferenceDose->value()); - m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID.c_str(), m_Controls->checkGlobalSync->isChecked()); + m_DoseVisNode->PutBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID,m_Controls->radioAbsDose->isChecked()); + m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID,m_Controls->checkGlobalVisColorWash->isChecked()); + m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID,m_Controls->checkGlobalVisIsoLine->isChecked()); + m_DoseVisNode->PutDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID,m_Controls->spinReferenceDose->value()); + m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, m_Controls->checkGlobalSync->isChecked()); mitk::StorePresetsMap(this->m_Presets); if (this->m_Presets.find(this->m_selectedPresetName)==this->m_Presets.end()) { //the preset currently selected in the application is not available any more. Change it to a valid one. mitk::SetSelectedPresetName(this->m_Presets.begin()->first); } if (this->m_LevelSetModel->isModified()) { this->m_presetMapChanged = true; } if (m_referenceDoseChanged) { mitk::SignalReferenceDoseChange(m_Controls->checkGlobalSync->isChecked(), m_Controls->spinReferenceDose->value(), mitk::org_mitk_gui_qt_dosevisualization_Activator::GetContext()); } if (m_presetMapChanged) { mitk::SignalPresetMapChange(mitk::org_mitk_gui_qt_dosevisualization_Activator::GetContext()); } if(m_globalVisChanged) { mitk::SignalGlobalVisChange(m_Controls->checkGlobalSync->isChecked(), m_Controls->checkGlobalVisIsoLine->isChecked(), m_Controls->checkGlobalVisColorWash->isChecked(), mitk::org_mitk_gui_qt_dosevisualization_Activator::GetContext()); } return true; } void DoseVisualizationPreferencePage::PerformCancel() { } void DoseVisualizationPreferencePage::Update() { - m_Controls->checkGlobalVisColorWash->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(), true)); - m_Controls->checkGlobalVisIsoLine->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID.c_str(), true)); - m_Controls->radioAbsDose->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID.c_str(), true)); - m_Controls->radioRelDose->setChecked(!(m_DoseVisNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID.c_str(), false))); - m_Controls->spinReferenceDose->setValue(m_DoseVisNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE)); - m_Controls->checkGlobalSync->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID.c_str(), true)); + m_Controls->checkGlobalVisColorWash->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID, true)); + m_Controls->checkGlobalVisIsoLine->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID, true)); + m_Controls->radioAbsDose->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, true)); + m_Controls->radioRelDose->setChecked(!(m_DoseVisNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, false))); + m_Controls->spinReferenceDose->setValue(m_DoseVisNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID, mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE)); + m_Controls->checkGlobalSync->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, true)); m_referenceDoseChanged = false; m_presetMapChanged = false; m_globalVisChanged = false; this->m_Presets = mitk::LoadPresetsMap(); if(m_Presets.empty()) return; this->m_selectedPresetName = mitk::GetSelectedPresetName(); UpdatePresetsWidgets(); } mitk::IsoDoseLevelSet* DoseVisualizationPreferencePage::GetSelectedIsoLevelSet() { QListWidgetItem* selectedItem = m_Controls->listPresets->currentItem(); mitk::IsoDoseLevelSet::Pointer result; if (selectedItem) { result = m_Presets[selectedItem->text().toStdString()]; } return result; } void DoseVisualizationPreferencePage::UpdateLevelSetWidgets() { this->m_Controls->btnAddLevel->setEnabled(this->GetSelectedIsoLevelSet()!=nullptr); QModelIndex selectedIndex = m_Controls->isoLevelSetView->currentIndex(); this->m_Controls->btnDelLevel->setEnabled(this->GetSelectedIsoLevelSet()!=nullptr && selectedIndex.isValid()); } void DoseVisualizationPreferencePage::UpdatePresetsWidgets() { m_Controls->listPresets->clear(); QListWidgetItem* selectedItem = nullptr; for (PresetMapType::iterator pos = m_Presets.begin(); pos != m_Presets.end(); ++pos) { QListWidgetItem* item = new QListWidgetItem(QString::fromStdString(pos->first)); if (!selectedItem) { selectedItem = item; } m_Controls->listPresets->addItem(item); } if (selectedItem) { m_Controls->listPresets->setCurrentItem(selectedItem); } if (this->m_LevelSetModel->isModified()) { this->m_presetMapChanged = true; } this->m_LevelSetModel->setIsoDoseLevelSet(this->GetSelectedIsoLevelSet()); m_Controls->btnDelPreset->setEnabled((m_Controls->listPresets->currentItem() != nullptr) && (m_Controls->listPresets->count()>1)); } void DoseVisualizationPreferencePage::OnCurrentItemChanged (QListWidgetItem*, QListWidgetItem*) { this->m_LevelSetModel->setIsoDoseLevelSet(this->GetSelectedIsoLevelSet()); } void DoseVisualizationPreferencePage::OnShowContextMenuIsoSet(const QPoint& pos) { QPoint globalPos = m_Controls->isoLevelSetView->viewport()->mapToGlobal(pos); QModelIndex selectedIndex = m_Controls->isoLevelSetView->currentIndex(); QMenu viewMenu; QAction* addLevelAct = viewMenu.addAction("Add new level"); QAction* delLevelAct = viewMenu.addAction("Delete selected level"); delLevelAct->setEnabled(selectedIndex.isValid()); viewMenu.addSeparator(); QAction* invertIsoLineAct = viewMenu.addAction("Invert iso line visibility"); QAction* activateIsoLineAct = viewMenu.addAction("Activate all iso lines"); QAction* deactivateIsoLineAct = viewMenu.addAction("Deactivate all iso lines"); viewMenu.addSeparator(); QAction* invertColorWashAct = viewMenu.addAction("Invert color wash visibility"); QAction* activateColorWashAct = viewMenu.addAction("Activate all color wash levels"); QAction* deactivateColorWashAct = viewMenu.addAction("Deactivate all color wash levels"); viewMenu.addSeparator(); QAction* swapAct = viewMenu.addAction("Swap iso line/color wash visibility"); QAction* selectedItem = viewMenu.exec(globalPos); if (selectedItem == invertIsoLineAct) { this->m_LevelSetModel->invertVisibilityIsoLines(); } else if (selectedItem == activateIsoLineAct) { this->m_LevelSetModel->switchVisibilityIsoLines(true); } else if (selectedItem == deactivateIsoLineAct) { this->m_LevelSetModel->switchVisibilityIsoLines(false); } else if (selectedItem == invertColorWashAct) { this->m_LevelSetModel->invertVisibilityColorWash(); } else if (selectedItem == activateColorWashAct) { this->m_LevelSetModel->switchVisibilityColorWash(true); } else if (selectedItem == deactivateColorWashAct) { this->m_LevelSetModel->switchVisibilityColorWash(false); } else if (selectedItem == swapAct) { this->m_LevelSetModel->swapVisibility(); } else if (selectedItem == addLevelAct) { this->m_LevelSetModel->addLevel(); } else if (selectedItem == delLevelAct) { this->m_LevelSetModel->deleteLevel(selectedIndex); } } void DoseVisualizationPreferencePage::OnAddPresetClicked(bool) { bool done = false; QString name = tr("new_preset"); while (!done) { bool ok; name = QInputDialog::getText(m_MainControl, tr("Define name of new preset."), tr("Preset name:"), QLineEdit::Normal, name, &ok); if (!ok) { return; //cancled by user; } bool uniqueName = m_Presets.find(name.toStdString()) == m_Presets.end(); if (!uniqueName) { QMessageBox box; box.setText(tr("New preset name is not unique. Please, choose another one.")); box.exec(); } bool validName = name.indexOf(tr("/")) ==-1; if (!validName) { QMessageBox box; box.setText(tr("New preset name is not valid. Please don't use \"/\".")); box.exec(); } done = uniqueName && validName; } mitk::IsoDoseLevelSet::Pointer newSet = mitk::GenerateIsoLevels_Virtuos(); m_Presets.insert(std::make_pair(name.toStdString(),newSet)); m_presetMapChanged = true; UpdatePresetsWidgets(); } void DoseVisualizationPreferencePage::OnDelPresetClicked(bool) { QListWidgetItem* selectedItem = m_Controls->listPresets->currentItem(); if (selectedItem) { if (m_Controls->listPresets->count() > 1) { m_Presets.erase(selectedItem->text().toStdString()); m_presetMapChanged = true; this->UpdatePresetsWidgets(); } } } void DoseVisualizationPreferencePage::OnResetPresetClicked(bool) { QMessageBox box; box.setText("Do you want to reset the presets?"); box.setInformativeText("If you reset the presets. All user defined presets will be removed and the default presets will be loaded."); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); box.setDefaultButton(QMessageBox::No); int ret = box.exec(); if (ret == QMessageBox::Yes) { mitk::IsoDoseLevelSet::Pointer newSet = mitk::GenerateIsoLevels_Virtuos(); m_Presets.clear(); m_Presets.insert(std::make_pair("Virtuos",newSet)); m_presetMapChanged = true; UpdatePresetsWidgets(); } } void DoseVisualizationPreferencePage::OnAddLevelClicked(bool) { this->m_LevelSetModel->addLevel(); } void DoseVisualizationPreferencePage::OnDelLevelClicked(bool) { QModelIndex selectedIndex = m_Controls->isoLevelSetView->currentIndex(); if (!selectedIndex.isValid()) { selectedIndex = m_Controls->isoLevelSetView->indexAt(QPoint(1,1)); } this->m_LevelSetModel->deleteLevel(selectedIndex); } void DoseVisualizationPreferencePage::OnReferenceDoseChanged(double) { this->m_referenceDoseChanged = true; } void DoseVisualizationPreferencePage::OnGlobalVisChanged(bool) { this->m_globalVisChanged = true; } diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h index 01ebe27190..4f36d50552 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h @@ -1,121 +1,125 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __DOSE_VISUALIZATION_PREFERENCE_PAGE_H #define __DOSE_VISUALIZATION_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" -#include "berryIPreferences.h" #include "ui_DoseVisualizationPreferencePageControls.h" #include <mitkIsoDoseLevelCollections.h> #include "mitkDoseVisPreferenceHelper.h" /*forward declarations*/ class QmitkIsoDoseLevelSetModel; class QmitkDoseColorDelegate; class QmitkDoseValueDelegate; class QmitkDoseVisualStyleDelegate; class QWidget; +namespace mitk +{ + class IPreferences; +} + /** * \class DoseVisualizationPreferencePage * \brief Preference page for RT Dose visualization */ class DoseVisualizationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: DoseVisualizationPreferencePage(); ~DoseVisualizationPreferencePage() override; /** * \brief Called by framework to initialize this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: void OnCurrentItemChanged ( QListWidgetItem * currentItem, QListWidgetItem * previousItem); void OnShowContextMenuIsoSet(const QPoint& pos); void OnAddPresetClicked(bool checked); void OnDelPresetClicked(bool checked); void OnResetPresetClicked(bool checked); void OnAddLevelClicked(bool checked); void OnDelLevelClicked(bool checked); void OnReferenceDoseChanged(double dose); void OnGlobalVisChanged(bool vis); protected: /** Method updates the presets widgets according to the internal members*/ void UpdatePresetsWidgets(); /** Method actualizes the level set model and edit buttons according to the currently selected item in the presets list view*/ void UpdateLevelSetWidgets(); /** Method returns the iso dose level set selected in the preset lists. May return nullptr if no preset is selected.*/ mitk::IsoDoseLevelSet* GetSelectedIsoLevelSet(); QWidget *m_MainControl; Ui::DoseVisualizationPreferencePageControls* m_Controls; - berry::IPreferences::Pointer m_DoseVisNode; + mitk::IPreferences* m_DoseVisNode; typedef mitk::PresetMapType PresetMapType; PresetMapType m_Presets; std::string m_selectedPresetName; bool m_referenceDoseChanged; bool m_presetMapChanged; bool m_globalVisChanged; QmitkIsoDoseLevelSetModel* m_LevelSetModel; QmitkDoseColorDelegate* m_DoseColorDelegate; QmitkDoseValueDelegate* m_DoseValueDelegate; QmitkDoseVisualStyleDelegate* m_DoseVisualDelegate; }; #endif diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp index 60d8fcf367..aa96a9d5fe 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp @@ -1,111 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "RTUIPreferencePage.h" #include "mitkRTUIConstants.h" -#include <berryIPreferencesService.h> -#include <berryPlatform.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> //----------------------------------------------------------------------------- RTUIPreferencePage::RTUIPreferencePage() : m_MainControl(nullptr), m_Controls(nullptr) { } //----------------------------------------------------------------------------- RTUIPreferencePage::~RTUIPreferencePage() { delete m_Controls; } //----------------------------------------------------------------------------- void RTUIPreferencePage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void RTUIPreferencePage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_PreferencesNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_PREFERENCE_NODE_ID.c_str()); + m_PreferencesNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_PREFERENCE_NODE_ID); m_MainControl = new QWidget(parent); m_Controls = new Ui::RTUIPreferencePageControls; m_Controls->setupUi( m_MainControl ); connect(m_Controls->radioDefault, SIGNAL(toggled(bool)), m_Controls->spinDefault, SLOT(setEnabled(bool))); connect(m_Controls->radioRelativeToMax, SIGNAL(toggled(bool)), m_Controls->spinRelativeToMax, SLOT(setEnabled(bool))); this->Update(); } //----------------------------------------------------------------------------- QWidget* RTUIPreferencePage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- bool RTUIPreferencePage::PerformOk() { bool useAsDefaultValue = m_Controls->radioDefault->isChecked(); - m_PreferencesNode->PutBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID.c_str(),useAsDefaultValue); + m_PreferencesNode->PutBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID, useAsDefaultValue); if (useAsDefaultValue) { - m_PreferencesNode->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID.c_str(), m_Controls->spinDefault->value()); + m_PreferencesNode->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, m_Controls->spinDefault->value()); } else { - m_PreferencesNode->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID.c_str(), m_Controls->spinRelativeToMax->value()/100.0); + m_PreferencesNode->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, m_Controls->spinRelativeToMax->value()/100.0); } return true; } //----------------------------------------------------------------------------- void RTUIPreferencePage::PerformCancel() { } //----------------------------------------------------------------------------- void RTUIPreferencePage::Update() { - bool useAsDefaultValue = m_PreferencesNode->GetBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID.c_str(), true); - double doseValue = m_PreferencesNode->GetDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID.c_str(), 50.0); + bool useAsDefaultValue = m_PreferencesNode->GetBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID, true); + double doseValue = m_PreferencesNode->GetDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, 50.0); m_Controls->radioDefault->setChecked(useAsDefaultValue); m_Controls->radioRelativeToMax->setChecked(!useAsDefaultValue); m_Controls->spinDefault->setEnabled(useAsDefaultValue); m_Controls->spinRelativeToMax->setEnabled(!useAsDefaultValue); if (useAsDefaultValue) { m_Controls->spinDefault->setValue(doseValue); } else { m_Controls->spinRelativeToMax->setValue(doseValue*100.0); } } diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h index 77d19dc299..c4490a8270 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h @@ -1,81 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __RT_UI_PREFERENCE_PAGE_H #define __RT_UI_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" -#include "berryIPreferences.h" #include "ui_RTUIPreferencePageControls.h" class QWidget; +namespace mitk +{ + class IPreferences; +} + /** * \class RTUIPreferencePage * \brief Preference page for general RT visualization settings. */ class RTUIPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: RTUIPreferencePage(); ~RTUIPreferencePage() override; /** * \brief Called by framework to initialize this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: protected: QWidget *m_MainControl; Ui::RTUIPreferencePageControls* m_Controls; - berry::IPreferences::Pointer m_PreferencesNode; + mitk::IPreferences* m_PreferencesNode; }; #endif diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.cpp b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.cpp index f22fab2b07..9efcb22f88 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.cpp +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.cpp @@ -1,281 +1,246 @@ /*============================================================================ 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 "mitkDoseVisPreferenceHelper.h" #include "mitkRTUIConstants.h" #include "mitkIsoLevelsGenerator.h" - -#include <berryIPreferencesService.h> - -#include <berryIPreferences.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <ctkPluginContext.h> #include <service/event/ctkEventAdmin.h> void mitk::StorePresetsMap(const PresetMapType& presetMap) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer doseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* doseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); + auto* presetsNode = doseVisNode->Node("isoPresets"); -// berry::IPreferences::Pointer presetsNode = doseVisNode->Node(mitk::RTUIConstants::ROOT_ISO_PRESETS_PREFERENCE_NODE_ID.c_str()); - berry::IPreferences::Pointer presetsNode = doseVisNode->Node("isoPresets"); - presetsNode->RemoveNode(); - doseVisNode->Flush(); - - //new empty preset node -// presetsNode = doseVisNode->Node(mitk::RTUIConstants::ROOT_ISO_PRESETS_PREFERENCE_NODE_ID.c_str()); - presetsNode = doseVisNode->Node("isoPresets"); + presetsNode->Clear(); //store map in new node for (PresetMapType::const_iterator pos = presetMap.begin(); pos != presetMap.end(); ++pos) { - berry::IPreferences::Pointer aPresetNode = presetsNode->Node(pos->first.c_str()); + auto* aPresetNode = presetsNode->Node(pos->first); unsigned int id = 0; for (mitk::IsoDoseLevelSet::ConstIterator levelPos = pos->second->Begin(); levelPos != pos->second->End(); ++levelPos, ++id ) { std::ostringstream stream; stream << id; - berry::IPreferences::Pointer levelNode = aPresetNode->Node(QString::fromStdString(stream.str())); + auto* levelNode = aPresetNode->Node(stream.str()); - levelNode->PutDouble(mitk::RTUIConstants::ISO_LEVEL_DOSE_VALUE_ID.c_str(),levelPos->GetDoseValue()); - levelNode->PutFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_RED_ID.c_str(),levelPos->GetColor().GetRed()); - levelNode->PutFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_GREEN_ID.c_str(),levelPos->GetColor().GetGreen()); - levelNode->PutFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_BLUE_ID.c_str(),levelPos->GetColor().GetBlue()); - levelNode->PutBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_ISOLINES_ID.c_str(),levelPos->GetVisibleIsoLine()); - levelNode->PutBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_COLORWASH_ID.c_str(),levelPos->GetVisibleColorWash()); - levelNode->Flush(); + levelNode->PutDouble(mitk::RTUIConstants::ISO_LEVEL_DOSE_VALUE_ID,levelPos->GetDoseValue()); + levelNode->PutFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_RED_ID,levelPos->GetColor().GetRed()); + levelNode->PutFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_GREEN_ID,levelPos->GetColor().GetGreen()); + levelNode->PutFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_BLUE_ID,levelPos->GetColor().GetBlue()); + levelNode->PutBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_ISOLINES_ID,levelPos->GetVisibleIsoLine()); + levelNode->PutBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_COLORWASH_ID,levelPos->GetVisibleColorWash()); } - - aPresetNode->Flush(); } presetsNode->Flush(); } bool mitk::GetGlobalIsolineVis() { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - berry::IPreferences::Pointer glIsolineVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* glIsolineVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - bool vis = glIsolineVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID.c_str(),false); + bool vis = glIsolineVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID,false); return vis; } bool mitk::GetGlobalColorwashVis() { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - berry::IPreferences::Pointer glDoseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* glDoseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - bool vis = glDoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(),false); + bool vis = glDoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID,false); return vis; } mitk::PresetMapType mitk::LoadPresetsMap() { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - berry::IPreferences::Pointer presetsNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_ISO_PRESETS_PREFERENCE_NODE_ID.c_str()); + auto* presetsNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_ISO_PRESETS_PREFERENCE_NODE_ID); - typedef QStringList NamesType; - NamesType names = presetsNode->ChildrenNames(); + auto names = presetsNode->ChildrenNames(); PresetMapType presetMap; if(!names.empty()){ - for (NamesType::const_iterator pos = names.begin(); pos != names.end(); ++pos) + for (const auto& name : names) { - berry::IPreferences::Pointer aPresetNode = presetsNode->Node(*pos); + auto* aPresetNode = presetsNode->Node(name); - if (aPresetNode.IsNull()) - { - mitkThrow()<< "Error in preference interface. Cannot find preset node under given name. Name: "<<(*pos).toStdString(); - } + if (aPresetNode == nullptr) + mitkThrow()<< "Error in preference interface. Cannot find preset node under given name. Name: " << name; mitk::IsoDoseLevelSet::Pointer levelSet = mitk::IsoDoseLevelSet::New(); - NamesType levelNames = aPresetNode->ChildrenNames(); - for (NamesType::const_iterator levelName = levelNames.begin(); levelName != levelNames.end(); ++levelName) + auto levelNames = aPresetNode->ChildrenNames(); + + for (const auto& levelName : levelNames) { - berry::IPreferences::Pointer levelNode = aPresetNode->Node(*levelName); - if (aPresetNode.IsNull()) - { - mitkThrow()<< "Error in preference interface. Cannot find level node under given preset name. Name: "<<(*pos).toStdString()<<"; Level id: "<<(*levelName).toStdString(); - } + auto* levelNode = aPresetNode->Node(levelName); + + if (aPresetNode == nullptr) + mitkThrow()<< "Error in preference interface. Cannot find level node under given preset name. Name: " << name << "; Level id: " << levelName; mitk::IsoDoseLevel::Pointer isoLevel = mitk::IsoDoseLevel::New(); - isoLevel->SetDoseValue(levelNode->GetDouble(mitk::RTUIConstants::ISO_LEVEL_DOSE_VALUE_ID.c_str(),0.0)); + isoLevel->SetDoseValue(levelNode->GetDouble(mitk::RTUIConstants::ISO_LEVEL_DOSE_VALUE_ID,0.0)); mitk::IsoDoseLevel::ColorType color; - color.SetRed(levelNode->GetFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_RED_ID.c_str(),1.0)); - color.SetGreen(levelNode->GetFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_GREEN_ID.c_str(),1.0)); - color.SetBlue(levelNode->GetFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_BLUE_ID.c_str(),1.0)); + color.SetRed(levelNode->GetFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_RED_ID,1.0)); + color.SetGreen(levelNode->GetFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_GREEN_ID,1.0)); + color.SetBlue(levelNode->GetFloat(mitk::RTUIConstants::ISO_LEVEL_COLOR_BLUE_ID,1.0)); isoLevel->SetColor(color); - isoLevel->SetVisibleIsoLine(levelNode->GetBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_ISOLINES_ID.c_str(),true)); - isoLevel->SetVisibleColorWash(levelNode->GetBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_COLORWASH_ID.c_str(),true)); + isoLevel->SetVisibleIsoLine(levelNode->GetBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_ISOLINES_ID,true)); + isoLevel->SetVisibleColorWash(levelNode->GetBool(mitk::RTUIConstants::ISO_LEVEL_VISIBILITY_COLORWASH_ID,true)); levelSet->SetIsoDoseLevel(isoLevel); } - presetMap.insert(std::make_pair((*pos).toStdString(),levelSet)); + presetMap.insert(std::make_pair(name,levelSet)); } } if (presetMap.size() == 0) { //if there are no presets use fallback and store it. presetMap = mitk::GenerateDefaultPresetsMap(); StorePresetsMap(presetMap); } return presetMap; } mitk::PresetMapType mitk::GenerateDefaultPresetsMap() { mitk::PresetMapType result; result.insert(std::make_pair(std::string("Virtuos"), mitk::GenerateIsoLevels_Virtuos())); return result; } std::string mitk::GetSelectedPresetName() { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); - - QString result = prefNode->Get(mitk::RTUIConstants::SELECTED_ISO_PRESET_ID.c_str(), ""); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - return result.toStdString(); + return prefNode->Get(mitk::RTUIConstants::SELECTED_ISO_PRESET_ID, ""); } void mitk::SetSelectedPresetName(const std::string& presetName) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); + auto* presetsNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_ISO_PRESETS_PREFERENCE_NODE_ID); - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); - berry::IPreferences::Pointer presetsNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_ISO_PRESETS_PREFERENCE_NODE_ID.c_str()); + auto presetNames = presetsNode->ChildrenNames(); - typedef QStringList NamesType; - typedef std::vector<std::string> StdNamesType; - NamesType presetNames = presetsNode->ChildrenNames(); + auto finding = std::find(presetNames.begin(), presetNames.end(), presetName); - StdNamesType stdPresetNames; - - for (NamesType::const_iterator pos = presetNames.begin(); pos != presetNames.end(); ++pos) - { - stdPresetNames.push_back((*pos).toStdString()); - } + if (finding == presetNames.end()) + mitkThrow() << "Error. Tried to set invalid selected preset name. Preset name does not exist in the defined presets. Preset name: " << presetName; - StdNamesType::iterator finding = std::find(stdPresetNames.begin(),stdPresetNames.end(),presetName); - - if (finding == stdPresetNames.end()) - { - mitkThrow()<< "Error. Tried to set invalid selected preset name. Preset name does not exist in the defined presets. Preset name: "<<presetName; - } - - prefNode->Put(mitk::RTUIConstants::SELECTED_ISO_PRESET_ID.c_str(),presetName.c_str()); + prefNode->Put(mitk::RTUIConstants::SELECTED_ISO_PRESET_ID, presetName); } bool mitk::GetReferenceDoseValue(mitk::DoseValueAbs& value) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); + bool result = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, true); - bool result = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID.c_str(), true); - value = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE); + value = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID, mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE); return result; } void mitk::SetReferenceDoseValue(bool globalSync, mitk::DoseValueAbs value) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - prefNode->PutBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID.c_str(), globalSync); + prefNode->PutBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, globalSync); + if (value >= 0) - { - prefNode->PutDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), value); - } + prefNode->PutDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID, value); } bool mitk::GetDoseDisplayAbsolute() { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - bool result = prefNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID.c_str(), false); - - return result; + return prefNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, false); } void mitk::SetDoseDisplayAbsolute(bool isAbsolute) { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - - berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - prefNode->PutBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID.c_str(), isAbsolute); + prefNode->PutBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, isAbsolute); } void mitk::SignalReferenceDoseChange(bool globalSync, mitk::DoseValueAbs value, ctkPluginContext* context) { ctkServiceReference ref = context->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = context->getService<ctkEventAdmin>(ref); ctkProperties props; props["value"] = value; props["globalSync"] = globalSync; ctkEvent presetMapChangedEvent(mitk::RTCTKEventConstants::TOPIC_REFERENCE_DOSE_CHANGED.c_str()); eventAdmin->sendEvent(presetMapChangedEvent); } } void mitk::SignalGlobalVisChange(bool globalSync, bool isolineVis, bool colorwashVis, ctkPluginContext *context) { ctkServiceReference ref = context->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = context->getService<ctkEventAdmin>(ref); ctkProperties props; props["globalIsolineVis"] = isolineVis; props["globalColorwashVis"] = colorwashVis; props["globalSync"] = globalSync; ctkEvent presetMapChangedEvent(mitk::RTCTKEventConstants::TOPIC_GLOBAL_VISIBILITY_CHANGED.c_str()); eventAdmin->sendEvent(presetMapChangedEvent); } } void mitk::SignalPresetMapChange(ctkPluginContext* context) { ctkServiceReference ref = context->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = context->getService<ctkEventAdmin>(ref); ctkEvent presetMapChangedEvent(mitk::RTCTKEventConstants::TOPIC_ISO_DOSE_LEVEL_PRESETS_CHANGED.c_str()); eventAdmin->sendEvent(presetMapChangedEvent); } } diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.h b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.h index 60658b60d4..fe3a803935 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.h +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/mitkDoseVisPreferenceHelper.h @@ -1,70 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __DOSE_VIS_PREFERENCE_HELPER_H #define __DOSE_VIS_PREFERENCE_HELPER_H -#include <berryIPreferencesService.h> -#include <berryPlatform.h> - #include "mitkIsoDoseLevelCollections.h" class ctkPluginContext; namespace mitk { typedef std::map<std::string, mitk::IsoDoseLevelSet::Pointer> PresetMapType; /** Stores the given preset map in the application preferences. */ void StorePresetsMap(const PresetMapType& presetMap); /** Loads all defined iso dose level presets from the preferences and stores them in a map. Key is the name of the preset. @remark If no presets are stored in the preferences this function will generate default presets (using GenerateDefaultPresetsMap()) and the stores it in the preferences (to guarantee a consistent state) before passing the default presets back.*/ PresetMapType LoadPresetsMap(); /** Generate the default presets map.*/ PresetMapType GenerateDefaultPresetsMap(); /**Retrieves the name of the preset, that is currently selected for the application, from the preferences.*/ std::string GetSelectedPresetName(); /** checks if the passed name exists in the preset map. If not an exception is thrown. If it exists, the new * value will be set.*/ void SetSelectedPresetName(const std::string& presetName); /** retrieves the reference dose from the preferences and indicates if global sync for reference dose is activated or not. @param value The reference dose value stored in the preferences. @return Indicator for global sync. True: global sync activated -> preference value is relevant. False: global sync deactivated. Value is irrelevant. Each node has its own value.*/ bool GetReferenceDoseValue(DoseValueAbs& value); /** Sets the global sync setting and dose reference value in the preferences. * @param globalSync Indicator if global sync should be set active (true) or inactive (false). If it is true, the value is irrelevant (but will be set). * @param value The dose reference value that should be stored in the preferences.If set to <0 it will be ignored and not changed/set.*/ void SetReferenceDoseValue(bool globalSync, DoseValueAbs value = -1); bool GetDoseDisplayAbsolute(); void SetDoseDisplayAbsolute(bool isAbsolute); bool GetGlobalIsolineVis(); bool GetGlobalColorwashVis(); void SignalReferenceDoseChange(bool globalSync, mitk::DoseValueAbs value, ctkPluginContext* context); void SignalPresetMapChange(ctkPluginContext* context); void SignalGlobalVisChange(bool globalSync, bool isolineVis, bool colorwashVis, ctkPluginContext* context); } #endif diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/org_mitk_gui_qt_dosevisualization_Activator.cpp b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/org_mitk_gui_qt_dosevisualization_Activator.cpp index ee97ffa7df..cbed06dbb0 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/org_mitk_gui_qt_dosevisualization_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/org_mitk_gui_qt_dosevisualization_Activator.cpp @@ -1,44 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ - #include "org_mitk_gui_qt_dosevisualization_Activator.h" #include "RTDoseVisualizer.h" #include "RTUIPreferencePage.h" #include "DoseVisualizationPreferencePage.h" +#include <usModuleInitialization.h> + +US_INITIALIZE_MODULE + namespace mitk { ctkPluginContext* org_mitk_gui_qt_dosevisualization_Activator::m_Context = nullptr; void org_mitk_gui_qt_dosevisualization_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(RTDoseVisualizer, context); BERRY_REGISTER_EXTENSION_CLASS(RTUIPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(DoseVisualizationPreferencePage, context) m_Context = context; } void org_mitk_gui_qt_dosevisualization_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context); m_Context = nullptr; } ctkPluginContext* org_mitk_gui_qt_dosevisualization_Activator::GetContext() { return m_Context; } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp index 6f202930a0..b421f5b46c 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp @@ -1,176 +1,173 @@ /*============================================================================ 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 "QmitkExtFileSaveProjectAction.h" #include "internal/QmitkCommonExtPlugin.h" #include <QFileDialog> #include <QMessageBox> #include <QApplication> #include <mitkSceneIO.h> #include <mitkProgressBar.h> #include <mitkNodePredicateNot.h> #include <mitkNodePredicateProperty.h> #include <mitkProperties.h> #include <mitkCoreObjectFactory.h> #include <mitkDataStorageEditorInput.h> #include <mitkIDataStorageService.h> #include <berryIEditorPart.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbenchWindow.h> -#include <berryIPreferencesService.h> -#include "berryPlatform.h" - QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) , m_Window(nullptr) { this->Init(window.GetPointer()); } QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow* window) : QAction(nullptr) , m_Window(nullptr) { this->Init(window); } void QmitkExtFileSaveProjectAction::Init(berry::IWorkbenchWindow* window) { m_Window = window; this->setText("&Save Project..."); this->setToolTip("Save content of Data Manager as a .mitk project file"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkExtFileSaveProjectAction::Run() { try { /** * @brief stores the last path of last saved file */ static QString m_LastPath; mitk::IDataStorageReference::Pointer dsRef; { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); mitk::IDataStorageService* dss = nullptr; ctkServiceReference dsServiceRef = context->getServiceReference<mitk::IDataStorageService>(); if (dsServiceRef) { dss = context->getService<mitk::IDataStorageService>(dsServiceRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dsRef = dss->GetDataStorage(); context->ungetService(dsServiceRef); } mitk::DataStorage::Pointer storage = dsRef->GetDataStorage(); QString dialogTitle = "Save MITK Scene (%1)"; QString fileName = QFileDialog::getSaveFileName(nullptr, dialogTitle.arg(dsRef->GetLabel()), m_LastPath, "MITK scene files (*.mitk)", nullptr ); if (fileName.isEmpty() ) return; // remember the location m_LastPath = fileName; if ( fileName.right(5) != ".mitk" ) fileName += ".mitk"; mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); /* Build list of nodes that should be saved */ mitk::NodePredicateNot::Pointer isNotHelperObject = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true))); mitk::DataStorage::SetOfObjects::ConstPointer nodesToBeSaved = storage->GetSubset(isNotHelperObject); if ( !sceneIO->SaveScene( nodesToBeSaved, storage, fileName.toStdString() ) ) { QMessageBox::information(nullptr, "Scene saving", "Scene could not be written completely. Please check the log.", QMessageBox::Ok); } mitk::ProgressBar::GetInstance()->Progress(2); mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes(); if (!failedNodes->empty()) { std::stringstream ss; ss << "The following nodes could not be serialized:" << std::endl; for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { ss << " - "; if ( mitk::BaseData* data =(*iter)->GetData() ) { ss << data->GetNameOfClass(); } else { ss << "(nullptr)"; } ss << " contained in node '" << (*iter)->GetName() << "'" << std::endl; } MITK_WARN << ss.str(); } mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties(); if (!failedProperties->GetMap()->empty()) { std::stringstream ss; ss << "The following properties could not be serialized:" << std::endl; const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { ss << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'" << std::endl; } MITK_WARN << ss.str(); } } catch (std::exception& e) { MITK_ERROR << "Exception caught during scene saving: " << e.what(); } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index 0a488bd357..91201dbe33 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1437 +1,1439 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkExtWorkbenchWindowAdvisor.h" #include "QmitkExtActionBarAdvisor.h" #include <QMenu> #include <QMenuBar> #include <QMainWindow> #include <QStatusBar> #include <QString> #include <QFile> #include <QRegExp> #include <QTextStream> #include <QSettings> #include <ctkPluginException.h> #include <service/event/ctkEventAdmin.h> #include <berryPlatform.h> #include <berryPlatformUI.h> #include <berryIActionBarConfigurer.h> #include <berryIWorkbenchWindow.h> #include <berryIWorkbenchPage.h> -#include <berryIPreferencesService.h> #include <berryIPerspectiveRegistry.h> #include <berryIPerspectiveDescriptor.h> #include <berryIProduct.h> #include <berryIWorkbenchPartConstants.h> #include <berryQtPreferences.h> #include <berryQtStyleManager.h> #include <berryWorkbenchPlugin.h> #include <internal/berryQtShowViewAction.h> #include <internal/berryQtOpenPerspectiveAction.h> #include <QmitkFileOpenAction.h> #include <QmitkFileSaveAction.h> #include <QmitkExtFileSaveProjectAction.h> #include <QmitkFileExitAction.h> #include <QmitkCloseProjectAction.h> #include <QmitkUndoAction.h> #include <QmitkRedoAction.h> #include <QmitkDefaultDropTargetListener.h> #include <QmitkStatusBar.h> #include <QmitkProgressBar.h> #include <QmitkMemoryUsageIndicatorView.h> #include <QmitkPreferencesDialog.h> #include <QmitkOpenDicomEditorAction.h> #include <QmitkOpenMxNMultiWidgetEditorAction.h> #include <QmitkOpenStdMultiWidgetEditorAction.h> #include <itkConfigure.h> #include <mitkVersion.h> #include <mitkIDataStorageService.h> #include <mitkIDataStorageReference.h> #include <mitkDataStorageEditorInput.h> #include <mitkWorkbenchUtil.h> +#include <mitkCoreServices.h> +#include <mitkIPreferencesService.h> +#include <mitkIPreferences.h> #include <vtkVersionMacros.h> // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include <QToolBar> #include <QToolButton> #include <QMessageBox> #include <QMouseEvent> #include <QLabel> #include <QmitkAboutDialog.h> QmitkExtWorkbenchWindowAdvisorHack* QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; static bool USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS = false; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const override { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref.Cast<berry::IEditorReference> ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref.Cast<berry::IEditorReference> ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) override { windowAdvisor->UpdateTitle(false); } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor) { windowAdvisor->UpdateTitle(true); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForViewNavigator: public berry::IPartListener { public: PartListenerForViewNavigator(QAction* act) : viewNavigatorAction(act) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.viewnavigator") { viewNavigatorAction->setChecked(false); } } private: QAction* viewNavigatorAction; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) , perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const override { if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED; } else { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED | Events::CLOSED | Events::OPENED; } } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { if (perspectivesClosed) { QListIterator<QAction*> i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } //GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser")) { windowAdvisor->openDicomEditorAction->setEnabled(true); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { windowAdvisor->openStdMultiWidgetEditorAction->setEnabled(true); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { windowAdvisor->openMxNMultiWidgetEditorAction->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->closeProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->viewNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(true); } } perspectivesClosed = false; } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { QList<berry::IPerspectiveDescriptor::Pointer> perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator<QAction*> i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser")) { windowAdvisor->openDicomEditorAction->setEnabled(false); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { windowAdvisor->openStdMultiWidgetEditorAction->setEnabled(false); } if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { windowAdvisor->openMxNMultiWidgetEditorAction->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->closeProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->viewNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(false); } } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const override { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) override { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) override { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer) , lastInput(nullptr) , wbAdvisor(wbAdvisor) , showViewToolbar(true) , showPerspectiveToolbar(false) , showVersionInfo(true) , showMitkVersionInfo(true) , showViewMenuItem(true) , showNewWindowMenuItem(false) , showClosePerspectiveMenuItem(true) , viewNavigatorFound(false) , showMemoryIndicator(true) , dropTargetListener(new QmitkDefaultDropTargetListener) { productName = QCoreApplication::applicationName(); viewExcludeList.push_back("org.mitk.views.viewnavigator"); } QmitkExtWorkbenchWindowAdvisor::~QmitkExtWorkbenchWindowAdvisor() { } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer) { if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) { berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkExtActionBarAdvisor(configurer)); return actionBarAdvisor; } else { return berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor(configurer); } } QWidget* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent) { QWidget* parentWidget = static_cast<QWidget*>(parent); auto label = new QLabel(parentWidget); label->setText("<b>No perspectives are open. Open a perspective in the <i>Window->Open Perspective</i> menu.</b>"); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show) { showClosePerspectiveMenuItem = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem() { return showClosePerspectiveMenuItem; } void QmitkExtWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show) { showMemoryIndicator = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowMemoryIndicator() { return showMemoryIndicator; } void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show) { showNewWindowMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show) { showViewMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show) { showPerspectiveToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::SetProductName(const QString& product) { productName = product; } void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon) { windowIcon = wndIcon; } void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = qobject_cast<QMainWindow*> (window->GetShell()->GetControl()); if (!windowIcon.isEmpty()) { mainWindow->setWindowIcon(QIcon(windowIcon)); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); // Load icon theme QIcon::setThemeSearchPaths(QStringList() << QStringLiteral(":/org_mitk_icons/icons/")); QIcon::setThemeName(QStringLiteral("awesome")); // ==== Application menu ============================ QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ menuBar->setNativeMenuBar(true); #else menuBar->setNativeMenuBar(false); #endif auto basePath = QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/"); auto fileOpenAction = new QmitkFileOpenAction(berry::QtStyleManager::ThemeIcon(basePath + "document-open.svg"), window); fileOpenAction->setShortcut(QKeySequence::Open); auto fileSaveAction = new QmitkFileSaveAction(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg"), window); fileSaveAction->setShortcut(QKeySequence::Save); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg")); closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "edit-delete.svg")); auto perspGroup = new QActionGroup(menuBar); std::map<QString, berry::IViewDescriptor::Pointer> VDMap; // sort elements (converting vector to map...) QList<berry::IViewDescriptor::Pointer>::const_iterator iter; berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const QList<berry::IViewDescriptor::Pointer> viewDescriptors = viewRegistry->GetViews(); bool skip = false; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { // if viewExcludeList is set, it contains the id-strings of view, which // should not appear as an menu-entry in the menu if (viewExcludeList.size() > 0) { for (int i=0; i<viewExcludeList.size(); i++) { if (viewExcludeList.at(i) == (*iter)->GetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; if ((*iter)->GetId() == "org.mitk.views.imagenavigator") continue; if ((*iter)->GetId() == "org.mitk.views.viewnavigator") continue; std::pair<QString, berry::IViewDescriptor::Pointer> p((*iter)->GetLabel(), (*iter)); VDMap.insert(p); } std::map<QString, berry::IViewDescriptor::Pointer>::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); viewActions.push_back(viewAction); } if (!USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) { QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); fileMenu->addAction(fileOpenAction); fileMenu->addAction(fileSaveAction); fileMenu->addAction(fileSaveProjectAction); fileMenu->addAction(closeProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "system-log-out.svg")); fileExitAction->setShortcut(QKeySequence::Quit); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"), "&Undo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), QKeySequence("CTRL+Z")); undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"), "&Redo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), QKeySequence("CTRL+Y")); redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); // ==== Window Menu ========================== QMenu* windowMenu = menuBar->addMenu("Window"); if (showNewWindowMenuItem) { windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); windowMenu->addSeparator(); } QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); QMenu* viewMenu = nullptr; if (showViewMenuItem) { viewMenu = windowMenu->addMenu("Show &View"); viewMenu->setObjectName("Show View"); } windowMenu->addSeparator(); resetPerspAction = windowMenu->addAction("&Reset Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); if(showClosePerspectiveMenuItem) closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); windowMenu->addSeparator(); windowMenu->addAction("&Preferences...", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), QKeySequence("CTRL+P")); // fill perspective menu berry::IPerspectiveRegistry* perspRegistry = window->GetWorkbench()->GetPerspectiveRegistry(); QList<berry::IPerspectiveDescriptor::Pointer> perspectives( perspRegistry->GetPerspectives()); skip = false; for (QList<berry::IPerspectiveDescriptor::Pointer>::iterator perspIt = perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (int i=0; i<perspectiveExcludeList.size(); i++) { if (perspectiveExcludeList.at(i) == (*perspIt)->GetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup); mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction); } perspMenu->addActions(perspGroup->actions()); if (showViewMenuItem) { for (auto viewAction : qAsConst(viewActions)) { viewMenu->addAction(viewAction); } } // ===== Help menu ==================================== QMenu* helpMenu = menuBar->addMenu("&Help"); helpMenu->addAction("&Welcome",this, SLOT(onIntro())); helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); helpMenu->addAction("&About",this, SLOT(onAbout())); // ===================================================== } else { undoAction = new QmitkUndoAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"), nullptr); undoAction->setShortcut(QKeySequence::Undo); redoAction = new QmitkRedoAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"), nullptr); redoAction->setShortcut(QKeySequence::Redo); } // toolbar for showing file open, undo, redo and other main actions auto mainActionsToolBar = new QToolBar; mainActionsToolBar->setObjectName("mainActionsToolBar"); mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif basePath = QStringLiteral(":/org.mitk.gui.qt.ext/"); imageNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(basePath + "image_navigator.svg"), "&Image Navigator", nullptr); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser")) { openDicomEditorAction = new QmitkOpenDicomEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "dicom.svg"), window); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { openStdMultiWidgetEditorAction = new QmitkOpenStdMultiWidgetEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "Editor.svg"), window); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { openMxNMultiWidgetEditorAction = new QmitkOpenMxNMultiWidgetEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "Editor.svg"), window); } if (imageNavigatorViewFound) { QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); imageNavigatorAction->setCheckable(true); // add part listener for image navigator imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction)); window->GetPartService()->AddPartListener(imageNavigatorPartListener.data()); berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); imageNavigatorAction->setChecked(false); if (imageNavigatorView) { bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) imageNavigatorAction->setChecked(true); } imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image"); } viewNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org.mitk.gui.qt.ext/view-manager.svg")),"&View Navigator", nullptr); viewNavigatorFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.viewnavigator"); if (viewNavigatorFound) { QObject::connect(viewNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onViewNavigator())); viewNavigatorAction->setCheckable(true); // add part listener for view navigator viewNavigatorPartListener.reset(new PartListenerForViewNavigator(viewNavigatorAction)); window->GetPartService()->AddPartListener(viewNavigatorPartListener.data()); berry::IViewPart::Pointer viewnavigatorview = window->GetActivePage()->FindView("org.mitk.views.viewnavigator"); viewNavigatorAction->setChecked(false); if (viewnavigatorview) { bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview); if (isViewNavigatorVisible) viewNavigatorAction->setChecked(true); } viewNavigatorAction->setToolTip("Toggle View Navigator"); } mainActionsToolBar->addAction(fileOpenAction); mainActionsToolBar->addAction(fileSaveProjectAction); mainActionsToolBar->addAction(closeProjectAction); mainActionsToolBar->addAction(undoAction); mainActionsToolBar->addAction(redoAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser")) { mainActionsToolBar->addAction(openDicomEditorAction); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget")) { mainActionsToolBar->addAction(openStdMultiWidgetEditorAction); } if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget")) { mainActionsToolBar->addAction(openMxNMultiWidgetEditorAction); } if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } if (viewNavigatorFound) { mainActionsToolBar->addAction(viewNavigatorAction); } mainWindow->addToolBar(mainActionsToolBar); // ==== Perspective Toolbar ================================== auto qPerspectiveToolbar = new QToolBar; qPerspectiveToolbar->setObjectName("perspectiveToolBar"); if (showPerspectiveToolbar) { qPerspectiveToolbar->addActions(perspGroup->actions()); mainWindow->addToolBar(qPerspectiveToolbar); } else delete qPerspectiveToolbar; if (showViewToolbar) { - auto prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); - berry::IPreferences::Pointer stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); bool showCategoryNames = stylePrefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true); // Order view descriptors by category QMultiMap<QString, berry::IViewDescriptor::Pointer> categoryViewDescriptorMap; for (const auto &labelViewDescriptorPair : VDMap) { auto viewDescriptor = labelViewDescriptorPair.second; auto category = !viewDescriptor->GetCategoryPath().isEmpty() ? viewDescriptor->GetCategoryPath().back() : QString(); categoryViewDescriptorMap.insert(category, viewDescriptor); } // Create a separate toolbar for each category for (const auto &category : categoryViewDescriptorMap.uniqueKeys()) { auto viewDescriptorsInCurrentCategory = categoryViewDescriptorMap.values(category); if (!viewDescriptorsInCurrentCategory.isEmpty()) { auto toolbar = new QToolBar; toolbar->setObjectName(category + " View Toolbar"); mainWindow->addToolBar(toolbar); if (showCategoryNames && !category.isEmpty()) { auto categoryButton = new QToolButton; categoryButton->setToolButtonStyle(Qt::ToolButtonTextOnly); categoryButton->setText(category); categoryButton->setStyleSheet("background: transparent; margin: 0; padding: 0;"); toolbar->addWidget(categoryButton); connect(categoryButton, &QToolButton::clicked, [toolbar]() { for (QWidget* widget : toolbar->findChildren<QWidget*>()) { if (QStringLiteral("qt_toolbar_ext_button") == widget->objectName() && widget->isVisible()) { QMouseEvent pressEvent(QEvent::MouseButtonPress, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QMouseEvent releaseEvent(QEvent::MouseButtonRelease, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(widget, &pressEvent); QApplication::sendEvent(widget, &releaseEvent); } } }); } for (const auto &viewDescriptor : qAsConst(viewDescriptorsInCurrentCategory)) { auto viewAction = new berry::QtShowViewAction(window, viewDescriptor); toolbar->addAction(viewAction); } } } } QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); auto qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar auto statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); auto progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); // progBar->AddStepsToDo(2); // progBar->Progress(1); mainWindow->setStatusBar(qStatusBar); if (showMemoryIndicator) { auto memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } } void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); // show the shortcut bar and progress indicator, which are hidden by // default //configurer->SetShowPerspectiveBar(true); //configurer->SetShowFastViewBars(true); //configurer->SetShowProgressIndicator(true); // // add the drag and drop support for the editor area // configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance()); // configurer.addEditorAreaTransfer(ResourceTransfer.getInstance()); // configurer.addEditorAreaTransfer(FileTransfer.getInstance()); // configurer.addEditorAreaTransfer(MarkerTransfer.getInstance()); // configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter( // configurer.getWindow())); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this)); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data()); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener.data()); } void QmitkExtWorkbenchWindowAdvisor::PostWindowOpen() { berry::WorkbenchWindowAdvisor::PostWindowOpen(); // Force Rendering Window Creation on startup. berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>(); if (serviceRef) { mitk::IDataStorageService *dsService = context->getService<mitk::IDataStorageService>(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef)); mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput); } } auto introPart = configurer->GetWindow()->GetWorkbench()->GetIntroManager()->GetIntro(); if (introPart.IsNotNull()) { configurer->GetWindow()->GetWorkbench()->GetIntroManager()->ShowIntro(GetWindowConfigurer()->GetWindow(), false); } } void QmitkExtWorkbenchWindowAdvisor::onIntro() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkExtWorkbenchWindowAdvisor::onHelp() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkExtWorkbenchWindowAdvisor::onHelpOpenHelpPerspective() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective(); } void QmitkExtWorkbenchWindowAdvisor::onAbout() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack() : QObject() { } QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack() { } void QmitkExtWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast<mitk::VerboseLimitedLinearUndo*>( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast<mitk::VerboseLimitedLinearUndo*>( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } // safe calls to the complete chain // berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); // to cover for all possible cases of closed pages etc. static void SafeHandleNavigatorView(QString view_query_name) { berry::IWorkbench* wbench = berry::PlatformUI::GetWorkbench(); if( wbench == nullptr ) return; berry::IWorkbenchWindow::Pointer wbench_window = wbench->GetActiveWorkbenchWindow(); if( wbench_window.IsNull() ) return; berry::IWorkbenchPage::Pointer wbench_page = wbench_window->GetActivePage(); if( wbench_page.IsNull() ) return; auto wbench_view = wbench_page->FindView( view_query_name ); if( wbench_view.IsNotNull() ) { bool isViewVisible = wbench_page->IsPartVisible( wbench_view ); if( isViewVisible ) { wbench_page->HideView( wbench_view ); return; } } wbench_page->ShowView( view_query_name ); } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // show/hide ImageNavigatorView SafeHandleNavigatorView("org.mitk.views.imagenavigator"); } void QmitkExtWorkbenchWindowAdvisorHack::onViewNavigator() { // show/hide viewnavigatorView SafeHandleNavigatorView("org.mitk.views.viewnavigator"); } void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkExtWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow() { berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(nullptr); } void QmitkExtWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)<title>(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(nullptr, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == nullptr) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = nullptr; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == nullptr) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkExtWorkbenchWindowAdvisorHack::onAbout() { auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),nullptr); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener.reset(new PartListenerForTitle(this)); titlePerspectiveListener.reset(new PerspectiveListenerForTitle(this)); editorPropertyListener.reset(new berry::PropertyChangeIntAdapter< QmitkExtWorkbenchWindowAdvisor>(this, &QmitkExtWorkbenchWindowAdvisor::PropertyChange)); // configurer.getWindow().addPageListener(new IPageListener() { // public void pageActivated(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageClosed(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageOpened(IWorkbenchPage page) { // // do nothing // } // }); configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener.data()); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data()); } QString QmitkExtWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } QString title; berry::IProduct::Pointer product = berry::Platform::GetProduct(); if (product.IsNotNull()) { title = product->GetName(); } if (title.isEmpty()) { // instead of the product name, we use a custom variable for now title = productName; } if(showMitkVersionInfo) { QString mitkVersionInfo = MITK_REVISION_DESC; if(mitkVersionInfo.isEmpty()) mitkVersionInfo = MITK_VERSION_STRING; title += " " + mitkVersionInfo; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 | VTK %4.%5.%6 | Qt %7)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR); title += versions; } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.isEmpty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); QString label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.isEmpty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); QString oldTitle = configurer->GetTitle(); QString newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = nullptr; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = nullptr; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } auto lockedLastActiveEditor = lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull()) { lockedLastActiveEditor->RemovePropertyListener(editorPropertyListener.data()); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener.data()); } RecomputeTitle(); } void QmitkExtWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { auto lockedLastActiveEditor = lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull()) { QString newTitle = lockedLastActiveEditor->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList& v) { this->perspectiveExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(const QList& v) { this->viewExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkExtWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp index cf328e3ec8..c0777cf9c4 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp @@ -1,77 +1,77 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkOpenDicomEditorAction.h" #include #include #include "mitkCoreObjectFactory.h" #include "mitkSceneIO.h" #include "mitkProgressBar.h" #include #include #include -#include #include -#include #include #include "mitkProperties.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" - +#include +#include +#include QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenDicomEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&DICOM"); this->setToolTip("Open dicom browser"); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenDicomEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } berry::IEditorInput::Pointer editorInput2(new berry::FileEditorInput(QString())); m_Window->GetActivePage()->OpenEditor(editorInput2, "org.mitk.editors.dicombrowser"); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h index fe1800bef6..2423e8f75f 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h @@ -1,43 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENDICOMEDITORACTION_H_ #define QMITKOPENDICOMEDITORACTION_H_ #include #include #include #include -#include + +namespace mitk +{ + class IPreferences; +} class MITK_QT_COMMON_EXT_EXPORT QmitkOpenDicomEditorAction : public QAction { Q_OBJECT public: QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init ( berry::IWorkbenchWindow::Pointer window ); berry::IWorkbenchWindow::Pointer m_Window; - berry::IPreferences::WeakPtr m_GeneralPreferencesNode; + mitk::IPreferences* m_GeneralPreferencesNode; }; #endif /*QMITKOPENDICOMEDITORACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp index c8ef3a2a4d..eda7494553 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp @@ -1,78 +1,79 @@ /*============================================================================ 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 "QmitkOpenMxNMultiWidgetEditorAction.h" #include "mitkCoreObjectFactory.h" #include #include -#include #include -#include #include +#include +#include +#include #include "internal/QmitkCommonExtPlugin.h" #include class ctkPluginContext; QmitkOpenMxNMultiWidgetEditorAction::QmitkOpenMxNMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenMxNMultiWidgetEditorAction::QmitkOpenMxNMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenMxNMultiWidgetEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("MxN Display"); this->setToolTip("Open the mxn multi widget editor"); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenMxNMultiWidgetEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService* dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(dsRef)); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.mxnmultiwidget", true, berry::IWorkbenchPage::MATCH_ID); } } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h index e7ff020a62..61ab084fd3 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h @@ -1,52 +1,56 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENMXNMULTIWIDGETEDITORACTION_H #define QMITKOPENMXNMULTIWIDGETEDITORACTION_H #ifdef __MINGW32__ // We need to include winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwise they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include #include -#include + +namespace mitk +{ + class IPreferences; +} class MITK_QT_COMMON_EXT_EXPORT QmitkOpenMxNMultiWidgetEditorAction : public QAction { Q_OBJECT public: QmitkOpenMxNMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenMxNMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init(berry::IWorkbenchWindow::Pointer window); berry::IWorkbenchWindow::Pointer m_Window; - berry::IPreferences::WeakPtr m_GeneralPreferencesNode; + mitk::IPreferences* m_GeneralPreferencesNode; }; #endif // QMITKOPENMXNMULTIWIDGETEDITORACTION_H diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp index 1c46f09643..7114fb1969 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp @@ -1,78 +1,79 @@ /*============================================================================ 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 "QmitkOpenStdMultiWidgetEditorAction.h" #include "mitkCoreObjectFactory.h" #include #include -#include #include -#include #include +#include +#include +#include #include "internal/QmitkCommonExtPlugin.h" #include class ctkPluginContext; QmitkOpenStdMultiWidgetEditorAction::QmitkOpenStdMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenStdMultiWidgetEditorAction::QmitkOpenStdMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenStdMultiWidgetEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("Standard Display"); this->setToolTip("Open the standard multi widget editor"); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenStdMultiWidgetEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService* dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(dsRef)); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.stdmultiwidget", true, berry::IWorkbenchPage::MATCH_ID); } } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h index c2afd2a9ac..f65b2b1db3 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h @@ -1,52 +1,56 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENSTDMULTIWIDGETEDITORACTION_H #define QMITKOPENSTDMULTIWIDGETEDITORACTION_H #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include #include -#include + +namespace mitk +{ + class IPreferences; +} class MITK_QT_COMMON_EXT_EXPORT QmitkOpenStdMultiWidgetEditorAction : public QAction { Q_OBJECT public: QmitkOpenStdMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenStdMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init(berry::IWorkbenchWindow::Pointer window); berry::IWorkbenchWindow::Pointer m_Window; - berry::IPreferences::WeakPtr m_GeneralPreferencesNode; + mitk::IPreferences* m_GeneralPreferencesNode; }; #endif // QMITKOPENSTDMULTIWIDGETEDITORACTION_H diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp index 59e65db1a4..aacfbc2ec1 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp @@ -1,75 +1,77 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkOpenXnatEditorAction.h" #include #include -#include #include -#include #include +#include +#include +#include + QmitkOpenXnatEditorAction::QmitkOpenXnatEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenXnatEditorAction::QmitkOpenXnatEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenXnatEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&XNAT"); this->setToolTip("Open XNAT tool"); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenXnatEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } QList editors = m_Window->GetActivePage()->FindEditors(berry::IEditorInput::Pointer(nullptr), "org.mitk.editors.xnat.browser", berry::IWorkbenchPage::MATCH_ID); if (editors.empty()) { // no XnatEditor is currently open, create a new one berry::IEditorInput::Pointer editorInput(new berry::FileEditorInput(QString())); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.xnat.browser"); } else { // reuse an existing editor berry::IEditorPart::Pointer reuseEditor = editors.front()->GetEditor(true); m_Window->GetActivePage()->Activate(reuseEditor); } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h index 270db89659..c40e613a4a 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h @@ -1,43 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENXNATEDITORACTION_H_ #define QMITKOPENXNATEDITORACTION_H_ #include #include #include #include -#include + +namespace mitk +{ + class IPreferences; +} class MITK_QT_COMMON_EXT_EXPORT QmitkOpenXnatEditorAction : public QAction { Q_OBJECT public: QmitkOpenXnatEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenXnatEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init ( berry::IWorkbenchWindow::Pointer window ); berry::IWorkbenchWindow::Pointer m_Window; - berry::IPreferences::WeakPtr m_GeneralPreferencesNode; + mitk::IPreferences* m_GeneralPreferencesNode; }; #endif /*QMITKOPENXNATEDITORACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp index 80dd10c054..566519241b 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp @@ -1,64 +1,64 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAppInstancesPreferencePage.h" -#include -#include -#include +#include +#include +#include QmitkAppInstancesPreferencePage::QmitkAppInstancesPreferencePage() { } void QmitkAppInstancesPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkAppInstancesPreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); prefs = prefService->GetSystemPreferences()->Node("/General"); Update(); } QWidget* QmitkAppInstancesPreferencePage::GetQtControl() const { return mainWidget; } bool QmitkAppInstancesPreferencePage::PerformOk() { prefs->PutBool("newInstance.always", controls.newInstanceAlways->isChecked()); prefs->PutBool("newInstance.scene", controls.newInstanceScene->isChecked()); return true; } void QmitkAppInstancesPreferencePage::PerformCancel() { } void QmitkAppInstancesPreferencePage::Update() { bool always = prefs->GetBool("newInstance.always", false); bool scene = prefs->GetBool("newInstance.scene", true); controls.newInstanceAlways->setChecked(always); controls.newInstanceScene->setChecked(scene); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h index 80613fc088..b9cd932254 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h @@ -1,52 +1,55 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKAPPINSTANCESPREFERENCEPAGE_H_ #define QMITKAPPINSTANCESPREFERENCEPAGE_H_ #include -#include #include +namespace mitk +{ + class IPreferences; +} class QmitkAppInstancesPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkAppInstancesPreferencePage(); QmitkAppInstancesPreferencePage(const QmitkAppInstancesPreferencePage& other); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; private: Ui::QmitkAppInstancesPreferencePage controls; - berry::IPreferences::Pointer prefs; + mitk::IPreferences* prefs; QWidget* mainWidget; }; #endif /* QMITKAPPINSTANCESPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp index 5c2a1f3381..baf901c607 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp @@ -1,233 +1,239 @@ /*============================================================================ 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 "QmitkCommonExtPlugin.h" #include #include "QmitkAboutHandler.h" #include "QmitkAppInstancesPreferencePage.h" #include "QmitkExternalProgramsPreferencePage.h" #include "QmitkInputDevicesPrefPage.h" #include "QmitkModuleView.h" #include #include #include #include #include +#include +#include +#include #include #include -#include #include #include #include #include +#include + +US_INITIALIZE_MODULE + ctkPluginContext* QmitkCommonExtPlugin::_context = nullptr; void QmitkCommonExtPlugin::start(ctkPluginContext* context) { this->_context = context; QtWidgetsExtRegisterClasses(); BERRY_REGISTER_EXTENSION_CLASS(QmitkAboutHandler, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAppInstancesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkExternalProgramsPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkInputDevicesPrefPage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context) if (qApp->metaObject()->indexOfSignal("messageReceived(QByteArray)") > -1) { connect(qApp, SIGNAL(messageReceived(QByteArray)), this, SLOT(handleIPCMessage(QByteArray))); } // This is a potentially long running operation. loadDataFromDisk(berry::Platform::GetApplicationArgs(), true); } void QmitkCommonExtPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = nullptr; } ctkPluginContext* QmitkCommonExtPlugin::getContext() { return _context; } void QmitkCommonExtPlugin::loadDataFromDisk(const QStringList &arguments, bool globalReinit) { if (!arguments.empty()) { ctkServiceReference serviceRef = _context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService* dataStorageService = _context->getService(serviceRef); mitk::DataStorage::Pointer dataStorage = dataStorageService->GetDefaultDataStorage()->GetDataStorage(); int argumentsAdded = 0; for (int i = 0; i < arguments.size(); ++i) { if (arguments[i].right(5) == ".mitk") { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); mitk::ProgressBar::GetInstance()->Progress(2); argumentsAdded++; } else if (arguments[i].right(15) == ".mitksceneindex") { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadSceneUnzipped(arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst); mitk::ProgressBar::GetInstance()->Progress(2); argumentsAdded++; } else { try { const std::string path(arguments[i].toStdString()); auto addedNodes = mitk::IOUtil::Load(path, *dataStorage); for (const auto& node : *addedNodes ) { node->SetIntProperty("layer", argumentsAdded); } argumentsAdded++; } catch(...) { MITK_WARN << "Failed to load command line argument: " << arguments[i].toStdString(); } } } // end for each command line argument if (argumentsAdded > 0 && globalReinit) { // calculate bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(dataStorage->ComputeBoundingGeometry3D()); } } else { MITK_ERROR << "A service reference for mitk::IDataStorageService does not exist"; } } } void QmitkCommonExtPlugin::startNewInstance(const QStringList &args, const QStringList& files) { QStringList newArgs(args); #ifdef Q_OS_UNIX newArgs << QString("--") + mitk::BaseApplication::ARG_NEWINSTANCE; #else newArgs << QString("/") + mitk::BaseApplication::ARG_NEWINSTANCE; #endif newArgs << files; QProcess::startDetached(qApp->applicationFilePath(), newArgs); } void QmitkCommonExtPlugin::handleIPCMessage(const QByteArray& msg) { QDataStream ds(msg); QString msgType; ds >> msgType; // we only handle messages containing command line arguments if (msgType != "$cmdLineArgs") return; // activate the current workbench window berry::IWorkbenchWindow::Pointer window = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); mainWindow->setWindowState(mainWindow->windowState() & ~Qt::WindowMinimized); mainWindow->raise(); mainWindow->activateWindow(); // Get the preferences for the instantiation behavior - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node("/General"); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* prefs = prefService->GetSystemPreferences()->Node("/General"); bool newInstanceAlways = prefs->GetBool("newInstance.always", false); bool newInstanceScene = prefs->GetBool("newInstance.scene", true); QStringList args; ds >> args; QStringList fileArgs; QStringList sceneArgs; foreach (QString arg, args) { if (arg.endsWith(".mitk")) { sceneArgs << arg; } else { fileArgs << arg; } } if (newInstanceAlways) { if (newInstanceScene) { startNewInstance(args, fileArgs); foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { fileArgs.append(sceneArgs); startNewInstance(args, fileArgs); } } else { loadDataFromDisk(fileArgs, false); if (newInstanceScene) { foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { loadDataFromDisk(sceneArgs, false); } } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp index 6f2257760f..0c627d8b0a 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp @@ -1,184 +1,185 @@ /*============================================================================ 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 "QmitkExternalProgramsPreferencePage.h" -static berry::IPreferences::Pointer GetPreferences() +static mitk::IPreferences* GetPreferences() { - berry::IPreferencesService* preferencesService = berry::Platform::GetPreferencesService(); + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); if (preferencesService != nullptr) { - berry::IPreferences::Pointer systemPreferences = preferencesService->GetSystemPreferences(); + auto* systemPreferences = preferencesService->GetSystemPreferences(); - if (systemPreferences.IsNotNull()) + if (systemPreferences != nullptr) return systemPreferences->Node("/org.mitk.gui.qt.ext.externalprograms"); } mitkThrow(); } QmitkExternalProgramsPreferencePage::QmitkExternalProgramsPreferencePage() : m_Preferences(GetPreferences()), m_Ui(new Ui::QmitkExternalProgramsPreferencePage), m_Control(nullptr), m_FFmpegProcess(nullptr), m_GnuplotProcess(nullptr) { } QmitkExternalProgramsPreferencePage::~QmitkExternalProgramsPreferencePage() { } void QmitkExternalProgramsPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_FFmpegProcess = new QProcess(m_Control); m_GnuplotProcess = new QProcess(m_Control); m_Ui->setupUi(m_Control); connect(m_FFmpegProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnFFmpegProcessError(QProcess::ProcessError))); connect(m_FFmpegProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnFFmpegProcessFinished(int, QProcess::ExitStatus))); connect(m_Ui->ffmpegButton, SIGNAL(clicked()), this, SLOT(OnFFmpegButtonClicked())); connect(m_GnuplotProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnGnuplotProcessError(QProcess::ProcessError))); connect(m_GnuplotProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnGnuplotProcessFinished(int, QProcess::ExitStatus))); connect(m_Ui->gnuplotButton, SIGNAL(clicked()), this, SLOT(OnGnuplotButtonClicked())); this->Update(); } void QmitkExternalProgramsPreferencePage::OnFFmpegButtonClicked() { QString filter = "ffmpeg executable "; #if defined(WIN32) filter += "(ffmpeg.exe)"; #else filter += "(ffmpeg)"; #endif QString ffmpegPath = QFileDialog::getOpenFileName(m_Control, "FFmpeg", "", filter); if (!ffmpegPath.isEmpty()) { m_FFmpegPath = ffmpegPath; m_FFmpegProcess->start(ffmpegPath, QStringList() << "-version", QProcess::ReadOnly); } } void QmitkExternalProgramsPreferencePage::OnFFmpegProcessError(QProcess::ProcessError) { m_FFmpegPath.clear(); m_Ui->ffmpegLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnFFmpegProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::NormalExit && exitCode == 0) { QString output = QTextCodec::codecForName("UTF-8")->toUnicode(m_FFmpegProcess->readAllStandardOutput()); if (output.startsWith("ffmpeg")) { m_Ui->ffmpegLineEdit->setText(m_FFmpegPath); return; } } m_FFmpegPath.clear(); m_Ui->ffmpegLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnGnuplotButtonClicked() { QString filter = "gnuplot executable "; #if defined(WIN32) filter += "(gnuplot.exe)"; #else filter += "(gnuplot)"; #endif QString gnuplotPath = QFileDialog::getOpenFileName(m_Control, "Gnuplot", "", filter); if (!gnuplotPath.isEmpty()) { m_GnuplotPath = gnuplotPath; m_GnuplotProcess->start(gnuplotPath, QStringList() << "--version", QProcess::ReadOnly); } } void QmitkExternalProgramsPreferencePage::OnGnuplotProcessError(QProcess::ProcessError) { m_GnuplotPath.clear(); m_Ui->gnuplotLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnGnuplotProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::NormalExit && exitCode == 0) { QString output = QTextCodec::codecForName("UTF-8")->toUnicode(m_GnuplotProcess->readAllStandardOutput()); if (output.startsWith("gnuplot")) { m_Ui->gnuplotLineEdit->setText(m_GnuplotPath); return; } } m_GnuplotPath.clear(); m_Ui->gnuplotLineEdit->clear(); } QWidget* QmitkExternalProgramsPreferencePage::GetQtControl() const { return m_Control; } void QmitkExternalProgramsPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkExternalProgramsPreferencePage::PerformCancel() { } bool QmitkExternalProgramsPreferencePage::PerformOk() { - m_Preferences->Put("ffmpeg", m_FFmpegPath); - m_Preferences->Put("gnuplot", m_GnuplotPath); + m_Preferences->Put("ffmpeg", m_FFmpegPath.toStdString()); + m_Preferences->Put("gnuplot", m_GnuplotPath.toStdString()); return true; } void QmitkExternalProgramsPreferencePage::Update() { - m_FFmpegPath = m_Preferences->Get("ffmpeg", ""); + m_FFmpegPath = QString::fromStdString(m_Preferences->Get("ffmpeg", "")); if (!m_FFmpegPath.isEmpty()) m_FFmpegProcess->start(m_FFmpegPath, QStringList() << "-version", QProcess::ReadOnly); - m_GnuplotPath = m_Preferences->Get("gnuplot", ""); + m_GnuplotPath = QString::fromStdString(m_Preferences->Get("gnuplot", "")); if (!m_GnuplotPath.isEmpty()) m_GnuplotProcess->start(m_GnuplotPath, QStringList() << "--version", QProcess::ReadOnly); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h index 68d936f44c..2ec515e341 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h @@ -1,63 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkExternalProgramsPreferencePage_h #define QmitkExternalProgramsPreferencePage_h -#include #include #include #include +namespace mitk +{ + class IPreferences; +} + namespace Ui { class QmitkExternalProgramsPreferencePage; } class QmitkExternalProgramsPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkExternalProgramsPreferencePage(); ~QmitkExternalProgramsPreferencePage() override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; void Init(berry::IWorkbench::Pointer) override; void PerformCancel() override; bool PerformOk() override; void Update() override; private slots: void OnFFmpegButtonClicked(); void OnFFmpegProcessError(QProcess::ProcessError error); void OnFFmpegProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); void OnGnuplotButtonClicked(); void OnGnuplotProcessError(QProcess::ProcessError error); void OnGnuplotProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); private: - berry::IPreferences::Pointer m_Preferences; + mitk::IPreferences* m_Preferences; QScopedPointer m_Ui; QWidget* m_Control; QProcess* m_FFmpegProcess; QString m_FFmpegPath; QProcess* m_GnuplotProcess; QString m_GnuplotPath; }; #endif diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp index e532e8476a..a6078e571a 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp @@ -1,184 +1,185 @@ /*============================================================================ 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 "QmitkInputDevicesPrefPage.h" -#include -#include +#include +#include +#include #include #include #include #include #include #include #include #include #include #include "QmitkCommonExtPlugin.h" QmitkInputDevicesPrefPage::QmitkInputDevicesPrefPage() : m_MainControl(nullptr) { // gets the old setting of the preferences and loads them into the preference node - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - this->m_InputDevicesPrefNode = prefService->GetSystemPreferences()->Node(mitk::CoreExtConstants::INPUTDEVICE_PREFERENCES); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + this->m_InputDevicesPrefNode = prefService->GetSystemPreferences()->Node(mitk::CoreExtConstants::INPUTDEVICE_PREFERENCES.toStdString()); } void QmitkInputDevicesPrefPage::Init(berry::IWorkbench::Pointer ) { } void QmitkInputDevicesPrefPage::CreateQtControl(QWidget* parent) { m_MainControl = new QWidget(parent); auto layout = new QVBoxLayout; QList temp(GetInputDeviceRegistry()->GetInputDevices()); for(QList::const_iterator it = temp.begin(); it != temp.end();++it) { QString inputDeviceName((*it)->GetName()); auto checkBox = new QCheckBox((inputDeviceName),m_MainControl); layout->addWidget(checkBox); m_InputDevices.insert(checkBox,(*it)->GetID()); if(inputDeviceName == "WiiMote") { m_WiiMoteModes = new QGroupBox("WiiMote Modus"); m_WiiMoteHeadTracking = new QRadioButton(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING); m_WiiMoteSurfaceInteraction = new QRadioButton(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION); m_WiiMoteHeadTracking->setChecked(true); auto vBoxLayout = new QVBoxLayout; vBoxLayout->addWidget(m_WiiMoteHeadTracking); vBoxLayout->addWidget(m_WiiMoteSurfaceInteraction); m_WiiMoteModes->setLayout(vBoxLayout); layout->addWidget(m_WiiMoteModes); } } layout->addStretch(); m_MainControl->setLayout(layout); this->Update(); } QWidget* QmitkInputDevicesPrefPage::GetQtControl() const { return m_MainControl; } bool QmitkInputDevicesPrefPage::PerformOk() { bool result = true; mitk::IInputDeviceRegistry* inputDeviceRegistry = GetInputDeviceRegistry(); QHashIterator it(m_InputDevices); while (it.hasNext()) { it.next(); mitk::IInputDeviceDescriptor::Pointer inputdevice(inputDeviceRegistry->Find(it.value())); if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { - QString headTracking(m_WiiMoteHeadTracking->text()); - QString surfaceInteraction(m_WiiMoteSurfaceInteraction->text()); + const auto headTracking(m_WiiMoteHeadTracking->text().toStdString()); + const auto surfaceInteraction(m_WiiMoteSurfaceInteraction->text().toStdString()); this->m_InputDevicesPrefNode->PutBool (headTracking, m_WiiMoteHeadTracking->isChecked()); this->m_InputDevicesPrefNode->PutBool (surfaceInteraction, m_WiiMoteSurfaceInteraction->isChecked()); // forced flush of the preferences is needed // because otherwise the mitk::WiiMoteActivator class // cannot distinguish the two different modes without // changing the interface for all input devices - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - if (prefService) + if (prefService != nullptr) { prefService->GetSystemPreferences()->Flush(); } } if(it.key()->isChecked()) { result &= inputdevice->CreateInputDevice()->RegisterInputDevice(); } else { result &= inputdevice->CreateInputDevice()->UnRegisterInputDevice(); // temporary fix, unclean solution: // e.g. user activates SpaceNavigator and leaves the // the wiimote deactivated, the user will get the warning // despite the fact that it has never been activated if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { // until now 2010-09-06 there were some unfixed problems // with reconnecting the wiimote after disconnecting it. // It was suggested that it might have something to do // with the type of stack, that is used for the pairing. // MS-Stack for example does not work properly. QMessageBox::information(nullptr,"WiiMote supportproblem", "A reconnect of the WiiMote is not yet supported! " "Please restart the application, if you want to " "activate the Wii remote/s again."); } } if(result) { - this->m_InputDevicesPrefNode->PutBool(it.value(),it.key()->isChecked()); + this->m_InputDevicesPrefNode->PutBool(it.value().toStdString(), it.key()->isChecked()); } } return result; } void QmitkInputDevicesPrefPage::PerformCancel() { } void QmitkInputDevicesPrefPage::Update() { QHashIterator it(m_InputDevices); while (it.hasNext()) { it.next(); - it.key()->setChecked(this->m_InputDevicesPrefNode->GetBool(it.value(), false)); + it.key()->setChecked(this->m_InputDevicesPrefNode->GetBool(it.value().toStdString(), false)); if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { m_WiiMoteHeadTracking->setChecked( - this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING,false)); + this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING.toStdString(), false)); m_WiiMoteSurfaceInteraction->setChecked - (this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION,false)); + (this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION.toStdString(), false)); } } } mitk::IInputDeviceRegistry *QmitkInputDevicesPrefPage::GetInputDeviceRegistry() const { ctkServiceReference serviceRef = QmitkCommonExtPlugin::getContext()->getServiceReference(); if (!serviceRef) return nullptr; return QmitkCommonExtPlugin::getContext()->getService(serviceRef); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h index 8af72603b0..354bbde14d 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h @@ -1,90 +1,90 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITK_INPUTDEVICESPREFPAGE_H_ #define QMITK_INPUTDEVICESPREFPAGE_H_ #include "berryIQtPreferencePage.h" -#include #include #include #include class QWidget; class QCheckBox; namespace mitk { struct IInputDeviceRegistry; +class IPreferences; } class QmitkInputDevicesPrefPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: /** * Default constructor */ QmitkInputDevicesPrefPage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench) override; /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget) override; /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const override; /** * @see berry::IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @see berry::IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @see berry::IPreferencePage::Update() */ void Update() override; protected: QWidget* m_MainControl; QHash m_InputDevices; // specific for Wiimote QGroupBox* m_WiiMoteModes; QRadioButton* m_WiiMoteHeadTracking; QRadioButton* m_WiiMoteSurfaceInteraction; - berry::IPreferences::Pointer m_InputDevicesPrefNode; + mitk::IPreferences* m_InputDevicesPrefNode; mitk::IInputDeviceRegistry* GetInputDeviceRegistry() const; }; #endif // QMITK_INPUTDEVICESPREFPAGE_H_ diff --git a/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp b/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp index a27da1b754..1608fade72 100644 --- a/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp +++ b/Plugins/org.mitk.gui.qt.flow.segmentation/src/internal/QmitkSegmentationTaskListWidget.cpp @@ -1,859 +1,859 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationTaskListWidget.h" #include "org_mitk_gui_qt_flow_segmentation_Activator.h" -#include -#include -#include +#include +#include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { - berry::IPreferences::Pointer GetSegmentationPreferences() + mitk::IPreferences* GetSegmentationPreferences() { - return berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); + return mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); } mitk::DataStorage* GetDataStorage() { auto* pluginContext = org_mitk_gui_qt_flow_segmentation_Activator::GetContext(); auto dataStorageServiceReference = pluginContext->getServiceReference(); if (dataStorageServiceReference) { auto* dataStorageService = pluginContext->getService(dataStorageServiceReference); if (dataStorageService != nullptr) { auto dataStorageReference = dataStorageService->GetDataStorage(); pluginContext->ungetService(dataStorageServiceReference); return dataStorageReference->GetDataStorage(); } } return nullptr; } std::filesystem::path GetInputLocation(const mitk::BaseData* data) { std::string result; if (data != nullptr) data->GetPropertyList()->GetStringProperty("MITK.IO.reader.inputlocation", result); return result; } QString ColorString(const QString& string, const QColor& color, const QColor& backgroundColor = QColor::Invalid) { if (!color.isValid() && !backgroundColor.isValid()) return string; auto result = QStringLiteral("%1").arg(string); return result; } } /* This constructor has three objectives: * 1. Do widget initialization that cannot be done in the .ui file * 2. Connect signals and slots * 3. Explicitly trigger a reset to a valid initial widget state */ QmitkSegmentationTaskListWidget::QmitkSegmentationTaskListWidget(QWidget* parent) : QWidget(parent), m_Ui(new Ui::QmitkSegmentationTaskListWidget), m_FileSystemWatcher(new QFileSystemWatcher(this)), m_UnsavedChanges(false) { m_Ui->setupUi(this); m_Ui->selectionWidget->SetDataStorage(GetDataStorage()); m_Ui->selectionWidget->SetSelectionIsOptional(true); m_Ui->selectionWidget->SetEmptyInfo(QStringLiteral("Select a segmentation task list")); m_Ui->selectionWidget->SetAutoSelectNewNodes(true); m_Ui->selectionWidget->SetNodePredicate(mitk::TNodePredicateDataType::New()); m_Ui->progressBar->setStyleSheet(QString("QProgressBar::chunk { background-color: %1; }").arg(QmitkStyleManager::GetIconAccentColor())); using Self = QmitkSegmentationTaskListWidget; connect(m_Ui->selectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &Self::OnSelectionChanged); connect(m_Ui->previousButton, &QToolButton::clicked, this, &Self::OnPreviousButtonClicked); connect(m_Ui->nextButton, &QToolButton::clicked, this, &Self::OnNextButtonClicked); connect(m_Ui->loadButton, &QPushButton::clicked, this, &Self::OnLoadButtonClicked); connect(m_FileSystemWatcher, &QFileSystemWatcher::directoryChanged, this, &Self::OnResultDirectoryChanged); auto* prevShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key::Key_P), this); connect(prevShortcut, &QShortcut::activated, this, &Self::OnPreviousTaskShortcutActivated); auto* prevUndoneShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key::Key_P), this); connect(prevUndoneShortcut, &QShortcut::activated, this, &Self::OnPreviousTaskShortcutActivated); auto* nextShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key::Key_N), this); connect(nextShortcut, &QShortcut::activated, this, &Self::OnNextTaskShortcutActivated); auto* nextUndoneShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key::Key_N), this); connect(nextUndoneShortcut, &QShortcut::activated, this, &Self::OnNextTaskShortcutActivated); auto* loadShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key::Key_L), this); connect(loadShortcut, &QShortcut::activated, this, &Self::OnLoadTaskShortcutActivated); this->OnSelectionChanged(m_Ui->selectionWidget->GetSelectedNodes()); } QmitkSegmentationTaskListWidget::~QmitkSegmentationTaskListWidget() { } void QmitkSegmentationTaskListWidget::OnUnsavedChangesSaved() { if (m_UnsavedChanges) { m_UnsavedChanges = false; if (this->ActiveTaskIsShown()) this->UpdateDetailsLabel(); } } /* Make sure that the widget transitions into a valid state whenever the * selection changes. */ void QmitkSegmentationTaskListWidget::OnSelectionChanged(const QmitkSingleNodeSelectionWidget::NodeList& nodes) { this->UnloadTasks(); this->ResetControls(); if (!nodes.empty()) { m_TaskListNode = nodes.front(); auto taskList = dynamic_cast(m_TaskListNode->GetData()); if (taskList != nullptr) { this->OnTaskListChanged(taskList); return; } } this->SetTaskList(nullptr); m_TaskListNode = nullptr; } /* Reset all controls to a default state as a common basis for further * adjustments. */ void QmitkSegmentationTaskListWidget::ResetControls() { m_Ui->progressBar->setEnabled(false); m_Ui->progressBar->setFormat(""); m_Ui->progressBar->setValue(0); m_Ui->progressBar->setMaximum(1); m_Ui->previousButton->setEnabled(false); m_Ui->nextButton->setEnabled(false); this->UpdateLoadButton(); this->UpdateDetailsLabel(); } /* If the segmentation task changed, reset all member variables to expected * default values and reset the file system watcher. */ void QmitkSegmentationTaskListWidget::SetTaskList(mitk::SegmentationTaskList* taskList) { if (m_TaskList != taskList) { m_TaskList = taskList; if (taskList != nullptr) { this->SetCurrentTaskIndex(0); } else { this->SetCurrentTaskIndex(std::nullopt); } this->ResetFileSystemWatcher(); } } void QmitkSegmentationTaskListWidget::ResetFileSystemWatcher() { auto paths = m_FileSystemWatcher->directories(); if (!paths.empty()) m_FileSystemWatcher->removePaths(paths); if (m_TaskList.IsNotNull()) { for (const auto& task : *m_TaskList) { auto resultPath = m_TaskList->GetAbsolutePath(task.GetResult()).remove_filename(); if (!std::filesystem::exists(resultPath)) { try { std::filesystem::create_directories(resultPath); } catch (const std::filesystem::filesystem_error& e) { MITK_ERROR << e.what(); } } if (std::filesystem::exists(resultPath)) m_FileSystemWatcher->addPath(QString::fromStdString(resultPath.string())); } } } void QmitkSegmentationTaskListWidget::OnResultDirectoryChanged(const QString&) { // TODO: If a segmentation was modified ("Unsaved changes"), saved ("Done"), and then the file is deleted, the status should be "Unsaved changes" instead of "Not done". this->UpdateProgressBar(); this->UpdateDetailsLabel(); } void QmitkSegmentationTaskListWidget::UpdateProgressBar() { int progress = 0; for (size_t i = 0; i < m_TaskList->GetNumberOfTasks(); ++i) { if (m_TaskList->IsDone(i)) ++progress; } m_Ui->progressBar->setValue(progress); } /* Provided that a valid segmentation task list is currently selected and the * widget is in its default state, update all controls accordingly. */ void QmitkSegmentationTaskListWidget::OnTaskListChanged(mitk::SegmentationTaskList* taskList) { this->SetTaskList(taskList); const auto numTasks = taskList->GetNumberOfTasks(); m_Ui->progressBar->setMaximum(numTasks); m_Ui->progressBar->setFormat(QStringLiteral("%v/%m Task(s) done")); m_Ui->progressBar->setEnabled(true); this->UpdateProgressBar(); m_Ui->loadButton->setEnabled(true); if (numTasks > 1) m_Ui->nextButton->setEnabled(true); } /* If possible, change the currently displayed task to the previous task. * Enable/disable navigation buttons according to the task's position. */ void QmitkSegmentationTaskListWidget::OnPreviousButtonClicked() { auto current = m_CurrentTaskIndex.value(); // If the shift modifier key is pressed, look for the previous undone task. if (QApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier)) { if (current > 0) { for (decltype(current) i = current; i > 0; --i) { if (!m_TaskList->IsDone(i - 1)) { this->SetCurrentTaskIndex(i - 1); break; } } } } else { if (current != 0) this->SetCurrentTaskIndex(current - 1); } this->UpdateNavigationButtons(); } /* If possible, change the currently displayed task to the next task. * Enable/disable navigation buttons according to the task's position. */ void QmitkSegmentationTaskListWidget::OnNextButtonClicked() { const auto numTasks = m_TaskList->GetNumberOfTasks(); auto current = m_CurrentTaskIndex.value(); // If the shift modifier key is pressed, look for the next undone task. if (QApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier)) { for (std::remove_const_t i = current + 1; i < numTasks; ++i) { if (!m_TaskList->IsDone(i)) { this->SetCurrentTaskIndex(i); break; } } } else { if (current < numTasks - 1) this->SetCurrentTaskIndex(current + 1); } this->UpdateNavigationButtons(); } void QmitkSegmentationTaskListWidget::UpdateNavigationButtons() { if (m_TaskList.IsNull() || m_TaskList->GetNumberOfTasks() == 0) { m_Ui->previousButton->setEnabled(false); m_Ui->nextButton->setEnabled(false); return; } const auto maxIndex = m_TaskList->GetNumberOfTasks() - 1; const auto current = m_CurrentTaskIndex.value(); m_Ui->previousButton->setEnabled(current != 0); m_Ui->nextButton->setEnabled(current != maxIndex); } /* Update affected controls when the currently displayed task changed. */ void QmitkSegmentationTaskListWidget::OnCurrentTaskChanged() { this->UpdateLoadButton(); this->UpdateNavigationButtons(); this->UpdateDetailsLabel(); } /* Update the load button according to the currently displayed task. */ void QmitkSegmentationTaskListWidget::UpdateLoadButton() { auto text = !this->ActiveTaskIsShown() ? QStringLiteral("Load task") : QStringLiteral("Task"); if (m_CurrentTaskIndex.has_value()) { const auto current = m_CurrentTaskIndex.value(); if (m_TaskList.IsNotNull()) { text += QString(" %1/%2").arg(current + 1).arg(m_TaskList->GetNumberOfTasks()); if (m_TaskList->HasName(current)) text += QStringLiteral(":\n") + QString::fromStdString(m_TaskList->GetName(current)); } m_Ui->loadButton->setDisabled(this->ActiveTaskIsShown()); } else { m_Ui->loadButton->setEnabled(false); } m_Ui->loadButton->setText(text); } /* Update the details label according to the currently display task. * The text is composed of the status of the task and a variable number * of text blocks according to the optional values provided by the task. */ void QmitkSegmentationTaskListWidget::UpdateDetailsLabel() { if (!m_CurrentTaskIndex.has_value()) { m_Ui->detailsLabel->clear(); return; } const auto current = m_CurrentTaskIndex.value(); bool isDone = m_TaskList->IsDone(current); auto details = QString("

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

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

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

Description: %1

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

%1

").arg(stringList.join(QStringLiteral("
"))); m_Ui->detailsLabel->setText(details); } /* Load/activate the currently displayed task. Unload all data nodes from * previously active tasks first, but spare and reuse the image if possible. */ void QmitkSegmentationTaskListWidget::OnLoadButtonClicked() { if (!this->HandleUnsavedChanges() || m_UnsavedChanges) return; m_Ui->loadButton->setEnabled(false); QApplication::setOverrideCursor(Qt::BusyCursor); this->LoadTask(this->GetImageDataNode(m_CurrentTaskIndex.value())); QApplication::restoreOverrideCursor(); } /* If present, return the image data node for the task with the specified * index. Otherwise, return nullptr. */ mitk::DataNode* QmitkSegmentationTaskListWidget::GetImageDataNode(size_t index) const { const auto imagePath = m_TaskList->GetAbsolutePath(m_TaskList->GetImage(index)); auto imageNodes = GetDataStorage()->GetDerivations(m_TaskListNode, mitk::NodePredicateFunction::New([imagePath](const mitk::DataNode* node) { return imagePath == GetInputLocation(node->GetData()); })); return !imageNodes->empty() ? imageNodes->front() : nullptr; } /* If present, return the segmentation data node for the task with the * specified index. Otherwise, return nullptr. */ mitk::DataNode* QmitkSegmentationTaskListWidget::GetSegmentationDataNode(size_t index) const { const auto* imageNode = this->GetImageDataNode(index); if (imageNode != nullptr) { auto segmentations = GetDataStorage()->GetDerivations(imageNode, mitk::TNodePredicateDataType::New()); if (!segmentations->empty()) return segmentations->front(); } return nullptr; } /* Unload all task data nodes but spare the passed image data node. */ void QmitkSegmentationTaskListWidget::UnloadTasks(const mitk::DataNode* skip) { this->UnsubscribeFromActiveSegmentation(); if (m_TaskListNode.IsNotNull()) { mitk::DataStorage::Pointer dataStorage = GetDataStorage(); auto imageNodes = dataStorage->GetDerivations(m_TaskListNode, mitk::TNodePredicateDataType::New()); for (auto imageNode : *imageNodes) { dataStorage->Remove(dataStorage->GetDerivations(imageNode, nullptr, false)); if (imageNode != skip) dataStorage->Remove(imageNode); } } this->SetActiveTaskIndex(std::nullopt); } void QmitkSegmentationTaskListWidget::LoadNextUnfinishedTask() { const auto current = m_CurrentTaskIndex.value(); const auto numTasks = m_TaskList->GetNumberOfTasks(); for (size_t unboundNext = current; unboundNext < current + numTasks; ++unboundNext) { auto next = unboundNext % numTasks; if (!m_TaskList->IsDone(next)) { this->SetCurrentTaskIndex(next); this->OnLoadButtonClicked(); break; } } } /* Load/activate the currently displayed task. The task must specify * an image. The segmentation is either created from scratch with an optional * name for the first label, possibly based on a label set preset specified by * the task, or loaded as specified by the task. If a result file does * exist, it is chosen as segmentation instead. */ void QmitkSegmentationTaskListWidget::LoadTask(mitk::DataNode::Pointer imageNode) { this->UnloadTasks(imageNode); const auto current = m_CurrentTaskIndex.value(); mitk::Image::Pointer image; mitk::LabelSetImage::Pointer segmentation; try { if (imageNode.IsNull()) { const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetImage(current)); image = mitk::IOUtil::Load(path.string()); } const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetResult(current)); const auto interimPath = m_TaskList->GetInterimPath(path); if (std::filesystem::exists(path)) { segmentation = mitk::IOUtil::Load(path.string()); } else if (std::filesystem::exists(interimPath)) { segmentation = mitk::IOUtil::Load(interimPath.string()); } else if (m_TaskList->HasSegmentation(current)) { const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetSegmentation(current)); segmentation = mitk::IOUtil::Load(path.string()); } } catch (const mitk::Exception&) { return; } auto dataStorage = GetDataStorage(); if (imageNode.IsNull()) { imageNode = mitk::DataNode::New(); imageNode->SetData(image); dataStorage->Add(imageNode, m_TaskListNode); mitk::RenderingManager::GetInstance()->InitializeViews(image->GetTimeGeometry()); } else { image = static_cast(imageNode->GetData()); } auto name = "Task " + std::to_string(current + 1); imageNode->SetName(name); if (segmentation.IsNull()) { mitk::Image::ConstPointer templateImage = image; if (templateImage->GetDimension() > 3) { if (m_TaskList->HasDynamic(current)) { if (!m_TaskList->GetDynamic(current)) templateImage = mitk::SegmentationHelper::GetStaticSegmentationTemplate(image); } else { QmitkStaticDynamicSegmentationDialog dialog(this); dialog.SetReferenceImage(templateImage); dialog.exec(); templateImage = dialog.GetSegmentationTemplate(); } } auto segmentationNode = mitk::LabelSetImageHelper::CreateNewSegmentationNode(imageNode, templateImage, name); segmentation = static_cast(segmentationNode->GetData()); if (m_TaskList->HasPreset(current)) { const auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetPreset(current)); mitk::LabelSetIOHelper::LoadLabelSetImagePreset(path.string(), segmentation); } else { auto label = mitk::LabelSetImageHelper::CreateNewLabel(segmentation); if (m_TaskList->HasLabelName(current)) label->SetName(m_TaskList->GetLabelName(current)); segmentation->GetActiveLabelSet()->AddLabel(label); } dataStorage->Add(segmentationNode, imageNode); } else { auto segmentationNode = mitk::DataNode::New(); segmentationNode->SetName(name); segmentationNode->SetData(segmentation); dataStorage->Add(segmentationNode, imageNode); } auto prefs = GetSegmentationPreferences(); - if (prefs.IsNotNull()) + if (prefs != nullptr) { if (m_TaskList->HasLabelNameSuggestions(current)) { auto path = m_TaskList->GetAbsolutePath(m_TaskList->GetLabelNameSuggestions(current)); prefs->PutBool("default label naming", false); - prefs->Put("label suggestions", QString::fromStdString(path.string())); + prefs->Put("label suggestions", path.string()); prefs->PutBool("replace standard suggestions", true); prefs->PutBool("suggest once", true); } else { prefs->PutBool("default label naming", true); prefs->Put("label suggestions", ""); } } m_UnsavedChanges = false; this->SetActiveTaskIndex(current); this->SubscribeToActiveSegmentation(); this->OnCurrentTaskChanged(); } void QmitkSegmentationTaskListWidget::SubscribeToActiveSegmentation() { if (m_ActiveTaskIndex.has_value()) { auto segmentationNode = this->GetSegmentationDataNode(m_ActiveTaskIndex.value()); if (segmentationNode != nullptr) { auto segmentation = static_cast(segmentationNode->GetData()); auto command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationTaskListWidget::OnSegmentationModified); m_SegmentationModifiedObserverTag = segmentation->AddObserver(itk::ModifiedEvent(), command); } } } void QmitkSegmentationTaskListWidget::UnsubscribeFromActiveSegmentation() { if (m_ActiveTaskIndex.has_value() && m_SegmentationModifiedObserverTag.has_value()) { auto segmentationNode = this->GetSegmentationDataNode(m_ActiveTaskIndex.value()); if (segmentationNode != nullptr) { auto segmentation = static_cast(segmentationNode->GetData()); segmentation->RemoveObserver(m_SegmentationModifiedObserverTag.value()); } m_SegmentationModifiedObserverTag.reset(); } } void QmitkSegmentationTaskListWidget::OnSegmentationModified() { if (!m_UnsavedChanges) { m_UnsavedChanges = true; if (m_ActiveTaskIndex.value() == m_CurrentTaskIndex) this->UpdateDetailsLabel(); } } void QmitkSegmentationTaskListWidget::SetActiveTaskIndex(const std::optional& index) { if (m_ActiveTaskIndex != index) { m_ActiveTaskIndex = index; emit ActiveTaskChanged(m_ActiveTaskIndex); } } void QmitkSegmentationTaskListWidget::SetCurrentTaskIndex(const std::optional& index) { if (m_CurrentTaskIndex != index) { m_CurrentTaskIndex = index; this->OnCurrentTaskChanged(); emit CurrentTaskChanged(m_CurrentTaskIndex); } } bool QmitkSegmentationTaskListWidget::ActiveTaskIsShown() const { return m_ActiveTaskIndex.has_value() && m_CurrentTaskIndex.has_value() && m_ActiveTaskIndex == m_CurrentTaskIndex; } bool QmitkSegmentationTaskListWidget::HandleUnsavedChanges(const QString& alternativeTitle) { if (m_UnsavedChanges) { const auto active = m_ActiveTaskIndex.value(); const auto current = m_CurrentTaskIndex.value(); QString title; if (alternativeTitle.isEmpty()) { title = QString("Load task %1").arg(current + 1); if (m_TaskList->HasName(current)) title += ": " + QString::fromStdString(m_TaskList->GetName(current)); } else { title = alternativeTitle; } auto text = QString("The currently active task %1 ").arg(active + 1); if (m_TaskList->HasName(active)) text += "(" + QString::fromStdString(m_TaskList->GetName(active)) + ") "; text += "has unsaved changes."; auto reply = QMessageBox::question(this, title, text, QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel); switch (reply) { case QMessageBox::Save: this->SaveActiveTask(!std::filesystem::exists(m_TaskList->GetResult(active))); break; case QMessageBox::Discard: m_UnsavedChanges = false; break; default: return false; } } return true; } void QmitkSegmentationTaskListWidget::SaveActiveTask(bool saveAsIntermediateResult) { if (!m_ActiveTaskIndex.has_value()) return; QApplication::setOverrideCursor(Qt::BusyCursor); try { const auto active = m_ActiveTaskIndex.value(); m_TaskList->SaveTask(active, this->GetSegmentationDataNode(active)->GetData(), saveAsIntermediateResult); this->OnUnsavedChangesSaved(); } catch (const mitk::Exception& e) { MITK_ERROR << e; } QApplication::restoreOverrideCursor(); } bool QmitkSegmentationTaskListWidget::OnPreShutdown() { return this->HandleUnsavedChanges(QStringLiteral("Application shutdown")); } void QmitkSegmentationTaskListWidget::OnPreviousTaskShortcutActivated() { m_Ui->previousButton->click(); } void QmitkSegmentationTaskListWidget::OnNextTaskShortcutActivated() { m_Ui->nextButton->click(); } void QmitkSegmentationTaskListWidget::OnLoadTaskShortcutActivated() { m_Ui->loadButton->click(); } diff --git a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkExtFileSaveProjectAction.cpp b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkExtFileSaveProjectAction.cpp index f420a3e2e5..1839c5c58a 100644 --- a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkExtFileSaveProjectAction.cpp +++ b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkExtFileSaveProjectAction.cpp @@ -1,177 +1,174 @@ /*============================================================================ 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 "QmitkExtFileSaveProjectAction.h" #include "QmitkFlowApplicationPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include -#include "berryPlatform.h" - QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) , m_Window(nullptr) { this->Init(window.GetPointer()); } QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow* window) : QAction(nullptr) , m_Window(nullptr) { this->Init(window); } void QmitkExtFileSaveProjectAction::Init(berry::IWorkbenchWindow* window) { m_Window = window; this->setText("&Save Project..."); this->setToolTip("Save content of Data Manager as a .mitk project file"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkExtFileSaveProjectAction::Run() { try { /** * @brief stores the last path of last saved file */ static QString m_LastPath; mitk::IDataStorageReference::Pointer dsRef; { ctkPluginContext* context = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext(); mitk::IDataStorageService* dss = nullptr; ctkServiceReference dsServiceRef = context->getServiceReference(); if (dsServiceRef) { dss = context->getService(dsServiceRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dsRef = dss->GetDataStorage(); context->ungetService(dsServiceRef); } mitk::DataStorage::Pointer storage = dsRef->GetDataStorage(); QString dialogTitle = "Save MITK Scene (%1)"; QString fileName = QFileDialog::getSaveFileName(nullptr, dialogTitle.arg(dsRef->GetLabel()), m_LastPath, "MITK scene files (*.mitk)", nullptr ); if (fileName.isEmpty() ) return; // remember the location m_LastPath = fileName; if ( fileName.right(5) != ".mitk" ) fileName += ".mitk"; mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); /* Build list of nodes that should be saved */ mitk::NodePredicateNot::Pointer isNotHelperObject = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true))); mitk::DataStorage::SetOfObjects::ConstPointer nodesToBeSaved = storage->GetSubset(isNotHelperObject); if ( !sceneIO->SaveScene( nodesToBeSaved, storage, fileName.toStdString() ) ) { QMessageBox::information(nullptr, "Scene saving", "Scene could not be written completely. Please check the log.", QMessageBox::Ok); } mitk::ProgressBar::GetInstance()->Progress(2); mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes(); if (!failedNodes->empty()) { std::stringstream ss; ss << "The following nodes could not be serialized:" << std::endl; for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { ss << " - "; if ( mitk::BaseData* data =(*iter)->GetData() ) { ss << data->GetNameOfClass(); } else { ss << "(nullptr)"; } ss << " contained in node '" << (*iter)->GetName() << "'" << std::endl; } MITK_WARN << ss.str(); } mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties(); if (!failedProperties->GetMap()->empty()) { std::stringstream ss; ss << "The following properties could not be serialized:" << std::endl; const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { ss << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'" << std::endl; } MITK_WARN << ss.str(); } } catch (std::exception& e) { MITK_ERROR << "Exception caught during scene saving: " << e.what(); } } diff --git a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationPlugin.cpp b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationPlugin.cpp index e045321fa6..684cd66257 100644 --- a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationPlugin.cpp @@ -1,81 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkFlowApplicationPlugin.h" #include "QmitkFlowApplication.h" #include #include #include +#include + +US_INITIALIZE_MODULE + QmitkFlowApplicationPlugin* QmitkFlowApplicationPlugin::inst = nullptr; QmitkFlowApplicationPlugin::QmitkFlowApplicationPlugin() : _context(nullptr) { inst = this; } QmitkFlowApplicationPlugin::~QmitkFlowApplicationPlugin() { } QmitkFlowApplicationPlugin* QmitkFlowApplicationPlugin::GetDefault() { return inst; } void QmitkFlowApplicationPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->_context = context; QtWidgetsExtRegisterClasses(); BERRY_REGISTER_EXTENSION_CLASS(QmitkFlowApplication, context); ctkServiceReference cmRef = context->getServiceReference(); ctkConfigurationAdmin* configAdmin = nullptr; if (cmRef) { configAdmin = context->getService(cmRef); } // Use the CTK Configuration Admin service to configure the BlueBerry help system if (configAdmin) { ctkConfigurationPtr conf = configAdmin->getConfiguration("org.blueberry.services.help", QString()); ctkDictionary helpProps; helpProps.insert("homePage", "qthelp://org.mitk.gui.qt.flowapplication/bundle/index.html"); conf->update(helpProps); context->ungetService(cmRef); } else { MITK_WARN << "Configuration Admin service unavailable, cannot set home page url."; } } void QmitkFlowApplicationPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = nullptr; } ctkPluginContext* QmitkFlowApplicationPlugin::GetPluginContext() const { return _context; } diff --git a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp index e13edad78c..3ecc52eac8 100644 --- a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp @@ -1,1151 +1,1152 @@ /*============================================================================ 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 "QmitkFlowApplicationWorkbenchWindowAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include #include #include #include #include #include #include #include -#include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkExtFileSaveProjectAction.h" #include #include #include #include #include #include #include +#include +#include +#include // UGLYYY #include "QmitkFlowApplicationWorkbenchWindowAdvisorHack.h" #include "QmitkFlowApplicationPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include #include #include QmitkFlowApplicationWorkbenchWindowAdvisorHack* QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack = new QmitkFlowApplicationWorkbenchWindowAdvisorHack(); QString QmitkFlowApplicationWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkFlowApplicationWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const override { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) override { windowAdvisor->UpdateTitle(false); } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor) { windowAdvisor->UpdateTitle(true); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor) { windowAdvisor->UpdateTitle(false); } } private: QmitkFlowApplicationWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkFlowApplicationWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) , perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const override { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED | Events::CLOSED | Events::OPENED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { if (perspectivesClosed) { QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); } perspectivesClosed = false; } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { QList perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); } } private: QmitkFlowApplicationWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkFlowApplicationWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const override { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) override { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) override { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkFlowApplicationWorkbenchWindowAdvisor* windowAdvisor; }; QmitkFlowApplicationWorkbenchWindowAdvisor::QmitkFlowApplicationWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer) , lastInput(nullptr) , wbAdvisor(wbAdvisor) , showViewToolbar(true) , showVersionInfo(true) , showMitkVersionInfo(true) , showMemoryIndicator(true) , dropTargetListener(new QmitkDefaultDropTargetListener) { productName = QCoreApplication::applicationName(); viewExcludeList.push_back("org.mitk.views.viewnavigator"); } QmitkFlowApplicationWorkbenchWindowAdvisor::~QmitkFlowApplicationWorkbenchWindowAdvisor() { } QWidget* QmitkFlowApplicationWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent) { QWidget* parentWidget = static_cast(parent); auto label = new QLabel(parentWidget); label->setText("No perspectives are open. Open a perspective in the Window->Open Perspective menu."); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show) { showMemoryIndicator = show; } bool QmitkFlowApplicationWorkbenchWindowAdvisor::GetShowMemoryIndicator() { return showMemoryIndicator; } void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkFlowApplicationWorkbenchWindowAdvisor::SetProductName(const QString& product) { productName = product; } void QmitkFlowApplicationWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon) { windowIcon = wndIcon; } void QmitkFlowApplicationWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = qobject_cast (window->GetShell()->GetControl()); if (!windowIcon.isEmpty()) { mainWindow->setWindowIcon(QIcon(windowIcon)); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); // Load icon theme QIcon::setThemeSearchPaths(QStringList() << QStringLiteral(":/org_mitk_icons/icons/")); QIcon::setThemeName(QStringLiteral("awesome")); // ==== Application menu ============================ QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ menuBar->setNativeMenuBar(true); #else menuBar->setNativeMenuBar(false); #endif auto basePath = QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/"); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg")); auto perspGroup = new QActionGroup(menuBar); std::map VDMap; // sort elements (converting vector to map...) QList::const_iterator iter; berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const QList viewDescriptors = viewRegistry->GetViews(); bool skip = false; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { // if viewExcludeList is set, it contains the id-strings of view, which // should not appear as an menu-entry in the menu if (viewExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; if ((*iter)->GetId() == "org.mitk.views.imagenavigator") continue; if ((*iter)->GetId() == "org.mitk.views.viewnavigator") continue; std::pair p((*iter)->GetLabel(), (*iter)); VDMap.insert(p); } std::map::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); viewActions.push_back(viewAction); } QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); fileMenu->addAction(fileSaveProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "system-log-out.svg")); fileExitAction->setShortcut(QKeySequence::Quit); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"), "&Undo", QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), QKeySequence("CTRL+Z")); undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"), "&Redo", QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), QKeySequence("CTRL+Y")); redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); // ==== Window Menu ========================== QMenu* windowMenu = menuBar->addMenu("Window"); QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); windowMenu->addSeparator(); resetPerspAction = windowMenu->addAction("&Reset Perspective", QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); windowMenu->addSeparator(); windowMenu->addAction("&Preferences...", QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), QKeySequence("CTRL+P")); // fill perspective menu berry::IPerspectiveRegistry* perspRegistry = window->GetWorkbench()->GetPerspectiveRegistry(); QList perspectives( perspRegistry->GetPerspectives()); skip = false; for (QList::iterator perspIt = perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup); mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction); } perspMenu->addActions(perspGroup->actions()); // ===== Help menu ==================================== QMenu* helpMenu = menuBar->addMenu("&Help"); helpMenu->addAction("&Welcome",this, SLOT(onIntro())); helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); helpMenu->addAction("&About",this, SLOT(onAbout())); // ===================================================== // toolbar for showing file open, undo, redo and other main actions auto mainActionsToolBar = new QToolBar; mainActionsToolBar->setObjectName("mainActionsToolBar"); mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif basePath = QStringLiteral(":/org.mitk.gui.qt.ext/"); imageNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(basePath + "image_navigator.svg"), "&Image Navigator", nullptr); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (imageNavigatorViewFound) { QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); imageNavigatorAction->setCheckable(true); // add part listener for image navigator imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction)); window->GetPartService()->AddPartListener(imageNavigatorPartListener.data()); berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); imageNavigatorAction->setChecked(false); if (imageNavigatorView) { bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) imageNavigatorAction->setChecked(true); } imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image"); } mainActionsToolBar->addAction(undoAction); mainActionsToolBar->addAction(redoAction); if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } mainWindow->addToolBar(mainActionsToolBar); // ==== View Toolbar ================================== if (showViewToolbar) { - auto prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); - berry::IPreferences::Pointer stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); bool showCategoryNames = stylePrefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true); // Order view descriptors by category QMultiMap categoryViewDescriptorMap; for (auto labelViewDescriptorPair : VDMap) { auto viewDescriptor = labelViewDescriptorPair.second; auto category = !viewDescriptor->GetCategoryPath().isEmpty() ? viewDescriptor->GetCategoryPath().back() : QString(); categoryViewDescriptorMap.insert(category, viewDescriptor); } // Create a separate toolbar for each category for (auto category : categoryViewDescriptorMap.uniqueKeys()) { auto viewDescriptorsInCurrentCategory = categoryViewDescriptorMap.values(category); QList > relevantViewDescriptors; for (auto viewDescriptor : viewDescriptorsInCurrentCategory) { if (viewDescriptor->GetId() != "org.mitk.views.flow.control") { relevantViewDescriptors.push_back(viewDescriptor); } } if (!relevantViewDescriptors.isEmpty()) { auto toolbar = new QToolBar; toolbar->setObjectName(category + " View Toolbar"); mainWindow->addToolBar(toolbar); if (showCategoryNames && !category.isEmpty()) { auto categoryButton = new QToolButton; categoryButton->setToolButtonStyle(Qt::ToolButtonTextOnly); categoryButton->setText(category); categoryButton->setStyleSheet("background: transparent; margin: 0; padding: 0;"); toolbar->addWidget(categoryButton); connect(categoryButton, &QToolButton::clicked, [toolbar]() { for (QWidget* widget : toolbar->findChildren()) { if (QStringLiteral("qt_toolbar_ext_button") == widget->objectName() && widget->isVisible()) { QMouseEvent pressEvent(QEvent::MouseButtonPress, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QMouseEvent releaseEvent(QEvent::MouseButtonRelease, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(widget, &pressEvent); QApplication::sendEvent(widget, &releaseEvent); } } }); } for (auto viewDescriptor : relevantViewDescriptors) { auto viewAction = new berry::QtShowViewAction(window, viewDescriptor); toolbar->addAction(viewAction); } } } } QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); auto qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar auto statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); auto progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); mainWindow->setStatusBar(qStatusBar); if (showMemoryIndicator) { auto memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } } void QmitkFlowApplicationWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this)); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data()); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener.data()); } void QmitkFlowApplicationWorkbenchWindowAdvisor::PostWindowOpen() { berry::WorkbenchWindowAdvisor::PostWindowOpen(); // Force Rendering Window Creation on startup. berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); ctkPluginContext* context = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService *dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef)); mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput); } } } void QmitkFlowApplicationWorkbenchWindowAdvisor::onIntro() { QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkFlowApplicationWorkbenchWindowAdvisor::onHelp() { QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkFlowApplicationWorkbenchWindowAdvisor::onHelpOpenHelpPerspective() { QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective(); } void QmitkFlowApplicationWorkbenchWindowAdvisor::onAbout() { QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onAbout(); } void QmitkFlowApplicationWorkbenchWindowAdvisor::HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener.reset(new PartListenerForTitle(this)); titlePerspectiveListener.reset(new PerspectiveListenerForTitle(this)); editorPropertyListener.reset(new berry::PropertyChangeIntAdapter< QmitkFlowApplicationWorkbenchWindowAdvisor>(this, &QmitkFlowApplicationWorkbenchWindowAdvisor::PropertyChange)); configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener.data()); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data()); } QString QmitkFlowApplicationWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } QString title; berry::IProduct::Pointer product = berry::Platform::GetProduct(); if (product.IsNotNull()) { title = product->GetName(); } if (title.isEmpty()) { // instead of the product name, we use a custom variable for now title = productName; } if(showMitkVersionInfo) { QString mitkVersionInfo = MITK_REVISION_DESC; if(mitkVersionInfo.isEmpty()) mitkVersionInfo = MITK_VERSION_STRING; title += " " + mitkVersionInfo; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 | VTK %4.%5.%6 | Qt %7)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR); title += versions; } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.isEmpty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); QString label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.isEmpty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkFlowApplicationWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); QString oldTitle = configurer->GetTitle(); QString newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkFlowApplicationWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = nullptr; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = nullptr; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } auto lockedLastActiveEditor = lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull()) { lockedLastActiveEditor->RemovePropertyListener(editorPropertyListener.data()); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener.data()); } RecomputeTitle(); } void QmitkFlowApplicationWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { auto lockedLastActiveEditor = lastActiveEditor.Lock(); if (lockedLastActiveEditor.IsNotNull()) { QString newTitle = lockedLastActiveEditor->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkFlowApplicationWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList& v) { this->perspectiveExcludeList = v; } QList QmitkFlowApplicationWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkFlowApplicationWorkbenchWindowAdvisor::SetViewExcludeList(const QList& v) { this->viewExcludeList = v; } QList QmitkFlowApplicationWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkFlowApplicationWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkFlowApplicationWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkFlowApplicationWorkbenchWindowAdvisorHack::QmitkFlowApplicationWorkbenchWindowAdvisorHack() : QObject() { } QmitkFlowApplicationWorkbenchWindowAdvisorHack::~QmitkFlowApplicationWorkbenchWindowAdvisorHack() { } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast(model)) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast(model)) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } // safe calls to the complete chain // berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); // to cover for all possible cases of closed pages etc. static void SafeHandleNavigatorView(QString view_query_name) { berry::IWorkbench* wbench = berry::PlatformUI::GetWorkbench(); if (wbench == nullptr) return; berry::IWorkbenchWindow::Pointer wbench_window = wbench->GetActiveWorkbenchWindow(); if (wbench_window.IsNull()) return; berry::IWorkbenchPage::Pointer wbench_page = wbench_window->GetActivePage(); if (wbench_page.IsNull()) return; auto wbench_view = wbench_page->FindView(view_query_name); if (wbench_view.IsNotNull()) { bool isViewVisible = wbench_page->IsPartVisible(wbench_view); if (isViewVisible) { wbench_page->HideView(wbench_view); return; } } wbench_page->ShowView(view_query_name); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onImageNavigator() { // show/hide ImageNavigatorView SafeHandleNavigatorView("org.mitk.views.imagenavigator"); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(nullptr, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext(); if (context == nullptr) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = nullptr; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == nullptr) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onAbout() { auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(), nullptr); aboutDialog->open(); } diff --git a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp index b946c576c1..84b00c4397 100644 --- a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp +++ b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp @@ -1,285 +1,269 @@ /*============================================================================ 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 "org_mitk_gui_qt_matchpoint_algorithm_browser_Activator.h" // Blueberry #include #include -#include // Qmitk #include "QmitkMatchPointBrowser.h" // Qt #include #include #include #include //MITK #include #include "MatchPointBrowserConstants.h" #include "mitkAlgorithmInfoSelectionProvider.h" +#include +#include +#include // MatchPoint #include "mapRegistrationAlgorithmInterface.h" #include "mapAlgorithmEvents.h" #include "mapAlgorithmWrapperEvent.h" #include "mapExceptionObjectMacros.h" #include "mapDeploymentDLLDirectoryBrowser.h" #include "mapDeploymentEvents.h" const std::string QmitkMatchPointBrowser::VIEW_ID = "org.mitk.views.matchpoint.algorithm.browser"; QmitkMatchPointBrowser::QmitkMatchPointBrowser() : m_Parent(nullptr), m_LoadedDLLHandle(nullptr), m_LoadedAlgorithm(nullptr) { } QmitkMatchPointBrowser::~QmitkMatchPointBrowser() { } -void QmitkMatchPointBrowser::OnPreferencesChanged(const berry::IBerryPreferences* /*prefs*/) +void QmitkMatchPointBrowser::OnPreferencesChanged(const mitk::IPreferences* /*prefs*/) { this->OnSearchFolderButtonPushed(); } void QmitkMatchPointBrowser::CreateConnections() { connect(m_Controls.m_pbSearchFolder, SIGNAL(clicked()), this, SLOT(OnSearchFolderButtonPushed())); connect(m_Controls.m_algoTreeView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(OnAlgoListSelectionChanged(const QModelIndex&))); connect(m_Controls.pbClearSearch, SIGNAL(clicked()), m_Controls.lineSearch, SLOT(clear())); connect(m_Controls.lineSearch, SIGNAL(textChanged(const QString&)), this, SLOT(OnSearchChanged(const QString&))); } void QmitkMatchPointBrowser::OnSearchFolderButtonPushed() { RetrieveAndStorePreferenceValues(); // test if some folder list non-empty int folderCount = m_currentSearchPaths.count(); if (!folderCount) { Error(QString("No search folder selected for MatchPoint algorithm browser! Please set search paths in the MatchPoint preference page.")); m_DLLInfoList.clear(); } else { map::deployment::DLLDirectoryBrowser::Pointer browser = map::deployment::DLLDirectoryBrowser::New(); auto validCommand = ::itk::MemberCommand::New(); validCommand->SetCallbackFunction(this, &QmitkMatchPointBrowser::OnValidDeploymentEvent); browser->AddObserver(::map::events::ValidDLLEvent(), validCommand); auto invalidCommand = ::itk::MemberCommand::New(); invalidCommand->SetCallbackFunction(this, &QmitkMatchPointBrowser::OnInvalidDeploymentEvent); browser->AddObserver(::map::events::InvalidDLLEvent(), invalidCommand); foreach(QString path, m_currentSearchPaths) { browser->addDLLSearchLocation(path.toStdString()); } browser->update(); m_DLLInfoList = browser->getLibraryInfos(); } m_Controls.groupWarning->setVisible(m_DLLInfoList.empty()); m_Controls.groupList->setVisible(!m_DLLInfoList.empty()); m_algModel->SetAlgorithms(m_DLLInfoList); m_Controls.lineSearch->clear(); } void QmitkMatchPointBrowser::OnAlgoListSelectionChanged(const QModelIndex& index) { QVariant vIndex = index.data(Qt::UserRole).toInt(); map::deployment::DLLInfo::ConstPointer currentItemInfo = nullptr; if (vIndex.isValid()) { std::size_t algListIndex = vIndex.toInt(); if (algListIndex < m_DLLInfoList.size()) { currentItemInfo = m_DLLInfoList[algListIndex]; } } m_Controls.m_teAlgorithmDetails->updateInfo(currentItemInfo); if (currentItemInfo) { //update selection provider mitk::MAPAlgorithmInfoSelection::Pointer infoSelection = mitk::MAPAlgorithmInfoSelection::Pointer( new mitk::MAPAlgorithmInfoSelection(currentItemInfo)); this->m_SelectionProvider->SetInfoSelection(infoSelection); } } void QmitkMatchPointBrowser::OnSearchChanged(const QString& text) { m_filterProxy->setFilterRegExp(text); m_filterProxy->setFilterCaseSensitivity(Qt::CaseInsensitive); }; void QmitkMatchPointBrowser::OnInvalidDeploymentEvent(const ::itk::Object *, const itk::EventObject &event) { auto deployEvent = dynamic_cast(&event); this->Error(QString("Error when try to inspect deployed registration algorithm. Details: ")+QString::fromStdString(deployEvent->getComment())); } void QmitkMatchPointBrowser::OnValidDeploymentEvent(const ::itk::Object *, const itk::EventObject &event) { auto deployEvent = dynamic_cast(&event); auto info = static_cast(deployEvent->getData()); MITK_INFO << "Successfully inspected deployed registration algorithm. UID: " << info->getAlgorithmUID().toStr() << ". Path: " << info->getLibraryFilePath(); } void QmitkMatchPointBrowser::CreateQtPartControl(QWidget* parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); m_Parent = parent; m_algModel = new QmitkAlgorithmListModel(parent); m_filterProxy = new QSortFilterProxyModel(parent); //! [Qt Selection Provider registration] // create new qt selection provider m_SelectionProvider = new mitk::AlgorithmInfoSelectionProvider(); m_filterProxy->setSourceModel(m_algModel); m_filterProxy->setDynamicSortFilter(true); m_filterProxy->setFilterKeyColumn(-1); m_Controls.m_algoTreeView->setModel(m_filterProxy); m_Controls.m_algoTreeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.m_algoTreeView->header()->setStretchLastSection(false); m_Controls.m_algoTreeView->header()->setSectionResizeMode(0, QHeaderView::Stretch); m_Controls.m_algoTreeView->setColumnHidden(3, true); this->CreateConnections(); } void QmitkMatchPointBrowser::SetSelectionProvider() { this->GetSite()->SetSelectionProvider(m_SelectionProvider); } void QmitkMatchPointBrowser::SetFocus() { } void QmitkMatchPointBrowser::Error(QString msg) { mitk::StatusBar::GetInstance()->DisplayErrorText(msg.toLatin1()); MITK_ERROR << msg.toStdString().c_str(); } void QmitkMatchPointBrowser::RetrieveAndStorePreferenceValues() { - berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); + auto* prefs = this->RetrievePreferences(); - bool loadApplicationDir = prefs->GetBool( - MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR.c_str(), true); - bool loadHomeDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR.c_str(), false); - bool loadCurrentDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR.c_str(), - false); - bool loadAutoLoadDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR.c_str(), - false); + bool loadApplicationDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, true); + bool loadHomeDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, false); + bool loadCurrentDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, false); + bool loadAutoLoadDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, false); // Get some default application paths. QStringList newPaths; // Here we can use the preferences to set up the builder, if (loadApplicationDir) { newPaths << QCoreApplication::applicationDirPath(); } if (loadHomeDir) { newPaths << QDir::homePath(); } if (loadCurrentDir) { newPaths << QDir::currentPath(); } if (loadAutoLoadDir) { char* deployedAlgorithmLoadPath = getenv("MAP_MDRA_LOAD_PATH"); if (deployedAlgorithmLoadPath != nullptr) { // The load path may in fact be a semi-colon or colon separated list of directories, not just one. QString paths(deployedAlgorithmLoadPath); #ifdef Q_OS_WIN32 QString pathSeparator(";"); #else QString pathSeparator(":"); #endif QStringList splitPath = paths.split(pathSeparator, QString::SkipEmptyParts); foreach(QString path, splitPath) { QDir dir = QDir(path); newPaths << dir.absolutePath(); } } } // We get additional directory paths from preferences. - QString pathString = prefs->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME.c_str(), - tr("")); + const auto pathString = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, "")); QStringList additionalPaths = pathString.split(";", QString::SkipEmptyParts); newPaths << additionalPaths; - QString additionalAlgorirthmsString = prefs->Get( - MatchPointBrowserConstants::MDAR_FILES_NODE_NAME.c_str(), tr("")); + const auto additionalAlgorirthmsString = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, "")); additionalPaths = additionalAlgorirthmsString.split(";", QString::SkipEmptyParts); newPaths << additionalPaths; m_currentSearchPaths = newPaths; } -berry::IBerryPreferences::Pointer QmitkMatchPointBrowser::RetrievePreferences() +mitk::IPreferences* QmitkMatchPointBrowser::RetrievePreferences() { - berry::IPreferencesService* prefService - = berry::Platform::GetPreferencesService(); - - assert(prefService); - - QString id = tr("/") + QString::fromStdString(MatchPointBrowserConstants::VIEW_ID); - berry::IBerryPreferences::Pointer prefs - = (prefService->GetSystemPreferences()->Node(id)) - .Cast(); - - assert(prefs); - - return prefs; + const auto id = "/" + MatchPointBrowserConstants::VIEW_ID; + return mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node(id); } - - diff --git a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.h b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.h index 9aaab74c8c..c8e526bd6d 100644 --- a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.h +++ b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.h @@ -1,125 +1,122 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __Q_MITK_MATCHPOINT_H #define __Q_MITK_MATCHPOINT_H #include #include -#include -#include -#include //QT #include // MatchPoint #include #include #include #include "ui_QmitkMatchPointBrowserControls.h" #include "QmitkMAPAlgorithmModel.h" #include "QmitkAlgorithmListModel.h" #include "mitkAlgorithmInfoSelectionProvider.h" /*! \brief MatchPoint \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \ingroup ${plugin_target}_internal */ class QmitkMatchPointBrowser : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; /** * Creates smartpointer typedefs */ berryObjectMacro(QmitkMatchPointBrowser); QmitkMatchPointBrowser(); ~QmitkMatchPointBrowser() override; /** * \brief Called by the framework to indicate that the preferences have changed. * \param prefs not used, as we call RetrievePreferenceValues(). */ - void OnPreferencesChanged(const berry::IBerryPreferences* prefs) override; + void OnPreferencesChanged(const mitk::IPreferences* prefs) override; protected slots: /** * @brief Connect all GUI elements to its corresponding slots */ virtual void CreateConnections(); /// \brief Called when the user clicks the GUI button void OnSearchFolderButtonPushed(); void OnAlgoListSelectionChanged(const QModelIndex&); void OnSearchChanged(const QString&); protected: void CreateQtPartControl(QWidget* parent) override; void SetFocus() override; Ui::MatchPointBrowserControls m_Controls; //! [Qt Selection Provider] /** @brief this pointer holds the selection provider*/ mitk::AlgorithmInfoSelectionProvider::Pointer m_SelectionProvider; //! [Qt Selection Provider] private: void SetSelectionProvider() override; void Error(QString msg); /** * \brief Called on startup and by OnPreferencesChanged to load all * preferences except the temporary folder into member variables. */ void RetrieveAndStorePreferenceValues(); void OnInvalidDeploymentEvent(const ::itk::Object *, const itk::EventObject &event); void OnValidDeploymentEvent(const ::itk::Object *, const itk::EventObject &event); /** * \brief Called to get hold of the actual preferences node. */ - berry::IBerryPreferences::Pointer RetrievePreferences(); + mitk::IPreferences* RetrievePreferences(); QWidget* m_Parent; ::map::deployment::DLLDirectoryBrowser::DLLInfoListType m_DLLInfoList; QStringList m_currentSearchPaths; QmitkAlgorithmListModel* m_algModel; QSortFilterProxyModel* m_filterProxy; ::map::deployment::DLLHandle::Pointer m_LoadedDLLHandle; ::map::algorithm::RegistrationAlgorithmBase::Pointer m_LoadedAlgorithm; }; #endif // MatchPoint_h diff --git a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/org_mitk_gui_qt_matchpoint_algorithm_browser_Activator.cpp b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/org_mitk_gui_qt_matchpoint_algorithm_browser_Activator.cpp index ecdb33462d..0d291577fb 100644 --- a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/org_mitk_gui_qt_matchpoint_algorithm_browser_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/org_mitk_gui_qt_matchpoint_algorithm_browser_Activator.cpp @@ -1,36 +1,40 @@ /*============================================================================ 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 "org_mitk_gui_qt_matchpoint_algorithm_browser_Activator.h" #include "QmitkMatchPointBrowser.h" +#include + +US_INITIALIZE_MODULE + ctkPluginContext* org_mitk_gui_qt_matchpoint_algorithm_browser_Activator::m_Context = nullptr; void org_mitk_gui_qt_matchpoint_algorithm_browser_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkMatchPointBrowser, context) m_Context = context; } void org_mitk_gui_qt_matchpoint_algorithm_browser_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_Context = nullptr; } ctkPluginContext* org_mitk_gui_qt_matchpoint_algorithm_browser_Activator::GetContext() { return m_Context; } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp index c2fcf07cde..b8e94d8bc7 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPart.cpp @@ -1,223 +1,217 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMitkWorkbenchIntroPart.h" #include "QmitkMitkWorkbenchIntroPlugin.h" #include -#include -#include #include #include #include #include #include #include +#include +#include +#include #include #include #include class QmitkMitkWorkbenchIntroPart::Impl { public: Impl() : View(nullptr) { } ~Impl() { } QWebEngineView* View; private: Impl(const Impl&); Impl& operator=(const Impl&); }; namespace { class QmitkWebEnginePage final : public QWebEnginePage { public: explicit QmitkWebEnginePage(QmitkMitkWorkbenchIntroPart* introPart, QObject* parent = nullptr); ~QmitkWebEnginePage() override; private: bool acceptNavigationRequest(const QUrl& url, NavigationType type, bool isMainFrame) override; QmitkMitkWorkbenchIntroPart* m_IntroPart; }; QmitkWebEnginePage::QmitkWebEnginePage(QmitkMitkWorkbenchIntroPart* introPart, QObject* parent) : QWebEnginePage(parent), m_IntroPart(introPart) { } QmitkWebEnginePage::~QmitkWebEnginePage() { } bool QmitkWebEnginePage::acceptNavigationRequest(const QUrl& url, NavigationType, bool) { QString scheme = url.scheme(); if (scheme.contains("mitk")) { if (url.path().isEmpty()) return false; if (url.host().contains("perspectives")) { QString id = url.path().simplified().replace("/", ""); auto introSite = m_IntroPart->GetIntroSite(); auto workbenchWindow = introSite->GetWorkbenchWindow(); auto workbench = workbenchWindow->GetWorkbench(); workbench->ShowPerspective(id, workbenchWindow); auto context = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPluginContext(); auto serviceReference = context->getServiceReference(); mitk::IDataStorageService* service = serviceReference ? context->getService(serviceReference) : nullptr; if (service) { berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(service->GetActiveDataStorage())); auto page = introSite->GetPage(); auto editorPart = page->FindEditor(editorInput); if (editorPart.IsNotNull()) page->Activate(editorPart); } } } else if (scheme.contains("https")) { QDesktopServices::openUrl(url); } else { return true; } return false; } } QmitkMitkWorkbenchIntroPart::QmitkMitkWorkbenchIntroPart() : m_Controls(nullptr), m_Impl(new Impl) { - berry::IPreferences::Pointer workbenchPrefs = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); + auto* workbenchPrefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } QmitkMitkWorkbenchIntroPart::~QmitkMitkWorkbenchIntroPart() { // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false - if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) - { - berry::IPreferences::Pointer workbenchPrefs = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); - workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false); - workbenchPrefs->Flush(); - } - else - { - berry::IPreferences::Pointer workbenchPrefs = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); - workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); - workbenchPrefs->Flush(); - } + bool showIntro = this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing(); + + auto* workbenchPrefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences(); + workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, showIntro); + workbenchPrefs->Flush(); // if workbench is not closing (Just welcome screen closing), open last used perspective if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId() == "org.mitk.mitkworkbench.perspectives.editor" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.mitkworkbench.perspectives.editor"); if (perspective) { this->GetIntroSite()->GetPage()->SetPerspective(perspective); } } delete m_Impl; } void QmitkMitkWorkbenchIntroPart::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkWelcomeScreenViewControls; m_Controls->setupUi(parent); // create a QWebView as well as a QWebPage and QWebFrame within the QWebview m_Impl->View = new QWebEngineView(parent); this->CreateConnections(); auto page = new QmitkWebEnginePage(this, parent); m_Impl->View->setPage(page); QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/index.html"), QUrl::TolerantMode); m_Impl->View->load( urlQtResource ); // adds the webview as a widget parent->layout()->addWidget(m_Impl->View); } } void QmitkMitkWorkbenchIntroPart::CreateConnections() { connect(m_Impl->View, &QWebEngineView::loadFinished, this, &QmitkMitkWorkbenchIntroPart::OnLoadFinished); } void QmitkMitkWorkbenchIntroPart::StandbyStateChanged(bool /*standby*/) { } void QmitkMitkWorkbenchIntroPart::SetFocus() { } void QmitkMitkWorkbenchIntroPart::ReloadPage() { if (m_Impl->View != nullptr) m_Impl->View->reload(); } void QmitkMitkWorkbenchIntroPart::OnLoadFinished(bool ok) { if (!ok) return; - auto prefs = QmitkMitkWorkbenchIntroPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.qt.extapplicationintro"); + auto* prefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.qt.extapplicationintro"); bool showTips = prefs->GetBool("show tips", true); if (showTips) { m_Impl->View->page()->runJavaScript("showRandomTip(); showTips()"); } else { m_Impl->View->page()->runJavaScript("hideTips()"); } } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp index a0af12b0f1..f78e96fb19 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPlugin.cpp @@ -1,55 +1,59 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMitkWorkbenchIntroPlugin.h" #include "QmitkMitkWorkbenchIntroPart.h" #include "QmitkMitkWorkbenchIntroPreferencePage.h" #include #include #include #include #include #include +#include + +US_INITIALIZE_MODULE + QmitkMitkWorkbenchIntroPlugin* QmitkMitkWorkbenchIntroPlugin::inst = nullptr; QmitkMitkWorkbenchIntroPlugin::QmitkMitkWorkbenchIntroPlugin() { inst = this; } QmitkMitkWorkbenchIntroPlugin::~QmitkMitkWorkbenchIntroPlugin() { } QmitkMitkWorkbenchIntroPlugin* QmitkMitkWorkbenchIntroPlugin::GetDefault() { return inst; } void QmitkMitkWorkbenchIntroPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkMitkWorkbenchIntroPart, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkMitkWorkbenchIntroPreferencePage, context) } ctkPluginContext* QmitkMitkWorkbenchIntroPlugin::GetPluginContext() const { return context; } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp index f1222ec90f..f5e91ecde4 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp @@ -1,76 +1,78 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMitkWorkbenchIntroPreferencePage.h" #include "QmitkMitkWorkbenchIntroPart.h" -#include -#include #include +#include +#include +#include + #include QmitkMitkWorkbenchIntroPreferencePage::QmitkMitkWorkbenchIntroPreferencePage() : m_Ui(new Ui::QmitkMitkWorkbenchIntroPreferencePage), m_Control(nullptr) { } QmitkMitkWorkbenchIntroPreferencePage::~QmitkMitkWorkbenchIntroPreferencePage() { } void QmitkMitkWorkbenchIntroPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkMitkWorkbenchIntroPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); m_MitkWorkbenchIntroPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.qt.extapplicationintro"); m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); this->Update(); } QWidget* QmitkMitkWorkbenchIntroPreferencePage::GetQtControl() const { return m_Control; } bool QmitkMitkWorkbenchIntroPreferencePage::PerformOk() { m_MitkWorkbenchIntroPreferencesNode->PutBool("show tips", m_Ui->showTipsCheckBox->isChecked()); auto intro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->GetIntro(); if (intro.IsNotNull()) { auto* workbenchIntro = dynamic_cast(intro.GetPointer()); if (workbenchIntro != nullptr) workbenchIntro->ReloadPage(); } return true; } void QmitkMitkWorkbenchIntroPreferencePage::PerformCancel() { } void QmitkMitkWorkbenchIntroPreferencePage::Update() { m_Ui->showTipsCheckBox->setChecked(m_MitkWorkbenchIntroPreferencesNode->GetBool("show tips", true)); } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h index e41d1e0c89..0e125b12ca 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h @@ -1,46 +1,51 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkMitkWorkbenchIntroPreferencePage_h #define QmitkMitkWorkbenchIntroPreferencePage_h #include +namespace mitk +{ + class IPreferences; +} + namespace Ui { class QmitkMitkWorkbenchIntroPreferencePage; } class QmitkMitkWorkbenchIntroPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkMitkWorkbenchIntroPreferencePage(); ~QmitkMitkWorkbenchIntroPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; private: - berry::IPreferences::Pointer m_MitkWorkbenchIntroPreferencesNode; + mitk::IPreferences* m_MitkWorkbenchIntroPreferencesNode; Ui::QmitkMitkWorkbenchIntroPreferencePage* m_Ui; QWidget* m_Control; }; #endif diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp index 2226e032cc..76e94a407e 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp @@ -1,657 +1,659 @@ /*============================================================================ 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 "QmitkMovieMakerView.h" #include #include "QmitkAnimationItemDelegate.h" #include "QmitkOrbitAnimationItem.h" #include "QmitkOrbitAnimationWidget.h" #include "QmitkSliceAnimationItem.h" #include "QmitkSliceAnimationWidget.h" #include "QmitkTimeSliceAnimationItem.h" #include "QmitkTimeSliceAnimationWidget.h" -#include +#include +#include +#include #include #include #include #include #include #include #include namespace { QmitkAnimationItem* CreateDefaultAnimation(const QString& widgetKey) { if (widgetKey == "Orbit") return new QmitkOrbitAnimationItem; if (widgetKey == "Slice") return new QmitkSliceAnimationItem; if (widgetKey == "Time") return new QmitkTimeSliceAnimationItem; return nullptr; } QString GetFFmpegPath() { - auto preferences = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.gui.qt.ext.externalprograms"); + auto* preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.gui.qt.ext.externalprograms"); - return preferences.IsNotNull() - ? preferences->Get("ffmpeg", "") - : ""; + return preferences != nullptr + ? QString::fromStdString(preferences->Get("ffmpeg", "")) + : QString(); } void ReadPixels(std::unique_ptr& frame, vtkRenderWindow* renderWindow, int x, int y, int width, int height) { if (nullptr == renderWindow) return; renderWindow->MakeCurrent(); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, frame.get()); } } const std::string QmitkMovieMakerView::VIEW_ID = "org.mitk.views.moviemaker"; QmitkMovieMakerView::QmitkMovieMakerView() : m_FFmpegWriter(nullptr), m_Ui(new Ui::QmitkMovieMakerView), m_AnimationModel(nullptr), m_AddAnimationMenu(nullptr), m_RecordMenu(nullptr), m_Timer(nullptr), m_TotalDuration(0.0), m_NumFrames(0), m_CurrentFrame(0) { } QmitkMovieMakerView::~QmitkMovieMakerView() { } void QmitkMovieMakerView::CreateQtPartControl(QWidget* parent) { m_FFmpegWriter = new QmitkFFmpegWriter(parent); m_Ui->setupUi(parent); this->InitializeAnimationWidgets(); this->InitializeAnimationTreeViewWidgets(); this->InitializePlaybackAndRecordWidgets(); this->InitializeTimer(parent); m_Ui->animationWidgetGroupBox->setVisible(false); } void QmitkMovieMakerView::InitializeAnimationWidgets() { m_AnimationWidgets["Orbit"] = new QmitkOrbitAnimationWidget; m_AnimationWidgets["Slice"] = new QmitkSliceAnimationWidget; m_AnimationWidgets["Time"] = new QmitkTimeSliceAnimationWidget; for (const auto& widget : m_AnimationWidgets) { if (nullptr != widget.second) { widget.second->setVisible(false); m_Ui->animationWidgetGroupBoxLayout->addWidget(widget.second); } } this->ConnectAnimationWidgets(); } void QmitkMovieMakerView::InitializeAnimationTreeViewWidgets() { this->InitializeAnimationModel(); this->InitializeAddAnimationMenu(); this->ConnectAnimationTreeViewWidgets(); } void QmitkMovieMakerView::InitializePlaybackAndRecordWidgets() { this->InitializeRecordMenu(); this->ConnectPlaybackAndRecordWidgets(); } void QmitkMovieMakerView::InitializeAnimationModel() { m_AnimationModel = new QStandardItemModel(m_Ui->animationTreeView); m_AnimationModel->setHorizontalHeaderLabels(QStringList() << "Animation" << "Timeline"); m_Ui->animationTreeView->setModel(m_AnimationModel); m_Ui->animationTreeView->setItemDelegate(new QmitkAnimationItemDelegate(m_Ui->animationTreeView)); } void QmitkMovieMakerView::InitializeAddAnimationMenu() { m_AddAnimationMenu = new QMenu(m_Ui->addAnimationButton); for(const auto& widget : m_AnimationWidgets) m_AddAnimationMenu->addAction(widget.first); } void QmitkMovieMakerView::InitializeRecordMenu() { std::array, 4> renderWindows = { std::make_pair(QStringLiteral("Axial"), QStringLiteral("stdmulti.widget0")), std::make_pair(QStringLiteral("Sagittal"), QStringLiteral("stdmulti.widget1")), std::make_pair(QStringLiteral("Coronal"), QStringLiteral("stdmulti.widget2")), std::make_pair(QStringLiteral("3D"), QStringLiteral("stdmulti.widget3")) }; m_RecordMenu = new QMenu(m_Ui->recordButton); for(const auto& renderWindow : renderWindows) { auto* action = new QAction(m_RecordMenu); action->setText(renderWindow.first); action->setData(renderWindow.second); m_RecordMenu->addAction(action); } } void QmitkMovieMakerView::InitializeTimer(QWidget* parent) { m_Timer = new QTimer(parent); this->OnFPSSpinBoxValueChanged(m_Ui->fpsSpinBox->value()); this->ConnectTimer(); } void QmitkMovieMakerView::ConnectAnimationTreeViewWidgets() { connect(m_AnimationModel, &QStandardItemModel::rowsInserted, this, &QmitkMovieMakerView::OnAnimationTreeViewRowsInserted); connect(m_AnimationModel, &QStandardItemModel::rowsRemoved, this, &QmitkMovieMakerView::OnAnimationTreeViewRowsRemoved); connect(m_Ui->animationTreeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QmitkMovieMakerView::OnAnimationTreeViewSelectionChanged); connect(m_Ui->moveAnimationUpButton, &QToolButton::clicked, this, &QmitkMovieMakerView::OnMoveAnimationUpButtonClicked); connect(m_Ui->moveAnimationDownButton, &QToolButton::clicked, this, &QmitkMovieMakerView::OnMoveAnimationDownButtonClicked); connect(m_Ui->addAnimationButton, &QToolButton::clicked, this, &QmitkMovieMakerView::OnAddAnimationButtonClicked); connect(m_Ui->removeAnimationButton, &QToolButton::clicked, this, &QmitkMovieMakerView::OnRemoveAnimationButtonClicked); } void QmitkMovieMakerView::ConnectAnimationWidgets() { connect(m_Ui->startComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnStartComboBoxCurrentIndexChanged(int))); connect(m_Ui->durationSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnDurationSpinBoxValueChanged(double))); connect(m_Ui->delaySpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnDelaySpinBoxValueChanged(double))); } void QmitkMovieMakerView::ConnectPlaybackAndRecordWidgets() { connect(m_Ui->playButton, &QToolButton::toggled, this, &QmitkMovieMakerView::OnPlayButtonToggled); connect(m_Ui->stopButton, &QToolButton::clicked, this, &QmitkMovieMakerView::OnStopButtonClicked); connect(m_Ui->recordButton, &QToolButton::clicked, this, &QmitkMovieMakerView::OnRecordButtonClicked); connect(m_Ui->fpsSpinBox, SIGNAL(valueChanged(int)), this, SLOT(OnFPSSpinBoxValueChanged(int))); } void QmitkMovieMakerView::ConnectTimer() { connect(m_Timer, &QTimer::timeout, this, &QmitkMovieMakerView::OnTimerTimeout); } void QmitkMovieMakerView::SetFocus() { m_Ui->addAnimationButton->setFocus(); } void QmitkMovieMakerView::OnMoveAnimationUpButtonClicked() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (!selection.isEmpty()) { const int selectedRow = selection[0].top(); if (selectedRow > 0) m_AnimationModel->insertRow(selectedRow - 1, m_AnimationModel->takeRow(selectedRow)); } this->CalculateTotalDuration(); } void QmitkMovieMakerView::OnMoveAnimationDownButtonClicked() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (!selection.isEmpty()) { const int rowCount = m_AnimationModel->rowCount(); const int selectedRow = selection[0].top(); if (selectedRow < rowCount - 1) m_AnimationModel->insertRow(selectedRow + 1, m_AnimationModel->takeRow(selectedRow)); } this->CalculateTotalDuration(); } void QmitkMovieMakerView::OnAddAnimationButtonClicked() { auto action = m_AddAnimationMenu->exec(QCursor::pos()); if (nullptr != action) { const auto key = action->text(); m_AnimationModel->appendRow(QList() << new QStandardItem(key) << CreateDefaultAnimation(key)); m_Ui->playbackAndRecordingGroupBox->setEnabled(true); } } void QmitkMovieMakerView::OnPlayButtonToggled(bool checked) { if (checked) { m_Ui->playButton->setIcon(QIcon(":/org_mitk_icons/icons/tango/scalable/actions/media-playback-pause.svg")); m_Ui->playButton->repaint(); m_Timer->start(static_cast(1000.0 / m_Ui->fpsSpinBox->value())); } else { m_Timer->stop(); m_Ui->playButton->setIcon(QIcon(":/org_mitk_icons/icons/tango/scalable/actions/media-playback-start.svg")); m_Ui->playButton->repaint(); } } void QmitkMovieMakerView::OnStopButtonClicked() { m_Ui->playButton->setChecked(false); m_Ui->stopButton->setEnabled(false); m_CurrentFrame = 0; this->RenderCurrentFrame(); } void QmitkMovieMakerView::OnRecordButtonClicked() { if (0 == m_NumFrames || 0.0 == m_TotalDuration) return; const QString ffmpegPath = GetFFmpegPath(); if (ffmpegPath.isEmpty()) { QMessageBox::information(nullptr, "Movie Maker", "

Set path to FFmpeg (ffmpeg.org) in preferences " "(Window -> Preferences... (Ctrl+P) -> External Programs) " "to be able to record your movies to video files.

"); return; } m_FFmpegWriter->SetFFmpegPath(GetFFmpegPath()); auto action = m_RecordMenu->exec(QCursor::pos()); if (nullptr == action) return; auto renderWindow = mitk::BaseRenderer::GetRenderWindowByName(action->data().toString().toStdString()); if (nullptr == renderWindow) return; const int border = 3; const int x = border; const int y = border; int width = renderWindow->GetSize()[0] - border * 2; int height = renderWindow->GetSize()[1] - border * 2; if (width & 1) --width; if (height & 1) --height; if (width < 16 || height < 16) return; m_FFmpegWriter->SetSize(width, height); m_FFmpegWriter->SetFramerate(m_Ui->fpsSpinBox->value()); QString saveFileName = QFileDialog::getSaveFileName(nullptr, "Specify a filename", "", "Movie (*.mp4)"); if (saveFileName.isEmpty()) return; if(!saveFileName.endsWith(".mp4")) saveFileName += ".mp4"; m_FFmpegWriter->SetOutputPath(saveFileName); try { auto frame = std::make_unique(width * height * 3); m_FFmpegWriter->Start(); for (m_CurrentFrame = 0; m_CurrentFrame < m_NumFrames; ++m_CurrentFrame) { this->RenderCurrentFrame(); ReadPixels(frame, renderWindow, x, y, width, height); m_FFmpegWriter->WriteFrame(frame.get()); } m_FFmpegWriter->Stop(); m_CurrentFrame = 0; this->RenderCurrentFrame(); } catch (const mitk::Exception& exception) { m_CurrentFrame = 0; this->RenderCurrentFrame(); QMessageBox::critical(nullptr, "Movie Maker", exception.GetDescription()); } } void QmitkMovieMakerView::OnRemoveAnimationButtonClicked() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (!selection.isEmpty()) m_AnimationModel->removeRow(selection[0].top()); } void QmitkMovieMakerView::OnAnimationTreeViewRowsInserted(const QModelIndex& parent, int start, int) { this->CalculateTotalDuration(); m_Ui->animationTreeView->selectionModel()->select( m_AnimationModel->index(start, 0, parent), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } void QmitkMovieMakerView::OnAnimationTreeViewRowsRemoved(const QModelIndex&, int, int) { this->CalculateTotalDuration(); this->UpdateWidgets(); } void QmitkMovieMakerView::OnAnimationTreeViewSelectionChanged(const QItemSelection&, const QItemSelection&) { this->UpdateWidgets(); } void QmitkMovieMakerView::OnStartComboBoxCurrentIndexChanged(int index) { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != nullptr) { item->SetStartWithPrevious(index); this->RedrawTimeline(); this->CalculateTotalDuration(); } } void QmitkMovieMakerView::OnDurationSpinBoxValueChanged(double value) { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != nullptr) { item->SetDuration(value); this->RedrawTimeline(); this->CalculateTotalDuration(); } } void QmitkMovieMakerView::OnDelaySpinBoxValueChanged(double value) { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != nullptr) { item->SetDelay(value); this->RedrawTimeline(); this->CalculateTotalDuration(); } } void QmitkMovieMakerView::OnFPSSpinBoxValueChanged(int value) { this->CalculateTotalDuration(); m_Timer->setInterval(static_cast(1000.0 / value)); } void QmitkMovieMakerView::OnTimerTimeout() { this->RenderCurrentFrame(); m_CurrentFrame = std::min(m_NumFrames, m_CurrentFrame + 1); if (m_CurrentFrame >= m_NumFrames) { m_Ui->playButton->setChecked(false); m_CurrentFrame = 0; this->RenderCurrentFrame(); } m_Ui->stopButton->setEnabled(m_CurrentFrame != 0); } void QmitkMovieMakerView::RenderCurrentFrame() { const double deltaT = m_TotalDuration / (m_NumFrames - 1); const auto activeAnimations = this->GetActiveAnimations(m_CurrentFrame * deltaT); for (const auto& animation : activeAnimations) { const auto nextActiveAnimations = this->GetActiveAnimations((m_CurrentFrame + 1) * deltaT); bool lastFrameForAnimation = true; for (const auto& nextAnimation : nextActiveAnimations) { if (nextAnimation.first == animation.first) { lastFrameForAnimation = false; break; } } animation.first->Animate(!lastFrameForAnimation ? animation.second : 1.0); } mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkMovieMakerView::UpdateWidgets() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (selection.isEmpty()) { m_Ui->moveAnimationUpButton->setEnabled(false); m_Ui->moveAnimationDownButton->setEnabled(false); m_Ui->removeAnimationButton->setEnabled(false); m_Ui->playbackAndRecordingGroupBox->setEnabled(false); this->HideCurrentAnimationWidget(); } else { const int rowCount = m_AnimationModel->rowCount(); const int selectedRow = selection[0].top(); m_Ui->moveAnimationUpButton->setEnabled(rowCount > 1 && selectedRow != 0); m_Ui->moveAnimationDownButton->setEnabled(rowCount > 1 && selectedRow < rowCount - 1); m_Ui->removeAnimationButton->setEnabled(true); m_Ui->playbackAndRecordingGroupBox->setEnabled(true); this->ShowAnimationWidget(dynamic_cast(m_AnimationModel->item(selectedRow, 1))); } this->UpdateAnimationWidgets(); } void QmitkMovieMakerView::UpdateAnimationWidgets() { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != nullptr) { m_Ui->startComboBox->setCurrentIndex(item->GetStartWithPrevious()); m_Ui->durationSpinBox->setValue(item->GetDuration()); m_Ui->delaySpinBox->setValue(item->GetDelay()); m_Ui->animationGroupBox->setEnabled(true); } else { m_Ui->animationGroupBox->setEnabled(false); } } void QmitkMovieMakerView::HideCurrentAnimationWidget() { if (m_Ui->animationWidgetGroupBox->isVisible()) { m_Ui->animationWidgetGroupBox->setVisible(false); int numWidgets = m_Ui->animationWidgetGroupBoxLayout->count(); for (int i = 0; i < numWidgets; ++i) m_Ui->animationWidgetGroupBoxLayout->itemAt(i)->widget()->setVisible(false); } } void QmitkMovieMakerView::ShowAnimationWidget(QmitkAnimationItem* animationItem) { this->HideCurrentAnimationWidget(); if (animationItem == nullptr) return; const QString widgetKey = animationItem->GetWidgetKey(); auto animationWidgetIter = m_AnimationWidgets.find(widgetKey); auto animationWidget = m_AnimationWidgets.end() != animationWidgetIter ? animationWidgetIter->second : nullptr; if (nullptr != animationWidget) { m_Ui->animationWidgetGroupBox->setTitle(widgetKey); animationWidget->SetAnimationItem(animationItem); animationWidget->setVisible(true); } m_Ui->animationWidgetGroupBox->setVisible(animationWidget != nullptr); } void QmitkMovieMakerView::RedrawTimeline() { if (m_AnimationModel->rowCount() > 1) { m_Ui->animationTreeView->dataChanged( m_AnimationModel->index(0, 1), m_AnimationModel->index(m_AnimationModel->rowCount() - 1, 1)); } } QmitkAnimationItem* QmitkMovieMakerView::GetSelectedAnimationItem() const { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); return !selection.isEmpty() ? dynamic_cast(m_AnimationModel->item(selection[0].top(), 1)) : nullptr; } void QmitkMovieMakerView::CalculateTotalDuration() { const int rowCount = m_AnimationModel->rowCount(); double totalDuration = 0.0; double previousStart = 0.0; for (int i = 0; i < rowCount; ++i) { auto item = dynamic_cast(m_AnimationModel->item(i, 1)); if (nullptr == item) continue; if (item->GetStartWithPrevious()) { totalDuration = std::max(totalDuration, previousStart + item->GetDelay() + item->GetDuration()); } else { previousStart = totalDuration; totalDuration += item->GetDelay() + item->GetDuration(); } } m_TotalDuration = totalDuration; m_NumFrames = static_cast(totalDuration * m_Ui->fpsSpinBox->value()); } std::vector> QmitkMovieMakerView::GetActiveAnimations(double t) const { const int rowCount = m_AnimationModel->rowCount(); std::vector> activeAnimations; double totalDuration = 0.0; double previousStart = 0.0; for (int i = 0; i < rowCount; ++i) { QmitkAnimationItem* item = dynamic_cast(m_AnimationModel->item(i, 1)); if (item == nullptr) continue; if (item->GetDuration() > 0.0) { double start = item->GetStartWithPrevious() ? previousStart + item->GetDelay() : totalDuration + item->GetDelay(); if (start <= t && t <= start + item->GetDuration()) activeAnimations.emplace_back(item, (t - start) / item->GetDuration()); } if (item->GetStartWithPrevious()) { totalDuration = std::max(totalDuration, previousStart + item->GetDelay() + item->GetDuration()); } else { previousStart = totalDuration; totalDuration += item->GetDelay() + item->GetDuration(); } } return activeAnimations; } diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.cpp index 0ac009a43e..0178c16e04 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.cpp @@ -1,30 +1,33 @@ /*============================================================================ 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 "mitkMovieMakerPluginActivator.h" #include "QmitkMovieMakerView.h" #include "QmitkScreenshotMaker.h" +#include + +US_INITIALIZE_MODULE namespace mitk { void MovieMakerPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkMovieMakerView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkScreenshotMaker, context) } void MovieMakerPluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.cpp index 9b86ce4441..3c98177cf9 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.cpp @@ -1,232 +1,234 @@ /*============================================================================ 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 "QmitkMxNMultiWidgetEditor.h" -#include -#include +#include +#include +#include + #include #include #include // mxn multi widget editor plugin #include "QmitkMultiWidgetDecorationManager.h" // mitk qt widgets module #include #include #include // qt #include const QString QmitkMxNMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.mxnmultiwidget"; struct QmitkMxNMultiWidgetEditor::Impl final { Impl(); ~Impl() = default; QmitkInteractionSchemeToolBar* m_InteractionSchemeToolBar; QmitkMultiWidgetConfigurationToolBar* m_ConfigurationToolBar; }; QmitkMxNMultiWidgetEditor::Impl::Impl() : m_InteractionSchemeToolBar(nullptr) , m_ConfigurationToolBar(nullptr) { // nothing here } ////////////////////////////////////////////////////////////////////////// // QmitkMxNMultiWidgetEditor ////////////////////////////////////////////////////////////////////////// QmitkMxNMultiWidgetEditor::QmitkMxNMultiWidgetEditor() : QmitkAbstractMultiWidgetEditor() , m_Impl(std::make_unique()) { // nothing here } QmitkMxNMultiWidgetEditor::~QmitkMxNMultiWidgetEditor() { GetSite()->GetPage()->RemovePartListener(this); } berry::IPartListener::Events::Types QmitkMxNMultiWidgetEditor::GetPartEventTypes() const { return Events::CLOSED | Events::OPENED | Events::HIDDEN | Events::VISIBLE; } void QmitkMxNMultiWidgetEditor::PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkMxNMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->RemovePlanesFromDataStorage(); multiWidget->ActivateMenuWidget(false); } } } void QmitkMxNMultiWidgetEditor::PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkMxNMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->AddPlanesToDataStorage(); multiWidget->ActivateMenuWidget(true); } } } void QmitkMxNMultiWidgetEditor::PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkMxNMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->ActivateMenuWidget(false); } } } void QmitkMxNMultiWidgetEditor::PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkMxNMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->ActivateMenuWidget(true); } } } void QmitkMxNMultiWidgetEditor::OnLayoutSet(int row, int column) { const auto &multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { QmitkAbstractMultiWidgetEditor::OnLayoutSet(row, column); multiWidget->AddPlanesToDataStorage(); } } void QmitkMxNMultiWidgetEditor::OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme) { const auto &multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return; } if (mitk::InteractionSchemeSwitcher::PACSStandard == scheme) { m_Impl->m_InteractionSchemeToolBar->setVisible(true); } else { m_Impl->m_InteractionSchemeToolBar->setVisible(false); } QmitkAbstractMultiWidgetEditor::OnInteractionSchemeChanged(scheme); } ////////////////////////////////////////////////////////////////////////// // PRIVATE ////////////////////////////////////////////////////////////////////////// void QmitkMxNMultiWidgetEditor::SetFocus() { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { multiWidget->setFocus(); } } void QmitkMxNMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { QHBoxLayout *layout = new QHBoxLayout(parent); layout->setContentsMargins(0, 0, 0, 0); - berry::IBerryPreferences *preferences = dynamic_cast(GetPreferences().GetPointer()); + auto* preferences = this->GetPreferences(); auto multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { multiWidget = new QmitkMxNMultiWidget(parent, 0, nullptr); // create left toolbar: interaction scheme toolbar to switch how the render window navigation behaves in PACS mode if (nullptr == m_Impl->m_InteractionSchemeToolBar) { m_Impl->m_InteractionSchemeToolBar = new QmitkInteractionSchemeToolBar(parent); layout->addWidget(m_Impl->m_InteractionSchemeToolBar); } m_Impl->m_InteractionSchemeToolBar->SetInteractionEventHandler(multiWidget->GetInteractionEventHandler()); multiWidget->SetDataStorage(GetDataStorage()); multiWidget->InitializeMultiWidget(); SetMultiWidget(multiWidget); } layout->addWidget(multiWidget); // create right toolbar: configuration toolbar to change the render window widget layout if (nullptr == m_Impl->m_ConfigurationToolBar) { m_Impl->m_ConfigurationToolBar = new QmitkMultiWidgetConfigurationToolBar(multiWidget); layout->addWidget(m_Impl->m_ConfigurationToolBar); } connect(m_Impl->m_ConfigurationToolBar, &QmitkMultiWidgetConfigurationToolBar::LayoutSet, this, &QmitkMxNMultiWidgetEditor::OnLayoutSet); connect(m_Impl->m_ConfigurationToolBar, &QmitkMultiWidgetConfigurationToolBar::Synchronized, this, &QmitkMxNMultiWidgetEditor::OnSynchronize); connect(m_Impl->m_ConfigurationToolBar, &QmitkMultiWidgetConfigurationToolBar::InteractionSchemeChanged, this, &QmitkMxNMultiWidgetEditor::OnInteractionSchemeChanged); GetSite()->GetPage()->AddPartListener(this); OnPreferencesChanged(preferences); } -void QmitkMxNMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* preferences) +void QmitkMxNMultiWidgetEditor::OnPreferencesChanged(const mitk::IPreferences* preferences) { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return; } // update decoration preferences //m_Impl->m_MultiWidgetDecorationManager->DecorationPreferencesChanged(preferences); int crosshairGapSize = preferences->GetInt("crosshair gap size", 32); multiWidget->SetCrosshairGap(crosshairGapSize); // zooming and panning preferences bool constrainedZooming = preferences->GetBool("Use constrained zooming and panning", true); mitk::RenderingManager::GetInstance()->SetConstrainedPanningZooming(constrainedZooming); bool PACSInteractionScheme = preferences->GetBool("PACS like mouse interaction", false); OnInteractionSchemeChanged(PACSInteractionScheme ? mitk::InteractionSchemeSwitcher::PACSStandard : mitk::InteractionSchemeSwitcher::MITKStandard); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.h index 377cd9dec7..5a154391da 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/QmitkMxNMultiWidgetEditor.h @@ -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. ============================================================================*/ #ifndef QMITKMXNMULTIWIDGETEDITOR_H #define QMITKMXNMULTIWIDGETEDITOR_H #include #include // c++ #include class QmitkMxNMultiWidget; class MXNMULTIWIDGETEDITOR_EXPORT QmitkMxNMultiWidgetEditor final : public QmitkAbstractMultiWidgetEditor { Q_OBJECT public: static const QString EDITOR_ID; QmitkMxNMultiWidgetEditor(); ~QmitkMxNMultiWidgetEditor() override; virtual QmitkLevelWindowWidget* GetLevelWindowWidget() const override { return nullptr; } /** * @brief Overridden from berry::IPartListener */ virtual berry::IPartListener::Events::Types GetPartEventTypes() const override; /** * @brief Overridden from berry::IPartListener */ virtual void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) override; void OnLayoutSet(int row, int column) override; void OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme) override; private: /** * @brief Overridden from QmitkAbstractRenderEditor */ void SetFocus() override; /** * @brief Overridden from QmitkAbstractRenderEditor */ void CreateQtPartControl(QWidget* parent) override; /** * @brief Overridden from QmitkAbstractRenderEditor */ - void OnPreferencesChanged(const berry::IBerryPreferences* preferences) override; + void OnPreferencesChanged(const mitk::IPreferences* preferences) override; struct Impl; std::unique_ptr m_Impl; }; #endif // QMITKMXNMULTIWIDGETEDITOR_H diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp index 3cef261dea..c822da0243 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp @@ -1,101 +1,101 @@ /*============================================================================ 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 "QmitkMxNMultiWidgetEditorPreferencePage.h" #include -// berry framework -#include -#include +#include +#include +#include QmitkMxNMultiWidgetEditorPreferencePage::QmitkMxNMultiWidgetEditorPreferencePage() : m_Preferences(nullptr) { // nothing here } QmitkMxNMultiWidgetEditorPreferencePage::~QmitkMxNMultiWidgetEditorPreferencePage() { //nothing here } void QmitkMxNMultiWidgetEditorPreferencePage::Init(berry::IWorkbench::Pointer) { // nothing here } void QmitkMxNMultiWidgetEditorPreferencePage::CreateQtControl(QWidget* parent) { m_MainControl = new QWidget(parent); m_Ui.setupUi(m_MainControl); - berry::IPreferencesService* preferenceService = berry::Platform::GetPreferencesService(); + auto* preferenceService = mitk::CoreServices::GetPreferencesService(); Q_ASSERT(preferenceService); - m_Preferences = preferenceService->GetSystemPreferences()->Node(QmitkMxNMultiWidgetEditor::EDITOR_ID); + m_Preferences = preferenceService->GetSystemPreferences()->Node(QmitkMxNMultiWidgetEditor::EDITOR_ID.toStdString()); connect(m_Ui.m_ColormapComboBox, SIGNAL(activated(int)), SLOT(ChangeColormap(int))); connect(m_Ui.m_ResetButton, SIGNAL(clicked()), SLOT(ResetPreferencesAndGUI())); Update(); } QWidget* QmitkMxNMultiWidgetEditorPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkMxNMultiWidgetEditorPreferencePage::PerformOk() { m_Preferences->PutBool("Use constrained zooming and panning", m_Ui.m_EnableFlexibleZooming->isChecked()); m_Preferences->PutBool("Show level/window widget", m_Ui.m_ShowLevelWindowWidget->isChecked()); m_Preferences->PutBool("PACS like mouse interaction", m_Ui.m_PACSLikeMouseMode->isChecked()); m_Preferences->PutInt("Render window widget colormap", m_Ui.m_ColormapComboBox->currentIndex()); m_Preferences->PutBool("Render window individual decorations", m_Ui.m_IndividualDecorations->isChecked()); m_Preferences->PutInt("crosshair gap size", m_Ui.m_CrosshairGapSize->value()); return true; } void QmitkMxNMultiWidgetEditorPreferencePage::PerformCancel() { // nothing here } void QmitkMxNMultiWidgetEditorPreferencePage::Update() { m_Ui.m_EnableFlexibleZooming->setChecked(m_Preferences->GetBool("Use constrained zooming and panning", true)); m_Ui.m_ShowLevelWindowWidget->setChecked(m_Preferences->GetBool("Show level/window widget", true)); m_Ui.m_PACSLikeMouseMode->setChecked(m_Preferences->GetBool("PACS like mouse interaction", false)); int colormap = m_Preferences->GetInt("Render window widget colormap", 0); m_Ui.m_ColormapComboBox->setCurrentIndex(colormap); m_Ui.m_IndividualDecorations->setChecked(m_Preferences->GetBool("Render window individual decorations", false)); m_Ui.m_CrosshairGapSize->setValue(m_Preferences->GetInt("crosshair gap size", 32)); } void QmitkMxNMultiWidgetEditorPreferencePage::ResetPreferencesAndGUI() { m_Preferences->Clear(); Update(); } void QmitkMxNMultiWidgetEditorPreferencePage::ChangeColormap(int i) { if (0 == i) { m_CurrentColormap = "Black and white"; } } diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h index 71dcd3fee0..ae2e247ab2 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h @@ -1,65 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKMXNMULTIWIDGETEDITORPREFERENCEPAGE_H #define QMITKMXNMULTIWIDGETEDITORPREFERENCEPAGE_H #include "ui_QmitkMxNMultiWidgetEditorPreferencePage.h" -#include #include #include #include #include +namespace mitk +{ + class IPreferences; +} + class QmitkMxNMultiWidgetEditorPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkMxNMultiWidgetEditorPreferencePage(); ~QmitkMxNMultiWidgetEditorPreferencePage() override; void Init(berry::IWorkbench::Pointer) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; public slots: /** * @brief ResetColors set default colors and refresh the GUI. */ void ResetPreferencesAndGUI(); void ChangeColormap(int i); protected: std::string m_CurrentColormap; /** * @brief m_Preferences the berry preferences. */ - berry::IPreferences::Pointer m_Preferences; + mitk::IPreferences* m_Preferences; private: Ui::QmitkMxNMultiWidgetEditorPreferencePage m_Ui; QWidget* m_MainControl; }; #endif // QMITKMXNMULTIWIDGETEDITORPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/mitkPluginActivator.cpp index 4656300ac4..0f07fc6f92 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/mitkPluginActivator.cpp @@ -1,41 +1,45 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include #include "QmitkMxNMultiWidgetEditorPreferencePage.h" +#include + +US_INITIALIZE_MODULE + namespace mitk { ctkPluginContext* MxNMultiWidgetActivator::m_Context = nullptr; void MxNMultiWidgetActivator::start(ctkPluginContext* context) { m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkMxNMultiWidgetEditor, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkMxNMultiWidgetEditorPreferencePage, context) } void MxNMultiWidgetActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_Context = nullptr; } ctkPluginContext* MxNMultiWidgetActivator::GetContext() { return m_Context; } } diff --git a/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp b/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp index af14922701..5a2270499a 100644 --- a/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp +++ b/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp @@ -1,532 +1,531 @@ /*============================================================================ 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 // Blueberry -#include #include #include // Qmitk #include "QmitkAddNewPropertyDialog.h" #include "QmitkOverlayManagerView.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include // Qt #include #include #include #include "internal/org_mitk_gui_qt_overlaymanager_Activator.h" #include "mitkAnnotationUtils.h" #include "mitkGetPropertyService.h" #include "mitkLayoutAnnotationRenderer.h" #include "mitkManualPlacementAnnotationRenderer.h" #include "mitkRenderingManager.h" #include #include #include #include #include #include #include #include #include const std::string QmitkOverlayManagerView::VIEW_ID = "org.mitk.views.overlaymanager"; QmitkOverlayManagerView::QmitkOverlayManagerView() : m_Parent(nullptr), m_PropertyNameChangedTag(0), m_OverlayManagerObserverTag(0), m_PropertyAliases(nullptr), m_PropertyDescriptions(nullptr), m_PropertyPersistence(nullptr), m_ProxyModel(nullptr), m_Model(nullptr), m_Delegate(nullptr), m_Renderer(nullptr), m_AddOverlayMenu(nullptr) { } QmitkOverlayManagerView::~QmitkOverlayManagerView() { } void QmitkOverlayManagerView::SetFocus() { } void QmitkOverlayManagerView::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); m_Controls.m_OverlayList->clear(); auto* renderWindowPart = this->GetRenderWindowPart(); if (renderWindowPart != nullptr) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH (QString renderWindow, renderWindows.keys()) { if (!m_Renderer) m_Renderer = renderWindows[renderWindow]->GetRenderer(); m_Controls.m_RendererCB->addItem(renderWindow); } } InitializeAddOverlayMenu(); m_ProxyModel = new QSortFilterProxyModel(m_Controls.m_PropertyTree); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.m_PropertyTree); m_Controls.m_PropertyTree->setItemDelegateForColumn(1, m_Delegate); m_Controls.m_PropertyTree->setModel(m_ProxyModel); m_Controls.m_PropertyTree->setColumnWidth(0, 160); m_Controls.m_PropertyTree->sortByColumn(0, Qt::AscendingOrder); m_Controls.m_PropertyTree->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.m_PropertyTree->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.m_PropertyTree->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); connect(m_Controls.m_RendererCB, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int))); connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty())); connect(m_Controls.m_PropertyTree->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(OnCurrentRowChanged(const QModelIndex &, const QModelIndex &))); connect(m_Controls.m_OverlayList, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(OnOverlaySelectionChanged(QListWidgetItem *, QListWidgetItem *))); connect(m_Controls.m_DeleteOverlay, SIGNAL(clicked()), this, SLOT(OnDelete())); connect(m_Controls.m_AddOverlay, SIGNAL(clicked()), this, SLOT(OnAddOverlay())); itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction(this, &QmitkOverlayManagerView::OnFocusChanged); m_RenderWindowFocusObserverTag = mitk::RenderingManager::GetInstance()->AddObserver(mitk::FocusChangedEvent(), command); } void QmitkOverlayManagerView::OnFocusChanged(itk::Object * /*caller*/, const itk::EventObject &event) { const mitk::FocusChangedEvent *focusEvent = dynamic_cast(&event); if (focusEvent) { QHash renderWindows = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindows(); m_Controls.m_RendererCB->clear(); Q_FOREACH (QString renderWindow, renderWindows.keys()) { m_Controls.m_RendererCB->addItem(renderWindow); if (renderWindows[renderWindow]->GetVtkRenderWindow() == mitk::RenderingManager::GetInstance()->GetFocusedRenderWindow()) { m_Controls.m_RendererCB->setCurrentText(renderWindow); } } this->OnActivateOverlayList(); } } QString QmitkOverlayManagerView::GetPropertyNameOrAlias(const QModelIndex &index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } void QmitkOverlayManagerView::OnCurrentRowChanged(const QModelIndex ¤t, const QModelIndex &) { if (m_PropertyDescriptions != nullptr && current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; if (m_PropertyAliases != nullptr) { std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector aliases; if (!isTrueName && m_PropertyAliases != nullptr) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } bool isPersistent = false; // QString persistenceKey; if (m_PropertyPersistence != nullptr) { isPersistent = m_PropertyPersistence->HasInfo(name.toStdString()); /*if (isPersistent) { persistenceKey = QString::fromStdString(m_PropertyPersistence->GetInfo(name.toStdString())->GetKey()); if (persistenceKey.isEmpty()) persistenceKey = name; }*/ } if (!description.isEmpty() || !aliases.empty() || isPersistent) { QString customizedDescription; if (!description.isEmpty()) customizedDescription += "

" + description + "

"; if (!aliases.empty() || isPersistent) { customizedDescription += "
"; if (!aliases.empty()) { customizedDescription += aliases.size() > 1 ? "" : ""; } if (isPersistent) customizedDescription += ""; customizedDescription += "
"; } return; } } } } void QmitkOverlayManagerView::OnPropertyNameChanged(const itk::EventObject &) { mitk::PropertyList *propertyList = m_Model->GetPropertyList(); if (propertyList != nullptr) { mitk::BaseProperty *nameProperty = propertyList->GetProperty("name"); if (nameProperty != nullptr) { QString partName = "Properties ("; partName.append(QString::fromStdString(nameProperty->GetValueAsString())).append(')'); this->SetPartName(partName); } } } void QmitkOverlayManagerView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList &) { } void QmitkOverlayManagerView::InitializeAddOverlayMenu() { m_AddOverlayMenu = new QMenu(m_Controls.m_AddOverlay); m_AddOverlayMenu->addAction("TextAnnotation2D"); m_AddOverlayMenu->addAction("TextAnnotation3D"); m_AddOverlayMenu->addAction("LabelAnnotation"); m_AddOverlayMenu->addAction("ColorBarAnnotation"); m_AddOverlayMenu->addAction("ScaleLegendAnnotation"); m_AddOverlayMenu->addAction("LogoAnnotation"); } void QmitkOverlayManagerView::Activated() { // this->OnActivateOverlayList(); } void QmitkOverlayManagerView::Deactivated() { } void QmitkOverlayManagerView::Visible() { this->OnActivateOverlayList(); } void QmitkOverlayManagerView::Hidden() { } void QmitkOverlayManagerView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.m_RendererCB->itemText(index); auto *renwin = this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer); m_Renderer = renwin ? renwin->GetRenderer() : nullptr; this->OnOverlaySelectionChanged(m_Controls.m_OverlayList->currentItem(), nullptr); this->OnActivateOverlayList(); } void QmitkOverlayManagerView::OnAddNewProperty() { std::unique_ptr dialog( new QmitkAddNewPropertyDialog(m_SelectedOverlay, m_Renderer, m_Parent)); if (dialog->exec() == QDialog::Accepted) this->m_Model->Update(); } void QmitkOverlayManagerView::OnActivateOverlayList() { if (!m_Renderer) return; std::vector arList = mitk::AnnotationUtils::GetAnnotationRenderer(m_Renderer->GetName()); m_Controls.m_OverlayList->clear(); for (auto ar : arList) { for (auto overlay : ar->GetServices()) { QListWidgetItem *item = new QListWidgetItem(); item->setData(Qt::UserRole, QVariant(overlay->GetMicroserviceID().c_str())); QString text(overlay->GetName().c_str()); if (text.length() > 0) { text.append(" : "); } text.append(overlay->GetNameOfClass()); item->setText(text); m_Controls.m_OverlayList->addItem(item); } } } void QmitkOverlayManagerView::OnOverlaySelectionChanged(QListWidgetItem *current, QListWidgetItem *) { mitk::PropertyList *propertyList = m_Model->GetPropertyList(); if (propertyList != nullptr) { mitk::BaseProperty *nameProperty = propertyList->GetProperty("name"); if (nameProperty != nullptr) nameProperty->RemoveObserver(m_PropertyNameChangedTag); m_PropertyNameChangedTag = 0; } mitk::Annotation *overlay = nullptr; QString oID; if (current) { oID = current->data(Qt::UserRole).toString(); OverlayMapType::iterator it = m_OverlayMap.find(oID.toStdString()); if (it != m_OverlayMap.end()) overlay = it->second; else { overlay = mitk::AnnotationUtils::GetAnnotation(oID.toStdString()); } } if (!overlay) { m_SelectedOverlay = nullptr; this->SetPartName("Overlay Properties"); m_Model->SetPropertyList(nullptr); m_Delegate->SetPropertyList(nullptr); m_Controls.newButton->setEnabled(false); } else { m_SelectedOverlay = overlay; QString selectionClassName = m_SelectedOverlay->GetNameOfClass(); m_SelectionClassName = selectionClassName.toStdString(); mitk::PropertyList::Pointer propertyList = overlay->GetPropertyList(); m_Model->SetPropertyList(propertyList, selectionClassName); m_Delegate->SetPropertyList(propertyList); OnPropertyNameChanged(itk::ModifiedEvent()); mitk::BaseProperty *nameProperty = m_SelectedOverlay->GetProperty("name"); if (nameProperty != nullptr) { itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkOverlayManagerView::OnPropertyNameChanged); m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command); } m_Controls.newButton->setEnabled(true); } if (!m_ProxyModel->filterRegExp().isEmpty()) m_Controls.m_PropertyTree->expandAll(); } void QmitkOverlayManagerView::OnDelete() { if (m_SelectedOverlay.IsNotNull()) { m_OverlayMap.erase(m_SelectedOverlay->GetMicroserviceID()); m_SelectedOverlay = nullptr; OnActivateOverlayList(); } } void QmitkOverlayManagerView::OnAddOverlay() { QAction *action = m_AddOverlayMenu->exec(QCursor::pos()); mitk::Annotation::Pointer overlay; if (action != nullptr) { const QString widgetKey = action->text(); if (widgetKey == "TextAnnotation2D") overlay = CreateTextOverlay2D(); else if (widgetKey == "TextAnnotation3D") overlay = CreateTextOverlay3D(); else if (widgetKey == "LabelAnnotation") overlay = CreateLabelOverlay(); else if (widgetKey == "ColorBarAnnotation") overlay = CreateColorBarOverlay(); else if (widgetKey == "ScaleLegendAnnotation") overlay = CreateScaleLegendOverlay(); else if (widgetKey == "LogoAnnotation") overlay = CreateLogoOverlay(); mitk::BaseRenderer *renderer = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow(m_Controls.m_RendererCB->currentText())->GetRenderer(); mitk::LayoutAnnotationRenderer::AddAnnotation(overlay, renderer); m_OverlayMap[overlay->GetMicroserviceID()] = overlay; } OnActivateOverlayList(); } mitk::Annotation::Pointer QmitkOverlayManagerView::CreateTextOverlay2D() { mitk::TextAnnotation2D::Pointer to = mitk::TextAnnotation2D::New(); to->SetText("Test"); return to.GetPointer(); } mitk::Annotation::Pointer QmitkOverlayManagerView::CreateTextOverlay3D() { mitk::TextAnnotation3D::Pointer to = mitk::TextAnnotation3D::New(); return to.GetPointer(); } mitk::Annotation::Pointer QmitkOverlayManagerView::CreateLabelOverlay() { mitk::LabelAnnotation3D::Pointer to = mitk::LabelAnnotation3D::New(); return to.GetPointer(); } mitk::Annotation::Pointer QmitkOverlayManagerView::CreateColorBarOverlay() { mitk::ColorBarAnnotation::Pointer to = mitk::ColorBarAnnotation::New(); return to.GetPointer(); } mitk::Annotation::Pointer QmitkOverlayManagerView::CreateScaleLegendOverlay() { mitk::ScaleLegendAnnotation::Pointer to = mitk::ScaleLegendAnnotation::New(); return to.GetPointer(); } mitk::Annotation::Pointer QmitkOverlayManagerView::CreateLogoOverlay() { mitk::LogoAnnotation::Pointer to = mitk::LogoAnnotation::New(); return to.GetPointer(); } void QmitkOverlayManagerView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_Controls.m_RendererCB->count() == 0) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH (QString renderWindow, renderWindows.keys()) { m_Controls.m_RendererCB->addItem(renderWindow); } } OnActivateOverlayList(); } void QmitkOverlayManagerView::RenderWindowPartDeactivated(mitk::IRenderWindowPart *) { if (m_Controls.m_RendererCB->count() > 0) { m_Controls.m_RendererCB->clear(); } m_Controls.m_OverlayList->clear(); } diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp index a6c3dd90d8..e243416aa3 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp @@ -1,395 +1,394 @@ /*============================================================================ 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 "QmitkAddNewPropertyDialog.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include "QmitkPropertyItemSortFilterProxyModel.h" #include "QmitkPropertyTreeView.h" -#include #include #include #include #include #include #include #include namespace { QmitkAbstractNodeSelectionWidget::NodeList GetInitialSelection(berry::ISelection::ConstPointer selection) { if (selection.IsNotNull() && !selection->IsEmpty()) { auto* dataNodeSelection = dynamic_cast(selection.GetPointer()); if (nullptr != dataNodeSelection) { auto firstSelectedDataNode = dataNodeSelection->GetSelectedDataNodes().front(); if (firstSelectedDataNode.IsNotNull()) { QmitkAbstractNodeSelectionWidget::NodeList initialSelection; initialSelection.push_back(firstSelectedDataNode); return initialSelection; } } } return QmitkAbstractNodeSelectionWidget::NodeList(); } } const std::string QmitkPropertyTreeView::VIEW_ID = "org.mitk.views.properties"; QmitkPropertyTreeView::QmitkPropertyTreeView() : m_PropertyAliases(mitk::CoreServices::GetPropertyAliases(nullptr), nullptr), m_PropertyDescriptions(mitk::CoreServices::GetPropertyDescriptions(nullptr), nullptr), m_PropertyPersistence(mitk::CoreServices::GetPropertyPersistence(nullptr), nullptr), m_ProxyModel(nullptr), m_Model(nullptr), m_Delegate(nullptr), m_Renderer(nullptr) { } QmitkPropertyTreeView::~QmitkPropertyTreeView() { } void QmitkPropertyTreeView::SetFocus() { m_Controls.filterLineEdit->setFocus(); } void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_Controls.propertyListComboBox->count() == 2) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); } } } void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) { if (m_Controls.propertyListComboBox->count() > 2) { m_Controls.propertyListComboBox->clear(); m_Controls.propertyListComboBox->addItem("Data node: common"); m_Controls.propertyListComboBox->addItem("Base data"); } } void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Controls.propertyListComboBox->addItem("Data node: common"); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); if (renderWindowPart != nullptr) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); for(const auto& renderWindow : renderWindows.keys()) { m_Controls.propertyListComboBox->addItem(QString("Data node: ") + renderWindow); } } m_Controls.propertyListComboBox->addItem("Base data"); m_Controls.newButton->setEnabled(false); this->HideAllIcons(); m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView); m_Controls.singleSlot->SetDataStorage(GetDataStorage()); m_Controls.singleSlot->SetSelectionIsOptional(true); m_Controls.singleSlot->SetEmptyInfo(QString("Please select a data node")); m_Controls.singleSlot->SetPopUpTitel(QString("Select data node")); m_SelectionServiceConnector = std::make_unique(); SetAsSelectionListener(true); m_Controls.filterLineEdit->setClearButtonEnabled(true); m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate); m_Controls.treeView->setModel(m_ProxyModel); m_Controls.treeView->setColumnWidth(0, 160); m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder); m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); const int ICON_SIZE = 32; auto icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tags.svg")); m_Controls.tagsLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tag.svg")); m_Controls.tagLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/document-save.svg")); m_Controls.saveLabel->setPixmap(icon.pixmap(ICON_SIZE)); connect(m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkPropertyTreeView::OnCurrentSelectionChanged); connect(m_Controls.filterLineEdit, &QLineEdit::textChanged, this, &QmitkPropertyTreeView::OnFilterTextChanged); connect(m_Controls.propertyListComboBox, static_cast(&QComboBox::currentIndexChanged), this, &QmitkPropertyTreeView::OnPropertyListChanged); connect(m_Controls.newButton, &QPushButton::clicked, this, &QmitkPropertyTreeView::OnAddNewProperty); connect(m_Controls.treeView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &QmitkPropertyTreeView::OnCurrentRowChanged); connect(m_Model, &QmitkPropertyItemModel::modelReset, this, &QmitkPropertyTreeView::OnModelReset); auto selection = this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); auto currentSelection = GetInitialSelection(selection); if (!currentSelection.isEmpty()) m_Controls.singleSlot->SetCurrentSelection(currentSelection); } void QmitkPropertyTreeView::SetAsSelectionListener(bool checked) { if (checked) { m_SelectionServiceConnector->AddPostSelectionListener(GetSite()->GetWorkbenchWindow()->GetSelectionService()); connect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); } else { m_SelectionServiceConnector->RemovePostSelectionListener(); disconnect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); } } QString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } void QmitkPropertyTreeView::OnCurrentSelectionChanged(QList nodes) { if (nodes.empty() || nodes.front().IsNull()) { m_SelectedNode = nullptr; this->SetPartName("Properties"); m_Model->SetPropertyList(nullptr); m_Delegate->SetPropertyList(nullptr); m_Controls.newButton->setEnabled(false); return; } // node is selected, create tree with node properties m_SelectedNode = nodes.front(); mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (m_Renderer == nullptr && m_Controls.propertyListComboBox->currentText() == "Base data") { propertyList = m_SelectedNode->GetData() != nullptr ? m_SelectedNode->GetData()->GetPropertyList() : nullptr; } else { propertyList = m_SelectedNode->GetPropertyList(m_Renderer); } QString selectionClassName = m_SelectedNode->GetData() != nullptr ? m_SelectedNode->GetData()->GetNameOfClass() : ""; m_SelectionClassName = selectionClassName.toStdString(); m_Model->SetPropertyList(propertyList, selectionClassName); m_Delegate->SetPropertyList(propertyList); m_Controls.newButton->setEnabled(true); m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::HideAllIcons() { m_Controls.tagLabel->hide(); m_Controls.tagsLabel->hide(); m_Controls.saveLabel->hide(); } void QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&) { if (current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector aliases; if (!isTrueName) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } bool isPersistent = m_PropertyPersistence->HasInfo(name.toStdString()); if (!description.isEmpty() || !aliases.empty() || isPersistent) { QString customizedDescription; if (!aliases.empty()) { customizedDescription = "

" + name + "

"; std::size_t numAliases = aliases.size(); std::size_t lastAlias = numAliases - 1; for (std::size_t i = 0; i < numAliases; ++i) { customizedDescription += i != lastAlias ? "
" : "
"; customizedDescription += QString::fromStdString(aliases[i]) + "
"; } } else { customizedDescription = "

" + name + "

"; } if (!description.isEmpty()) customizedDescription += "

" + description + "

"; m_Controls.tagsLabel->setVisible(!aliases.empty() && aliases.size() > 1); m_Controls.tagLabel->setVisible(!aliases.empty() && aliases.size() == 1); m_Controls.saveLabel->setVisible(isPersistent); m_Controls.descriptionLabel->setText(customizedDescription); m_Controls.descriptionLabel->show(); return; } } } m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } void QmitkPropertyTreeView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.propertyListComboBox->itemText(index); if (renderer.startsWith("Data node: ")) renderer = QString::fromStdString(renderer.toStdString().substr(11)); m_Renderer = nullptr; if (renderer != "common" && renderer != "Base data") { auto* renderWindowPart = this->GetRenderWindowPart(); if (nullptr != renderWindowPart) m_Renderer = renderWindowPart->GetQmitkRenderWindow(renderer)->GetRenderer(); } QList nodes; if (m_SelectedNode.IsNotNull()) nodes << m_SelectedNode; this->OnCurrentSelectionChanged(nodes); } void QmitkPropertyTreeView::OnAddNewProperty() { std::unique_ptr dialog(m_Controls.propertyListComboBox->currentText() != "Base data" ? new QmitkAddNewPropertyDialog(m_SelectedNode, m_Renderer) : new QmitkAddNewPropertyDialog(m_SelectedNode->GetData())); if (dialog->exec() == QDialog::Accepted) this->m_Model->Update(); } void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) { m_ProxyModel->setFilterWildcard(filter); m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::OnModelReset() { m_Controls.treeView->expandAll(); m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp index b9733bb2cf..ae8f174479 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp @@ -1,370 +1,370 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkNewSegmentationDialog.h" #include #include #include #include -#include -#include -#include +#include +#include +#include #include #include #include #include #include namespace { // Get standard label name and color suggestions from embedded XML preset file for anatomical structures. QmitkNewSegmentationDialog::SuggestionsType GetStandardSuggestions() { vtkNew presets; presets->LoadPreset(); auto colorPresets = presets->GetColorPresets(); QmitkNewSegmentationDialog::SuggestionsType standardSuggestions; standardSuggestions.reserve(colorPresets.size()); for (const auto& preset : colorPresets) { auto name = QString::fromStdString(preset.first); auto color = QColor::fromRgbF(preset.second.GetRed(), preset.second.GetGreen(), preset.second.GetBlue()); standardSuggestions.emplace_back(name, color); } std::sort(begin(standardSuggestions), end(standardSuggestions), [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; }); return standardSuggestions; } // Parse label name and color suggestions from a JSON file. An array of objects is expected, each consisting // of a "name" string and an optional "color" string. If present, the "color" string must follow the conventions // of QColor::setNamedColor(), i.e., #rrggbb or any SVG color keyword name like CornflowerBlue. Everything else // in the JSON file is simply ignored. In case of any error, an empty map is returned. QmitkNewSegmentationDialog::SuggestionsType ParseSuggestions(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { MITK_ERROR << "Could not open \"" << filename << "\"!"; return {}; } auto json = nlohmann::json::parse(file, nullptr, false); if (json.is_discarded() || !json.is_array()) { MITK_ERROR << "Could not parse \"" << filename << "\" as JSON array!"; return {}; } QmitkNewSegmentationDialog::SuggestionsType parsedSuggestions; for (const auto& obj : json) { if (!obj.is_object() || !obj.contains("name")) continue; auto name = QString::fromStdString(obj["name"]); QColor color; if (obj.contains("color")) color.setNamedColor(QString::fromStdString(obj["color"])); auto it = std::find_if(begin(parsedSuggestions), end(parsedSuggestions), [&name](const auto& suggestion) { return name == suggestion.first; }); // Ignore duplicates... if (it != parsedSuggestions.end()) { // unless we can complete the original suggestion with a valid color. if (!it->second.isValid() && color.isValid()) { it->second = color; } else { MITK_WARN << "Ignoring duplicate of suggestion \"" << name.toStdString() << "\"!"; } continue; } parsedSuggestions.emplace_back(name, color); } if (parsedSuggestions.empty()) MITK_WARN << "Could not parse any suggestions from \"" << filename << "\"!"; return parsedSuggestions; } struct Preferences { - QString labelSuggestions; + std::string labelSuggestions; bool replaceStandardSuggestions; bool suggestOnce; - QByteArray geometry; + std::vector geometry; }; // Get all relevant preferences and consider command-line arguments overrides. Preferences GetPreferences() { - auto nodePrefs = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); + auto* nodePrefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); Preferences prefs; - prefs.labelSuggestions = QString::fromStdString(mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), "")); + prefs.labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), ""); - if (prefs.labelSuggestions.isEmpty()) + if (prefs.labelSuggestions.empty()) prefs.labelSuggestions = nodePrefs->Get("label suggestions", ""); prefs.replaceStandardSuggestions = nodePrefs->GetBool("replace standard suggestions", true); prefs.suggestOnce = nodePrefs->GetBool("suggest once", true); - prefs.geometry = nodePrefs->GetByteArray("QmitkNewSegmentationDialog geometry", QByteArray()); + prefs.geometry = nodePrefs->GetByteArray("QmitkNewSegmentationDialog geometry", nullptr, 0); return prefs; } - void SaveGeometry(QByteArray geometry) + void SaveGeometry(const QByteArray& geometry) { - auto nodePrefs = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); - nodePrefs->PutByteArray("QmitkNewSegmentationDialog geometry", geometry); + auto* nodePrefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); + nodePrefs->PutByteArray("QmitkNewSegmentationDialog geometry", reinterpret_cast(geometry.data()), geometry.size()); } // Get names of all labels in all layers of a LabelSetImage. QStringList GetExistingLabelNames(mitk::LabelSetImage* labelSetImage) { QStringList existingLabelNames; existingLabelNames.reserve(labelSetImage->GetTotalNumberOfLabels()); const auto numLayers = labelSetImage->GetNumberOfLayers(); for (std::remove_const_t layerIndex = 0; layerIndex < numLayers; ++layerIndex) { const auto* labelSet = labelSetImage->GetLabelSet(layerIndex); for (auto labelIter = labelSet->IteratorConstBegin(); labelIter != labelSet->IteratorConstEnd(); ++labelIter) { if (0 == labelIter->first) continue; // Ignore background label auto name = QString::fromStdString(labelIter->second->GetName()); if (!name.isEmpty()) // Potential duplicates do not matter for our purpose existingLabelNames.push_back(name); } } return existingLabelNames; } // Remove blacklisted suggestions. QmitkNewSegmentationDialog::SuggestionsType FilterSuggestions(const QmitkNewSegmentationDialog::SuggestionsType& suggestions, const QStringList& blacklist) { QmitkNewSegmentationDialog::SuggestionsType filteredSuggestions; std::remove_copy_if(begin(suggestions), end(suggestions), std::inserter(filteredSuggestions, end(filteredSuggestions)), [&blacklist](const auto& suggestion) { return blacklist.contains(suggestion.first); }); return filteredSuggestions; } } QmitkNewSegmentationDialog::QmitkNewSegmentationDialog(QWidget *parent, mitk::LabelSetImage* labelSetImage, Mode mode) : QDialog(parent), m_Ui(new Ui::QmitkNewSegmentationDialog), m_SuggestOnce(true), m_Color(Qt::red) { m_Ui->setupUi(this); if (RenameLabel == mode) { this->setWindowTitle("Rename Label"); m_Ui->label->setText("New name and color of the label"); m_Ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Rename label"); } else { m_Ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Create label"); } m_Ui->nameLineEdit->setFocus(); connect(this, &QDialog::finished, this, &QmitkNewSegmentationDialog::OnFinished); connect(m_Ui->colorButton, &QToolButton::clicked, this, &QmitkNewSegmentationDialog::OnColorButtonClicked); connect(m_Ui->nameLineEdit, &QLineEdit::textChanged, this, &QmitkNewSegmentationDialog::OnTextChanged); connect(m_Ui->nameList, &QListWidget::itemSelectionChanged, this, &QmitkNewSegmentationDialog::OnSuggestionSelected); connect(m_Ui->nameList, &QListWidget::itemDoubleClicked, this, &QmitkNewSegmentationDialog::OnAccept); connect(m_Ui->buttonBox, &QDialogButtonBox::accepted, this, &QmitkNewSegmentationDialog::OnAccept); this->UpdateColorButtonBackground(); auto prefs = GetPreferences(); - if (!prefs.labelSuggestions.isEmpty()) + if (!prefs.labelSuggestions.empty()) { - auto suggestions = ParseSuggestions(prefs.labelSuggestions.toStdString()); + auto suggestions = ParseSuggestions(prefs.labelSuggestions); this->SetSuggestions(suggestions, prefs.replaceStandardSuggestions && !suggestions.empty()); } else { this->SetSuggestions(GetStandardSuggestions(), true); } if (nullptr != labelSetImage && prefs.suggestOnce) { auto existingLabelNames = GetExistingLabelNames(labelSetImage); m_Suggestions = FilterSuggestions(m_Suggestions, existingLabelNames); this->UpdateNameList(); } - if (!(prefs.geometry.isNull() || prefs.geometry.isEmpty())) - this->restoreGeometry(prefs.geometry); + if (!(prefs.geometry.empty())) + this->restoreGeometry(QByteArray(reinterpret_cast(prefs.geometry.data()), prefs.geometry.size())); } QmitkNewSegmentationDialog::~QmitkNewSegmentationDialog() { } void QmitkNewSegmentationDialog::OnFinished(int) { SaveGeometry(this->saveGeometry()); } void QmitkNewSegmentationDialog::UpdateColorButtonBackground() { m_Ui->colorButton->setStyleSheet("background-color:" + m_Color.name()); } QString QmitkNewSegmentationDialog::GetName() const { return m_Name; } mitk::Color QmitkNewSegmentationDialog::GetColor() const { mitk::Color color; if (m_Color.isValid()) { color.SetRed(m_Color.redF()); color.SetGreen(m_Color.greenF()); color.SetBlue(m_Color.blueF()); } else { color.Set(1.0f, 0.0f, 0.0f); } return color; } void QmitkNewSegmentationDialog::SetName(const QString& name) { m_Ui->nameLineEdit->setText(name); } void QmitkNewSegmentationDialog::SetColor(const mitk::Color& color) { m_Color.setRgbF(color.GetRed(), color.GetGreen(), color.GetBlue()); this->UpdateColorButtonBackground(); } void QmitkNewSegmentationDialog::SetSuggestions(const SuggestionsType& suggestions, bool replaceStandardSuggestions) { m_Suggestions = suggestions; if (!replaceStandardSuggestions) { auto standardSuggestions = GetStandardSuggestions(); // Append all standard suggestions with unique names to the list of custom suggestions std::remove_copy_if(begin(standardSuggestions), end(standardSuggestions), std::inserter(m_Suggestions, end(m_Suggestions)), [this](const auto& suggestion) { return m_Suggestions.end() != std::find_if(begin(m_Suggestions), end(m_Suggestions), [&suggestion](const auto& otherSuggestion) { return suggestion.first == otherSuggestion.first; }); }); } this->UpdateNameList(); } void QmitkNewSegmentationDialog::UpdateNameList() { QStringList names; for (const auto& suggestion : m_Suggestions) names << suggestion.first; m_Ui->nameList->clear(); m_Ui->nameList->addItems(names); } void QmitkNewSegmentationDialog::OnAccept() { m_Name = m_Ui->nameLineEdit->text(); this->accept(); } void QmitkNewSegmentationDialog::OnTextChanged(const QString& text) { auto finding = m_Ui->nameList->findItems(text, Qt::MatchFlag::MatchExactly); if (!finding.isEmpty()) m_Ui->nameList->setCurrentItem(finding.first()); } void QmitkNewSegmentationDialog::OnColorButtonClicked() { auto color = QColorDialog::getColor(m_Color); if (color.isValid()) { m_Color = color; this->UpdateColorButtonBackground(); } } void QmitkNewSegmentationDialog::OnSuggestionSelected() { const auto* currentItem = m_Ui->nameList->currentItem(); if (currentItem == nullptr) return; auto row = m_Ui->nameList->selectionModel()->selectedIndexes().first().row(); m_Ui->nameLineEdit->setText(m_Suggestions[row].first); auto color = m_Suggestions[row].second; if (color.isValid()) { m_Color = color; this->UpdateColorButtonBackground(); } } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp index 803a62ff55..7e5541808f 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp @@ -1,146 +1,146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationPreferencePage.h" -#include -#include - #include +#include +#include +#include #include #include QmitkSegmentationPreferencePage::QmitkSegmentationPreferencePage() : m_Ui(new Ui::QmitkSegmentationPreferencePageControls), m_Control(nullptr), m_Initializing(false) { } QmitkSegmentationPreferencePage::~QmitkSegmentationPreferencePage() { } void QmitkSegmentationPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkSegmentationPreferencePage::CreateQtControl(QWidget* parent) { m_Initializing = true; - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); m_SegmentationPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); connect(m_Ui->labelSetPresetToolButton, SIGNAL(clicked()), this, SLOT(OnLabelSetPresetButtonClicked())); connect(m_Ui->suggestionsToolButton, SIGNAL(clicked()), this, SLOT(OnSuggestionsButtonClicked())); this->Update(); m_Initializing = false; } QWidget* QmitkSegmentationPreferencePage::GetQtControl() const { return m_Control; } bool QmitkSegmentationPreferencePage::PerformOk() { m_SegmentationPreferencesNode->PutBool("slim view", m_Ui->slimViewCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("draw outline", m_Ui->outlineRadioButton->isChecked()); m_SegmentationPreferencesNode->PutBool("selection mode", m_Ui->selectionModeCheckBox->isChecked()); - m_SegmentationPreferencesNode->Put("label set preset", m_Ui->labelSetPresetLineEdit->text()); + m_SegmentationPreferencesNode->Put("label set preset", m_Ui->labelSetPresetLineEdit->text().toStdString()); m_SegmentationPreferencesNode->PutBool("default label naming", m_Ui->defaultNameRadioButton->isChecked()); - m_SegmentationPreferencesNode->Put("label suggestions", m_Ui->suggestionsLineEdit->text()); + m_SegmentationPreferencesNode->Put("label suggestions", m_Ui->suggestionsLineEdit->text().toStdString()); m_SegmentationPreferencesNode->PutBool("replace standard suggestions", m_Ui->replaceStandardSuggestionsCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("suggest once", m_Ui->suggestOnceCheckBox->isChecked()); return true; } void QmitkSegmentationPreferencePage::PerformCancel() { } void QmitkSegmentationPreferencePage::Update() { m_Ui->slimViewCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("slim view", false)); if (m_SegmentationPreferencesNode->GetBool("draw outline", true)) { m_Ui->outlineRadioButton->setChecked(true); } else { m_Ui->overlayRadioButton->setChecked(true); } m_Ui->selectionModeCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("selection mode", false)); auto labelSetPreset = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), ""); bool isOverriddenByCmdLineArg = !labelSetPreset.empty(); if (!isOverriddenByCmdLineArg) - labelSetPreset = m_SegmentationPreferencesNode->Get("label set preset", "").toStdString(); + labelSetPreset = m_SegmentationPreferencesNode->Get("label set preset", ""); m_Ui->labelSetPresetLineEdit->setDisabled(isOverriddenByCmdLineArg); m_Ui->labelSetPresetToolButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->labelSetPresetCmdLineArgLabel->setVisible(isOverriddenByCmdLineArg); m_Ui->labelSetPresetLineEdit->setText(QString::fromStdString(labelSetPreset)); if (m_SegmentationPreferencesNode->GetBool("default label naming", true)) { m_Ui->defaultNameRadioButton->setChecked(true); } else { m_Ui->askForNameRadioButton->setChecked(true); } auto labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), ""); isOverriddenByCmdLineArg = !labelSuggestions.empty(); if (!isOverriddenByCmdLineArg) - labelSuggestions = m_SegmentationPreferencesNode->Get("label suggestions", "").toStdString(); + labelSuggestions = m_SegmentationPreferencesNode->Get("label suggestions", ""); m_Ui->defaultNameRadioButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->askForNameRadioButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsLineEdit->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsToolButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsCmdLineArgLabel->setVisible(isOverriddenByCmdLineArg); m_Ui->suggestionsLineEdit->setText(QString::fromStdString(labelSuggestions)); m_Ui->replaceStandardSuggestionsCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("replace standard suggestions", true)); m_Ui->suggestOnceCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("suggest once", true)); } void QmitkSegmentationPreferencePage::OnLabelSetPresetButtonClicked() { const auto filename = QFileDialog::getOpenFileName(m_Control, QStringLiteral("Load Label Set Preset"), QString(), QStringLiteral("Label set preset (*.lsetp)")); if (!filename.isEmpty()) m_Ui->labelSetPresetLineEdit->setText(filename); } void QmitkSegmentationPreferencePage::OnSuggestionsButtonClicked() { const auto filename = QFileDialog::getOpenFileName(m_Control, QStringLiteral("Load Label Suggestions"), QString(), QStringLiteral("Label suggestions (*.json)")); if (!filename.isEmpty()) m_Ui->suggestionsLineEdit->setText(filename); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h index cd54461ba2..48384f06df 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h @@ -1,65 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSEGMENTATIONPREFERENCEPAGE_H #define QMITKSEGMENTATIONPREFERENCEPAGE_H #include "org_mitk_gui_qt_segmentation_Export.h" -#include #include class QWidget; +namespace mitk +{ + class IPreferences; +} + namespace Ui { class QmitkSegmentationPreferencePageControls; } class MITK_QT_SEGMENTATION QmitkSegmentationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkSegmentationPreferencePage(); ~QmitkSegmentationPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; protected Q_SLOTS: void OnLabelSetPresetButtonClicked(); void OnSuggestionsButtonClicked(); protected: Ui::QmitkSegmentationPreferencePageControls* m_Ui; QWidget* m_Control; bool m_Initializing; - berry::IPreferences::Pointer m_SegmentationPreferencesNode; + mitk::IPreferences* m_SegmentationPreferencesNode; }; #endif // QMITKSEGMENTATIONPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp index 54c3c99e6d..ab52dcf2cf 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp @@ -1,134 +1,135 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkCreatePolygonModelAction.h" // MITK #include #include #include #include #include +#include +#include +#include + // Blueberry -#include -#include -#include #include using namespace berry; using namespace mitk; using namespace std; QmitkCreatePolygonModelAction::QmitkCreatePolygonModelAction() { } QmitkCreatePolygonModelAction::~QmitkCreatePolygonModelAction() { } void QmitkCreatePolygonModelAction::Run(const QList &selectedNodes) { DataNode::Pointer selectedNode = selectedNodes[0]; Image::Pointer image = dynamic_cast(selectedNode->GetData()); if (image.IsNull()) { return; } try { // Get preference properties for smoothing and decimation - IPreferencesService* prefService = Platform::GetPreferencesService(); - IPreferences::Pointer segPref = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* segPref = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); bool smoothingHint = segPref->GetBool("smoothing hint", true); ScalarType smoothing = segPref->GetDouble("smoothing value", 1.0); ScalarType decimation = segPref->GetDouble("decimation rate", 0.5); if (smoothingHint) { smoothing = 0.0; Vector3D spacing = image->GetGeometry()->GetSpacing(); for (Vector3D::Iterator iter = spacing.Begin(); iter != spacing.End(); ++iter) smoothing = max(smoothing, *iter); } ShowSegmentationAsSurface::Pointer surfaceFilter = ShowSegmentationAsSurface::New(); // Activate callback functions itk::SimpleMemberCommand::Pointer successCommand = itk::SimpleMemberCommand::New(); successCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(ResultAvailable(), successCommand); itk::SimpleMemberCommand::Pointer errorCommand = itk::SimpleMemberCommand::New(); errorCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(ProcessingError(), errorCommand); // set filter parameter surfaceFilter->SetDataStorage(*m_DataStorage); surfaceFilter->SetPointerParameter("Input", image); surfaceFilter->SetPointerParameter("Group node", selectedNode); surfaceFilter->SetParameter("Show result", true); surfaceFilter->SetParameter("Sync visibility", false); surfaceFilter->SetParameter("Median kernel size", 3u); surfaceFilter->SetParameter("Decimate mesh", m_IsDecimated); surfaceFilter->SetParameter("Decimation rate", decimation); if (m_IsSmoothed) { surfaceFilter->SetParameter("Apply median", true); surfaceFilter->SetParameter("Smooth", true); surfaceFilter->SetParameter("Gaussian SD", sqrt(smoothing)); // use sqrt to account for setting of variance in preferences StatusBar::GetInstance()->DisplayText("Smoothed surface creation started in background..."); } else { surfaceFilter->SetParameter("Apply median", false); surfaceFilter->SetParameter("Smooth", false); StatusBar::GetInstance()->DisplayText("Surface creation started in background..."); } surfaceFilter->StartAlgorithm(); } catch(...) { MITK_ERROR << "Surface creation failed!"; } } void QmitkCreatePolygonModelAction::OnSurfaceCalculationDone() { StatusBar::GetInstance()->Clear(); } void QmitkCreatePolygonModelAction::SetDataStorage(DataStorage *dataStorage) { m_DataStorage = dataStorage; } void QmitkCreatePolygonModelAction::SetSmoothed(bool smoothed) { m_IsSmoothed = smoothed; } void QmitkCreatePolygonModelAction::SetDecimated(bool decimated) { m_IsDecimated = decimated; } void QmitkCreatePolygonModelAction::SetFunctionality(QtViewPart *) { } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp index 5d9a9bf351..d04f4693c7 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp @@ -1,1137 +1,1138 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationView.h" #include "mitkPluginActivator.h" // blueberry #include // mitk #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include // Qmitk #include #include #include // us #include #include // Qt #include #include #include // vtk #include #include const std::string QmitkSegmentationView::VIEW_ID = "org.mitk.views.segmentation"; QmitkSegmentationView::QmitkSegmentationView() : m_Parent(nullptr) , m_Controls(nullptr) , m_RenderWindowPart(nullptr) , m_ToolManager(nullptr) , m_ReferenceNode(nullptr) , m_WorkingNode(nullptr) , m_DrawOutline(true) , m_SelectionMode(false) , m_MouseCursorSet(false) , m_DefaultLabelNaming(true) , m_SelectionChangeIsAlreadyBeingHandled(false) { auto isImage = mitk::TNodePredicateDataType::New(); auto isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); auto isDti = mitk::NodePredicateDataType::New("TensorImage"); auto isOdf = mitk::NodePredicateDataType::New("OdfImage"); auto isSegment = mitk::NodePredicateDataType::New("Segment"); auto validImages = mitk::NodePredicateOr::New(); validImages->AddPredicate(mitk::NodePredicateAnd::New(isImage, mitk::NodePredicateNot::New(isSegment))); validImages->AddPredicate(isDwi); validImages->AddPredicate(isDti); validImages->AddPredicate(isOdf); auto isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); auto isMask = mitk::NodePredicateAnd::New(isBinary, isImage); auto validSegmentations = mitk::NodePredicateOr::New(); validSegmentations->AddPredicate(mitk::TNodePredicateDataType::New()); validSegmentations->AddPredicate(isMask); m_SegmentationPredicate = mitk::NodePredicateAnd::New(); m_SegmentationPredicate->AddPredicate(validSegmentations); m_SegmentationPredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))); m_SegmentationPredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("hidden object"))); m_ReferencePredicate = mitk::NodePredicateAnd::New(); m_ReferencePredicate->AddPredicate(validImages); m_ReferencePredicate->AddPredicate(mitk::NodePredicateNot::New(m_SegmentationPredicate)); m_ReferencePredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))); m_ReferencePredicate->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("hidden object"))); m_SegmentationInteractor = mitk::SegmentationInteractor::New(); // add observer for the 'SegmentationInteractionEvent' itk::ReceptorMemberCommand::Pointer geometryNotAlignedCommand = itk::ReceptorMemberCommand::New(); geometryNotAlignedCommand->SetCallbackFunction(this, &QmitkSegmentationView::ValidateRendererGeometry); m_SegmentationInteractor->AddObserver(mitk::SegmentationInteractionEvent(nullptr, true), geometryNotAlignedCommand); m_SegmentationInteractor->Disable(); } QmitkSegmentationView::~QmitkSegmentationView() { if (nullptr != m_Controls) { this->LooseLabelSetConnection(); // deactivate all tools m_ToolManager->ActivateTool(-1); // removing all observers from working data for (NodeTagMapType::iterator dataIter = m_WorkingDataObserverTags.begin(); dataIter != m_WorkingDataObserverTags.end(); ++dataIter) { (*dataIter).first->GetProperty("visible")->RemoveObserver((*dataIter).second); } m_WorkingDataObserverTags.clear(); // removing all observers from reference data for (NodeTagMapType::iterator dataIter = m_ReferenceDataObserverTags.begin(); dataIter != m_ReferenceDataObserverTags.end(); ++dataIter) { (*dataIter).first->GetProperty("visible")->RemoveObserver((*dataIter).second); } m_ReferenceDataObserverTags.clear(); mitk::RenderingManager::GetInstance()->RemoveObserver(m_RenderingManagerObserverTag); ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); service->RemoveAllPlanePositions(); context->ungetService(ppmRef); m_ToolManager->SetReferenceData(nullptr); m_ToolManager->SetWorkingData(nullptr); } m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); delete m_Controls; } /**********************************************************************/ /* private Q_SLOTS */ /**********************************************************************/ void QmitkSegmentationView::OnReferenceSelectionChanged(QList) { this->OnAnySelectionChanged(); } void QmitkSegmentationView::OnSegmentationSelectionChanged(QList) { this->OnAnySelectionChanged(); } void QmitkSegmentationView::OnAnySelectionChanged() { // When only a segmentation has been selected and the method is then called by a reference image selection, // the already selected segmentation may not match the geometry predicate of the new reference image anymore. // This will trigger a recursive call of this method further below. While it would be resolved gracefully, we // can spare the extra call with an early-out. The original call of this method will handle the segmentation // selection change afterwards anyway. if (m_SelectionChangeIsAlreadyBeingHandled) return; auto selectedReferenceNode = m_Controls->referenceNodeSelector->GetSelectedNode(); bool referenceNodeChanged = false; m_ToolManager->ActivateTool(-1); if (m_ReferenceNode != selectedReferenceNode) { referenceNodeChanged = true; // Remove visibility observer for the current reference node if (m_ReferenceDataObserverTags.find(m_ReferenceNode) != m_ReferenceDataObserverTags.end()) { m_ReferenceNode->GetProperty("visible")->RemoveObserver(m_ReferenceDataObserverTags[m_ReferenceNode]); m_ReferenceDataObserverTags.erase(m_ReferenceNode); } // Set new reference node m_ReferenceNode = selectedReferenceNode; m_ToolManager->SetReferenceData(m_ReferenceNode); // Prepare for a potential recursive call when changing node predicates of the working node selector m_SelectionChangeIsAlreadyBeingHandled = true; if (m_ReferenceNode.IsNull()) { // Without a reference image, allow all segmentations to be selected m_Controls->workingNodeSelector->SetNodePredicate(m_SegmentationPredicate); m_SelectionChangeIsAlreadyBeingHandled = false; } else { // With a reference image, only allow segmentations that fit the geometry of the reference image to be selected. m_Controls->workingNodeSelector->SetNodePredicate(mitk::NodePredicateAnd::New( mitk::NodePredicateSubGeometry::New(m_ReferenceNode->GetData()->GetGeometry()), m_SegmentationPredicate.GetPointer())); m_SelectionChangeIsAlreadyBeingHandled = false; this->ApplySelectionModeOnReferenceNode(); // Add visibility observer for the new reference node auto command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); m_ReferenceDataObserverTags[m_ReferenceNode] = m_ReferenceNode->GetProperty("visible")->AddObserver(itk::ModifiedEvent(), command); } } auto selectedWorkingNode = m_Controls->workingNodeSelector->GetSelectedNode(); bool workingNodeChanged = false; if (m_WorkingNode != selectedWorkingNode) { workingNodeChanged = true; // Remove visibility observer for the current working node if (m_WorkingDataObserverTags.find(m_WorkingNode) != m_WorkingDataObserverTags.end()) { m_WorkingNode->GetProperty("visible")->RemoveObserver(m_WorkingDataObserverTags[m_WorkingNode]); m_WorkingDataObserverTags.erase(m_WorkingNode); } // Disconnect from current label set image this->LooseLabelSetConnection(); // Set new working node m_WorkingNode = selectedWorkingNode; m_ToolManager->SetWorkingData(m_WorkingNode); if (m_WorkingNode.IsNotNull()) { this->ApplySelectionModeOnWorkingNode(); // Connect to new label set image this->EstablishLabelSetConnection(); m_Controls->labelSetWidget->ResetAllTableWidgetItems(); // Add visibility observer for the new segmentation node auto command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); m_WorkingDataObserverTags[m_WorkingNode] = m_WorkingNode->GetProperty("visible")->AddObserver(itk::ModifiedEvent(), command); } } // Reset camera if any selection changed but only if both reference node and working node are set if ((referenceNodeChanged || workingNodeChanged) && (m_ReferenceNode.IsNotNull() && m_WorkingNode.IsNotNull())) { if (nullptr != m_RenderWindowPart) { m_RenderWindowPart->SetReferenceGeometry(m_ReferenceNode->GetData()->GetTimeGeometry(), false); } } this->UpdateGUI(); } void QmitkSegmentationView::OnVisibilityShortcutActivated() { if (m_WorkingNode.IsNull()) { return; } bool isVisible = false; m_WorkingNode->GetBoolProperty("visible", isVisible); m_WorkingNode->SetVisibility(!isVisible); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::OnLabelToggleShortcutActivated() { if (m_WorkingNode.IsNull()) { return; } auto workingImage = dynamic_cast(m_WorkingNode->GetData()); if (nullptr == workingImage) { return; } this->WaitCursorOn(); workingImage->GetActiveLabelSet()->SetNextActiveLabel(); workingImage->Modified(); this->WaitCursorOff(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::OnNewSegmentation() { m_ToolManager->ActivateTool(-1); if (m_ReferenceNode.IsNull()) { MITK_ERROR << "'Create new segmentation' button should never be clickable unless a reference image is selected."; return; } mitk::Image::ConstPointer referenceImage = dynamic_cast(m_ReferenceNode->GetData()); if (referenceImage.IsNull()) { QMessageBox::information( m_Parent, "New segmentation", "Please load and select an image before starting some action."); return; } if (referenceImage->GetDimension() <= 1) { QMessageBox::information( m_Parent, "New segmentation", "Segmentation is currently not supported for 2D images"); return; } auto segTemplateImage = referenceImage; if (referenceImage->GetDimension() > 3) { QmitkStaticDynamicSegmentationDialog dialog(m_Parent); dialog.SetReferenceImage(referenceImage.GetPointer()); dialog.exec(); segTemplateImage = dialog.GetSegmentationTemplate(); } mitk::DataNode::Pointer newSegmentationNode; try { this->WaitCursorOn(); newSegmentationNode = mitk::LabelSetImageHelper::CreateNewSegmentationNode(m_ReferenceNode, segTemplateImage); this->WaitCursorOff(); } catch (mitk::Exception& e) { this->WaitCursorOff(); MITK_ERROR << "Exception caught: " << e.GetDescription(); QMessageBox::warning(m_Parent, "New segmentation", "Could not create a new segmentation."); return; } auto newLabelSetImage = dynamic_cast(newSegmentationNode->GetData()); if (nullptr == newLabelSetImage) { // something went wrong return; } const auto labelSetPreset = this->GetDefaultLabelSetPreset(); if (labelSetPreset.empty() || !mitk::LabelSetIOHelper::LoadLabelSetImagePreset(labelSetPreset, newLabelSetImage)) { auto newLabel = mitk::LabelSetImageHelper::CreateNewLabel(newLabelSetImage); if (!m_DefaultLabelNaming) { QmitkNewSegmentationDialog dialog(m_Parent); dialog.SetName(QString::fromStdString(newLabel->GetName())); dialog.SetColor(newLabel->GetColor()); if (QDialog::Rejected == dialog.exec()) return; auto name = dialog.GetName(); if (!name.isEmpty()) newLabel->SetName(name.toStdString()); newLabel->SetColor(dialog.GetColor()); } newLabelSetImage->GetActiveLabelSet()->AddLabel(newLabel); } if (!this->GetDataStorage()->Exists(newSegmentationNode)) { this->GetDataStorage()->Add(newSegmentationNode, m_ReferenceNode); } if (m_ToolManager->GetWorkingData(0)) { m_ToolManager->GetWorkingData(0)->SetSelected(false); } newSegmentationNode->SetSelected(true); m_Controls->workingNodeSelector->SetCurrentSelectedNode(newSegmentationNode); } std::string QmitkSegmentationView::GetDefaultLabelSetPreset() const { auto labelSetPreset = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), ""); if (labelSetPreset.empty()) labelSetPreset = m_LabelSetPresetPreference.toStdString(); return labelSetPreset; } void QmitkSegmentationView::OnManualTool2DSelected(int id) { this->ResetMouseCursor(); mitk::StatusBar::GetInstance()->DisplayText(""); if (id >= 0) { std::string text = "Active Tool: \""; text += m_ToolManager->GetToolById(id)->GetName(); text += "\""; mitk::StatusBar::GetInstance()->DisplayText(text.c_str()); us::ModuleResource resource = m_ToolManager->GetToolById(id)->GetCursorIconResource(); this->SetMouseCursor(resource, 0, 0); } } void QmitkSegmentationView::OnShowMarkerNodes(bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = m_ToolManager->GetTools().size(); for (unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(m_ToolManager->GetToolById(i)); if (nullptr == manualSegmentationTool) { continue; } manualSegmentationTool->SetShowMarkerNodes(state); } } void QmitkSegmentationView::OnLayersChanged() { this->EstablishLabelSetConnection(); m_Controls->labelSetWidget->ResetAllTableWidgetItems(); } void QmitkSegmentationView::OnShowLabelTable(bool value) { m_Controls->labelSetWidget->setVisible(value); } void QmitkSegmentationView::OnGoToLabel(const mitk::Point3D& pos) { if (m_RenderWindowPart) { m_RenderWindowPart->SetSelectedPosition(pos); } } void QmitkSegmentationView::OnLabelSetWidgetReset() { this->ValidateSelectionInput(); } /**********************************************************************/ /* private */ /**********************************************************************/ void QmitkSegmentationView::CreateQtPartControl(QWidget* parent) { m_Parent = parent; m_Controls = new Ui::QmitkSegmentationViewControls; m_Controls->setupUi(parent); // *------------------------ // * SHORTCUTS // *------------------------ QShortcut* visibilityShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key::Key_H), parent); connect(visibilityShortcut, &QShortcut::activated, this, &QmitkSegmentationView::OnVisibilityShortcutActivated); QShortcut* labelToggleShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key::Key_L, Qt::CTRL | Qt::Key::Key_I), parent); connect(labelToggleShortcut, &QShortcut::activated, this, &QmitkSegmentationView::OnLabelToggleShortcutActivated); // *------------------------ // * DATA SELECTION WIDGETS // *------------------------ m_Controls->referenceNodeSelector->SetDataStorage(GetDataStorage()); m_Controls->referenceNodeSelector->SetNodePredicate(m_ReferencePredicate); m_Controls->referenceNodeSelector->SetInvalidInfo("Select an image"); m_Controls->referenceNodeSelector->SetPopUpTitel("Select an image"); m_Controls->referenceNodeSelector->SetPopUpHint("Select an image that should be used to define the geometry and bounds of the segmentation."); m_Controls->workingNodeSelector->SetDataStorage(GetDataStorage()); m_Controls->workingNodeSelector->SetNodePredicate(m_SegmentationPredicate); m_Controls->workingNodeSelector->SetInvalidInfo("Select a segmentation"); m_Controls->workingNodeSelector->SetPopUpTitel("Select a segmentation"); m_Controls->workingNodeSelector->SetPopUpHint("Select a segmentation that should be modified. Only segmentation with the same geometry and within the bounds of the reference image are selected."); connect(m_Controls->referenceNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkSegmentationView::OnReferenceSelectionChanged); connect(m_Controls->workingNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkSegmentationView::OnSegmentationSelectionChanged); // *------------------------ // * TOOLMANAGER // *------------------------ m_ToolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); m_ToolManager->SetDataStorage(*(this->GetDataStorage())); m_ToolManager->InitializeTools(); QString segTools2D = tr("Add Subtract Lasso Fill Erase Close Paint Wipe 'Region Growing' 'Live Wire'"); QString segTools3D = tr("Threshold 'UL Threshold' Otsu 'Region Growing 3D' Picking GrowCut"); #ifdef __linux__ segTools3D.append(" nnUNet"); // plugin not enabled for MacOS / Windows #endif std::regex extSegTool2DRegEx("SegTool2D$"); std::regex extSegTool3DRegEx("SegTool3D$"); auto tools = m_ToolManager->GetTools(); for (const auto &tool : tools) { if (std::regex_search(tool->GetNameOfClass(), extSegTool2DRegEx)) { segTools2D.append(QString(" '%1'").arg(tool->GetName())); } else if (std::regex_search(tool->GetNameOfClass(), extSegTool3DRegEx)) { segTools3D.append(QString(" '%1'").arg(tool->GetName())); } } // setup 2D tools m_Controls->toolSelectionBox2D->SetToolManager(*m_ToolManager); m_Controls->toolSelectionBox2D->SetGenerateAccelerators(true); m_Controls->toolSelectionBox2D->SetToolGUIArea(m_Controls->toolGUIArea2D); m_Controls->toolSelectionBox2D->SetDisplayedToolGroups(segTools2D.toStdString()); m_Controls->toolSelectionBox2D->SetLayoutColumns(3); connect(m_Controls->toolSelectionBox2D, &QmitkToolSelectionBox::ToolSelected, this, &QmitkSegmentationView::OnManualTool2DSelected); // setup 3D Tools m_Controls->toolSelectionBox3D->SetToolManager(*m_ToolManager); m_Controls->toolSelectionBox3D->SetGenerateAccelerators(true); m_Controls->toolSelectionBox3D->SetToolGUIArea(m_Controls->toolGUIArea3D); m_Controls->toolSelectionBox3D->SetDisplayedToolGroups(segTools3D.toStdString()); m_Controls->toolSelectionBox3D->SetLayoutColumns(3); m_Controls->slicesInterpolator->SetDataStorage(this->GetDataStorage()); // create general signal / slot connections connect(m_Controls->newSegmentationButton, &QToolButton::clicked, this, &QmitkSegmentationView::OnNewSegmentation); connect(m_Controls->slicesInterpolator, &QmitkSlicesInterpolator::SignalShowMarkerNodes, this, &QmitkSegmentationView::OnShowMarkerNodes); connect(m_Controls->layersWidget, &QmitkLayersWidget::LayersChanged, this, &QmitkSegmentationView::OnLayersChanged); connect(m_Controls->labelsWidget, &QmitkLabelsWidget::ShowLabelTable, this, &QmitkSegmentationView::OnShowLabelTable); // *------------------------ // * LABELSETWIDGET // *------------------------ connect(m_Controls->labelSetWidget, &QmitkLabelSetWidget::goToLabel, this, &QmitkSegmentationView::OnGoToLabel); connect(m_Controls->labelSetWidget, &QmitkLabelSetWidget::LabelSetWidgetReset, this, &QmitkSegmentationView::OnLabelSetWidgetReset); m_Controls->labelSetWidget->SetDataStorage(this->GetDataStorage()); m_Controls->labelSetWidget->hide(); auto command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::ValidateSelectionInput); m_RenderingManagerObserverTag = mitk::RenderingManager::GetInstance()->AddObserver(mitk::RenderingManagerViewsInitializedEvent(), command); m_RenderWindowPart = this->GetRenderWindowPart(); if (nullptr != m_RenderWindowPart) { this->RenderWindowPartActivated(m_RenderWindowPart); } // Make sure the GUI notices if appropriate data is already present on creation. // Should be done last, if everything else is configured because it triggers the autoselection of data. m_Controls->referenceNodeSelector->SetAutoSelectNewNodes(true); m_Controls->workingNodeSelector->SetAutoSelectNewNodes(true); this->UpdateGUI(); } void QmitkSegmentationView::ActiveToolChanged() { auto activeTool = m_ToolManager->GetActiveTool(); if (nullptr == activeTool) { // no tool activated, deactivate the segmentation interactor m_SegmentationInteractor->Disable(); return; } // activate segmentation interactor to get informed about render window entered / left events m_SegmentationInteractor->Enable(); } void QmitkSegmentationView::ValidateRendererGeometry(const itk::EventObject& event) { if (!mitk::SegmentationInteractionEvent().CheckEvent(&event)) { return; } const auto* segmentationInteractionEvent = dynamic_cast(&event); const mitk::BaseRenderer::Pointer sendingRenderer = segmentationInteractionEvent->GetSender(); if (nullptr == sendingRenderer) { return; } bool entered = segmentationInteractionEvent->HasEnteredRenderWindow(); if (entered) { // mouse cursor of tool inside render window // check if tool can be used: reference geometry needs to be aligned with renderer geometry const auto* referenceDataNode = m_ToolManager->GetReferenceData(0); if (nullptr != referenceDataNode) { const auto workingImage = dynamic_cast(referenceDataNode->GetData()); if (nullptr != workingImage) { const mitk::TimeGeometry* workingImageGeometry = workingImage->GetTimeGeometry(); if (nullptr != workingImageGeometry) { bool isGeometryAligned = false; try { isGeometryAligned = mitk::BaseRendererHelper::IsRendererAlignedWithSegmentation(sendingRenderer, workingImageGeometry); } catch (const mitk::Exception& e) { MITK_ERROR << "Unable to validate renderer geometry\n" << "Reason: " << e.GetDescription(); this->ShowRenderWindowWarning(sendingRenderer, true); this->UpdateWarningLabel( tr("Unable to validate renderer geometry. Please see log!")); return; } if (!isGeometryAligned) { this->ShowRenderWindowWarning(sendingRenderer, true); this->UpdateWarningLabel( tr("Please perform a reinit on the segmentation image inside the entered Render Window!")); return; } } } } } this->ShowRenderWindowWarning(sendingRenderer, false); this->UpdateWarningLabel(tr("")); } void QmitkSegmentationView::ShowRenderWindowWarning(mitk::BaseRenderer* baseRenderer, bool show) { const auto* rendererName = baseRenderer->GetName(); auto* renderWindow = m_RenderWindowPart->GetQmitkRenderWindow(rendererName); renderWindow->ShowOverlayMessage(show); } void QmitkSegmentationView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_RenderWindowPart != renderWindowPart) { m_RenderWindowPart = renderWindowPart; } if (nullptr != m_Parent) { m_Parent->setEnabled(true); } if (nullptr == m_Controls) { return; } if (nullptr != m_RenderWindowPart) { // tell the interpolation about tool manager, data storage and render window part QList controllers; controllers.push_back(m_RenderWindowPart->GetQmitkRenderWindow("axial")->GetSliceNavigationController()); controllers.push_back(m_RenderWindowPart->GetQmitkRenderWindow("sagittal")->GetSliceNavigationController()); controllers.push_back(m_RenderWindowPart->GetQmitkRenderWindow("coronal")->GetSliceNavigationController()); m_Controls->slicesInterpolator->Initialize(m_ToolManager, controllers); if (!m_RenderWindowPart->HasCoupledRenderWindows()) { // react if the active tool changed, only if a render window part with decoupled render windows is used m_ToolManager->ActiveToolChanged += mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); } } } void QmitkSegmentationView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* /*renderWindowPart*/) { m_RenderWindowPart = nullptr; if (nullptr != m_Parent) { m_Parent->setEnabled(false); } // remove message-connection to make sure no message is processed if no render window part is available m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate(this, &QmitkSegmentationView::ActiveToolChanged); } -void QmitkSegmentationView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) +void QmitkSegmentationView::OnPreferencesChanged(const mitk::IPreferences* prefs) { auto labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), ""); m_DefaultLabelNaming = labelSuggestions.empty() ? prefs->GetBool("default label naming", true) : false; // No default label naming when label suggestions are enforced via command-line argument if (nullptr != m_Controls) { m_Controls->labelsWidget->SetDefaultLabelNaming(m_DefaultLabelNaming); bool slimView = prefs->GetBool("slim view", false); m_Controls->toolSelectionBox2D->SetShowNames(!slimView); m_Controls->toolSelectionBox3D->SetShowNames(!slimView); } m_DrawOutline = prefs->GetBool("draw outline", true); m_SelectionMode = prefs->GetBool("selection mode", false); - m_LabelSetPresetPreference = prefs->Get("label set preset", ""); + m_LabelSetPresetPreference = QString::fromStdString(prefs->Get("label set preset", "")); this->ApplyDisplayOptions(); this->ApplySelectionMode(); } void QmitkSegmentationView::NodeAdded(const mitk::DataNode* node) { if (m_SegmentationPredicate->CheckNode(node)) this->ApplyDisplayOptions(const_cast(node)); this->ApplySelectionMode(); } void QmitkSegmentationView::NodeRemoved(const mitk::DataNode* node) { if (!m_SegmentationPredicate->CheckNode(node)) { return; } // remove all possible contour markers of the segmentation mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = this->GetDataStorage()->GetDerivations( node, mitk::NodePredicateProperty::New("isContourMarker", mitk::BoolProperty::New(true))); ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t + 1).c_str()) - 1; service->RemovePlanePosition(id); this->GetDataStorage()->Remove(it->Value()); } context->ungetService(ppmRef); service = nullptr; mitk::Image* image = dynamic_cast(node->GetData()); mitk::SurfaceInterpolationController::GetInstance()->RemoveInterpolationSession(image); } void QmitkSegmentationView::EstablishLabelSetConnection() { if (m_WorkingNode.IsNull()) return; auto workingImage = dynamic_cast(m_WorkingNode->GetData()); workingImage->GetActiveLabelSet()->AddLabelEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->RemoveLabelEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->ModifyLabelEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->AllLabelsModifiedEvent += mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->ActiveLabelEvent += mitk::MessageDelegate1(m_Controls->labelSetWidget, &QmitkLabelSetWidget::SelectLabelByPixelValue); workingImage->AfterChangeLayerEvent += mitk::MessageDelegate( this, &QmitkSegmentationView::UpdateGUI); } void QmitkSegmentationView::LooseLabelSetConnection() { if (m_WorkingNode.IsNull()) return; auto workingImage = dynamic_cast(m_WorkingNode->GetData()); workingImage->GetActiveLabelSet()->AddLabelEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->RemoveLabelEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::ResetAllTableWidgetItems); workingImage->GetActiveLabelSet()->ModifyLabelEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->AllLabelsModifiedEvent -= mitk::MessageDelegate( m_Controls->labelSetWidget, &QmitkLabelSetWidget::UpdateAllTableWidgetItems); workingImage->GetActiveLabelSet()->ActiveLabelEvent -= mitk::MessageDelegate1(m_Controls->labelSetWidget, &QmitkLabelSetWidget::SelectLabelByPixelValue); workingImage->AfterChangeLayerEvent -= mitk::MessageDelegate( this, &QmitkSegmentationView::UpdateGUI); } void QmitkSegmentationView::ApplyDisplayOptions() { if (nullptr == m_Parent) { return; } if (nullptr == m_Controls) { return; // might happen on initialization (preferences loaded) } mitk::DataStorage::SetOfObjects::ConstPointer allImages = this->GetDataStorage()->GetSubset(m_SegmentationPredicate); for (mitk::DataStorage::SetOfObjects::const_iterator iter = allImages->begin(); iter != allImages->end(); ++iter) { this->ApplyDisplayOptions(*iter); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::ApplyDisplayOptions(mitk::DataNode* node) { if (nullptr == node) { return; } auto labelSetImage = dynamic_cast(node->GetData()); if (nullptr != labelSetImage) { // node is a multi label segmentation // its outline property can be set in the segmentation preference page node->SetProperty("labelset.contour.active", mitk::BoolProperty::New(m_DrawOutline)); // force render window update to show outline node->GetData()->Modified(); } else if (nullptr != node->GetData()) { // node is a legacy binary segmentation bool isBinary = false; node->GetBoolProperty("binary", isBinary); if (isBinary) { node->SetProperty("outline binary", mitk::BoolProperty::New(m_DrawOutline)); node->SetProperty("outline width", mitk::FloatProperty::New(2.0)); // force render window update to show outline node->GetData()->Modified(); } } } void QmitkSegmentationView::ApplySelectionMode() { if (!m_SelectionMode) return; this->ApplySelectionModeOnReferenceNode(); this->ApplySelectionModeOnWorkingNode(); } void QmitkSegmentationView::ApplySelectionModeOnReferenceNode() { this->ApplySelectionMode(m_ReferenceNode, m_ReferencePredicate); } void QmitkSegmentationView::ApplySelectionModeOnWorkingNode() { this->ApplySelectionMode(m_WorkingNode, m_SegmentationPredicate); } void QmitkSegmentationView::ApplySelectionMode(mitk::DataNode* node, mitk::NodePredicateBase* predicate) { if (!m_SelectionMode || node == nullptr || predicate == nullptr) return; auto nodes = this->GetDataStorage()->GetSubset(predicate); for (auto iter = nodes->begin(); iter != nodes->end(); ++iter) (*iter)->SetVisibility(*iter == node); } void QmitkSegmentationView::OnContourMarkerSelected(const mitk::DataNode* node) { QmitkRenderWindow* selectedRenderWindow = nullptr; auto* renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN); auto* axialRenderWindow = renderWindowPart->GetQmitkRenderWindow("axial"); auto* sagittalRenderWindow = renderWindowPart->GetQmitkRenderWindow("sagittal"); auto* coronalRenderWindow = renderWindowPart->GetQmitkRenderWindow("coronal"); auto* threeDRenderWindow = renderWindowPart->GetQmitkRenderWindow("3d"); bool PlanarFigureInitializedWindow = false; // find initialized renderwindow if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, axialRenderWindow->GetRenderer())) { selectedRenderWindow = axialRenderWindow; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, sagittalRenderWindow->GetRenderer())) { selectedRenderWindow = sagittalRenderWindow; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, coronalRenderWindow->GetRenderer())) { selectedRenderWindow = coronalRenderWindow; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, threeDRenderWindow->GetRenderer())) { selectedRenderWindow = threeDRenderWindow; } // make node visible if (nullptr != selectedRenderWindow) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t + 1).c_str()) - 1; ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); selectedRenderWindow->GetSliceNavigationController()->ExecuteOperation(service->GetPlanePosition(id)); context->ungetService(ppmRef); selectedRenderWindow->GetRenderer()->GetCameraController()->Fit(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSegmentationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& nodes) { if (0 == nodes.size()) { return; } std::string markerName = "Position"; unsigned int numberOfNodes = nodes.size(); std::string nodeName = nodes.at(0)->GetName(); if ((numberOfNodes == 1) && (nodeName.find(markerName) == 0)) { this->OnContourMarkerSelected(nodes.at(0)); return; } } void QmitkSegmentationView::ResetMouseCursor() { if (m_MouseCursorSet) { mitk::ApplicationCursor::GetInstance()->PopCursor(); m_MouseCursorSet = false; } } void QmitkSegmentationView::SetMouseCursor(const us::ModuleResource& resource, int hotspotX, int hotspotY) { // Remove previously set mouse cursor if (m_MouseCursorSet) { this->ResetMouseCursor(); } if (resource) { us::ModuleResourceStream cursor(resource, std::ios::binary); mitk::ApplicationCursor::GetInstance()->PushCursor(cursor, hotspotX, hotspotY); m_MouseCursorSet = true; } } void QmitkSegmentationView::UpdateGUI() { mitk::DataNode* referenceNode = m_ToolManager->GetReferenceData(0); bool hasReferenceNode = referenceNode != nullptr; mitk::DataNode* workingNode = m_ToolManager->GetWorkingData(0); bool hasWorkingNode = workingNode != nullptr; m_Controls->newSegmentationButton->setEnabled(false); if (hasReferenceNode) { m_Controls->newSegmentationButton->setEnabled(true); } if (hasWorkingNode && hasReferenceNode) { int layer = -1; referenceNode->GetIntProperty("layer", layer); workingNode->SetIntProperty("layer", layer + 1); } m_Controls->layersWidget->UpdateGUI(); m_Controls->labelsWidget->UpdateGUI(); this->ValidateSelectionInput(); } void QmitkSegmentationView::ValidateSelectionInput() { auto referenceNode = m_Controls->referenceNodeSelector->GetSelectedNode(); auto workingNode = m_Controls->workingNodeSelector->GetSelectedNode(); bool hasReferenceNode = referenceNode.IsNotNull(); bool hasWorkingNode = workingNode.IsNotNull(); bool hasBothNodes = hasReferenceNode && hasWorkingNode; QString warning; bool toolSelectionBoxesEnabled = hasReferenceNode && hasWorkingNode; unsigned int numberOfLabels = 0; m_Controls->layersWidget->setEnabled(hasWorkingNode); m_Controls->labelsWidget->setEnabled(hasWorkingNode); m_Controls->labelSetWidget->setEnabled(hasWorkingNode); m_Controls->toolSelectionBox2D->setEnabled(hasBothNodes); m_Controls->toolSelectionBox3D->setEnabled(hasBothNodes); m_Controls->slicesInterpolator->setEnabled(false); m_Controls->interpolatorWarningLabel->hide(); if (hasReferenceNode) { if (!referenceNode->IsVisible(nullptr)) { warning += tr("The selected reference image is currently not visible!"); toolSelectionBoxesEnabled = false; } } if (hasWorkingNode) { if (!workingNode->IsVisible(nullptr)) { warning += (!warning.isEmpty() ? "
" : "") + tr("The selected segmentation is currently not visible!"); toolSelectionBoxesEnabled = false; } auto labelSetImage = dynamic_cast(workingNode->GetData()); auto activeLayer = labelSetImage->GetActiveLayer(); numberOfLabels = labelSetImage->GetNumberOfLabels(activeLayer); if (2 == numberOfLabels) { m_Controls->slicesInterpolator->setEnabled(true); } else if (2 < numberOfLabels) { m_Controls->interpolatorWarningLabel->setText( "Interpolation only works for single label segmentations."); m_Controls->interpolatorWarningLabel->show(); } } toolSelectionBoxesEnabled &= numberOfLabels > 1; // Here we need to check whether the geometry of the selected segmentation image (working image geometry) // is aligned with the geometry of the 3D render window. // It is not allowed to use a geometry different from the working image geometry for segmenting. // We only need to this if the tool selection box would be enabled without this check. if (toolSelectionBoxesEnabled && nullptr != m_RenderWindowPart && m_RenderWindowPart->HasCoupledRenderWindows()) { const mitk::BaseGeometry* workingNodeGeometry = workingNode->GetData()->GetGeometry(); const mitk::BaseGeometry* renderWindowGeometry = m_RenderWindowPart->GetQmitkRenderWindow("3d")->GetSliceNavigationController()->GetCurrentGeometry3D(); if (nullptr != workingNodeGeometry && nullptr != renderWindowGeometry) { if (!mitk::Equal(*workingNodeGeometry->GetBoundingBox(), *renderWindowGeometry->GetBoundingBox(), mitk::eps, true)) { warning += (!warning.isEmpty() ? "
" : "") + tr("Please reinitialize the selected segmentation image!"); toolSelectionBoxesEnabled = false; } } } m_Controls->toolSelectionBox2D->setEnabled(toolSelectionBoxesEnabled); m_Controls->toolSelectionBox3D->setEnabled(toolSelectionBoxesEnabled); this->UpdateWarningLabel(warning); m_ToolManager->SetReferenceData(referenceNode); m_ToolManager->SetWorkingData(workingNode); } void QmitkSegmentationView::UpdateWarningLabel(QString text) { if (text.isEmpty()) { m_Controls->selectionWarningLabel->hide(); } else { m_Controls->selectionWarningLabel->setText("" + text + ""); m_Controls->selectionWarningLabel->show(); } } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h index 721db55df7..5710410c5c 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h @@ -1,206 +1,204 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSEGMENTATIONVIEW_H #define QMITKSEGMENTATIONVIEW_H #include "ui_QmitkSegmentationViewControls.h" #include #include -#include - #include /** * @brief The segmentation view provides a set of tool to use different segmentation algorithms. * It provides two selection widgets to load an image node and a segmentation node * on which to perform the segmentation. Creating new segmentation nodes is also possible. * The available segmentation tools are grouped into "2D"- and "3D"-tools. * * Most segmentation tools / algorithms need some kind of user interaction, where the * user is asked to draw something in the image display or set some seed points / start values. * The tools also often provide additional propeties so that a user can modify the * algorithm's behavior. * * This class additionally provides options to work with different layers (create new layers, * switch between layers). * Moreover, a multilabel widget displays all the existing labels of a multilabel segmentation * for the currently active layer. * The multilabel widget allows to control the labels by creatin new one, removing existing ones, * showing / hiding single labels, merging labels, (re-)naming them etc. * * Additionally the view provides an option to create "2D"- and "3D"-interpolations between * neighboring segmentation masks on unsegmented slices. * Interpolation for multilabel segmentations is currently not implemented. */ class QmitkSegmentationView : public QmitkAbstractView, public mitk::IRenderWindowPartListener { Q_OBJECT public: static const std::string VIEW_ID; QmitkSegmentationView(); ~QmitkSegmentationView() override; private Q_SLOTS: // reaction to the selection of a new reference image in the selection widget void OnReferenceSelectionChanged(QList nodes); // reaction to the selection of a new segmentation image in the selection widget void OnSegmentationSelectionChanged(QList nodes); // reaction to the shortcut ("CTRL+H") for toggling the visibility of the working node void OnVisibilityShortcutActivated(); // reaction to the shortcut ("CTRL+L") for iterating over all labels void OnLabelToggleShortcutActivated(); // reaction to the button "New segmentation" void OnNewSegmentation(); void OnManualTool2DSelected(int id); void OnShowMarkerNodes(bool); void OnLayersChanged(); void OnShowLabelTable(bool); void OnGoToLabel(const mitk::Point3D &pos); void OnLabelSetWidgetReset(); private: void CreateQtPartControl(QWidget* parent) override; void SetFocus() override {} /** * @brief Enable or disable the SegmentationInteractor. * * The active tool is retrieved from the tool manager. * If the active tool is valid, the SegmentationInteractor is enabled * to listen to 'SegmentationInteractionEvent's. */ void ActiveToolChanged(); /** * @brief Test whether the geometry of the reference image * fits the world geometry of the respective renderer. * * The respective renderer is retrieved from the given event, which * needs to be a 'SegmentationInteractionEvent'. * This event provides not only the sending base renderer but also a * bool that indicates whether the mouse cursor entered or left the * base renderer. * This information is used to compare the renderer's world geometry * with the oriented time geometry of the current reference image. * If the geometries align, the renderer is not blocked anymore and the * view's warning message is removed. * If the geometries do not align, 'ShowRenderWindowWarning' is called * and a warning message is added to the top of this plugin view. * * @param event The observed mitk::SegmentationInteractionEvent. */ void ValidateRendererGeometry(const itk::EventObject& event); /** * @brief Show a warning on the given base renderer. * * This function will show the overlay on the QmitkRenderWindow * corresponding to the given base renderer to indicate that the * renderer should not be used for interactive image segmentation. * * @param baseRenderer The base renderer to "block" * @param show If true, the overlay widget will be shown. * If false, the overlay widget will be hid. */ void ShowRenderWindowWarning(mitk::BaseRenderer* baseRenderer, bool show); void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override; - void OnPreferencesChanged(const berry::IBerryPreferences* prefs) override; + void OnPreferencesChanged(const mitk::IPreferences* prefs) override; void NodeAdded(const mitk::DataNode* node) override; void NodeRemoved(const mitk::DataNode* node) override; void EstablishLabelSetConnection(); void LooseLabelSetConnection(); void OnAnySelectionChanged(); // make sure all images / segmentations look according to the user preference settings void ApplyDisplayOptions(); // decorates a DataNode according to the user preference settings void ApplyDisplayOptions(mitk::DataNode* node); void ApplySelectionMode(); void ApplySelectionModeOnReferenceNode(); void ApplySelectionModeOnWorkingNode(); void ApplySelectionMode(mitk::DataNode* node, mitk::NodePredicateBase* predicate); // If a contourmarker is selected, the plane in the related widget will be reoriented according to the marker`s geometry void OnContourMarkerSelected(const mitk::DataNode* node); void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) override; void ResetMouseCursor(); void SetMouseCursor(const us::ModuleResource&, int hotspotX, int hotspotY); void UpdateGUI(); void ValidateSelectionInput(); void UpdateWarningLabel(QString text); std::string GetDefaultLabelSetPreset() const; QWidget* m_Parent; Ui::QmitkSegmentationViewControls* m_Controls; mitk::IRenderWindowPart* m_RenderWindowPart; mitk::ToolManager* m_ToolManager; mitk::DataNode::Pointer m_ReferenceNode; mitk::DataNode::Pointer m_WorkingNode; mitk::SegmentationInteractor::Pointer m_SegmentationInteractor; typedef std::map NodeTagMapType; NodeTagMapType m_WorkingDataObserverTags; NodeTagMapType m_ReferenceDataObserverTags; unsigned int m_RenderingManagerObserverTag; mitk::NodePredicateAnd::Pointer m_ReferencePredicate; mitk::NodePredicateAnd::Pointer m_SegmentationPredicate; bool m_DrawOutline; bool m_SelectionMode; bool m_MouseCursorSet; QString m_LabelSetPresetPreference; bool m_DefaultLabelNaming; bool m_SelectionChangeIsAlreadyBeingHandled; }; #endif // QMITKSEGMENTATIONVIEW_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp index e50a27bfcd..7d6054779d 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp @@ -1,74 +1,78 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "QmitkSegmentationView.h" #include "QmitkSegmentationPreferencePage.h" #include "SegmentationUtilities/QmitkSegmentationUtilitiesView.h" #include "QmitkAutocropAction.h" #include "QmitkAutocropLabelSetImageAction.h" #include "QmitkCreatePolygonModelAction.h" #include "QmitkLoadMultiLabelPresetAction.h" #include "QmitkSaveMultiLabelPresetAction.h" #include "QmitkConvertSurfaceToLabelAction.h" #include "QmitkConvertMaskToLabelAction.h" #include "QmitkConvertToMultiLabelSegmentationAction.h" #include "QmitkCreateMultiLabelSegmentationAction.h" +#include + +US_INITIALIZE_MODULE + using namespace mitk; ctkPluginContext* PluginActivator::m_context = nullptr; PluginActivator* PluginActivator::m_Instance = nullptr; PluginActivator::PluginActivator() { m_Instance = this; } PluginActivator::~PluginActivator() { m_Instance = nullptr; } void PluginActivator::start(ctkPluginContext *context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationUtilitiesView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAutocropAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAutocropLabelSetImageAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkCreatePolygonModelAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkLoadMultiLabelPresetAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSaveMultiLabelPresetAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertSurfaceToLabelAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertMaskToLabelAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkConvertToMultiLabelSegmentationAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkCreateMultiLabelSegmentationAction, context) this->m_context = context; } void PluginActivator::stop(ctkPluginContext *) { this->m_context = nullptr; } PluginActivator* PluginActivator::getDefault() { return m_Instance; } ctkPluginContext*PluginActivator::getContext() { return m_context; } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp index dd081bb3ea..ae9296d22f 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp @@ -1,396 +1,398 @@ /*============================================================================ 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 "QmitkStdMultiWidgetEditor.h" #include #include -#include -#include + +#include +#include +#include #include #include #include #include #include // mitk qt widgets module #include #include #include #include // mitk gui qt common plugin #include const QString QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; struct QmitkStdMultiWidgetEditor::Impl final { Impl(); ~Impl() = default; QmitkInteractionSchemeToolBar* m_InteractionSchemeToolBar; QmitkLevelWindowWidget* m_LevelWindowWidget; std::unique_ptr m_MultiWidgetDecorationManager; }; QmitkStdMultiWidgetEditor::Impl::Impl() : m_InteractionSchemeToolBar(nullptr) , m_LevelWindowWidget(nullptr) { // nothing here } ////////////////////////////////////////////////////////////////////////// // QmitkStdMultiWidgetEditor ////////////////////////////////////////////////////////////////////////// QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : QmitkAbstractMultiWidgetEditor() , m_Impl(std::make_unique()) { // nothing here } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { GetSite()->GetPage()->RemovePartListener(this); } berry::IPartListener::Events::Types QmitkStdMultiWidgetEditor::GetPartEventTypes() const { return Events::CLOSED | Events::OPENED | Events::HIDDEN | Events::VISIBLE; } void QmitkStdMultiWidgetEditor::PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->RemovePlanesFromDataStorage(); multiWidget->ActivateMenuWidget(false); } } } void QmitkStdMultiWidgetEditor::PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->AddPlanesToDataStorage(); multiWidget->ActivateMenuWidget(true); } } } void QmitkStdMultiWidgetEditor::PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->ActivateMenuWidget(false); } } } void QmitkStdMultiWidgetEditor::PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr != multiWidget) { multiWidget->ActivateMenuWidget(true); } } } QmitkLevelWindowWidget* QmitkStdMultiWidgetEditor::GetLevelWindowWidget() const { return m_Impl->m_LevelWindowWidget; } void QmitkStdMultiWidgetEditor::EnableSlicingPlanes(bool enable) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr == multiWidget) { return; } multiWidget->SetWidgetPlanesVisibility(enable); } bool QmitkStdMultiWidgetEditor::IsSlicingPlanesEnabled() const { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr == multiWidget) { return false; } mitk::DataNode::Pointer node = multiWidget->GetWidgetPlane1(); if (node.IsNotNull()) { bool visible = false; node->GetVisibility(visible, nullptr); return visible; } else { return false; } } void QmitkStdMultiWidgetEditor::OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme) { const auto& multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { return; } if (mitk::InteractionSchemeSwitcher::PACSStandard == scheme) { m_Impl->m_InteractionSchemeToolBar->setVisible(true); } else { m_Impl->m_InteractionSchemeToolBar->setVisible(false); } QmitkAbstractMultiWidgetEditor::OnInteractionSchemeChanged(scheme); } void QmitkStdMultiWidgetEditor::ShowLevelWindowWidget(bool show) { if (show) { m_Impl->m_LevelWindowWidget->disconnect(this); m_Impl->m_LevelWindowWidget->SetDataStorage(GetDataStorage()); m_Impl->m_LevelWindowWidget->show(); } else { m_Impl->m_LevelWindowWidget->disconnect(this); m_Impl->m_LevelWindowWidget->hide(); } } void QmitkStdMultiWidgetEditor::SetFocus() { const auto& multiWidget = GetMultiWidget(); if (nullptr != multiWidget) { multiWidget->setFocus(); } } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { QHBoxLayout* layout = new QHBoxLayout(parent); layout->setContentsMargins(0, 0, 0, 0); - berry::IBerryPreferences* preferences = dynamic_cast(GetPreferences().GetPointer()); + auto* preferences = this->GetPreferences(); auto multiWidget = GetMultiWidget(); if (nullptr == multiWidget) { multiWidget = new QmitkStdMultiWidget(parent); // create left toolbar: interaction scheme toolbar to switch how the render window navigation behaves (in PACS mode) if (nullptr == m_Impl->m_InteractionSchemeToolBar) { m_Impl->m_InteractionSchemeToolBar = new QmitkInteractionSchemeToolBar(parent); layout->addWidget(m_Impl->m_InteractionSchemeToolBar); } m_Impl->m_InteractionSchemeToolBar->SetInteractionEventHandler(multiWidget->GetInteractionEventHandler()); multiWidget->SetDataStorage(GetDataStorage()); multiWidget->InitializeMultiWidget(); SetMultiWidget(multiWidget); } layout->addWidget(multiWidget); // create level window slider on the right side if (nullptr == m_Impl->m_LevelWindowWidget) { m_Impl->m_LevelWindowWidget = new QmitkLevelWindowWidget(parent); m_Impl->m_LevelWindowWidget->setObjectName(QString::fromUtf8("levelWindowWidget")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(m_Impl->m_LevelWindowWidget->sizePolicy().hasHeightForWidth()); m_Impl->m_LevelWindowWidget->setSizePolicy(sizePolicy); m_Impl->m_LevelWindowWidget->setMaximumWidth(50); } layout->addWidget(m_Impl->m_LevelWindowWidget); m_Impl->m_MultiWidgetDecorationManager = std::make_unique(multiWidget); GetSite()->GetPage()->AddPartListener(this); InitializePreferences(preferences); OnPreferencesChanged(preferences); } -void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* preferences) +void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const mitk::IPreferences* preferences) { const auto& multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr == multiWidget) { return; } // change and apply decoration preferences GetPreferenceDecorations(preferences); m_Impl->m_MultiWidgetDecorationManager->DecorationPreferencesChanged(preferences); QmitkAbstractMultiWidget::RenderWindowWidgetMap renderWindowWidgets = multiWidget->GetRenderWindowWidgets(); int i = 0; for (const auto& renderWindowWidget : renderWindowWidgets) { auto decorationColor = renderWindowWidget.second->GetDecorationColor(); multiWidget->SetDecorationColor(i, decorationColor); ++i; } int crosshairGapSize = preferences->GetInt("crosshair gap size", 32); multiWidget->SetCrosshairGap(crosshairGapSize); // zooming and panning preferences bool constrainedZooming = preferences->GetBool("Use constrained zooming and panning", true); mitk::RenderingManager::GetInstance()->SetConstrainedPanningZooming(constrainedZooming); // mouse modes switcher toolbar bool PACSInteractionScheme = preferences->GetBool("PACS like mouse interaction", false); OnInteractionSchemeChanged(PACSInteractionScheme ? mitk::InteractionSchemeSwitcher::PACSStandard : mitk::InteractionSchemeSwitcher::MITKStandard); // level window setting bool showLevelWindowWidget = preferences->GetBool("Show level/window widget", true); ShowLevelWindowWidget(showLevelWindowWidget); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } -void QmitkStdMultiWidgetEditor::InitializePreferences(berry::IBerryPreferences * preferences) +void QmitkStdMultiWidgetEditor::InitializePreferences(mitk::IPreferences * preferences) { auto multiWidget = this->GetMultiWidget(); if (nullptr == multiWidget) return; this->GetPreferenceDecorations(preferences); // Override if preferences are defined for (const auto& renderWindowWidget : multiWidget->GetRenderWindowWidgets()) { - auto widgetName = renderWindowWidget.second->GetWidgetName(); + auto widgetName = renderWindowWidget.second->GetWidgetName().toStdString(); auto gradientBackgroundColors = renderWindowWidget.second->GetGradientBackgroundColors(); preferences->Put(widgetName + " first background color", this->MitkColorToHex(gradientBackgroundColors.first)); preferences->Put(widgetName + " second background color", this->MitkColorToHex(gradientBackgroundColors.second)); auto decorationColor = renderWindowWidget.second->GetDecorationColor(); preferences->Put(widgetName + " decoration color", this->MitkColorToHex(decorationColor)); auto cornerAnnotation = renderWindowWidget.second->GetCornerAnnotationText(); - preferences->Put(widgetName + " corner annotation", QString::fromStdString(cornerAnnotation)); + preferences->Put(widgetName + " corner annotation", cornerAnnotation); } } -void QmitkStdMultiWidgetEditor::GetPreferenceDecorations(const berry::IBerryPreferences * preferences) +void QmitkStdMultiWidgetEditor::GetPreferenceDecorations(const mitk::IPreferences * preferences) { auto multiWidget = dynamic_cast(GetMultiWidget()); if (nullptr == multiWidget) return; auto hexBlack = "#000000"; auto gradientBlack = "#191919"; auto gradientGray = "#7F7F7F"; auto renderWindowWidgets = multiWidget->GetRenderWindowWidgets(); int i = 0; for (const auto& renderWindowWidget : renderWindowWidgets) { - auto widgetName = renderWindowWidget.second->GetWidgetName(); + auto widgetName = renderWindowWidget.second->GetWidgetName().toStdString(); if (mitk::BaseRenderer::Standard3D == mitk::BaseRenderer::GetInstance(renderWindowWidget.second->GetRenderWindow()->GetVtkRenderWindow())->GetMapperID()) { auto upper = preferences->Get(widgetName + " first background color", gradientBlack); auto lower = preferences->Get(widgetName + " second background color", gradientGray); renderWindowWidget.second->SetGradientBackgroundColors(HexColorToMitkColor(upper), HexColorToMitkColor(lower)); } else { auto upper = preferences->Get(widgetName + " first background color", hexBlack); auto lower = preferences->Get(widgetName + " second background color", hexBlack); renderWindowWidget.second->SetGradientBackgroundColors(HexColorToMitkColor(upper), HexColorToMitkColor(lower)); } auto defaultDecorationColor = multiWidget->GetDecorationColor(i); auto decorationColor = preferences->Get(widgetName + " decoration color", MitkColorToHex(defaultDecorationColor)); renderWindowWidget.second->SetDecorationColor(HexColorToMitkColor(decorationColor)); auto defaultCornerAnnotation = renderWindowWidget.second->GetCornerAnnotationText(); - auto cornerAnnotation = preferences->Get(widgetName + " corner annotation", QString::fromStdString(defaultCornerAnnotation)); - renderWindowWidget.second->SetCornerAnnotationText(cornerAnnotation.toStdString()); + auto cornerAnnotation = preferences->Get(widgetName + " corner annotation", defaultCornerAnnotation); + renderWindowWidget.second->SetCornerAnnotationText(cornerAnnotation); ++i; } } -mitk::Color QmitkStdMultiWidgetEditor::HexColorToMitkColor(const QString& hexColor) +mitk::Color QmitkStdMultiWidgetEditor::HexColorToMitkColor(const std::string& hexColor) { - QColor qColor(hexColor); + QColor qColor(hexColor.c_str()); mitk::Color returnColor; float colorMax = 255.0f; - if (hexColor.isEmpty()) // default value + if (hexColor.empty()) // default value { returnColor[0] = 1.0; returnColor[1] = 1.0; returnColor[2] = 1.0; - MITK_ERROR << "Using default color for unknown hex color " << qPrintable(hexColor); + MITK_ERROR << "Using default color for unknown hex color " << hexColor; } else { returnColor[0] = qColor.red() / colorMax; returnColor[1] = qColor.green() / colorMax; returnColor[2] = qColor.blue() / colorMax; } return returnColor; } -QString QmitkStdMultiWidgetEditor::MitkColorToHex(const mitk::Color& color) +std::string QmitkStdMultiWidgetEditor::MitkColorToHex(const mitk::Color& color) { QColor returnColor; float colorMax = 255.0f; returnColor.setRed(static_cast(color[0] * colorMax + 0.5)); returnColor.setGreen(static_cast(color[1] * colorMax + 0.5)); returnColor.setBlue(static_cast(color[2] * colorMax + 0.5)); - return returnColor.name(); + return returnColor.name().toStdString(); } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h index d63c876a90..95fe0399b0 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h @@ -1,125 +1,130 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSTDMULTIWIDGETEDITOR_H #define QMITKSTDMULTIWIDGETEDITOR_H // mitk gui qt common plugin #include #include #include // c++ #include class QmitkStdMultiWidget; class QmitkStdMultiWidgetEditorPrivate; +namespace mitk +{ + class IPreferences; +} + /** * @brief */ class ORG_MITK_GUI_QT_STDMULTIWIDGETEDITOR QmitkStdMultiWidgetEditor final : public QmitkAbstractMultiWidgetEditor, public mitk::ILinkedRenderWindowPart { Q_OBJECT public: static const QString EDITOR_ID; QmitkStdMultiWidgetEditor(); virtual ~QmitkStdMultiWidgetEditor() override; virtual QmitkLevelWindowWidget* GetLevelWindowWidget() const override; /** * @brief Overridden from mitk::ILinkedRenderWindowPart */ virtual void EnableSlicingPlanes(bool enable) override; /** * @brief Overridden from mitk::ILinkedRenderWindowPart */ virtual bool IsSlicingPlanesEnabled() const override; /** * @brief Overridden from berry::IPartListener */ virtual berry::IPartListener::Events::Types GetPartEventTypes() const override; /** * @brief Overridden from berry::IPartListener */ virtual void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) override; void OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme) override; void ShowLevelWindowWidget(bool show); private: /** * @brief Overridden from QmitkAbstractRenderEditor */ virtual void SetFocus() override; /** * @brief Overridden from QmitkAbstractRenderEditor */ virtual void CreateQtPartControl(QWidget* parent) override; /** * @brief Overridden from QmitkAbstractRenderEditor */ - virtual void OnPreferencesChanged(const berry::IBerryPreferences* preferences) override; + virtual void OnPreferencesChanged(const mitk::IPreferences* preferences) override; /** * @brief InitializePreferences Internal helper method to set default preferences. * This method is used to show the current preferences in the first call of * the preference page (the GUI). * * @param preferences berry preferences. */ - void InitializePreferences(berry::IBerryPreferences *preferences); + void InitializePreferences(mitk::IPreferences *preferences); /** * @brief GetPreferenceDecorations Getter to fill internal members with values of preferences. * @param preferences The berry preferences. * * If a preference is set, the value will overwrite the current value. If it does not exist, * the value will not change. */ - void GetPreferenceDecorations(const berry::IBerryPreferences *preferences); + void GetPreferenceDecorations(const mitk::IPreferences *preferences); /** * @brief GetColorForWidget helper method to convert a saved color string to mitk::Color. * @param hexColor color in hex format (#12356) where each digit is in the form (0-F). * @return the color in mitk format. */ - mitk::Color HexColorToMitkColor(const QString& hexColor); + mitk::Color HexColorToMitkColor(const std::string& hexColor); /** * @brief MitkColorToHex Convert an mitk::Color to hex string. * @param color mitk format. * @return String in hex (#RRGGBB). */ - QString MitkColorToHex(const mitk::Color& color); + std::string MitkColorToHex(const mitk::Color& color); struct Impl; std::unique_ptr m_Impl; }; #endif // QMITKSTDMULTIWIDGETEDITOR_H diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp index bfed013049..04d9e7ef59 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp @@ -1,245 +1,245 @@ /*============================================================================ 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 "QmitkStdMultiWidgetEditorPreferencePage.h" #include #include -#include -#include +#include +#include +#include #include QmitkStdMultiWidgetEditorPreferencePage::QmitkStdMultiWidgetEditorPreferencePage() : m_Preferences(nullptr), m_Ui(new Ui::QmitkStdMultiWidgetEditorPreferencePage), m_Control(nullptr) { } QmitkStdMultiWidgetEditorPreferencePage::~QmitkStdMultiWidgetEditorPreferencePage() { } void QmitkStdMultiWidgetEditorPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - Q_ASSERT(prefService); + mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); - m_Preferences = prefService->GetSystemPreferences()->Node(QmitkStdMultiWidgetEditor::EDITOR_ID); + m_Preferences = prefService->GetSystemPreferences()->Node(QmitkStdMultiWidgetEditor::EDITOR_ID.toStdString()); QObject::connect( m_Ui->m_ColorButton1, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_ColorButton2, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_ResetButton, SIGNAL( clicked() ) , this, SLOT( ResetPreferencesAndGUI() ) ); QObject::connect( m_Ui->m_RenderWindowDecorationColor, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_RenderWindowChooser, SIGNAL(activated(int) ) , this, SLOT( OnWidgetComboBoxChanged(int) ) ); QObject::connect( m_Ui->m_RenderWindowDecorationText, SIGNAL(textChanged(QString) ) , this, SLOT( AnnotationTextChanged(QString) ) ); this->Update(); } QWidget* QmitkStdMultiWidgetEditorPreferencePage::GetQtControl() const { return m_Control; } void QmitkStdMultiWidgetEditorPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkStdMultiWidgetEditorPreferencePage::PerformCancel() { } bool QmitkStdMultiWidgetEditorPreferencePage::PerformOk() { - m_Preferences->Put("stdmulti.widget0 corner annotation", m_WidgetAnnotation[0]); - m_Preferences->Put("stdmulti.widget1 corner annotation", m_WidgetAnnotation[1]); - m_Preferences->Put("stdmulti.widget2 corner annotation", m_WidgetAnnotation[2]); - m_Preferences->Put("stdmulti.widget3 corner annotation", m_WidgetAnnotation[3]); - - m_Preferences->Put("stdmulti.widget0 decoration color", m_WidgetDecorationColor[0]); - m_Preferences->Put("stdmulti.widget1 decoration color", m_WidgetDecorationColor[1]); - m_Preferences->Put("stdmulti.widget2 decoration color", m_WidgetDecorationColor[2]); - m_Preferences->Put("stdmulti.widget3 decoration color", m_WidgetDecorationColor[3]); - - m_Preferences->Put("stdmulti.widget0 first background color", m_WidgetBackgroundColor1[0]); - m_Preferences->Put("stdmulti.widget1 first background color", m_WidgetBackgroundColor1[1]); - m_Preferences->Put("stdmulti.widget2 first background color", m_WidgetBackgroundColor1[2]); - m_Preferences->Put("stdmulti.widget3 first background color", m_WidgetBackgroundColor1[3]); - m_Preferences->Put("stdmulti.widget0 second background color", m_WidgetBackgroundColor2[0]); - m_Preferences->Put("stdmulti.widget1 second background color", m_WidgetBackgroundColor2[1]); - m_Preferences->Put("stdmulti.widget2 second background color", m_WidgetBackgroundColor2[2]); - m_Preferences->Put("stdmulti.widget3 second background color", m_WidgetBackgroundColor2[3]); + m_Preferences->Put("stdmulti.widget0 corner annotation", m_WidgetAnnotation[0].toStdString()); + m_Preferences->Put("stdmulti.widget1 corner annotation", m_WidgetAnnotation[1].toStdString()); + m_Preferences->Put("stdmulti.widget2 corner annotation", m_WidgetAnnotation[2].toStdString()); + m_Preferences->Put("stdmulti.widget3 corner annotation", m_WidgetAnnotation[3].toStdString()); + + m_Preferences->Put("stdmulti.widget0 decoration color", m_WidgetDecorationColor[0].toStdString()); + m_Preferences->Put("stdmulti.widget1 decoration color", m_WidgetDecorationColor[1].toStdString()); + m_Preferences->Put("stdmulti.widget2 decoration color", m_WidgetDecorationColor[2].toStdString()); + m_Preferences->Put("stdmulti.widget3 decoration color", m_WidgetDecorationColor[3].toStdString()); + + m_Preferences->Put("stdmulti.widget0 first background color", m_WidgetBackgroundColor1[0].toStdString()); + m_Preferences->Put("stdmulti.widget1 first background color", m_WidgetBackgroundColor1[1].toStdString()); + m_Preferences->Put("stdmulti.widget2 first background color", m_WidgetBackgroundColor1[2].toStdString()); + m_Preferences->Put("stdmulti.widget3 first background color", m_WidgetBackgroundColor1[3].toStdString()); + m_Preferences->Put("stdmulti.widget0 second background color", m_WidgetBackgroundColor2[0].toStdString()); + m_Preferences->Put("stdmulti.widget1 second background color", m_WidgetBackgroundColor2[1].toStdString()); + m_Preferences->Put("stdmulti.widget2 second background color", m_WidgetBackgroundColor2[2].toStdString()); + m_Preferences->Put("stdmulti.widget3 second background color", m_WidgetBackgroundColor2[3].toStdString()); m_Preferences->PutInt("crosshair gap size", m_Ui->m_CrosshairGapSize->value()); m_Preferences->PutBool("Use constrained zooming and panning" , m_Ui->m_EnableFlexibleZooming->isChecked()); m_Preferences->PutBool("Show level/window widget", m_Ui->m_ShowLevelWindowWidget->isChecked()); m_Preferences->PutBool("PACS like mouse interaction", m_Ui->m_PACSLikeMouseMode->isChecked()); return true; } void QmitkStdMultiWidgetEditorPreferencePage::Update() { //Note: there should be default preferences already defined in the //QmitkStdMultiWidgetEditor::InitializePreferences(). Therefore, //all default values here are not relevant. //gradient background colors - m_WidgetBackgroundColor1[0] = m_Preferences->Get("stdmulti.widget0 first background color", "#000000"); - m_WidgetBackgroundColor2[0] = m_Preferences->Get("stdmulti.widget0 second background color", "#000000"); - m_WidgetBackgroundColor1[1] = m_Preferences->Get("stdmulti.widget1 first background color", "#000000"); - m_WidgetBackgroundColor2[1] = m_Preferences->Get("stdmulti.widget1 second background color", "#000000"); - m_WidgetBackgroundColor1[2] = m_Preferences->Get("stdmulti.widget2 first background color", "#000000"); - m_WidgetBackgroundColor2[2] = m_Preferences->Get("stdmulti.widget2 second background color", "#000000"); - m_WidgetBackgroundColor1[3] = m_Preferences->Get("stdmulti.widget3 first background color", "#191919"); - m_WidgetBackgroundColor2[3] = m_Preferences->Get("stdmulti.widget3 second background color", "#7F7F7F"); + m_WidgetBackgroundColor1[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 first background color", "#000000")); + m_WidgetBackgroundColor2[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 second background color", "#000000")); + m_WidgetBackgroundColor1[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 first background color", "#000000")); + m_WidgetBackgroundColor2[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 second background color", "#000000")); + m_WidgetBackgroundColor1[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 first background color", "#000000")); + m_WidgetBackgroundColor2[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 second background color", "#000000")); + m_WidgetBackgroundColor1[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 first background color", "#191919")); + m_WidgetBackgroundColor2[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 second background color", "#7F7F7F")); //decoration colors - m_WidgetDecorationColor[0] = m_Preferences->Get("stdmulti.widget0 decoration color", "#c00000"); - m_WidgetDecorationColor[1] = m_Preferences->Get("stdmulti.widget1 decoration color", "#00b000"); - m_WidgetDecorationColor[2] = m_Preferences->Get("stdmulti.widget2 decoration color", "#0080ff"); - m_WidgetDecorationColor[3] = m_Preferences->Get("stdmulti.widget3 decoration color", "#ffff00"); + m_WidgetDecorationColor[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 decoration color", "#c00000")); + m_WidgetDecorationColor[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 decoration color", "#00b000")); + m_WidgetDecorationColor[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 decoration color", "#0080ff")); + m_WidgetDecorationColor[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 decoration color", "#ffff00")); //annotation text - m_WidgetAnnotation[0] = m_Preferences->Get("stdmulti.widget0 corner annotation", "Axial"); - m_WidgetAnnotation[1] = m_Preferences->Get("stdmulti.widget1 corner annotation", "Sagittal"); - m_WidgetAnnotation[2] = m_Preferences->Get("stdmulti.widget2 corner annotation", "Coronal"); - m_WidgetAnnotation[3] = m_Preferences->Get("stdmulti.widget3 corner annotation", "3D"); + m_WidgetAnnotation[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 corner annotation", "Axial")); + m_WidgetAnnotation[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 corner annotation", "Sagittal")); + m_WidgetAnnotation[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 corner annotation", "Coronal")); + m_WidgetAnnotation[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 corner annotation", "3D")); //Ui stuff int index = m_Ui->m_RenderWindowChooser->currentIndex(); QColor firstBackgroundColor(m_WidgetBackgroundColor1[index]); QColor secondBackgroundColor(m_WidgetBackgroundColor2[index]); QColor widgetColor(m_WidgetDecorationColor[index]); this->SetStyleSheetToColorChooserButton(firstBackgroundColor, m_Ui->m_ColorButton1); this->SetStyleSheetToColorChooserButton(secondBackgroundColor, m_Ui->m_ColorButton2); this->SetStyleSheetToColorChooserButton(widgetColor, m_Ui->m_RenderWindowDecorationColor); m_Ui->m_RenderWindowDecorationText->setText(m_WidgetAnnotation[index]); m_Ui->m_EnableFlexibleZooming->setChecked(m_Preferences->GetBool("Use constrained zooming and panning", true)); m_Ui->m_ShowLevelWindowWidget->setChecked(m_Preferences->GetBool("Show level/window widget", true)); m_Ui->m_PACSLikeMouseMode->setChecked(m_Preferences->GetBool("PACS like mouse interaction", false)); m_Ui->m_CrosshairGapSize->setValue(m_Preferences->GetInt("crosshair gap size", 32)); } void QmitkStdMultiWidgetEditorPreferencePage::ColorChooserButtonClicked() { unsigned int widgetIndex = m_Ui->m_RenderWindowChooser->currentIndex(); if(widgetIndex > 3) { MITK_ERROR << "Selected index for unknown."; return; } QObject *senderObj = sender(); // This will give Sender button //find out last used color and set it QColor initialColor; if( senderObj->objectName() == m_Ui->m_ColorButton1->objectName()) { initialColor = QColor(m_WidgetBackgroundColor1[widgetIndex]); }else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) { initialColor = QColor(m_WidgetBackgroundColor2[widgetIndex]); }else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) { initialColor = QColor(m_WidgetDecorationColor[widgetIndex]); } //get the new color QColor newcolor = QColorDialog::getColor(initialColor); if(!newcolor.isValid()) { newcolor = initialColor; } this->SetStyleSheetToColorChooserButton(newcolor, static_cast(senderObj)); //convert it to std string and apply it if( senderObj->objectName() == m_Ui->m_ColorButton1->objectName()) { m_WidgetBackgroundColor1[widgetIndex] = newcolor.name(); } else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) { m_WidgetBackgroundColor2[widgetIndex] = newcolor.name(); } else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) { m_WidgetDecorationColor[widgetIndex] = newcolor.name(); } } void QmitkStdMultiWidgetEditorPreferencePage::SetStyleSheetToColorChooserButton(QColor backgroundcolor, QPushButton* button) { button->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(backgroundcolor.red())); styleSheet.append(","); styleSheet.append(QString::number(backgroundcolor.green())); styleSheet.append(","); styleSheet.append(QString::number(backgroundcolor.blue())); styleSheet.append(")"); button->setStyleSheet(styleSheet); } void QmitkStdMultiWidgetEditorPreferencePage::AnnotationTextChanged(QString text) { unsigned int widgetIndex = m_Ui->m_RenderWindowChooser->currentIndex(); if( widgetIndex > 3) { MITK_INFO << "Selected index for unknown widget."; return; } m_WidgetAnnotation[widgetIndex] = text; } void QmitkStdMultiWidgetEditorPreferencePage::ResetPreferencesAndGUI() { m_Preferences->Clear(); this->Update(); } void QmitkStdMultiWidgetEditorPreferencePage::OnWidgetComboBoxChanged(int i) { if( i > 3) { MITK_ERROR << "Selected unknown widget."; return; } QColor widgetColor(m_WidgetDecorationColor[i]); QColor gradientBackground1(m_WidgetBackgroundColor1[i]); QColor gradientBackground2(m_WidgetBackgroundColor2[i]); this->SetStyleSheetToColorChooserButton(widgetColor, m_Ui->m_RenderWindowDecorationColor); this->SetStyleSheetToColorChooserButton(gradientBackground1, m_Ui->m_ColorButton1); this->SetStyleSheetToColorChooserButton(gradientBackground2, m_Ui->m_ColorButton2); m_Ui->m_RenderWindowDecorationText->setText(m_WidgetAnnotation[i]); } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h index 60b3c5c45b..db30fd9535 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h @@ -1,105 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkStdMultiWidgetEditorPreferencePage_h #define QmitkStdMultiWidgetEditorPreferencePage_h -#include #include -#include #include -#include +#include + +#include + +class QPushButton; + +namespace mitk +{ + class IPreferences; +} namespace Ui { -class QmitkStdMultiWidgetEditorPreferencePage; + class QmitkStdMultiWidgetEditorPreferencePage; } class QmitkStdMultiWidgetEditorPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkStdMultiWidgetEditorPreferencePage(); ~QmitkStdMultiWidgetEditorPreferencePage() override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; void Init(berry::IWorkbench::Pointer) override; void PerformCancel() override; bool PerformOk() override; void Update() override; public slots: /** * @brief ResetColors set default colors and refresh the GUI. */ void ResetPreferencesAndGUI(); /** * @brief OnWidgetComboBoxChanged slot called when the QComboBox to chose the widget was modified. * @param i index of the combobox to select the widget (1-4). */ void OnWidgetComboBoxChanged(int i); /** * @brief AnnotationTextChanged called when QLineEdit for the annotation was changed. * @param text The new text. */ void AnnotationTextChanged(QString text); protected: /** * @brief m_WidgetBackgroundColor1 the background colors. * * If two different colors are chosen, a gradient background appears. */ - QString m_WidgetBackgroundColor1[4]; - QString m_WidgetBackgroundColor2[4]; + std::array m_WidgetBackgroundColor1; + std::array m_WidgetBackgroundColor2; /** * @brief m_WidgetDecorationColor the decoration color. * * The rectangle prop, the crosshair, the 3D planes and the corner annotation use this. */ - QString m_WidgetDecorationColor[4]; + std::array m_WidgetDecorationColor; /** * @brief m_Widget1Annotation the text of the corner annotation. */ - QString m_WidgetAnnotation[4]; + std::array m_WidgetAnnotation; /** * @brief m_Preferences the berry preferences. */ - berry::IPreferences::Pointer m_Preferences; + mitk::IPreferences* m_Preferences; /** * @brief SetStyleSheetToColorChooserButton colorize a button. * @param backgroundcolor color for the button. * @param button the button. */ void SetStyleSheetToColorChooserButton(QColor backgroundcolor, QPushButton* button); protected slots: /** * @brief ColorChooserButtonClicked slot called when a button to choose color was clicked. */ void ColorChooserButtonClicked(); private: QScopedPointer m_Ui; QWidget* m_Control; }; #endif //QmitkStdMultiWidgetEditorPreferencePage_h diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp index 7705e5867a..31ecddd21a 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp @@ -1,40 +1,44 @@ /*============================================================================ 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 "org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h" #include "../QmitkStdMultiWidgetEditor.h" #include "QmitkStdMultiWidgetEditorPreferencePage.h" +#include + +US_INITIALIZE_MODULE + ctkPluginContext* org_mitk_gui_qt_stdmultiwidgeteditor_Activator::m_Context = nullptr; void org_mitk_gui_qt_stdmultiwidgeteditor_Activator::start(ctkPluginContext* context) { m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkStdMultiWidgetEditor, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkStdMultiWidgetEditorPreferencePage, context) } void org_mitk_gui_qt_stdmultiwidgeteditor_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_Context = nullptr; } ctkPluginContext *org_mitk_gui_qt_stdmultiwidgeteditor_Activator::GetContext() { return m_Context; } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp index 501c48963e..c97741b79b 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp @@ -1,300 +1,286 @@ /*============================================================================ 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 "QmitkXnatConnectionPreferencePage.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" -#include "berryIPreferencesService.h" -#include "berryPlatform.h" - #include #include #include #include #include #include #include #include #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include +#include +#include +#include using namespace berry; QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(nullptr) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { - IPreferencesService* prefService = Platform::GetPreferencesService(); - berry::IPreferences::Pointer _XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID); - m_XnatConnectionPreferencesNode = _XnatConnectionPreferencesNode; + auto* prefService = mitk::CoreServices::GetPreferencesService(); + m_XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID.toStdString()); m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch (std::invalid_argument&) { session = nullptr; } if (session != nullptr && session->isOpen()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green"); m_Controls.xnatTestConnectionLabel->setText("Already connected."); m_Controls.xnatTestConnectionButton->setEnabled(false); } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked())); m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { - IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); - if (_XnatConnectionPreferencesNode.IsNotNull()) + if (m_XnatConnectionPreferencesNode != nullptr) { - _XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text()); + m_XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString()); // Network proxy settings - _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text(), m_Controls.cbUseNetworkProxy->isChecked()); - _XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text()); - _XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text()); + m_XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text().toStdString(), m_Controls.cbUseNetworkProxy->isChecked()); + m_XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString()); + m_XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString()); // Silent Mode - _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text(), m_Controls.cbUseSilentMode->isChecked()); + m_XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text().toStdString(), m_Controls.cbUseSilentMode->isChecked()); //Write - _XnatConnectionPreferencesNode->Flush(); + m_XnatConnectionPreferencesNode->Flush(); return true; } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { - IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); - if (_XnatConnectionPreferencesNode.IsNotNull()) + if (m_XnatConnectionPreferencesNode != nullptr) { - m_Controls.inXnatHostAddress->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text())); - m_Controls.inXnatPort->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text())); - m_Controls.inXnatUsername->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text())); - m_Controls.inXnatPassword->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text())); - m_Controls.inXnatDownloadPath->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text())); + m_Controls.inXnatHostAddress->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString()))); + m_Controls.inXnatPort->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString()))); + m_Controls.inXnatUsername->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString()))); + m_Controls.inXnatPassword->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString()))); + m_Controls.inXnatDownloadPath->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString()))); // Network proxy settings - m_Controls.cbUseNetworkProxy->setChecked(_XnatConnectionPreferencesNode->GetBool( - m_Controls.cbUseNetworkProxy->text(), false)); - m_Controls.inProxyAddress->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text())); - m_Controls.inProxyPort->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text())); - m_Controls.inProxyUsername->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text())); - m_Controls.inProxyPassword->setText(_XnatConnectionPreferencesNode->Get( - m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text())); + m_Controls.cbUseNetworkProxy->setChecked(m_XnatConnectionPreferencesNode->GetBool(m_Controls.cbUseNetworkProxy->text().toStdString(), false)); + m_Controls.inProxyAddress->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString()))); + m_Controls.inProxyPort->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString()))); + m_Controls.inProxyUsername->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString()))); + m_Controls.inProxyPassword->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString()))); // Silent Mode - m_Controls.cbUseSilentMode->setChecked(_XnatConnectionPreferencesNode->GetBool( - m_Controls.cbUseSilentMode->text(), false)); + m_Controls.cbUseSilentMode->setChecked(m_XnatConnectionPreferencesNode->GetBool(m_Controls.cbUseSilentMode->text().toStdString(), false)); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet(""); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("background-color: red"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet(""); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("background-color: red"); } } } void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status) { m_Controls.groupBoxProxySettings->setVisible(status); } void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked() { QString dir = QFileDialog::getExistingDirectory(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void QmitkXnatConnectionPreferencePage::TestConnection() { if(UserInformationEmpty()) { return; } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch (const std::invalid_argument &) { if (!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green"); m_Controls.xnatTestConnectionLabel->setText("Connecting successful."); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkXnatAuthenticationException& auth) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Adress\nPossibly due to missing OpenSSL for HTTPS connections"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h index 84dc344919..d4b5227294 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h @@ -1,83 +1,87 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKXNATCONNECTIONPREFERENCEPAGE_H_ #define QMITKXNATCONNECTIONPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" -#include #include "ui_QmitkXnatConnectionPreferencePageControls.h" +namespace mitk +{ + class IPreferences; +} + class QWidget; class QLineEdit; struct QmitkXnatConnectionPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkXnatConnectionPreferencePage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected slots: virtual void UrlChanged(); virtual void DownloadPathChanged(); void OnDownloadPathButtonClicked(); /// /// Toggles the Connection in the Service Registry from opened to closed or the other way around. /// virtual void TestConnection(); virtual void onUseNetworkProxy(bool); protected: Ui::QmitkXnatConnectionPreferencePageControls m_Controls; QWidget* m_Control; - berry::IPreferences::WeakPtr m_XnatConnectionPreferencesNode; + mitk::IPreferences* m_XnatConnectionPreferencesNode; private: /// /// Checks if the entered user information is empty. /// virtual bool UserInformationEmpty(); }; #endif /* QMITKXNATCONNECTIONPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp index c69947397a..20d52799b8 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp @@ -1,569 +1,571 @@ /*============================================================================ 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 "QmitkXnatEditor.h" // Qmitk #include "QmitkXnatObjectEditorInput.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" // CTK XNAT Core #include "ctkXnatObject.h" #include "ctkXnatDataModel.h" #include "ctkXnatFile.h" #include "ctkXnatResource.h" #include "ctkXnatScan.h" #include "ctkXnatScanFolder.h" #include "ctkXnatAssessor.h" #include "ctkXnatAssessorFolder.h" #include "ctkXnatReconstruction.h" #include "ctkXnatReconstructionFolder.h" // CTK XNAT Widgets #include "ctkXnatListModel.h" // Blueberry #include #include -#include // Qt #include #include #include #include #include #include // MITK #include #include +#include +#include +#include // Poco #include const QString QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser"; QmitkXnatEditor::QmitkXnatEditor() : -m_DownloadPath(berry::Platform::GetPreferencesService()-> -GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", "")), +m_DownloadPath(QString::fromStdString(mitk::CoreServices::GetPreferencesService()-> +GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", ""))), m_ListModel(new ctkXnatListModel()), m_Session(0), m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()), m_SelectionListener(new berry::SelectionChangedAdapter(this, &QmitkXnatEditor::SelectionChanged)) { m_DataStorageServiceTracker.open(); if (m_DownloadPath.isEmpty()) { QString xnatFolder = "XNAT_DOWNLOADS"; QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath()); dir.mkdir(xnatFolder); dir.setPath(dir.path() + "/" + xnatFolder); m_DownloadPath = dir.path() + "/"; } } QmitkXnatEditor::~QmitkXnatEditor() { delete m_ListModel; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); s->RemoveSelectionListener(m_SelectionListener.data()); m_DataStorageServiceTracker.close(); } bool QmitkXnatEditor::IsDirty() const { return false; } bool QmitkXnatEditor::IsSaveAsAllowed() const { return false; } void QmitkXnatEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { this->SetSite(site); berry::QtEditorPart::SetInput(input); this->SetInput(input); } void QmitkXnatEditor::DoSave() { } void QmitkXnatEditor::DoSaveAs() { } void QmitkXnatEditor::SetInput(berry::IEditorInput::Pointer input) { QmitkXnatObjectEditorInput::Pointer oPtr = input.Cast(); if (oPtr.IsNotNull()) { berry::QtEditorPart::SetInput(oPtr); this->GetEditorInput().Cast()->GetXnatObject()->fetch(); } } void QmitkXnatEditor::SetFocus() { } void QmitkXnatEditor::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); m_Controls.buttonDownload->setEnabled(false); m_Controls.labelDownload->setText("Select a xnat file, resource, scan, or scan folder to download..."); GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data()); connect(m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnObjectActivated(const QModelIndex&))); connect(m_Controls.buttonDownload, SIGNAL(clicked()), this, SLOT(DownloadResource())); connect(m_Controls.buttonDataModel, SIGNAL(clicked()), this, SLOT(OnDataModelButtonClicked())); connect(m_Controls.buttonProject, SIGNAL(clicked()), this, SLOT(OnProjectButtonClicked())); connect(m_Controls.buttonSubject, SIGNAL(clicked()), this, SLOT(OnSubjectButtonClicked())); connect(m_Controls.buttonExperiment, SIGNAL(clicked()), this, SLOT(OnExperimentButtonClicked())); connect(m_Controls.buttonKindOfData, SIGNAL(clicked()), this, SLOT(OnKindOfDataButtonClicked())); connect(m_Controls.buttonSession, SIGNAL(clicked()), this, SLOT(OnSessionButtonClicked())); connect(m_Controls.buttonResource, SIGNAL(clicked()), this, SLOT(OnResourceButtonClicked())); connect(m_Controls.treeView, SIGNAL(clicked(const QModelIndex&)), SLOT(itemSelected(const QModelIndex&))); m_Tracker = new mitk::XnatSessionTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()); connect(m_Tracker, SIGNAL(AboutToBeClosed(ctkXnatSession*)), this, SLOT(CleanListModel(ctkXnatSession*))); connect(m_Tracker, SIGNAL(Opened(ctkXnatSession*)), this, SLOT(UpdateSession(ctkXnatSession*))); m_Tracker->Open(); // Makes the breadcrumb feature invisible for (int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count() - 1; i++) { QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(false); } for (int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count() - 1; i++) { QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i); child->widget()->setVisible(false); } QmitkXnatObjectEditorInput::Pointer oPtr = GetEditorInput().Cast(); if (oPtr.IsNotNull()) { UpdateList(); } else { ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch (std::invalid_argument) { session = 0; } UpdateSession(session); } } void QmitkXnatEditor::UpdateList() { QmitkXnatObjectEditorInput::Pointer xoPtr(GetEditorInput().Cast()); if (xoPtr.IsNull()) return; ctkXnatObject* inputObject = xoPtr->GetXnatObject(); if (inputObject == nullptr) return; m_Controls.treeView->setModel(m_ListModel); m_ListModel->setRootObject(inputObject); m_Controls.treeView->reset(); // recursive method to check parents of the inputObject m_ParentCount = ParentChecker(inputObject); // breadcrumb labels for (int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count() - 1; i++) { QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(false); } for (int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count() - 1; i++) { QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i); child->widget()->setVisible(false); } ctkXnatObject* parent = nullptr; for (int i = m_ParentCount * 2; i >= 0; i--) { if (i > 12) break; m_Controls.breadcrumbDescriptionLayout->itemAt(i)->widget()->setVisible(true); QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(true); if (i > 0) { m_Controls.breadcrumbHorizontalLayout->itemAt(i - 1)->widget()->setVisible(true); m_Controls.breadcrumbDescriptionLayout->itemAt(i - 1)->widget()->setVisible(true); } if (parent == nullptr) { parent = inputObject; } // create breadcrumb button QPushButton* breadcrumbButton = dynamic_cast(child->widget()); breadcrumbButton->setText(parent->id()); parent = parent->parent(); i--; } m_Controls.buttonDataModel->setText("root"); m_Controls.buttonDownload->setEnabled(false); m_Controls.labelDownload->setVisible(true); } void QmitkXnatEditor::SelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection) { // check for null selection if (selection.IsNull()) { return; } // exclude own selection events and check whether this kind of selection can be handled if (sourcepart != this && selection.Cast()) { berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast(); // iterates over the selection for (berry::IStructuredSelection::iterator itr = currentSelection->Begin(); itr != currentSelection->End(); ++itr) { if (berry::SmartPointer objectPointer = itr->Cast()) { // get object of selected ListWidgetElement ctkXnatObject* object = objectPointer->GetQModelIndex().data(Qt::UserRole).value(); // if a file is selected, don't change the input and list view if (dynamic_cast(object) == nullptr) { QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(object)); berry::IEditorInput::Pointer editorInput(oPtr); if (!(editorInput == this->GetEditorInput())) this->SetInput(editorInput); UpdateList(); } } } } } void QmitkXnatEditor::DownloadResource() { if (!m_Controls.listView->selectionModel()->hasSelection()) return; const QModelIndex index = m_Controls.listView->selectionModel()->currentIndex(); QVariant variant = m_ListModel->data(index, Qt::UserRole); if (variant.isValid()) { ctkXnatObject* resource = variant.value(); if (dynamic_cast(resource) == nullptr) { MITK_INFO << "Download started ..."; MITK_INFO << "..."; QString resourceName = m_ListModel->data(index, Qt::DisplayRole).toString(); QString resourcePath = m_DownloadPath + resourceName + ".zip"; resource->download(resourcePath); // Testing if the path exists QDir downDir(m_DownloadPath); if (downDir.exists(resourceName + ".zip")) { MITK_INFO << "Download of " << resourceName.toStdString() << ".zip was completed!"; } else { MITK_INFO << "Download of " << resourceName.toStdString() << ".zip failed!"; } } else { InternalFileDownload(index); } } } void QmitkXnatEditor::DownloadFile() { if (!m_Controls.listView->selectionModel()->hasSelection()) return; const QModelIndex index = m_Controls.listView->selectionModel()->currentIndex(); InternalFileDownload(index); } void QmitkXnatEditor::ToHigherLevel() { ctkXnatObject* parent = GetEditorInput().Cast()->GetXnatObject()->parent(); if (parent == nullptr) { return; } QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(parent)); berry::IEditorInput::Pointer editorInput(oPtr); this->SetInput(editorInput); UpdateList(); } void QmitkXnatEditor::OnObjectActivated(const QModelIndex &index) { if (!index.isValid()) return; ctkXnatObject* child = GetEditorInput().Cast()->GetXnatObject()->children().at(index.row()); if (child != nullptr) { ctkXnatFile* file = dynamic_cast(child); if (file != nullptr) { // Download file and put into datamanager InternalFileDownload(index); mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService(); if (dsService != nullptr) { QString name = file->property("Name"); QString filePath = m_DownloadPath + name; if (file->property("collection") == "DICOM") { QDirIterator it(m_DownloadPath, QStringList() << name, QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); filePath = it.filePath(); } } mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService(); mitk::DataStorage::Pointer dataStorage = dsService->GetDataStorage()->GetDataStorage(); QStringList list; list << filePath; try { QmitkIOUtil::Load(list, *dataStorage); } catch (const mitk::Exception& e) { MITK_INFO << e; return; } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects( dsService->GetDataStorage()->GetDataStorage()); } } else { // Updates the root item QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(child)); berry::IEditorInput::Pointer editorInput(oPtr); this->SetInput(editorInput); this->GetEditorInput().Cast()->GetXnatObject()->fetch(); UpdateList(); } } } void QmitkXnatEditor::InternalFileDownload(const QModelIndex& index) { QVariant variant = m_ListModel->data(index, Qt::UserRole); if (variant.isValid()) { ctkXnatFile* file = dynamic_cast(variant.value()); if (file != nullptr) { // Testing if the file exists QDir downDir(m_DownloadPath); if (downDir.exists(file->property("Name"))) { MITK_INFO << "File exists already!"; return; } if (file->property("collection") == QString("DICOM")) { ctkXnatObject* parent = file->parent(); QString filePath = m_DownloadPath + parent->property("label") + ".zip"; parent->download(filePath); std::ifstream in(filePath.toStdString().c_str(), std::ios::binary); poco_assert(in); // decompress to XNAT_DOWNLOAD dir Poco::Zip::Decompress dec(in, Poco::Path(m_DownloadPath.toStdString())); dec.decompressAllFiles(); in.close(); QFile::remove(filePath); } else { MITK_INFO << "Download started ..."; MITK_INFO << "..."; QString name = file->property("Name"); QString filePath = m_DownloadPath + name; file->download(filePath); // Testing if the file exists QDir downDir(m_DownloadPath); if (downDir.exists(name)) { MITK_INFO << "Download of " << file->name().toStdString() << " was completed!"; } else { MITK_INFO << "Download of " << file->name().toStdString() << " failed!"; } } } else { MITK_INFO << "Selection was not a file!"; } } } int QmitkXnatEditor::ParentChecker(ctkXnatObject* child) { int sum; if (child->parent() == nullptr) { return 0; } else { sum = 1 + ParentChecker(child->parent()); } return sum; } void QmitkXnatEditor::OnDataModelButtonClicked() { for (int i = m_ParentCount; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnProjectButtonClicked() { for (int i = m_ParentCount - 1; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnSubjectButtonClicked() { for (int i = m_ParentCount - 2; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnExperimentButtonClicked() { for (int i = m_ParentCount - 3; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnKindOfDataButtonClicked() { for (int i = m_ParentCount - 4; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnSessionButtonClicked() { for (int i = m_ParentCount - 5; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnResourceButtonClicked() { for (int i = m_ParentCount - 6; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::UpdateSession(ctkXnatSession* session) { GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data()); if (session != 0 && session->isOpen()) { m_Controls.labelInfo->setText("Current Position:"); m_Controls.labelInfo->setStyleSheet("QLabel { color: black; }"); // Fill model and show in the GUI QmitkXnatObjectEditorInput::Pointer xoPtr(new QmitkXnatObjectEditorInput(session->dataModel())); berry::IEditorInput::Pointer editorInput(xoPtr); this->SetInput(editorInput); this->GetEditorInput().Cast()->GetXnatObject()->fetch(); UpdateList(); } else { m_Controls.labelInfo->setText("Please check the Preferences of the XNAT Connection.\nMaybe they are not ok."); m_Controls.labelInfo->setStyleSheet("QLabel { color: red; }"); } GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data()); } void QmitkXnatEditor::CleanListModel(ctkXnatSession* session) { if (session != 0) { m_Controls.listView->setModel(0); m_ListModel->setRootObject(0); m_Controls.treeView->reset(); } } void QmitkXnatEditor::itemSelected(const QModelIndex &index) { ctkXnatObject* xnatObject = m_ListModel->data(index, Qt::UserRole).value(); bool downloadable = false; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; downloadable |= dynamic_cast(xnatObject) != nullptr; m_Controls.buttonDownload->setEnabled(downloadable); m_Controls.labelDownload->setVisible(!downloadable); } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp index e67f840161..c467e93497 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp @@ -1,102 +1,103 @@ /*============================================================================ 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 "QmitkXnatSessionManager.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" -#include "berryPlatform.h" -#include "berryIPreferences.h" +#include +#include +#include #include "mitkLogMacros.h" #include #include #include #include "ctkXnatSession.h" #include "ctkXnatException.h" QmitkXnatSessionManager::QmitkXnatSessionManager() : m_Session(nullptr) { } QmitkXnatSessionManager::~QmitkXnatSessionManager() { if(m_SessionRegistration != nullptr) { m_SessionRegistration.Unregister(); } if(m_Session != nullptr) { delete m_Session; } } void QmitkXnatSessionManager::OpenXnatSession() { ctkXnatSession* session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(m_SessionRegistration.GetReference()); if(session == nullptr) return; if(!session->isOpen()) { session->open(); } } void QmitkXnatSessionManager::CreateXnatSession() { - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer nodeConnectionPref = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID); + auto* prefService = mitk::CoreServices::GetPreferencesService(); + auto* nodeConnectionPref = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID.toStdString()); - QUrl url(nodeConnectionPref->Get("Server Address", "")); - url.setPort(nodeConnectionPref->Get("Port", "").toInt()); + QUrl url(QString::fromStdString(nodeConnectionPref->Get("Server Address", ""))); + url.setPort(std::stoi(nodeConnectionPref->Get("Port", ""))); ctkXnatLoginProfile profile; profile.setName("Default"); profile.setServerUrl(url); - profile.setUserName(nodeConnectionPref->Get("Username", "")); - profile.setPassword(nodeConnectionPref->Get("Password", "")); + profile.setUserName(QString::fromStdString(nodeConnectionPref->Get("Username", ""))); + profile.setPassword(QString::fromStdString(nodeConnectionPref->Get("Password", ""))); profile.setDefault(true); m_Session = new ctkXnatSession(profile); if (nodeConnectionPref->Get("Proxy Server Address", "").length() != 0) { QNetworkProxy proxy; proxy.setType(QNetworkProxy::HttpProxy); - proxy.setHostName(nodeConnectionPref->Get("Proxy Server Address", "")); - proxy.setPort(nodeConnectionPref->Get("Proxy Port", "").toUShort()); + proxy.setHostName(QString::fromStdString(nodeConnectionPref->Get("Proxy Server Address", ""))); + proxy.setPort(QString::fromStdString(nodeConnectionPref->Get("Proxy Port", "")).toUShort()); if (nodeConnectionPref->Get("Proxy Username", "").length() != 0 && nodeConnectionPref->Get("Proxy Password", "").length() != 0) { - proxy.setUser(nodeConnectionPref->Get("Proxy Username", "")); - proxy.setPassword(nodeConnectionPref->Get("Proxy Password", "")); + proxy.setUser(QString::fromStdString(nodeConnectionPref->Get("Proxy Username", ""))); + proxy.setPassword(QString::fromStdString(nodeConnectionPref->Get("Proxy Password", ""))); } // Setting the proxy m_Session->setHttpNetworkProxy(proxy); } m_SessionRegistration = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->RegisterService(m_Session); } void QmitkXnatSessionManager::CloseXnatSession() { ctkXnatSession* session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(m_SessionRegistration.GetReference()); session->close(); m_SessionRegistration.Unregister(); m_SessionRegistration = 0; delete m_Session; m_Session = nullptr; } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h index 10263a7102..1b78d5b978 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h @@ -1,49 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKXNATSESSIONMANAGER_H_ #define QMITKXNATSESSIONMANAGER_H_ -#include - #include "ctkXnatLoginProfile.h" #include "mitkXnatSessionTracker.h" class QmitkXnatSessionManager { public: QmitkXnatSessionManager(); ~QmitkXnatSessionManager(); /// \brief Opens a xnat session. void OpenXnatSession(); /// \brief Creates the xnat session. void CreateXnatSession(); void CloseXnatSession(); bool LastSessionIsValid(); int AmountOfCreatedSessions(); private: us::ServiceRegistration m_SessionRegistration; ctkXnatSession* m_Session; }; #endif /*QMITKXNATSESSIONMANAGER_H_*/ diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp index 69d0ece8e1..b30b0f326a 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp @@ -1,1338 +1,1338 @@ /*============================================================================ 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 "QmitkXnatTreeBrowserView.h" +#include +#include +#include + // Qmitk #include "org_mitk_gui_qt_xnatinterface_Activator.h" -// Blueberry -#include - // CTK XNAT Core #include #include #include #include #include #include "ctkXnatFile.h" #include #include #include #include #include #include #include #include - // MITK XNAT #include #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include // Poco #include const QString QmitkXnatTreeBrowserView::VIEW_ID = "org.mitk.views.xnat.treebrowser"; static bool isDirWriteable(QDir myDir) { const QFileInfoList tmpInfo = myDir.entryInfoList(); foreach (QFileInfo f, tmpInfo) { if(f.fileName() == ".") return f.isWritable(); } return true; } static bool doesDirExist(QDir myDir) { if (!myDir.exists()) { if(!myDir.mkpath(".")) { MITK_INFO << "Path Creation Failed."; return false; } } return true; } QmitkXnatTreeBrowserView::QmitkXnatTreeBrowserView() : m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()), m_TreeModel(new QmitkXnatTreeModel()), m_Tracker(nullptr), - m_DownloadPath(berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node(VIEW_ID)->Get("Download Path", "")), + m_DownloadPath(QString::fromStdString(mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node(VIEW_ID.toStdString())->Get("Download Path", ""))), m_SilentMode(false) { m_DataStorageServiceTracker.open(); // Set DownloadPath if (m_DownloadPath.isEmpty()) { QString xnatFolder = "XNAT_DOWNLOADS"; QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath()); dir.mkdir(xnatFolder); dir.setPath(dir.path() + "/" + xnatFolder); m_DownloadPath = dir.path() + "/"; } } QmitkXnatTreeBrowserView::~QmitkXnatTreeBrowserView() { m_DataStorageServiceTracker.close(); delete m_TreeModel; delete m_Tracker; } void QmitkXnatTreeBrowserView::SetFocus() { } void QmitkXnatTreeBrowserView::FilePathNotAvailableWarning(QString file) { MITK_INFO << "Download of " << file.toStdString() << " failed! Download Path not available!"; QMessageBox::critical(m_Controls.treeView, "Download failed!", "Download of " + file + " failed!\nDownload Path " + m_DownloadPath + " not available. \n\nChange Download Path in Settings!"); QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.SetSelectedPage("org.mitk.gui.qt.application.XnatConnectionPreferencePage"); _PreferencesDialog.exec(); m_Controls.groupBox->hide(); } void QmitkXnatTreeBrowserView::ToggleConnection() { ctkXnatSession* session = nullptr; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch (std::invalid_argument&) { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } if (session != nullptr && session->isOpen()) { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); m_Controls.btnXnatConnect->setToolTip("Connect"); m_Controls.btnXnatConnect->setIcon(QIcon(":/xnat-plugin/xnat-connect.png")); CleanUp(); } else if (session != nullptr && !session->isOpen()) { try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.btnXnatConnect->setToolTip("Disconnect"); m_Controls.btnXnatConnect->setIcon(QIcon(":/xnat-plugin/xnat-disconnect.png")); m_Controls.searchField->setEnabled(true); m_Controls.searchModeBox->setEnabled(true); } catch (const ctkXnatAuthenticationException& auth) { MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.SetSelectedPage("org.mitk.gui.qt.application.XnatConnectionPreferencePage"); _PreferencesDialog.exec(); } catch (const ctkException& e) { MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.SetSelectedPage("org.mitk.gui.qt.application.XnatConnectionPreferencePage"); _PreferencesDialog.exec(); } catch (...) { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.SetSelectedPage("org.mitk.gui.qt.application.XnatConnectionPreferencePage"); _PreferencesDialog.exec(); } } } void QmitkXnatTreeBrowserView::CreateQtPartControl(QWidget *parent) { // Create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); m_Controls.treeView->setModel(m_TreeModel); m_Controls.treeView->header()->hide(); m_Controls.treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_Controls.treeView->setAcceptDrops(true); m_Controls.treeView->setDropIndicatorShown(true); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setContextMenuPolicy(Qt::CustomContextMenu); m_Controls.groupBox->hide(); m_Controls.wgtExperimentInfo->hide(); m_Controls.wgtSubjectInfo->hide(); m_Controls.wgtProjectInfo->hide(); m_Tracker = new mitk::XnatSessionTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()); m_ContextMenu = new QMenu(m_Controls.treeView); connect(m_Controls.treeView, SIGNAL(clicked(const QModelIndex&)), SLOT(ItemSelected(const QModelIndex&))); connect(m_Controls.treeView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(OnContextMenuRequested(const QPoint&))); connect(m_Tracker, SIGNAL(AboutToBeClosed(ctkXnatSession*)), this, SLOT(CleanTreeModel(ctkXnatSession*))); connect(m_Tracker, SIGNAL(Opened(ctkXnatSession*)), this, SLOT(UpdateSession(ctkXnatSession*))); m_Tracker->Open(); connect(m_Controls.treeView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(OnActivatedNode(const QModelIndex&))); connect(m_Controls.treeView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(OnXnatNodeSelected(const QModelIndex&))); connect(m_TreeModel, SIGNAL(ResourceDropped(const QList&, ctkXnatObject*, const QModelIndex&)), this, SLOT(OnUploadResource(const QList&, ctkXnatObject*, const QModelIndex&))); connect(m_Controls.btnXnatConnect, SIGNAL(clicked()), SLOT(ToggleConnection())); connect(m_Controls.btnXnatUpload, SIGNAL(clicked()), this, SLOT(OnUploadFromDataStorage())); connect(m_Controls.btnXnatDownload, SIGNAL(clicked()), this, SLOT(OnDownloadSelectedXnatFile())); connect(m_Controls.btnCreateXnatFolder, SIGNAL(clicked()), this, SLOT(OnCreateResourceFolder())); connect(m_Controls.searchField, SIGNAL(textChanged(const QString&)), this, SLOT(Search(const QString&))); } void QmitkXnatTreeBrowserView::OnCreateResourceFolder() { QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); if(!index.isValid()) return; ctkXnatObject* parent = index.data(Qt::UserRole).value(); this->InternalAddResourceFolder(parent); OnContextMenuRefreshItem(); } void QmitkXnatTreeBrowserView::Search(const QString &toSearch) { if(m_AlreadyInSearch) return; m_AlreadyInSearch = true; m_Controls.treeView->collapseAll(); m_Controls.treeView->expandToDepth(m_Controls.searchModeBox->currentIndex()); m_Controls.treeView->clearSelection(); foreach (const QModelIndex &hidden, m_hiddenItems) { m_Controls.treeView->setRowHidden(hidden.row(),hidden.parent(),false); } m_hiddenItems.clear(); if(toSearch.isEmpty()) { m_Controls.treeView->collapseAll(); m_Controls.treeView->expandToDepth(0); m_AlreadyInSearch = false; return; } QModelIndexList items = m_Controls.treeView->model()->match( m_Controls.treeView->model()->index(0,0), Qt::DisplayRole, QVariant::fromValue(toSearch), -1, Qt::MatchContains|Qt::MatchRecursive); if(!items.isEmpty()) { foreach (const QModelIndex &match, items) { int depth = 0; QModelIndex tparent = match; while ( tparent.parent().isValid() ) { tparent = tparent.parent(); depth++; } switch (depth) { case 1: //Project Level if(m_Controls.searchModeBox->currentIndex() == ProjectLevel) { m_hiddenItems.append(match); m_Controls.treeView->setRowHidden(match.row(),match.parent(),true); } break; case 2: //Patient level if(m_Controls.searchModeBox->currentIndex() == SubjectLevel) { m_hiddenItems.append(match); m_Controls.treeView->setRowHidden(match.row(),match.parent(),true); } break; default: break; } } } m_AlreadyInSearch = false; } void QmitkXnatTreeBrowserView::OnDownloadSelectedXnatFile() { QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); if(!index.isValid()) return; ctkXnatObject* selectedXnatObject = index.data(Qt::UserRole).value(); bool enableDownload = dynamic_cast(selectedXnatObject) != nullptr; enableDownload |= dynamic_cast(selectedXnatObject) != nullptr; if (enableDownload) { this->InternalFileDownload(index, true); } } void QmitkXnatTreeBrowserView::OnUploadFromDataStorage() { QmitkXnatUploadFromDataStorageDialog dialog; dialog.SetDataStorage(this->GetDataStorage()); int result = dialog.exec(); if (result == QDialog::Accepted) { QList nodes; nodes << dialog.GetSelectedNode().GetPointer(); QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); if (!index.isValid()) return; ctkXnatObject* parent = m_TreeModel->xnatObject(index); this->OnUploadResource(nodes, parent, index); } } void QmitkXnatTreeBrowserView::OnXnatNodeSelected(const QModelIndex& index) { if (!index.isValid()) return; ctkXnatObject* selectedXnatObject = index.data(Qt::UserRole).value(); // enable download button bool enableDownload = dynamic_cast(selectedXnatObject) != nullptr; enableDownload |= dynamic_cast(selectedXnatObject) != nullptr; m_Controls.btnXnatDownload->setEnabled(enableDownload); // enable folder creation bool enableCreateFolder = dynamic_cast(selectedXnatObject) != nullptr; enableCreateFolder |= dynamic_cast(selectedXnatObject) != nullptr; enableCreateFolder |= dynamic_cast(selectedXnatObject) != nullptr; enableCreateFolder |= dynamic_cast(selectedXnatObject) != nullptr; m_Controls.btnCreateXnatFolder->setEnabled(enableCreateFolder); // enable upload bool enableUpload = dynamic_cast(selectedXnatObject) != nullptr; m_Controls.btnXnatUpload->setEnabled(enableUpload); } void QmitkXnatTreeBrowserView::OnActivatedNode(const QModelIndex& index) { if (!index.isValid()) return; ctkXnatObject* selectedXnatObject = index.data(Qt::UserRole).value(); bool enableDownload = dynamic_cast(selectedXnatObject) != nullptr; enableDownload |= dynamic_cast(selectedXnatObject) != nullptr; if (enableDownload) { if(!m_SilentMode) { QMessageBox msgBox; QString fname = selectedXnatObject->name() != "" ? selectedXnatObject->name() : index.data(Qt::DisplayRole).toString(); QString msg ("Do you want to download "+ fname +"?"); msgBox.setWindowTitle("MITK XNAT download"); msgBox.setText(msg); msgBox.setIcon(QMessageBox::Question); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); int result = msgBox.exec(); if (result == QMessageBox::Ok) { InternalFileDownload(index, true); } } else { InternalFileDownload(index, true); } } } void QmitkXnatTreeBrowserView::UpdateSession(ctkXnatSession* session) { if (session != nullptr && session->isOpen()) { // Fill model and show in the GUI m_TreeModel->addDataModel(session->dataModel()); m_Controls.treeView->reset(); connect(session, SIGNAL(progress(QUuid,double)), this, SLOT(OnProgress(QUuid,double))); connect(session, SIGNAL(timedOut()), this, SLOT(SessionTimedOutMsg())); connect(session, SIGNAL(aboutToTimeOut()), this, SLOT(SessionTimesOutSoonMsg())); } } void QmitkXnatTreeBrowserView::CleanTreeModel(ctkXnatSession* session) { if (session != nullptr) { m_TreeModel->removeDataModel(session->dataModel()); m_Controls.treeView->reset(); } } void QmitkXnatTreeBrowserView::OnProgress(QUuid /*queryID*/, double progress) { if (progress > 0) { unsigned int currentProgress = progress*100; if (m_Controls.groupBox->isHidden()) { m_Controls.groupBox->show(); m_Controls.progressBar->setValue(0); } m_Controls.progressBar->setValue(currentProgress); } } -void QmitkXnatTreeBrowserView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) +void QmitkXnatTreeBrowserView::OnPreferencesChanged(const mitk::IPreferences* prefs) { - QString downloadPath = prefs->Get("Download Path", ""); + QString downloadPath = QString::fromStdString(prefs->Get("Download Path", "")); QDir downloadDir (downloadPath); if (downloadPath.length() != 0 && downloadDir.exists()) m_DownloadPath = downloadPath; m_SilentMode = prefs->GetBool("Silent Mode", false); } void QmitkXnatTreeBrowserView::InternalFileDownload(const QModelIndex& index, bool loadData) { if (!index.isValid()) return; QDir rootDownloadDir(m_DownloadPath); if(isDirWriteable(rootDownloadDir) == false) { MITK_INFO << "Download directory access permission unsufficient! " << m_DownloadPath; QMessageBox::critical(nullptr,"Download directory access permission unsufficient!", "You have no permission to write to selected download directory " + m_DownloadPath +"!\n\nChange Download Path in Settings!"); QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.SetSelectedPage("org.mitk.gui.qt.application.XnatConnectionPreferencePage"); _PreferencesDialog.exec(); return; } ctkXnatObject* xnatObject = m_TreeModel->xnatObject(index); if (xnatObject != nullptr) { m_Controls.progressBar->setMinimum(0); m_Controls.progressBar->setMaximum(100); // The path to the downloaded file QString filePath; QDir downloadPath (m_DownloadPath); - QString serverURL = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node(VIEW_ID)->Get("Server Address", ""); + auto serverURL = QString::fromStdString(mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node(VIEW_ID.toStdString())->Get("Server Address", "")); bool isDICOM (false); bool filePathExists (true); // If a scan was selected, downloading the contained DICOM folder as ZIP ctkXnatScan* scan = dynamic_cast(xnatObject); if (scan != nullptr) { isDICOM = true; if (!scan->isFetched()) scan->fetch(); QList children = scan->children(); foreach (ctkXnatObject* obj, children) { if (obj->name() == "DICOM") { QString uriId = obj->resourceUri(); uriId.replace("/data/archive/projects/", ""); QString folderName = m_DownloadPath + uriId + "/"; downloadPath = folderName; filePathExists = doesDirExist(downloadPath); if(filePathExists) { try { this->InternalDICOMDownload(obj, downloadPath); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); return; } serverURL = obj->resourceUri(); } else { FilePathNotAvailableWarning("DICOM folder"); return; } } } } else { ctkXnatFile* file = dynamic_cast(xnatObject); if (file == nullptr) { MITK_ERROR << "Selected XNAT object not downloadable!"; return; } QString uriId = file->parent()->resourceUri(); uriId.replace("/data/archive/projects/", ""); QString folderName = m_DownloadPath + uriId + "/"; downloadPath = folderName; filePathExists = doesDirExist(downloadPath); filePath = folderName + file->name(); // Checking if the file exists already if (downloadPath.exists(file->name())) { MITK_INFO << "File '" << file->name().toStdString() << "' already exists!"; serverURL = file->parent()->resourceUri(); } else { if (file->property("collection") == QString("DICOM")) { isDICOM = true; ctkXnatObject* parent = file->parent(); QString uriId = parent->resourceUri(); uriId.replace("/data/archive/projects/", ""); QString folderName = m_DownloadPath + uriId + "/"; downloadPath = folderName; filePathExists = doesDirExist(downloadPath); if(filePathExists) { try { this->InternalDICOMDownload(parent, downloadPath); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); return; } } else { FilePathNotAvailableWarning(parent->name()); return; } serverURL = parent->resourceUri(); } //Normal file download, no DICOM download else { if(filePathExists) { this->SetStatusInformation("Downloading file " + file->name()); file->download(filePath); } else { MITK_INFO << "File Download Failed."; } serverURL = file->parent()->resourceUri(); // Checking if the file exists now if (downloadPath.exists(file->name())) { MITK_INFO << "Download of " << file->name().toStdString() << " completed!"; if(!m_SilentMode) { QMessageBox msgBox; msgBox.setText("Download of " + file->name() + " completed!"); msgBox.setIcon(QMessageBox::Information); msgBox.exec(); } m_Controls.groupBox->hide(); } else { if(filePathExists) { MITK_INFO << "Download of " << file->name().toStdString() << " failed!"; QMessageBox::critical(m_Controls.treeView, "Download failed!", "Download of " + file->name() + " failed!"); m_Controls.groupBox->hide(); return; } else { FilePathNotAvailableWarning(file->name()); return; } } } } } if (loadData) { QFileInfoList fileList; if (isDICOM) { fileList = downloadPath.entryInfoList(QDir::Files); } else { QFileInfo fileInfo(filePath); fileList << fileInfo; } mitk::StringProperty::Pointer xnatURL = mitk::StringProperty::New(serverURL.toStdString()); try { this->InternalOpenFiles(fileList, xnatURL); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); return; } } } } void QmitkXnatTreeBrowserView::InternalDICOMDownload(ctkXnatObject *obj, QDir &DICOMDirPath) { QString filePath = m_DownloadPath + obj->property("label") + ".zip"; this->SetStatusInformation("Downloading DICOM series " + obj->parent()->name()); // In case of DICOM zip download we do not know the total file size // Because of that the dowload progres cannot be calculated // Because of that we use the busy indicator of the progress bar by setting min and max to 0 m_Controls.progressBar->setMinimum(0); m_Controls.progressBar->setMaximum(0); m_Controls.progressBar->show(); obj->download(filePath); std::ifstream in(filePath.toStdString().c_str(), std::ios::binary); poco_assert(in); // decompress to XNAT_DOWNLOAD dir Poco::Zip::Decompress dec(in, Poco::Path(DICOMDirPath.path().toStdString()), true); dec.decompressAllFiles(); in.close(); QFile::remove(filePath); // Checking if the file exists now if (DICOMDirPath.exists()) { if(!m_SilentMode) { MITK_INFO << "Download of DICOM series completed!"; QMessageBox msgBox; msgBox.setText("Download of DICOM series completed!"); msgBox.setIcon(QMessageBox::Information); msgBox.exec(); m_Controls.groupBox->hide(); } } else { MITK_INFO << "Download of DICOM series failed!"; QMessageBox msgBox; msgBox.setText("Download of DICOM series failed!"); msgBox.setIcon(QMessageBox::Critical); msgBox.exec(); m_Controls.groupBox->hide(); } } void QmitkXnatTreeBrowserView::InternalOpenFiles(const QFileInfoList & fileList, mitk::StringProperty::Pointer xnatURL) { if (fileList.isEmpty()) { MITK_WARN << "No files available for loading!"; return; } mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService(); mitk::DataStorage::Pointer dataStorage = dsService->GetDataStorage()->GetDataStorage(); QStringList list; list << fileList.at(0).absoluteFilePath(); try { mitk::DataStorage::SetOfObjects::Pointer nodes = QmitkIOUtil::Load(list, *dataStorage); if (nodes->size() == 1) { mitk::DataNode* node = nodes->at(0); node->SetProperty("xnat.url", xnatURL); } } catch (const mitk::Exception& e) { MITK_INFO << e; return; } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects( dsService->GetDataStorage()->GetDataStorage()); } void QmitkXnatTreeBrowserView::OnContextMenuDownloadFile() { QModelIndex index = m_Controls.treeView->currentIndex(); InternalFileDownload(index, false); } void QmitkXnatTreeBrowserView::OnContextMenuDownloadAndOpenFile() { QModelIndex index = m_Controls.treeView->currentIndex(); InternalFileDownload(index, true); } void QmitkXnatTreeBrowserView::OnContextMenuCreateResourceFolder() { const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); ctkXnatObject* parentObject = m_TreeModel->xnatObject(index); if (parentObject != nullptr) { this->InternalAddResourceFolder(parentObject); } } ctkXnatResource* QmitkXnatTreeBrowserView::InternalAddResourceFolder(ctkXnatObject *parent) { bool ok; QString folderName = QInputDialog::getText(m_Controls.treeView, tr("Create XNAT resource folder"), tr("Folder name:"), QLineEdit::Normal, tr("data"), &ok); if (ok) { if (folderName.isEmpty()) folderName = "NO LABEL"; // if called on the resource-folder level we need to provide he corresponding // parent instead of the folder ctkXnatResourceFolder* resourceFolder = dynamic_cast(parent); if (resourceFolder != nullptr) { parent = parent->parent(); } try { return parent->addResourceFolder(folderName); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); return nullptr; } } else { return nullptr; } } void QmitkXnatTreeBrowserView::InternalFileUpload(ctkXnatFile* file) { m_Controls.groupBox->setTitle("Uploading file..."); m_Controls.groupBox->show(); try { file->save(); MITK_INFO << "Upload of " << file->name().toStdString() << " completed!"; if(!m_SilentMode) { QMessageBox msgBox; msgBox.setText("Upload of " + file->name() + " completed!"); msgBox.setIcon(QMessageBox::Information); msgBox.show(); msgBox.exec(); } } catch (ctkXnatException &e) { QMessageBox msgbox; msgbox.setText(e.what()); msgbox.setIcon(QMessageBox::Critical); msgbox.exec(); m_Controls.progressBar->setValue(0); } m_Controls.groupBox->hide(); } void QmitkXnatTreeBrowserView::OnContextMenuUploadFile() { QString filename = QFileDialog::getOpenFileName(m_Controls.treeView, tr("Open File"), QDir::homePath()); const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); ctkXnatResource* resource = dynamic_cast(m_TreeModel->xnatObject(index)); if (resource != nullptr && filename.length() != 0) { ctkXnatFile* file = new ctkXnatFile(resource); file->setLocalFilePath(filename); QFileInfo fileInfo (filename); file->setName(fileInfo.fileName()); try { this->InternalFileUpload(file); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); return; } m_TreeModel->addChildNode(index, file); } } void QmitkXnatTreeBrowserView::OnContextMenuCopyXNATUrlToClipboard() { const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); ctkXnatObject* currentXnatObject = m_TreeModel->xnatObject(index); if (currentXnatObject != nullptr) { - QString serverURL = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node(VIEW_ID)->Get("Server Address", ""); + auto serverURL = QString::fromStdString(mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node(VIEW_ID.toStdString())->Get("Server Address", "")); serverURL.append(currentXnatObject->resourceUri()); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(serverURL); } } void QmitkXnatTreeBrowserView::OnContextMenuRefreshItem() { const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); if (index.isValid()) { this->m_TreeModel->refresh(index); } } void QmitkXnatTreeBrowserView::OnUploadResource(const QList& droppedNodes, ctkXnatObject* parentObject, const QModelIndex& parentIndex) { if (parentObject == nullptr) return; //1. If not dropped on a resource, create a new folder //temporarily remove the annoying message box that upload was successful.. ctkXnatResource* resource = dynamic_cast(parentObject); // store original resource folder object for later use ctkXnatResourceFolder* originalResourceFolder = dynamic_cast(parentObject); if (resource == nullptr) { resource = this->InternalAddResourceFolder(parentObject); } if (resource == nullptr) { MITK_WARN << "Resource folder could not be created!"; return; } //2. Save files locally //3. Upload file mitk::DataNode* node = nullptr; foreach (node, droppedNodes) { mitk::BaseData* data = node->GetData(); if (!data) return; //We have to replace special characters due to XNAT inability to get along with them (" " is replaced by "%20", what leads to nasty behaviour!) QString fileName(QString::fromStdString(ReplaceSpecialChars(node->GetName()))); ctkXnatFile* xnatFile = new ctkXnatFile(resource); if (dynamic_cast(data)) { fileName.append(".nrrd"); } else if (dynamic_cast(data)) { fileName.append(".vtk"); } else if (dynamic_cast(data)) { fileName.append(".mps"); } else { MITK_WARN << "Could not upload file! File-type not supported"; QMessageBox msgbox; msgbox.setText("Could not upload file! File-type not supported"); msgbox.setIcon(QMessageBox::Critical); msgbox.exec(); return; } xnatFile->setName(fileName); QString xnatFolder = "XNAT_UPLOADS"; QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath()); dir.mkdir(xnatFolder); fileName = dir.path().append("/" + fileName); mitk::IOUtil::Save (data, fileName.toStdString()); // TODO Check if file exists // AbstractFileReader::SetDefaultDataNodeProperties // und in die andere SetDefaultDataNodeProperties // PropertyName klein: mtime.initial + Kommentar mitk::StringProperty::Pointer orignalFilePath = mitk::StringProperty::New(); node->GetProperty(orignalFilePath, "path"); xnatFile->setLocalFilePath(fileName); try { this->InternalFileUpload(xnatFile); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); return; } QFile::remove(fileName); if (originalResourceFolder == nullptr) { m_TreeModel->refresh(parentIndex); } else { m_TreeModel->refresh(parentIndex.parent()); } // The filename for uploading // QFileInfo fileInfo; // if (surface) // { // // Save surface // fileName.append(".stl"); // xnatFile->setName(fileName); // dir.setPath(dir.path().append("/" + fileName)); // QString origFile = QString::fromStdString(orignalFilePath->GetValueAsString()); // origFile.append("/" + fileName); // origFile.append(".stl"); // fileInfo.setFile(origFile); // if (!fileInfo.exists()) // mitk::IOUtil::Save(surface, dir.path().toStdString()); // } // this->uploadFileToXnat(xnatFile, dir.path()); } } void QmitkXnatTreeBrowserView::OnContextMenuRequested(const QPoint & pos) { if(m_TreeModel==nullptr) { return; } QModelIndex index = m_Controls.treeView->indexAt(pos); if(index.isValid() == false) { return; } m_ContextMenu->clear(); QAction* actRefreshItem = new QAction("Refresh", m_ContextMenu); m_ContextMenu->addAction(actRefreshItem); connect(actRefreshItem, SIGNAL(triggered()), this, SLOT(OnContextMenuRefreshItem())); QAction* actGetXNATURL = new QAction("Copy XNAT URL to clipboard", m_ContextMenu); m_ContextMenu->addAction(actGetXNATURL); connect(actGetXNATURL, SIGNAL(triggered()), this, SLOT(OnContextMenuCopyXNATUrlToClipboard())); m_ContextMenu->addSeparator(); ctkXnatObject* xnatObject = m_TreeModel->xnatObject(index); bool downloadable = false; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; downloadable |= dynamic_cast(xnatObject)!=nullptr; bool canHaveResourceFolder = false; canHaveResourceFolder |= dynamic_cast(xnatObject) != nullptr; canHaveResourceFolder |= dynamic_cast(xnatObject) != nullptr; canHaveResourceFolder |= dynamic_cast(xnatObject) != nullptr; canHaveResourceFolder |= dynamic_cast(xnatObject) != nullptr; bool uploadFilePossible = false; uploadFilePossible |= dynamic_cast(xnatObject) != nullptr; uploadFilePossible |= dynamic_cast(xnatObject) != nullptr; uploadFilePossible |= dynamic_cast(xnatObject) != nullptr; if (downloadable) { QAction* actDownload = new QAction("Download", m_ContextMenu); connect(actDownload, SIGNAL(triggered()), this, SLOT(OnContextMenuDownloadFile())); m_ContextMenu->addAction(actDownload); ctkXnatFile* file = dynamic_cast(xnatObject); if (file) { QAction* actView = new QAction("Download and Open", m_ContextMenu); connect(actView, SIGNAL(triggered()), this, SLOT(OnContextMenuDownloadAndOpenFile())); m_ContextMenu->addAction(actView); } } if (canHaveResourceFolder) { QAction* actCreateResource = new QAction("Add resource folder", m_ContextMenu); connect(actCreateResource, SIGNAL(triggered()), this, SLOT(OnContextMenuCreateResourceFolder())); m_ContextMenu->addAction(actCreateResource); } if (uploadFilePossible) { QAction* actUploadFile = new QAction("Upload File", m_ContextMenu); connect(actUploadFile, SIGNAL(triggered()), this, SLOT(OnContextMenuUploadFile())); m_ContextMenu->addAction(actUploadFile); } ctkXnatProject* project = dynamic_cast(xnatObject); if (project != nullptr) { QAction* actCreateSubject = new QAction("Create new subject", m_ContextMenu); m_ContextMenu->addAction(actCreateSubject); connect(actCreateSubject, SIGNAL(triggered()), this, SLOT(OnContextMenuCreateNewSubject())); } ctkXnatSubject* subject = dynamic_cast(xnatObject); if (subject != nullptr) { QAction* actCreateExperiment = new QAction("Create new experiment", m_ContextMenu); m_ContextMenu->addAction(actCreateExperiment); connect(actCreateExperiment, SIGNAL(triggered()), this, SLOT(OnContextMenuCreateNewExperiment())); } m_ContextMenu->popup(QCursor::pos()); } void QmitkXnatTreeBrowserView::CleanUp() { m_Controls.wgtExperimentInfo->hide(); m_Controls.wgtSubjectInfo->hide(); m_Controls.wgtProjectInfo->hide(); m_Controls.btnCreateXnatFolder->setEnabled(false); m_Controls.btnXnatDownload->setEnabled(false); m_Controls.btnXnatUpload->setEnabled(false); m_Controls.searchField->setEnabled(false); m_Controls.searchField->setText(""); m_Controls.searchModeBox->setEnabled(false); } std::string QmitkXnatTreeBrowserView::ReplaceSpecialChars(const std::string& input) const { QString convertedString = QString(QUrl::toPercentEncoding(QString::fromStdString(input))); return convertedString.toStdString(); } void QmitkXnatTreeBrowserView::ItemSelected(const QModelIndex& index) { //TODO: CTK seems to ignore spaces while creating the http request. This will lead to corrupted http request that will fail. QVariant variant = m_TreeModel->data(index, Qt::UserRole); if (variant.isValid()) { ctkXnatSession *session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); ctkXnatObject* object = variant.value(); ctkXnatProject* project = dynamic_cast(object); ctkXnatSubject* subject = dynamic_cast(object); ctkXnatExperiment* experiment = dynamic_cast(object); if (project != nullptr) { m_Controls.wgtExperimentInfo->hide(); m_Controls.wgtSubjectInfo->hide(); m_Controls.wgtProjectInfo->SetProject(project); m_Controls.wgtProjectInfo->show(); } else if (subject != nullptr) { QMap paramMap; paramMap.insert("columns", "dob,gender,handedness,weight,height"); QUuid requestID = session->httpGet(QString("%1/subjects").arg(subject->parent()->resourceUri()), paramMap); QList results = session->httpSync(requestID); foreach(const QVariantMap& propertyMap, results) { QMapIterator it(propertyMap); bool isConcretSubject = false; if (it.hasNext()) { it.next(); QVariant var = it.value(); // After CTK Change (subjectID = name) to (subjectID = ID) // CHANGE TO: if (var == subject->property("ID")) if (var == subject->property("URI").right(11)) { isConcretSubject = true; } else { isConcretSubject = false; } it.toFront(); } while (it.hasNext() && isConcretSubject) { it.next(); QString str = it.key().toLatin1().data(); QVariant var = it.value(); subject->setProperty(str, var); } } m_Controls.wgtExperimentInfo->hide(); m_Controls.wgtProjectInfo->hide(); m_Controls.wgtSubjectInfo->SetSubject(subject); m_Controls.wgtSubjectInfo->show(); } else if (experiment != nullptr) { QMap paramMap; paramMap.insert("columns", "date,time,scanner,modality"); QUuid requestID = session->httpGet(QString("%1/experiments").arg(experiment->parent()->resourceUri()), paramMap); QList results = session->httpSync(requestID); foreach(const QVariantMap& propertyMap, results) { QMapIterator it(propertyMap); bool isConcretExperiment = false; if (it.hasNext()) { it.next(); QVariant var = it.value(); if (var == experiment->property("URI")) { isConcretExperiment = true; } else { isConcretExperiment = false; } it.toFront(); } while (it.hasNext() && isConcretExperiment) { it.next(); QString str = it.key().toLatin1().data(); QVariant var = it.value(); experiment->setProperty(str, var); } } m_Controls.wgtSubjectInfo->hide(); m_Controls.wgtProjectInfo->hide(); m_Controls.wgtExperimentInfo->SetExperiment(experiment); m_Controls.wgtExperimentInfo->show(); } } } void QmitkXnatTreeBrowserView::OnContextMenuCreateNewSubject() { QModelIndex index = m_Controls.treeView->currentIndex(); QVariant variant = m_TreeModel->data(index, Qt::UserRole); if (variant.isValid()) { QmitkXnatCreateObjectDialog* dialog = new QmitkXnatCreateObjectDialog(QmitkXnatCreateObjectDialog::SpecificType::SUBJECT); if (dialog->exec() == QDialog::Accepted) { ctkXnatProject* project = dynamic_cast(variant.value()); ctkXnatSubject* subject = dynamic_cast(dialog->GetXnatObject()); subject->setParent(project); try { subject->save(); } catch(const ctkRuntimeException& exc) { //TODO: Implement isValid-flag to check if ctkRuntimeExceptio is valid http-exception. QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); project->remove(subject); delete subject; return; } // Get xnat session from micro service ctkXnatSession* session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); // Update View m_TreeModel->removeDataModel(session->dataModel()); UpdateSession(session); } } } void QmitkXnatTreeBrowserView::OnContextMenuCreateNewExperiment() { QModelIndex index = m_Controls.treeView->currentIndex(); QVariant variant = m_TreeModel->data(index, Qt::UserRole); if (variant.isValid()) { QmitkXnatCreateObjectDialog* dialog = new QmitkXnatCreateObjectDialog(QmitkXnatCreateObjectDialog::SpecificType::EXPERIMENT); if (dialog->exec() == QDialog::Accepted) { ctkXnatSubject* subject = dynamic_cast(variant.value()); ctkXnatExperiment* experiment = dynamic_cast(dialog->GetXnatObject()); experiment->setParent(subject); experiment->setProperty("xsiType", experiment->imageModality()); try { experiment->save(); } catch(const ctkRuntimeException& exc) { QmitkHttpStatusCodeHandler::HandleErrorMessage(exc.what()); subject->remove(experiment); delete experiment; return; } // Get xnat session from micro service ctkXnatSession* session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); // Update View m_TreeModel->removeDataModel(session->dataModel()); UpdateSession(session); } } } void QmitkXnatTreeBrowserView::SetStatusInformation(const QString& text) { m_Controls.groupBox->setTitle(text); m_Controls.progressBar->setValue(0); m_Controls.groupBox->show(); } void QmitkXnatTreeBrowserView::SessionTimedOutMsg() { ctkXnatSession* session = qobject_cast(QObject::sender()); if (session == nullptr) return; ctkXnatDataModel* dataModel = session->dataModel(); m_TreeModel->removeDataModel(dataModel); m_Controls.treeView->reset(); session->close(); QMessageBox::warning(m_Controls.treeView, "Session Timeout", "The session timed out."); m_Controls.btnXnatConnect->setToolTip("Connect"); m_Controls.btnXnatConnect->setIcon(QIcon(":/xnat-plugin/xnat-connect.png")); CleanUp(); } void QmitkXnatTreeBrowserView::SessionTimesOutSoonMsg() { ctkXnatSession* session = qobject_cast(QObject::sender()); if (session == nullptr) return; QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setWindowTitle("Session Timeout Soon"); msgBox.setText("The session will time out in 1 minute.\nDo you want to renew the session?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); msgBox.show(); QTimer* timer = new QTimer(this); timer->start(60000); this->connect(timer, SIGNAL(timeout()), &msgBox, SLOT(reject())); if (msgBox.exec() == QMessageBox::Yes){ session->renew(); } timer->stop(); } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.h index 0cdb3d0ef0..87936fa4c2 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.h @@ -1,145 +1,142 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKXNATTREEBROWSERVIEW_H #define QMITKXNATTREEBROWSERVIEW_H #include #include "ui_QmitkXnatTreeBrowserViewControls.h" #include "QmitkHttpStatusCodeHandler.h" // ctkXnatCore #include "ctkXnatSession.h" // ctkXnatWidget #include "QmitkXnatTreeModel.h" // MitkXNAT Module #include "mitkXnatSessionTracker.h" #include #include -#include - class QMenu; - /*! \brief QmitkXnatTreeBrowserView \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \ingroup ${plugin_target}_internal */ class QmitkXnatTreeBrowserView : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: QmitkXnatTreeBrowserView(); ~QmitkXnatTreeBrowserView() override; static const QString VIEW_ID; void CreateQtPartControl(QWidget *parent) override; enum SearchMethod { ProjectLevel = 0, SubjectLevel = 1 }; protected slots: /// \brief Opens or reuses the xnat editor with the activated node as root item. void OnActivatedNode(const QModelIndex& index); /// \brief Updates the ctkXnatSession and the user interface void UpdateSession(ctkXnatSession* session); /// \brief Cleans the tree model void CleanTreeModel(ctkXnatSession* session); /// \brief Searches the tree model void Search(const QString &toSearch); void OnContextMenuRequested(const QPoint & pos); void OnContextMenuDownloadAndOpenFile(); void OnContextMenuDownloadFile(); void OnContextMenuCreateResourceFolder(); void OnContextMenuUploadFile(); void OnContextMenuCreateNewSubject(); void OnContextMenuCreateNewExperiment(); void OnContextMenuCopyXNATUrlToClipboard(); void OnContextMenuRefreshItem(); void OnUploadResource(const QList& , ctkXnatObject *, const QModelIndex &parentIndex); void OnProgress(QUuid, double); void ItemSelected(const QModelIndex& index); void OnUploadFromDataStorage(); void SessionTimedOutMsg(); void SessionTimesOutSoonMsg(); void ToggleConnection(); protected: void SetFocus() override; Ui::QmitkXnatTreeBrowserViewControls m_Controls; private slots: void OnXnatNodeSelected(const QModelIndex &index); void OnDownloadSelectedXnatFile(); void OnCreateResourceFolder(); private: - void OnPreferencesChanged(const berry::IBerryPreferences*) override; + void OnPreferencesChanged(const mitk::IPreferences*) override; void InternalFileDownload(const QModelIndex& index, bool loadData); void InternalDICOMDownload(ctkXnatObject* obj, QDir &DICOMDirPath); void InternalFileUpload(ctkXnatFile *file); ctkXnatResource* InternalAddResourceFolder(ctkXnatObject* parent); void InternalOpenFiles(const QFileInfoList&, mitk::StringProperty::Pointer xnatURL); void SetStatusInformation(const QString&); void FilePathNotAvailableWarning(QString file); void CleanUp(); ctkServiceTracker m_DataStorageServiceTracker; QmitkXnatTreeModel* m_TreeModel; mitk::XnatSessionTracker* m_Tracker; QString m_DownloadPath; QMenu* m_ContextMenu; bool m_SilentMode; QModelIndexList m_hiddenItems; bool m_AlreadyInSearch = false; std::string ReplaceSpecialChars(const std::string& input) const; }; #endif // QMITKXNATTREEBROWSERVIEW_H diff --git a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp index 04b2961fc2..8db8d026eb 100644 --- a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp +++ b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp @@ -1,156 +1,151 @@ /*============================================================================ 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 "MatchPointBrowserPreferencesPage.h" #include "MatchPointBrowserConstants.h" #include #include #include #include #include #include #include #include -#include -#include + +#include +#include +#include #include "QmitkDirectoryListWidget.h" #include "QmitkFileListWidget.h" //----------------------------------------------------------------------------- MatchPointBrowserPreferencesPage::MatchPointBrowserPreferencesPage() : m_MainControl(nullptr) , m_AlgDirectories(nullptr) , m_AlgFiles(nullptr) , m_LoadFromHomeDir(nullptr) , m_LoadFromCurrentDir(nullptr) , m_LoadFromApplicationDir(nullptr) , m_LoadFromAutoLoadPathDir(nullptr) , m_BrowserPreferencesNode(nullptr) { } //----------------------------------------------------------------------------- MatchPointBrowserPreferencesPage::~MatchPointBrowserPreferencesPage() { } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService* prefService - = berry::Platform::GetPreferencesService(); + auto* prefService = mitk::CoreServices::GetPreferencesService(); - QString id = tr("/") + tr(MatchPointBrowserConstants::VIEW_ID.c_str()); + const auto id = "/" + MatchPointBrowserConstants::VIEW_ID; m_BrowserPreferencesNode = prefService->GetSystemPreferences()->Node(id); m_MainControl = new QWidget(parent); m_AlgDirectories = new QmitkDirectoryListWidget(m_MainControl); m_AlgDirectories->m_Label->setText("Select directories to scan:"); m_AlgFiles = new QmitkFileListWidget(m_MainControl); m_AlgFiles->m_Label->setText("Select additional executables:"); m_DebugOutput = new QCheckBox(m_MainControl); m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl); m_LoadFromApplicationDir = new QCheckBox(m_MainControl); m_LoadFromHomeDir = new QCheckBox(m_MainControl); m_LoadFromCurrentDir = new QCheckBox(m_MainControl); QFormLayout *formLayout = new QFormLayout; formLayout->addRow("show debug output:", m_DebugOutput); formLayout->addRow("scan home directory:", m_LoadFromHomeDir); formLayout->addRow("scan current directory:", m_LoadFromCurrentDir); formLayout->addRow("scan installation directory:", m_LoadFromApplicationDir); formLayout->addRow("scan MAP_MDRA_LOAD_PATH:", m_LoadFromAutoLoadPathDir); formLayout->addRow("additional algorithm directories:", m_AlgDirectories); formLayout->addRow("additional algorithms:", m_AlgFiles); m_MainControl->setLayout(formLayout); this->Update(); } //----------------------------------------------------------------------------- QWidget* MatchPointBrowserPreferencesPage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- -QString MatchPointBrowserPreferencesPage::ConvertToString( const QStringList& list ) +std::string MatchPointBrowserPreferencesPage::ConvertToString( const QStringList& list ) { - QString output; - for (int i = 0; i < list.count(); i++) - { - QString path = list[i] + ";"; - output = output + path; - } - return output; + return list.join(';').toStdString(); } //----------------------------------------------------------------------------- bool MatchPointBrowserPreferencesPage::PerformOk() { - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME.c_str(), m_DebugOutput->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR.c_str(), m_LoadFromApplicationDir->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR.c_str(), m_LoadFromHomeDir->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR.c_str(), m_LoadFromCurrentDir->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR.c_str(), m_LoadFromAutoLoadPathDir->isChecked()); + m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); + m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); + m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); + m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); + m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); - QString paths = this->ConvertToString(m_AlgDirectories->directories()); - m_BrowserPreferencesNode->Put(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME.c_str(), paths); + const auto paths = this->ConvertToString(m_AlgDirectories->directories()); + m_BrowserPreferencesNode->Put(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, paths); - QString modules = this->ConvertToString(m_AlgFiles->files()); - m_BrowserPreferencesNode->Put(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME.c_str(), modules); + const auto modules = this->ConvertToString(m_AlgFiles->files()); + m_BrowserPreferencesNode->Put(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, modules); return true; } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::PerformCancel() { } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::Update() { - m_DebugOutput->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME.c_str(), false)); - m_LoadFromApplicationDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR.c_str(), true)); - m_LoadFromHomeDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR.c_str(), false)); - m_LoadFromCurrentDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR.c_str(), false)); - m_LoadFromAutoLoadPathDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR.c_str(), false)); + m_DebugOutput->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, false)); + m_LoadFromApplicationDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, true)); + m_LoadFromHomeDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, false)); + m_LoadFromCurrentDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, false)); + m_LoadFromAutoLoadPathDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); - QString paths = m_BrowserPreferencesNode->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME.c_str(), tr("")); + QString paths = QString::fromStdString(m_BrowserPreferencesNode->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, "")); QStringList directoryList = paths.split(";", QString::SkipEmptyParts); m_AlgDirectories->setDirectories(directoryList); - QString files = m_BrowserPreferencesNode->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME.c_str(), tr("")); + QString files = QString::fromStdString(m_BrowserPreferencesNode->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, "")); QStringList fileList = files.split(";", QString::SkipEmptyParts); m_AlgFiles->setFiles(fileList); } diff --git a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h index 17d5ba923f..d2863268f4 100644 --- a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h +++ b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h @@ -1,94 +1,97 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __MATCHPOINT_BROWSER_PREFERENCE_PAGE_H #define __MATCHPOINT_BROWSER_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" class QWidget; class QCheckBox; class QComboBox; class QSpinBox; class QmitkDirectoryListWidget; class QmitkFileListWidget; class ctkDirectoryButton; -class berryIPreferences; +namespace mitk +{ + class IPreferences; +} /** * \class MatchPointBrowserPreferencesPage * \brief Preference page for the MatchPoint Browser plugin */ class MatchPointBrowserPreferencesPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: MatchPointBrowserPreferencesPage(); ~MatchPointBrowserPreferencesPage() override; /** * \brief Called by framework to initialise this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: protected: QWidget* m_MainControl; QCheckBox* m_DebugOutput; QmitkDirectoryListWidget* m_AlgDirectories; QmitkFileListWidget* m_AlgFiles; QCheckBox* m_LoadFromHomeDir; QCheckBox* m_LoadFromCurrentDir; QCheckBox* m_LoadFromApplicationDir; QCheckBox* m_LoadFromAutoLoadPathDir; - berry::IPreferences::Pointer m_BrowserPreferencesNode; + mitk::IPreferences* m_BrowserPreferencesNode; private: - QString ConvertToString(const QStringList& list); + std::string ConvertToString(const QStringList& list); }; #endif // COMMANDLINEMODULESPREFERENCESPAGE_H diff --git a/Plugins/org.mitk.matchpoint.core.helper/src/internal/org_mitk_matchpoint_core_helper_Activator.cpp b/Plugins/org.mitk.matchpoint.core.helper/src/internal/org_mitk_matchpoint_core_helper_Activator.cpp index 6d3072f7f4..00bcc7bca4 100644 --- a/Plugins/org.mitk.matchpoint.core.helper/src/internal/org_mitk_matchpoint_core_helper_Activator.cpp +++ b/Plugins/org.mitk.matchpoint.core.helper/src/internal/org_mitk_matchpoint_core_helper_Activator.cpp @@ -1,68 +1,71 @@ /*============================================================================ 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 "org_mitk_matchpoint_core_helper_Activator.h" #include "MatchPointBrowserPreferencesPage.h" #include "QmitkNodeDescriptorManager.h" #include "QmitkStyleManager.h" #include "mitkNodePredicateDataType.h" +#include + +US_INITIALIZE_MODULE ctkPluginContext* org_mitk_matchpoint_core_helper_Activator::m_Context = nullptr; org_mitk_matchpoint_core_helper_Activator* org_mitk_matchpoint_core_helper_Activator::m_Instance = nullptr; org_mitk_matchpoint_core_helper_Activator::org_mitk_matchpoint_core_helper_Activator() { m_Instance = this; } org_mitk_matchpoint_core_helper_Activator::~org_mitk_matchpoint_core_helper_Activator() { m_Instance = nullptr; } void org_mitk_matchpoint_core_helper_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(MatchPointBrowserPreferencesPage, context) this->m_Context = context; QmitkNodeDescriptorManager* manager = QmitkNodeDescriptorManager::GetInstance(); mitk::NodePredicateDataType::Pointer isMITKRegistrationWrapper = mitk::NodePredicateDataType::New("MAPRegistrationWrapper"); auto desc = new QmitkNodeDescriptor(QObject::tr("MAPRegistrationWrapper"), QmitkStyleManager::ThemeIcon(QStringLiteral(":/QmitkMatchPointCore/MAPRegData.svg")), isMITKRegistrationWrapper, manager); manager->AddDescriptor(desc); } void org_mitk_matchpoint_core_helper_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) this->m_Context = nullptr; } ctkPluginContext* org_mitk_matchpoint_core_helper_Activator::getContext() { return m_Context; } org_mitk_matchpoint_core_helper_Activator* org_mitk_matchpoint_core_helper_Activator::getDefault() { return m_Instance; }