diff --git a/Modules/C3js/resource/C3js.qrc b/Modules/C3js/resource/C3js.qrc index ef0618eb41..4ebbe5d81c 100644 --- a/Modules/C3js/resource/C3js.qrc +++ b/Modules/C3js/resource/C3js.qrc @@ -1,13 +1,14 @@ c3.min.css Histogram.css Histogram_dark.css c3.min.js d3.min.js empty.html + empty.js QmitkC3jsWidget.html Histogram.js diff --git a/Modules/C3js/resource/Histogram.css b/Modules/C3js/resource/Histogram.css index 9cd7975c64..ae37a3ae09 100644 --- a/Modules/C3js/resource/Histogram.css +++ b/Modules/C3js/resource/Histogram.css @@ -1,29 +1,28 @@ -/*--body { - background-color: darkgrey !important; -}--*/ - +body { + background-color: rgb(240, 240, 240) !important; +} /*-- Bar --*/ .c3-bar { fill-opacity: 1; } .c3-bar._expanded_ { fill: red !important; /*-- The !important tag prevnts the color from being overwritten at rendering--*/ fill-opacity: 1; } /*-- Line --*/ .c3-line { stroke-width: 1px; /*stroke-dasharray: 5,5; /*to make it dashed*/ } /*-- Point --*/ .c3-circle._expanded_ { stroke-width: 1px; stroke: red !important; fill: red !important; /*-- The !important tag prevnts the color from being overwritten at rendering--*/} /*path.domain { stroke: white; } .tick text { stroke: white; } .c3-legend-item text { stroke: grey; }*/ \ No newline at end of file diff --git a/Modules/C3js/resource/Histogram.js b/Modules/C3js/resource/Histogram.js index c34e9730c8..beb467a345 100644 --- a/Modules/C3js/resource/Histogram.js +++ b/Modules/C3js/resource/Histogram.js @@ -1,343 +1,341 @@ -document.body.style.backgroundColor = 'rgb(240, 240, 240)'; - var greyvalue; //needed to display the tooltip in the right format var binSize = 10; var min; var max; var minHeight = 255; var chart = c3.generate({ data: { x : 'x', //use first "column" as x axis values columns: [], //initialize empty. Data will be loaded in function setupChart(initValues) type: 'bar', selection: { enabled: false, multiple: false, } }, legend: { position: 'inset' }, grid: { y: { lines: [{value:0}] //Draws a horizontal line at y=0 } }, bar: { width: { ratio: 0.95 // this makes bar width 95% of length between ticks } }, zoom: { enabled: true, }, subchart: { show: true //Shows a subchart that shows the region the primary chart is zoomed in to by overlay. }, axis: { x: { type: 'category', //only for type 'category' the bars will be rescaled in width on zoom tick: { multiline: false, fit: false, //to make more x labels appear on zoom centered: true, }, }, y: { tick: { format: d3.format("s"), }, //for some reason, there is an offset for our linegraph. This is prevented by the following lines min: 0, padding: { top: 0, bottom: 0 } } }, //Style data points in linegraph point: { r: 0.2, focus: { expand: { r: 4 } } }, tooltip: { format: { title: function (d) { var endValue = (parseFloat(greyvalue[d]) + binSize); endValue = endValue.toFixed(3); return 'Greyvalue: ' + greyvalue[d] + '...' + endValue; }, } } }); var initValues; window.onload = function() { new QWebChannel(qt.webChannelTransport, function(channel) { initValues = channel.objects.initValues; setupChart(initValues) }); } //This is necessary to resize the chart, after the size of the parent changed window.onresize = function () { var size = window.innerHeight-(window.innerHeight/100*10); //subtract 5% of height to hide vertical scrool bar if (size < minHeight) { size = minHeight; } chart.resize({ height: size, }); } function ReloadChart(useLineChart, showSubchart) { initValues.m_UseLineChart = useLineChart; initValues.m_ShowSubchart = showSubchart; var chartType = 'bar'; if (initValues.m_UseLineChart) { chartType = 'line'; } if (initValues.m_ShowSubchart) { ShowSubchart(chartType) } else { HideSubchart(chartType) } setupChart(initValues); } function setupChart(initValues) { window.onresize(); calcBinSize(initValues); //copy measurements to xValues for x-axis-labels and to greyvalues for tooltips var xValues = initValues.m_XData.slice(0); greyvalue = initValues.m_XData.slice(0); for (var i = 0; i < xValues.length; i++) { greyvalue[i] = greyvalue[i] - (binSize / 2); greyvalue[i] = greyvalue[i].toFixed(3); //change number format for x axis. Need to do it here, because it is not working on chart generation. xValues[i] = xValues[i]; xValues[i] = xValues[i].toFixed(); xValues[i] = d3.format("s")(xValues[i]); } xValues.unshift('x'); //add label to x array xValues.push(null); //append null value, to make sure the last tick on x-axis is displayed correctly var yValues = initValues.m_YData; yValues.unshift('Frequency'); //add label to y array xValues.push(null); //append null value, to make sure the last tick on x-axis is displayed correctly var chartType = 'bar'; if (initValues.m_UseLineChart) { chartType = 'line'; } if (initValues.m_ShowSubchart) { ShowSubchart(chartType) } else { HideSubchart(chartType) } chart.unload(); //unload data before loading new data chart.load({ columns:[ xValues, yValues ] }); } /* * Calculation of the bin size. */ function calcBinSize(initValues) { if (1 < initValues.m_XData.length) { min = d3.min(initValues.m_XData); max = d3.max(initValues.m_XData); binSize = ((max - min) / (initValues.m_XData.length - 1)); } else { binSize = 10; } } //Transforamtion between bar and line chart //takes the name of the chart type as a parameter //calles by QmitkC3jsWidget function transformView(TransformTo) { chart.transform(TransformTo); }; function changeTheme(color) { if (color == 'dark') { link = document.getElementsByTagName("link")[0]; link.href = "Histogram_dark.css"; } else { link = document.getElementsByTagName("link")[0]; link.href = "Histogram.css"; } }; function ShowSubchart(chartType) { chart = c3.generate({ data: { x : 'x', //use first "column" as x axis values columns: [], //initialize empty. Data will be loaded in function setupChart(initValues) type: chartType, selection: { enabled: false, multiple: false, } }, legend: { position: 'inset' }, grid: { y: { lines: [{value:0}] //Draws a horizontal line at y=0 } }, bar: { width: { ratio: 0.95 // this makes bar width 95% of length between ticks } }, zoom: { enabled: true, }, subchart: { show: true //Shows a subchart that shows the region the primary chart is zoomed in to by overlay. }, axis: { x: { type: 'category', //only for type 'category' the bars will be rescaled in width on zoom tick: { multiline: false, fit: false, //to make more x labels appear on zoom centered: true, }, }, y: { tick: { format: d3.format("s"), }, //for some reason, there is an offset for our linegraph. This is prevented by the following lines //min: 0, //padding: { top: 0, bottom: 0 } } }, //Style data points in linegraph point: { r: 0.2, focus: { expand: { r: 4 } } }, tooltip: { format: { title: function (d) { var endValue = (parseFloat(greyvalue[d]) + binSize); endValue = endValue.toFixed(3); return 'Greyvalue: ' + greyvalue[d] + '...' + endValue; }, } } }); } function HideSubchart(chartType) { chart = c3.generate({ data: { x : 'x', //use first "column" as x axis values columns: [], //initialize empty. Data will be loaded in function setupChart(initValues) type: chartType, selection: { enabled: false, multiple: false, } }, legend: { position: 'inset' }, grid: { y: { lines: [{value:0}] //Draws a horizontal line at y=0 } }, bar: { width: { ratio: 0.95 // this makes bar width 95% of length between ticks } }, zoom: { enabled: true, }, subchart: { show: false //Shows a subchart that shows the region the primary chart is zoomed in to by overlay. }, axis: { x: { type: 'category', //only for type 'category' the bars will be rescaled in width on zoom tick: { multiline: false, fit: false, //to make more x labels appear on zoom centered: true, }, }, y: { tick: { format: d3.format("s"), }, //for some reason, there is an offset for our linegraph. This is prevented by the following lines //min: 0, //padding: { top: 0, bottom: 0 } } }, //Style data points in linegraph point: { r: 0.2, focus: { expand: { r: 4 } } }, tooltip: { format: { title: function (d) { var endValue = (parseFloat(greyvalue[d]) + binSize); endValue = endValue.toFixed(3); return 'Greyvalue: ' + greyvalue[d] + '...' + endValue; }, } } }); } \ No newline at end of file diff --git a/Modules/C3js/resource/Histogram_dark.css b/Modules/C3js/resource/Histogram_dark.css index a69610d1b1..9e09ba3384 100644 --- a/Modules/C3js/resource/Histogram_dark.css +++ b/Modules/C3js/resource/Histogram_dark.css @@ -1,36 +1,36 @@ body { - background-color: darkgrey !important; + background-color: #323231 !important; } /*-- Bar --*/ .c3-bar { fill-opacity: 1; } .c3-bar._expanded_ { fill: red !important; /*-- The !important tag prevents the color from being overwritten at rendering--*/ fill-opacity: 1; } /*-- Line --*/ .c3-line { stroke-width: 1px; - stroke: white; + stroke: #ADB1B6; /*stroke-dasharray: 5,5; /*to make it dashed*/ } /*-- Point --*/ .c3-circle._expanded_ { stroke-width: 1px; stroke: red !important; fill: red !important; /*-- The !important tag prevents the color from being overwritten at rendering--*/} -path.domain { stroke: white !important; } +path.domain { stroke: #ADB1B6 !important; } .c3 .c3-axis-x path, .c3 .c3-axis-x line { - stroke: white !important; + stroke: #ADB1B6 !important; } .c3 .c3-axis-y path, .c3 .c3-axis-y line { - stroke: white !important; + stroke: #ADB1B6 !important; } -.tick text { stroke: white !important; } -.c3-legend-item text { stroke: white !important; } \ No newline at end of file +.tick text { stroke: #ADB1B6 !important; } +.c3-legend-item text { stroke: #323231 !important; } \ No newline at end of file diff --git a/Modules/C3js/resource/QmitkC3jsWidget.html b/Modules/C3js/resource/QmitkC3jsWidget.html index 81e4f0c89a..40b2ce4942 100644 --- a/Modules/C3js/resource/QmitkC3jsWidget.html +++ b/Modules/C3js/resource/QmitkC3jsWidget.html @@ -1,16 +1,16 @@ - +
diff --git a/Modules/C3js/resource/empty.html b/Modules/C3js/resource/empty.html index 0051579c81..011d8e9980 100644 --- a/Modules/C3js/resource/empty.html +++ b/Modules/C3js/resource/empty.html @@ -1,11 +1,16 @@ - - - - - - - - - + + + + + + + + + + + + +
+ + + \ No newline at end of file diff --git a/Modules/C3js/resource/empty.js b/Modules/C3js/resource/empty.js new file mode 100644 index 0000000000..8f84f04ed6 --- /dev/null +++ b/Modules/C3js/resource/empty.js @@ -0,0 +1,11 @@ +function changeTheme(color) { + if (color == 'dark') { + link = document.getElementsByTagName("link")[0]; + link.href = "Histogram_dark.css"; + } + else + { + link = document.getElementsByTagName("link")[0]; + link.href = "Histogram.css"; + } +}; diff --git a/Modules/C3js/resource/empty_dark.html b/Modules/C3js/resource/empty_dark.html new file mode 100644 index 0000000000..4146f9e1f7 --- /dev/null +++ b/Modules/C3js/resource/empty_dark.html @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/Modules/C3js/src/QmitkC3jsWidget.cpp b/Modules/C3js/src/QmitkC3jsWidget.cpp index 1bee6b8939..939c06bc09 100644 --- a/Modules/C3js/src/QmitkC3jsWidget.cpp +++ b/Modules/C3js/src/QmitkC3jsWidget.cpp @@ -1,285 +1,285 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include "mitkImageTimeSelector.h" class QmitkC3jsWidget::Impl final { public: explicit Impl(QWidget* parent); ~Impl(); Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; QWebChannel* GetWebChannel(); void ClearJavaScriptChart(); void initializeJavaScriptChart(); void callJavaScriptFuntion(QString command); QmitkC3Data* GetC3Data() { return &m_c3Data; }; mitk::Image::Pointer GetImage() { return m_Image; }; const void SetImage(const mitk::Image::Pointer image) { m_Image = image; }; mitk::PlanarFigure::ConstPointer GetPlanarFigure() { return m_PlanarFigure; }; const void SetPlanarFigure(const mitk::PlanarFigure::ConstPointer planarFigure) { m_PlanarFigure = planarFigure; }; private: QWidget* m_Parent; QWebChannel* m_WebChannel; QWebEngineView* m_WebEngineView; QmitkC3Data m_c3Data; /** * \brief Reference image. * * Holds the image to calculate an intensity profile. */ mitk::Image::Pointer m_Image; /** * \brief Pathelement. * * Holds a not closed planar figure to calculate an intensity profile. */ mitk::PlanarFigure::ConstPointer m_PlanarFigure; }; QmitkC3jsWidget::Impl::Impl(QWidget* parent) : m_WebChannel(new QWebChannel(parent)), m_WebEngineView(new QWebEngineView(parent)), m_Parent(parent) { //disable context menu for QWebEngineView m_WebEngineView->setContextMenuPolicy(Qt::NoContextMenu); //Set the webengineview to an initial empty page. The actual chart will be loaded once the data is calculated. m_WebEngineView->setUrl(QUrl(QStringLiteral("qrc:///C3js/empty.html"))); m_WebEngineView->page()->setWebChannel(m_WebChannel); connect( m_WebEngineView, SIGNAL( loadFinished(bool) ), parent, SLOT( OnLoadFinished(bool) ) ); auto layout = new QGridLayout(parent); layout->setMargin(0); layout->addWidget(m_WebEngineView); parent->setLayout(layout); } QmitkC3jsWidget::Impl::~Impl() { } QWebChannel* QmitkC3jsWidget::Impl::GetWebChannel() { return m_WebChannel; } QmitkC3jsWidget::QmitkC3jsWidget(QWidget* parent) : QWidget(parent), m_Impl(new Impl(this)) { m_Statistics = mitk::ImageStatisticsCalculator::StatisticsContainer::New(); } void QmitkC3jsWidget::Impl::callJavaScriptFuntion(QString command) { m_WebEngineView->page()->runJavaScript(command); } void QmitkC3jsWidget::Impl::ClearJavaScriptChart() { - m_WebEngineView->setUrl(QUrl(QStringLiteral("qrc:///C3js/empty.html"))); + m_WebEngineView->setUrl(QUrl(QStringLiteral("qrc:///C3js/empty.html"))); } void QmitkC3jsWidget::Impl::initializeJavaScriptChart() { m_WebChannel->registerObject(QStringLiteral("initValues"), &m_c3Data); - m_WebEngineView->load(QUrl(QStringLiteral("qrc:///C3js/QmitkC3jsWidget.html"))); + m_WebEngineView->setUrl(QUrl(QStringLiteral("qrc:///C3js/QmitkC3jsWidget.html"))); } QmitkC3jsWidget::QmitkC3jsWidget(const QString& id, QObject* object, QWidget* parent) : QWidget(parent), m_Impl(new Impl(this)) { if (!id.isEmpty() && object != nullptr) m_Impl->GetWebChannel()->registerObject(id, object); m_Statistics = mitk::ImageStatisticsCalculator::StatisticsContainer::New(); } QmitkC3jsWidget::~QmitkC3jsWidget() { delete m_Impl; } void QmitkC3jsWidget::OnLoadFinished(bool isLoadSuccessfull) { emit PageSuccessfullyLoaded(); } void QmitkC3jsWidget::TransformView(QString transformTo) { QString command = QString("transformView('" + transformTo + "')"); m_Impl->callJavaScriptFuntion(command); } void QmitkC3jsWidget::SendCommand(QString command) { m_Impl->callJavaScriptFuntion(command); } void QmitkC3jsWidget::SetAppearance(bool useLineChart, bool showSubChart) { this->m_Impl->GetC3Data()->SetAppearance(useLineChart, showSubChart); } // method to expose data to JavaScript by using properties void QmitkC3jsWidget::ComputeHistogram(HistogramType* histogram, bool useLineChart, bool showSubChart) { this->m_Impl->GetC3Data()->SetHistogram(histogram); SetAppearance(useLineChart, showSubChart); HistogramConstIteratorType startIt = this->m_Impl->GetC3Data()->GetHistogram()->End(); HistogramConstIteratorType endIt = this->m_Impl->GetC3Data()->GetHistogram()->End(); HistogramConstIteratorType it = this->m_Impl->GetC3Data()->GetHistogram()->Begin(); //Clear old data befor loading new data. this->m_Impl->GetC3Data()->ClearData(); unsigned int i = 0; bool firstValue = false; // removes frequencies of 0, which are outside the first and last bin for (; it != this->m_Impl->GetC3Data()->GetHistogram()->End(); ++it) { if (it.GetFrequency() > 0.0) { endIt = it; if (!firstValue) { firstValue = true; startIt = it; } } } ++endIt; // generating Lists of measurement and frequencies for (it = startIt; it != endIt; ++it, ++i) { QVariant frequency = QVariant::fromValue(it.GetFrequency()); QVariant measurement = it.GetMeasurementVector()[0]; this->m_Impl->GetC3Data()->GetYDataPointer()->insert(i, frequency); this->m_Impl->GetC3Data()->GetXDataPointer()->insert(i, measurement); } m_Impl->initializeJavaScriptChart(); } void QmitkC3jsWidget::ComputeIntensityProfile(unsigned int timeStep, bool computeStatistics) { this->ClearHistogram(); //m_Impl->GetC3Data()->ClearData(); //m_ParametricPath->Initialize(); if (m_Impl->GetPlanarFigure().IsNull()) { mitkThrow() << "PlanarFigure not set!"; } if (m_Impl->GetImage().IsNull()) { mitkThrow() << "Image not set!"; } mitk::Image::Pointer image; if (m_Impl->GetImage()->GetDimension() == 4) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(m_Impl->GetImage()); timeSelector->SetTimeNr(timeStep); timeSelector->Update(); image = timeSelector->GetOutput(); } else { image = m_Impl->GetImage(); } mitk::IntensityProfile::Pointer intensityProfile = mitk::ComputeIntensityProfile( image, const_cast(m_Impl->GetPlanarFigure().GetPointer())); //m_Frequency.clear(); //m_Measurement.clear(); int i = -1; mitk::IntensityProfile::ConstIterator end = intensityProfile->End(); for (mitk::IntensityProfile::ConstIterator it = intensityProfile->Begin(); it != end; ++it) { m_Impl->GetC3Data()->GetYDataPointer()->push_back(it.GetMeasurementVector()[0]); //m_Impl->GetC3Data()->GetFrequencyPointer()->push_back(50000); m_Impl->GetC3Data()->GetXDataPointer()->push_back(++i); } if (computeStatistics) { mitk::ComputeIntensityProfileStatistics(intensityProfile, m_Statistics); } m_Impl->initializeJavaScriptChart(); } void QmitkC3jsWidget::ClearHistogram() { m_Impl->GetC3Data()->ClearData(); m_Impl->ClearJavaScriptChart(); } mitk::Image::Pointer QmitkC3jsWidget::GetImage() const { return m_Impl->GetImage(); } void QmitkC3jsWidget::SetImage(const mitk::Image::Pointer image) { m_Impl->SetImage(image); } mitk::PlanarFigure::ConstPointer QmitkC3jsWidget::GetPlanarFigure() const { return m_Impl->GetPlanarFigure(); } void QmitkC3jsWidget::SetPlanarFigure(const mitk::PlanarFigure::ConstPointer planarFigure) { m_Impl->SetPlanarFigure(planarFigure); } \ No newline at end of file diff --git a/Plugins/org.blueberry.ui.qt/files.cmake b/Plugins/org.blueberry.ui.qt/files.cmake index 3dfa892c60..03c9203eb5 100644 --- a/Plugins/org.blueberry.ui.qt/files.cmake +++ b/Plugins/org.blueberry.ui.qt/files.cmake @@ -1,513 +1,513 @@ set(SRC_CPP_FILES berryAbstractSourceProvider.cpp berryAbstractUICTKPlugin.cpp berryConstants.cpp berryDisplay.cpp berryEditorPart.cpp berryExtensionFactory.cpp berryFileEditorInput.cpp berryGeometry.cpp berryIActionBars.h berryIContextService.cpp berryIContributionRoot.h berryIDropTargetListener.cpp berryIEditorDescriptor.cpp berryIEditorInput.cpp berryIEditorMatchingStrategy.cpp berryIEditorPart.cpp berryIEditorReference.cpp berryIEditorRegistry.cpp berryIEditorSite.cpp berryIElementFactory.cpp berryIFileEditorMapping.cpp berryIFolderLayout.cpp berryIMemento.cpp berryINullSelectionListener.cpp berryIPageLayout.cpp berryIPartListener.cpp berryIPageService.cpp berryIPartService.cpp berryIPathEditorInput.cpp berryIPersistable.cpp berryIPersistableElement.h berryIPerspectiveDescriptor.cpp berryIPerspectiveFactory.cpp berryIPerspectiveListener.cpp berryIPerspectiveRegistry.cpp berryIPlaceholderFolderLayout.cpp berryIPluginContribution.h berryIPostSelectionProvider.cpp berryIPreferencePage.cpp berryIPropertyChangeListener.cpp berryIQtPreferencePage.cpp berryIQtStyleManager.cpp berryIReusableEditor.cpp berryISaveablePart.cpp berryISaveablesLifecycleListener.cpp berryISaveablesSource.cpp berryISelection.cpp berryISelectionChangedListener.cpp berryISelectionListener.cpp berryISelectionProvider.cpp berryISelectionService.cpp berryIShellListener.cpp berryIShellProvider.cpp berryIShowInSource.h berryIShowInTarget.h berryISizeProvider.cpp berryISourceProvider.cpp berryISourceProviderListener.cpp berryISources.cpp berryIStickyViewDescriptor.cpp berryIStructuredSelection.cpp berryIViewCategory.cpp berryIViewDescriptor.cpp berryIViewLayout.cpp berryIViewPart.cpp berryIViewReference.cpp berryIViewRegistry.cpp berryIViewSite.cpp berryIWorkbenchCommandConstants.cpp berryIWindowListener.cpp berryIWorkbench.cpp berryIWorkbenchListener.cpp berryIWorkbenchPage.cpp berryIWorkbenchPart.cpp berryIWorkbenchPartConstants.cpp berryIWorkbenchPartDescriptor.cpp berryIWorkbenchPartReference.cpp berryIWorkbenchPartSite.cpp berryIWorkbenchSite.cpp berryIWorkbenchWindow.cpp berryMenuUtil.cpp berryPlatformUI.cpp berryPropertyChangeEvent.cpp berryQModelIndexObject.cpp berryQtEditorPart.cpp berryQtItemSelection.cpp berryQtIntroPart.cpp berryQtPreferences.cpp berryQtSelectionProvider.cpp berryQtViewPart.cpp berrySameShellProvider.cpp berrySaveable.cpp berrySaveablesLifecycleEvent.cpp berrySelectionChangedEvent.cpp berryShell.cpp berryShellEvent.cpp berryShowInContext.cpp berryUIException.cpp berryViewPart.cpp berryWindow.cpp berryWorkbenchActionConstants.cpp berryWorkbenchPart.cpp + berryWorkbenchPlugin.cpp berryWorkbenchPreferenceConstants.cpp berryXMLMemento.cpp #actions actions/berryAbstractContributionFactory.cpp actions/berryCommandContributionItem.cpp actions/berryCommandContributionItemParameter.cpp actions/berryContributionItem.cpp actions/berryContributionItemFactory.cpp actions/berryContributionManager.cpp actions/berryGroupMarker.cpp actions/berryIContributionItem.h actions/berryIContributionManager.h actions/berryIContributionManagerOverrides.cpp actions/berryIMenuManager.h #actions/berryMenuBarManager.cpp actions/berryMenuManager.cpp actions/berryQActionContributionItem.cpp actions/berryQActionProperties.cpp actions/berrySeparator.cpp actions/berrySubContributionItem.cpp #application application/berryActionBarAdvisor.cpp application/berryIActionBarConfigurer.cpp application/berryIWorkbenchConfigurer.cpp application/berryIWorkbenchWindowConfigurer.cpp application/berryWorkbenchAdvisor.cpp application/berryWorkbenchWindowAdvisor.cpp #commands commands/berryICommandImageService.cpp commands/berryICommandService.cpp commands/berryIElementReference.h commands/berryIElementUpdater.h commands/berryIMenuService.h commands/berryUIElement.cpp #guitk guitk/berryGuiTkControlEvent.cpp guitk/berryGuiTkEvent.cpp guitk/berryGuiTkIControlListener.cpp guitk/berryGuiTkISelectionListener.cpp guitk/berryGuiTkSelectionEvent.cpp #handlers handlers/berryHandlerUtil.cpp handlers/berryIHandlerActivation.cpp handlers/berryIHandlerService.cpp handlers/berryRadioState.cpp handlers/berryRegistryToggleState.cpp handlers/berryToggleState.cpp #intro intro/berryIIntroManager.cpp intro/berryIIntroPart.cpp intro/berryIIntroSite.cpp intro/berryIntroPart.cpp #models model/berryPerspectiveListModel.cpp model/berryViewTreeModel.cpp #tweaklets tweaklets/berryGuiWidgetsTweaklet.cpp tweaklets/berryWorkbenchPageTweaklet.cpp tweaklets/berryWorkbenchTweaklet.cpp #presentations presentations/berryIPresentablePart.cpp presentations/berryIPresentationFactory.cpp presentations/berryIPresentationSerializer.cpp presentations/berryIStackPresentationSite.cpp presentations/berryStackDropResult.cpp presentations/berryStackPresentation.cpp #services services/berryIDisposable.cpp services/berryIEvaluationReference.h services/berryIEvaluationService.cpp services/berryINestable.cpp services/berryIServiceFactory.cpp services/berryIServiceLocator.cpp services/berryIServiceScopes.cpp services/berryIServiceWithSources.cpp services/berryISourceProviderService.cpp #testing testing/berryTestableObject.cpp #util util/berryISafeRunnableRunner.cpp util/berrySafeRunnable.cpp # application application/berryQtWorkbenchAdvisor.cpp ) set(INTERNAL_CPP_FILES defaultpresentation/berryEmptyTabFolder.cpp defaultpresentation/berryEmptyTabItem.cpp defaultpresentation/berryNativeTabFolder.cpp defaultpresentation/berryNativeTabItem.cpp defaultpresentation/berryQCTabBar.cpp defaultpresentation/berryQtWorkbenchPresentationFactory.cpp dialogs/berryPerspectivesPreferencePage.cpp dialogs/berrySavePerspectiveDialog.cpp handlers/berryCloseAllPerspectivesHandler.cpp handlers/berryClosePerspectiveHandler.cpp handlers/berryDynamicHelpHandler.cpp handlers/berryHelpContentsHandler.cpp handlers/berryIntroHandler.cpp handlers/berryNewEditorHandler.cpp handlers/berryOpenInNewWindowHandler.cpp handlers/berryQuitHandler.cpp handlers/berryResetPerspectiveHandler.cpp handlers/berrySavePerspectiveHandler.cpp handlers/berryShowPerspectiveHandler.cpp handlers/berryShowViewHandler.cpp util/berryAbstractTabFolder.cpp util/berryAbstractTabItem.cpp util/berryIPresentablePartList.cpp util/berryLeftToRightTabOrder.cpp util/berryPartInfo.cpp util/berryPresentablePartFolder.cpp util/berryReplaceDragHandler.cpp util/berryTabbedStackPresentation.cpp util/berryTabDragHandler.cpp util/berryTabFolderEvent.cpp util/berryTabOrder.cpp #intro intro/berryEditorIntroAdapterPart.cpp intro/berryIIntroDescriptor.cpp intro/berryIIntroRegistry.cpp intro/berryIntroConstants.cpp intro/berryIntroDescriptor.cpp intro/berryIntroPartAdapterSite.cpp intro/berryIntroRegistry.cpp intro/berryViewIntroAdapterPart.cpp intro/berryWorkbenchIntroManager.cpp berryAbstractGroupMarker.cpp berryAbstractMenuAdditionCacheEntry.cpp berryAbstractPartSelectionTracker.cpp berryAbstractSelectionService.cpp berryActivePartExpression.cpp berryAlwaysEnabledExpression.cpp berryAndExpression.cpp berryBundleUtility.cpp berryChangeToPerspectiveMenu.cpp berryCommandParameter.cpp berryCommandPersistence.cpp berryCommandService.cpp berryCommandServiceFactory.cpp berryCommandStateProxy.cpp berryCompositeExpression.cpp berryContainerPlaceholder.cpp berryContributionRoot.cpp berryDetachedPlaceHolder.cpp berryDefaultSaveable.cpp berryDefaultStackPresentationSite.cpp berryDetachedWindow.cpp berryDirtyPerspectiveMarker.cpp berryDragUtil.cpp berryEditorAreaHelper.cpp berryEditorDescriptor.cpp berryEditorHistory.cpp berryEditorHistoryItem.cpp berryEditorManager.cpp berryEditorReference.cpp berryEditorRegistry.cpp berryEditorRegistryReader.cpp berryEditorSashContainer.cpp berryEditorSite.cpp berryElementReference.cpp berryErrorViewPart.cpp berryEvaluationAuthority.cpp berryEvaluationReference.cpp berryEvaluationResultCache.cpp berryEvaluationService.cpp berryExpressionAuthority.cpp berryFileEditorMapping.cpp berryFolderLayout.cpp berryHandlerActivation.cpp berryHandlerAuthority.cpp berryHandlerPersistence.cpp berryHandlerProxy.cpp berryHandlerService.cpp berryHandlerServiceFactory.cpp berryIDragOverListener.cpp berryIDropTarget.cpp berryIEvaluationResultCache.cpp berryILayoutContainer.cpp berryInternalMenuService.h berryIServiceLocatorCreator.cpp berryIStickyViewManager.cpp berryIWorkbenchLocationService.cpp berryKeywordRegistry.cpp berryLayoutHelper.cpp berryLayoutPart.cpp berryLayoutPartSash.cpp berryLayoutTree.cpp berryLayoutTreeNode.cpp berryMenuServiceFactory.cpp berryNestableHandlerService.cpp berryNullEditorInput.cpp berryOpenPerspectivePropertyTester.cpp berryPageLayout.cpp berryPagePartSelectionTracker.cpp berryPageSelectionService.cpp berryParameterValueConverterProxy.cpp berryPartList.cpp berryPartPane.cpp berryPartPlaceholder.cpp berryPartSashContainer.cpp berryPartService.cpp berryPartSite.cpp berryPartStack.cpp berryPartTester.cpp berryPersistentState.cpp berryPerspective.cpp berryPerspectiveDescriptor.cpp berryPerspectiveExtensionReader.cpp berryPerspectiveHelper.cpp berryPerspectiveParameterValues.cpp berryPerspectiveRegistry.cpp berryPerspectiveRegistryReader.cpp berryPlaceholderFolderLayout.cpp berryPolicy.cpp berryPreferenceConstants.cpp berryPreferencePageParameterValues.cpp berryPresentablePart.cpp berryPresentationFactoryUtil.cpp berryPresentationSerializer.cpp berryQtControlWidget.cpp berryQtDnDControlWidget.cpp berryQtDisplay.cpp berryQtGlobalEventFilter.cpp berryQtMainWindowControl.cpp berryQtOpenPerspectiveAction.cpp berryQtPerspectiveSwitcher.cpp berryQtSash.cpp berryQtShell.cpp berryQtShowPerspectiveDialog.cpp berryQtShowViewAction.cpp berryQtShowViewDialog.cpp berryQtStyleManager.cpp berryQtStylePreferencePage.cpp berryQtTracker.cpp berryQtWidgetController.cpp berryQtWidgetsTweaklet.cpp berryQtWidgetsTweakletImpl.cpp berryQtWorkbenchPageTweaklet.cpp berryQtWorkbenchTweaklet.cpp berryRegistryPersistence.cpp berryRegistryReader.cpp berryReopenEditorMenu.cpp berrySaveablesList.cpp berryShowViewMenu.cpp berryServiceLocator.cpp berryServiceLocatorCreator.cpp berryShellPool.cpp berrySlaveCommandService.cpp berrySlaveHandlerService.cpp berrySlaveMenuService.cpp berrySourceProviderService.cpp berrySourcePriorityNameMapping.cpp berryStatusUtil.cpp berryStickyViewDescriptor.cpp berryStickyViewManager.cpp berrySwitchToWindowMenu.cpp berryTweaklets.cpp berryUIExtensionTracker.cpp berryUtil.cpp berryViewDescriptor.cpp berryViewFactory.cpp berryViewLayout.cpp berryViewReference.cpp berryViewRegistry.cpp berryViewRegistryReader.cpp berryViewSashContainer.cpp berryViewSite.cpp berryWorkbenchPage.cpp berryWindowManager.cpp berryWindowPartSelectionTracker.cpp berryWindowSelectionService.cpp berryWorkbench.cpp berryWorkbenchConfigurer.cpp berryWorkbenchConstants.cpp berryWorkbenchLocationService.cpp berryWorkbenchMenuService.cpp berryWorkbenchPagePartList.cpp berryWorkbenchPartReference.cpp - berryWorkbenchPlugin.cpp berryWorkbenchRegistryConstants.cpp berryWorkbenchServiceRegistry.cpp berryWorkbenchSourceProvider.cpp berryWorkbenchTestable.cpp berryWorkbenchWindow.cpp berryWorkbenchWindowConfigurer.cpp berryWorkbenchWindowExpression.cpp berryWWinActionBars.cpp berryWWinPartService.cpp ) set(MOC_H_FILES src/berryAbstractUICTKPlugin.h src/berryEditorPart.h src/berryExtensionFactory.h src/berryQtSelectionProvider.h src/berryViewPart.h src/berryWorkbenchPart.h + src/berryWorkbenchPlugin.h src/actions/berryCommandContributionItem.h src/actions/berryMenuManager.h src/intro/berryIntroPart.h src/model/berryPerspectiveListModel.h src/model/berryViewTreeModel.h src/internal/berryChangeToPerspectiveMenu.h src/internal/berryCommandServiceFactory.h src/internal/berryHandlerServiceFactory.h src/internal/berryMenuServiceFactory.h src/internal/berryOpenPerspectivePropertyTester.h src/internal/berryPerspectiveParameterValues.h src/internal/berryPreferencePageParameterValues.h src/internal/berryQtDisplay.h src/internal/berryQtGlobalEventFilter.h src/internal/berryQtMainWindowControl.h src/internal/berryQtOpenPerspectiveAction.h src/internal/berryQtPerspectiveSwitcher.h src/internal/berryQtSash.h src/internal/berryQtShowPerspectiveDialog.h src/internal/berryQtShowViewAction.h src/internal/berryQtShowViewDialog.h src/internal/berryQtStyleManager.h src/internal/berryQtStylePreferencePage.h src/internal/berryQtTracker.h src/internal/berryQtWidgetsTweaklet.h src/internal/berryQtWidgetsTweakletImpl.h src/internal/berryQtWorkbenchTweaklet.h src/internal/berryQtWorkbenchPageTweaklet.h src/internal/berryReopenEditorMenu.h src/internal/berryShowViewMenu.h src/internal/berrySwitchToWindowMenu.h - src/internal/berryWorkbenchPlugin.h src/internal/berryWorkbenchSourceProvider.h src/internal/defaultpresentation/berryNativeTabFolder.h src/internal/defaultpresentation/berryNativeTabItem.h src/internal/defaultpresentation/berryQCTabBar.h src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h src/internal/dialogs/berryPerspectivesPreferencePage.h src/internal/dialogs/berrySavePerspectiveDialog.h src/internal/handlers/berryCloseAllPerspectivesHandler.h src/internal/handlers/berryClosePerspectiveHandler.h src/internal/handlers/berryDynamicHelpHandler.h src/internal/handlers/berryHelpContentsHandler.h src/internal/handlers/berryIntroHandler.h src/internal/handlers/berryNewEditorHandler.h src/internal/handlers/berryOpenInNewWindowHandler.h src/internal/handlers/berryQuitHandler.h src/internal/handlers/berryResetPerspectiveHandler.h src/internal/handlers/berrySavePerspectiveHandler.h src/internal/handlers/berryShowPerspectiveHandler.h src/internal/handlers/berryShowViewHandler.h src/internal/intro/berryEditorIntroAdapterPart.h ) set(UI_FILES src/internal/berryQtShowPerspectiveDialog.ui src/internal/berryQtShowViewDialog.ui src/internal/berryQtStylePreferencePage.ui src/internal/berryQtStatusPart.ui src/internal/dialogs/berryPerspectivesPreferencePage.ui src/internal/dialogs/berrySavePerspectiveDialog.ui ) set(QRC_FILES resources/org_blueberry_ui_qt.qrc ) set(CACHED_RESOURCE_FILES plugin.xml ) 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.ui.qt/src/actions/berryCommandContributionItem.cpp b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp index a6386da4f6..d51b5aec7a 100644 --- a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,730 +1,730 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryCommandContributionItem.h" #include "berryIMenuService.h" #include "berryICommandService.h" #include "berryICommandImageService.h" #include "berryIContributionManager.h" #include "berryIElementReference.h" #include "berryIElementUpdater.h" #include "berryUIElement.h" #include #include #include #include #include #include #include #include #include "../berryDisplay.h" #include "../berryAsyncRunnable.h" #include "../handlers/berryIHandlerService.h" #include "../services/berryIServiceLocator.h" -#include "../internal/berryWorkbenchPlugin.h" +#include "../berryWorkbenchPlugin.h" #include #include #include #include #include namespace berry { ContributionItem::Modes CommandContributionItem::modes = ContributionItem::MODE_FORCE_TEXT; //class CommandUIElementListener : public IUIElementListener //{ //private: // CommandContributionItem* item; // public: // CommandUIElementListener(CommandContributionItem* item); // void UIElementDisposed(UIElement* item); //void UIElementSelected(SmartPointer item); //}; CommandContributionItem::CommandContributionItem( const SmartPointer& contributionParameters) : ContributionItem(contributionParameters->id) , action(nullptr) , checkedState(false) { this->icon = contributionParameters->icon; this->label = contributionParameters->label; this->mnemonic = contributionParameters->mnemonic; this->shortcut = contributionParameters->shortcut; this->tooltip = contributionParameters->tooltip; this->style = contributionParameters->style; this->helpContextId = contributionParameters->helpContextId; this->visibleEnabled = contributionParameters->visibleEnabled; this->mode = contributionParameters->mode; menuService = contributionParameters->serviceLocator->GetService(); commandService = contributionParameters->serviceLocator->GetService(); handlerService = contributionParameters->serviceLocator->GetService(); // bindingService = (IBindingService) contributionParameters.serviceLocator // .getService(IBindingService.class); this->CreateCommand(contributionParameters->commandId, contributionParameters->parameters); if (command) { try { class CommandUIElement : public UIElement { private: CommandContributionItem* item; public: CommandUIElement(CommandContributionItem* item, IServiceLocator* serviceLocator) : UIElement(serviceLocator), item(item) {} void SetText(const QString& text) override { item->SetText(text); } void SetToolTip(const QString& text) override { item->SetToolTip(text); } void SetIcon(const QIcon& icon) override { item->SetIcon(icon); } void SetChecked(bool checked) override { item->SetChecked(checked); } void SetDropDownId(const QString& id) override { item->dropDownMenuOverride = id; } }; UIElement::Pointer callback(new CommandUIElement(this, contributionParameters->serviceLocator)); elementRef = commandService->RegisterElementForCommand(command, callback); command->GetCommand()->AddCommandListener(this->GetCommandListener()); this->SetImages(contributionParameters->serviceLocator, contributionParameters->iconStyle); if (contributionParameters->helpContextId.isEmpty()) { try { this->helpContextId = commandService->GetHelpContextId( contributionParameters->commandId); } catch (const NotDefinedException& /*e*/) { // it's OK to not have a helpContextId } } // IWorkbenchLocationService::Pointer wls = contributionParameters.serviceLocator // ->GetService(IWorkbenchLocationService::GetManifestName()).Cast(); // const IWorkbench* workbench = wls->GetWorkbench();; // if (workbench != 0 && !helpContextId.empty()) { // this->workbenchHelpSystem = workbench->GetHelpSystem(); // } } catch (const NotDefinedException& /*e*/) { WorkbenchPlugin::Log(QString("Unable to register menu item \"") + this->GetId() + "\", command \"" + contributionParameters->commandId + "\" not defined"); } } } void CommandContributionItem::Fill(QMenu* parent, QAction* before) { if (!command || action || parent == nullptr) { return; } // Menus don't support the pulldown style Style tmpStyle = style; if (tmpStyle == STYLE_PULLDOWN) tmpStyle = STYLE_PUSH; QAction* item = nullptr; if (before) { item = new QAction(icon, label, parent); parent->insertAction(before, item); } else { item = parent->addAction(icon, label); } // Remove this when key binding support is fully implemented if (!shortcut.isEmpty()) { item->setShortcut(shortcut); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(item, helpContextId); // } connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection())); connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); } void CommandContributionItem::Fill(QToolBar *parent, QAction *before) { if (!command || action || parent == nullptr) { return; } QAction* item = nullptr; if (before) { item = parent->addAction(icon, label); } else { item = new QAction(icon, label, parent); parent->insertAction(before, item); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection())); connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); } void CommandContributionItem::Update() { this->Update(QString::null); } void CommandContributionItem::Update(const QString& /*id*/) { if (action) { QWidget* parent = action->parentWidget(); if(qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateToolItem(); } } } void CommandContributionItem::UpdateMenuItem() { QString text = label; if (text.isEmpty()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } text = UpdateMnemonic(text); // String keyBindingText = null; // if (command != null) // { // TriggerSequence binding = bindingService // .getBestActiveBindingFor(command); // if (binding != null) // { // keyBindingText = binding.format(); // } // } // if (text != null) // { // if (keyBindingText == null) // { // item.setText(text); // } // else // { // item.setText(text + '\t' + keyBindingText); // } // } if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } void CommandContributionItem::UpdateToolItem() { QString text = label; QString tooltip = label; if (text.isNull()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); tooltip = command->GetCommand()->GetDescription(); if (tooltip.trimmed().isEmpty()) { tooltip = text; } } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } if ((icon.isNull() || (mode & MODE_FORCE_TEXT) == MODE_FORCE_TEXT) && !text.isNull()) { action->setText(text); } QString toolTipText = GetToolTipText(tooltip); action->setToolTip(toolTipText); if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } CommandContributionItem::~CommandContributionItem() { if (elementRef) { commandService->UnregisterElement(elementRef); } if (commandListener) { command->GetCommand()->RemoveCommandListener(commandListener.data()); } } bool CommandContributionItem::IsEnabled() const { if (command) { command->GetCommand()->SetEnabled(menuService->GetCurrentState()); return command->GetCommand()->IsEnabled(); } return false; } bool CommandContributionItem::IsVisible() const { if (visibleEnabled) { return ContributionItem::IsVisible() && this->IsEnabled(); } return ContributionItem::IsVisible(); } void CommandContributionItem::SetImages(IServiceLocator* locator, const QString& iconStyle) { if (icon.isNull()) { ICommandImageService* service = locator->GetService(); if (service) { icon = service->GetImage(command->GetId(), iconStyle); } } } ICommandListener* CommandContributionItem::GetCommandListener() { if (!commandListener) { class MyCommandListener : public ICommandListener { private: CommandContributionItem* item; public: MyCommandListener(CommandContributionItem* item) : item(item) {} void CommandChanged(const SmartPointer& commandEvent) override { if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged() || commandEvent->IsDefinedChanged()) { item->UpdateCommandProperties(commandEvent); } } }; commandListener.reset(new MyCommandListener(this)); } return commandListener.data(); } void CommandContributionItem::UpdateCommandProperties(const SmartPointer< const CommandEvent> commandEvent) { if (commandEvent->IsHandledChanged()) { dropDownMenuOverride = ""; } if (!action) { return; } Display* display = Display::GetDefault(); typedef AsyncRunnable, CommandContributionItem > UpdateRunnable; Poco::Runnable* update = new UpdateRunnable(this, &CommandContributionItem::UpdateCommandPropertiesInUI, commandEvent); if (display->InDisplayThread()) { update->run(); } else { display->AsyncExec(update); } } void CommandContributionItem::UpdateCommandPropertiesInUI(const SmartPointer< const CommandEvent>& commandEvent) { if (commandEvent->GetCommand()->IsDefined()) { this->Update(); } if (commandEvent->IsEnabledChanged() || commandEvent->IsHandledChanged()) { if (visibleEnabled) { IContributionManager* parent = this->GetParent(); if (parent) { parent->Update(true); } } } } void CommandContributionItem::HandleActionDestroyed() { this->action = nullptr; } bool CommandContributionItem::ShouldRestoreAppearance(const SmartPointer& handler) { // if no handler or handler doesn't implement IElementUpdater, // restore the contributed elements if (handler.IsNull()) return true; if (!(handler.Cast())) return true; // special case, if its HandlerProxy, then check the actual handler // if (handler instanceof HandlerProxy) { // HandlerProxy handlerProxy = (HandlerProxy) handler; // IHandler actualHandler = handlerProxy.getHandler(); // return shouldRestoreAppearance(actualHandler); // } return false; } SmartPointer CommandContributionItem::GetCommand() const { return command; } void CommandContributionItem::CreateCommand(const QString &commandId, const QHash ¶meters) { if (commandId.isEmpty()) { // StatusManager.getManager().handle(StatusUtil.newStatus(IStatus.ERROR, // "Unable to create menu item \"" + getId() // + "\", no command id", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", no command id"; return; } Command::Pointer cmd = commandService->GetCommand(commandId); if (!cmd->IsDefined()) { // StatusManager.getManager().handle(StatusUtil.newStatus( // IStatus.ERROR, "Unable to create menu item \"" + getId() // + "\", command \"" + commandId + "\" not defined", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", command \"" << commandId.toStdString() << "\" not defined"; return; } command = ParameterizedCommand::GenerateCommand(cmd, parameters); } QString CommandContributionItem::GetToolTipText(const QString& text) const { QString tooltipText = tooltip; if (tooltip.isNull()) { if (!text.isNull()) { tooltipText = text; } else { tooltipText = ""; } } // TriggerSequence activeBinding = bindingService // .getBestActiveBindingFor(command); // if (activeBinding != null && !activeBinding.isEmpty()) // { // String acceleratorText = activeBinding.format(); // if (acceleratorText != null // && acceleratorText.length() != 0) // { // tooltipText = NLS.bind(CommandMessages.Tooltip_Accelerator, // tooltipText, acceleratorText); // } // } return tooltipText; } QString CommandContributionItem::UpdateMnemonic(const QString &s) { if (mnemonic.isNull() || s.isEmpty()) { return s; } int idx = s.indexOf(mnemonic); if (idx == -1) { return s; } return s.left(idx) + '&' + s.mid(idx); } //SmartPointer CommandContributionItem::GetItemListener() //{ // if (!itemListener) // { // itemListener = new CommandUIElementListener(this); // } // return itemListener; //} void CommandContributionItem::HandleWidgetSelection() { // // Special check for ToolBar dropdowns... // if (this->OpenDropDownMenu(event)) // //return; if ((style & STYLE_CHECK) != 0) { checkedState = action->isChecked(); } try { handlerService->ExecuteCommand(command, UIElement::Pointer(nullptr)); } catch (const ExecutionException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotDefinedException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotEnabledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotHandledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } } //TODO Tool item drop down menu contributions //bool CommandContributionItem::OpenDropDownMenu(SmartPointer event) //{ //Widget item = event.widget; //if (item != null) //{ // int style = item.getStyle(); // if ((style & SWT.DROP_DOWN) != 0) // { // if (event.detail == 4) // { // on drop-down button // ToolItem ti = (ToolItem) item; // // final MenuManager menuManager = new MenuManager(); // Menu menu = menuManager.createContextMenu(ti.getParent()); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(menu, helpContextId); // } // menuManager.addMenuListener(new IMenuListener() // { // public void menuAboutToShow(IMenuManager manager) // { // String id = getId(); // if (dropDownMenuOverride != null) // { // id = dropDownMenuOverride; // } // menuService.populateContributionManager( // menuManager, "menu:" + id); //$NON-NLS-1$ // } // }); // // // position the menu below the drop down item // Point point = ti.getParent().toDisplay( // new Point(event.x, event.y)); // menu.setLocation(point.x, point.y); // waiting for SWT // // 0.42 // menu.setVisible(true); // return true; // we don't fire the action // } // } //} // //return false; //} void CommandContributionItem::SetIcon(const QIcon &icon) { this->icon = icon; this->UpdateIcons(); } void CommandContributionItem::UpdateIcons() { action->setIcon(icon); } void CommandContributionItem::SetText(const QString &text) { label = text; this->Update(); } void CommandContributionItem::SetChecked(bool checked) { if (checkedState == checked) { return; } checkedState = checked; action->setChecked(checkedState); } void CommandContributionItem::SetToolTip(const QString &text) { tooltip = text; action->setToolTip(text); } } diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp b/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp index 52867618a9..06ac0593b5 100755 --- a/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp +++ b/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp @@ -1,63 +1,63 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryQtWorkbenchAdvisor.h" #include "internal/berryQtGlobalEventFilter.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include "berryQtPreferences.h" #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, ""); QString fontSize = prefs->Get(QtPreferences::QT_FONT_SIZE, ""); 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 c5989e81d9..cc227f8fea 100644 --- a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp @@ -1,144 +1,144 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchWindowAdvisor.h" #include #include #include #include #include #include #include #include "internal/berryWorkbenchWindowConfigurer.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" 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(); 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 44f2d81e38..13d4c37888 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp @@ -1,281 +1,281 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryAbstractUICTKPlugin.h" #include "internal/berryBundleUtility.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include "berryPlatformUI.h" #include "berryIPreferencesService.h" #include "berryIPreferences.h" #include #include 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 { // 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; } SmartPointer AbstractUICTKPlugin::GetPreferences() const { IPreferencesService* prefService = this->GetPreferencesService(); if (prefService == nullptr) return IPreferences::Pointer(nullptr); return prefService->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); 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/berryWorkbenchPart.cpp b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp index d1375381a6..669b4231d0 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp @@ -1,290 +1,290 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchPart.h" #include "berryIWorkbenchPartConstants.h" #include #include #include -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include #include namespace berry { class PropChangedRunnable : public SafeRunnable { public: berryObjectMacro(PropChangedRunnable) IPropertyChangeListener::Events::EventType::AbstractDelegate* delegate; PropChangedRunnable(PropertyChangeEvent::Pointer event) : event(event) {} void Run() override { delegate->Execute(event); } private: PropertyChangeEvent::Pointer event; }; WorkbenchPart::~WorkbenchPart() { } WorkbenchPart::WorkbenchPart() :m_Title(""), m_ToolTip(""), m_PartName(""), m_ContentDescription("") { } void WorkbenchPart::InternalSetContentDescription( const QString& description) { //assert(description != 0) //Do not send changes if they are the same if (this->m_ContentDescription == description) { return; } this->m_ContentDescription = description; this->FirePropertyChange(IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION); } void WorkbenchPart::InternalSetPartName(const QString& partName) { //partName = Util.safeString(partName); //assert(partName != 0); //Do not send changes if they are the same if (this->m_PartName == partName) { return; } this->m_PartName = partName; this->FirePropertyChange(IWorkbenchPartConstants::PROP_PART_NAME); } // IConfigurationElement* GetConfigurationElement() // { // return m_ConfigElement; // } // protected Image getDefaultImage() { // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); // } void WorkbenchPart::SetSite(IWorkbenchPartSite::Pointer site) { this->CheckSite(site); this->m_PartSite = site; } void WorkbenchPart::CheckSite(IWorkbenchPartSite::Pointer /*site*/) { // do nothing } void WorkbenchPart::SetTitleImage(const QIcon& titleImage) { //assert(titleImage == 0 || !titleImage.isDisposed()); //Do not send changes if they are the same if (this->m_TitleImage.cacheKey() == titleImage.cacheKey()) { return; } this->m_TitleImage = titleImage; this->FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void WorkbenchPart::SetTitleToolTip(const QString& toolTip) { //toolTip = Util.safeString(toolTip); //Do not send changes if they are the same if (this->m_ToolTip == toolTip) { return; } this->m_ToolTip = toolTip; this->FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void WorkbenchPart::SetPartName(const QString& partName) { InternalSetPartName(partName); //setDefaultTitle(); } void WorkbenchPart::SetContentDescription(const QString& description) { InternalSetContentDescription(description); //setDefaultTitle(); } void WorkbenchPart::FirePropertyChanged(const QString& key, const QString& oldValue, const QString& newValue) { ObjectString::Pointer objOldVal(new ObjectString(oldValue)); ObjectString::Pointer objNewVal(new ObjectString(newValue)); Object::Pointer source(this); PropertyChangeEvent::Pointer event( new PropertyChangeEvent(source, key, objOldVal, objNewVal)); typedef IPropertyChangeListener::Events::EventType::ListenerList ListenerList; PropChangedRunnable::Pointer runnable(new PropChangedRunnable(event)); const ListenerList& listeners = partChangeEvents.propertyChange.GetListeners(); for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { runnable->delegate = *iter; SafeRunner::Run(runnable); } } void WorkbenchPart::FirePropertyChange(int propertyId) { ObjectInt::Pointer val(new ObjectInt(propertyId)); Object::Pointer source(this); PropertyChangeEvent::Pointer event( new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); typedef IPropertyChangeListener::Events::EventType::ListenerList ListenerList; PropChangedRunnable::Pointer runnable(new PropChangedRunnable(event)); const ListenerList& listeners = partChangeEvents.propertyChange.GetListeners(); for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { runnable->delegate = *iter; SafeRunner::Run(runnable); } } void WorkbenchPart::AddPropertyListener(IPropertyChangeListener* l) { partChangeEvents.AddListener(l); } void WorkbenchPart::RemovePropertyListener(IPropertyChangeListener* l) { partChangeEvents.RemoveListener(l); } void WorkbenchPart::SetPartProperty(const QString& key, const QString& value) { QHash::iterator iter = partProperties.find(key); QString oldValue; if (iter != partProperties.end()) oldValue = iter.value(); if (value == "") { partProperties.remove(key); } else { partProperties.insert(key, value); } this->FirePropertyChanged(key, oldValue, value); } QString WorkbenchPart::GetPartProperty(const QString& key) const { QHash::const_iterator itr = partProperties.find(key); if (itr == partProperties.end()) return ""; return itr.value(); } const QHash &WorkbenchPart::GetPartProperties() const { return partProperties; } IWorkbenchPartSite::Pointer WorkbenchPart::GetSite() const { return this->m_PartSite; } QString WorkbenchPart::GetPartName() const { return this->m_PartName; } QString WorkbenchPart::GetContentDescription() const { return this->m_ContentDescription; } QIcon WorkbenchPart::GetTitleImage() const { return this->m_TitleImage; //return GetDefaultImage(); } QString WorkbenchPart::GetTitleToolTip() const { return this->m_ToolTip; } void WorkbenchPart::SetInitializationData(const IConfigurationElement::Pointer& cfig, const QString& /*propertyName*/, const Object::Pointer& /*data*/) { // Save config element. m_ConfigElement = cfig; // Part name and title. m_PartName = cfig->GetAttribute("name"); m_Title = m_PartName; // Icon. QString strIcon = cfig->GetAttribute("icon"); if (strIcon.isEmpty()) { return; } m_TitleImage = AbstractUICTKPlugin::ImageDescriptorFromPlugin( m_ConfigElement->GetContributor()->GetName(), strIcon); } } // namespace berry diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp similarity index 88% rename from Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp rename to Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp index 6b324440f7..69ddb42e73 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp @@ -1,467 +1,467 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "berryWorkbenchPlugin.h" -#include "berryWorkbenchRegistryConstants.h" -#include "berryWorkbench.h" +#include "internal/berryWorkbenchRegistryConstants.h" +#include "internal/berryWorkbench.h" #include "berryPlatform.h" -#include "intro/berryEditorIntroAdapterPart.h" -#include "defaultpresentation/berryQtWorkbenchPresentationFactory.h" +#include "internal/intro/berryEditorIntroAdapterPart.h" +#include "internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h" -#include "berryQtStyleManager.h" +#include "internal/berryQtStyleManager.h" #include "berryExtensionFactory.h" -#include "berryQtWorkbenchTweaklet.h" -#include "berryQtWorkbenchPageTweaklet.h" -#include "berryQtWidgetsTweaklet.h" -#include "dialogs/berryPerspectivesPreferencePage.h" -#include "berryQtStylePreferencePage.h" -#include "berryStatusUtil.h" -#include "berryHandlerServiceFactory.h" -#include "berryMenuServiceFactory.h" -#include "berryCommandServiceFactory.h" -#include "berryWorkbenchSourceProvider.h" +#include "internal/berryQtWorkbenchTweaklet.h" +#include "internal/berryQtWorkbenchPageTweaklet.h" +#include "internal/berryQtWidgetsTweaklet.h" +#include "internal/dialogs/berryPerspectivesPreferencePage.h" +#include "internal/berryQtStylePreferencePage.h" +#include "internal/berryStatusUtil.h" +#include "internal/berryHandlerServiceFactory.h" +#include "internal/berryMenuServiceFactory.h" +#include "internal/berryCommandServiceFactory.h" +#include "internal/berryWorkbenchSourceProvider.h" #include "berryObjectString.h" #include "berryObjects.h" -#include "berryPolicy.h" -#include "berryHandlerAuthority.h" - -#include "berryOpenPerspectivePropertyTester.h" -#include "berryPerspectiveParameterValues.h" - -#include "handlers/berryCloseAllPerspectivesHandler.h" -#include "handlers/berryClosePerspectiveHandler.h" -#include "handlers/berryDynamicHelpHandler.h" -#include "handlers/berryHelpContentsHandler.h" -#include "handlers/berryIntroHandler.h" -#include "handlers/berryOpenInNewWindowHandler.h" -#include "handlers/berryNewEditorHandler.h" -#include "handlers/berryQuitHandler.h" -#include "handlers/berryResetPerspectiveHandler.h" -#include "handlers/berrySavePerspectiveHandler.h" -#include "handlers/berryShowPerspectiveHandler.h" -#include "handlers/berryShowViewHandler.h" +#include "internal/berryPolicy.h" +#include "internal/berryHandlerAuthority.h" + +#include "internal/berryOpenPerspectivePropertyTester.h" +#include "internal/berryPerspectiveParameterValues.h" + +#include "internal/handlers/berryCloseAllPerspectivesHandler.h" +#include "internal/handlers/berryClosePerspectiveHandler.h" +#include "internal/handlers/berryDynamicHelpHandler.h" +#include "internal/handlers/berryHelpContentsHandler.h" +#include "internal/handlers/berryIntroHandler.h" +#include "internal/handlers/berryOpenInNewWindowHandler.h" +#include "internal/handlers/berryNewEditorHandler.h" +#include "internal/handlers/berryQuitHandler.h" +#include "internal/handlers/berryResetPerspectiveHandler.h" +#include "internal/handlers/berrySavePerspectiveHandler.h" +#include "internal/handlers/berryShowPerspectiveHandler.h" +#include "internal/handlers/berryShowViewHandler.h" #include "berryIQtStyleManager.h" #include "berryIContributor.h" #include "berryILog.h" #include "berryIElementFactory.h" #include "berryIExtension.h" #include namespace berry { bool WorkbenchPlugin::DEBUG = false; char WorkbenchPlugin::PREFERENCE_PAGE_CATEGORY_SEPARATOR = '/'; WorkbenchPlugin* WorkbenchPlugin::inst = nullptr; WorkbenchPlugin::WorkbenchPlugin() : AbstractUICTKPlugin() { inst = this; presentationFactory = nullptr; editorRegistry = nullptr; viewRegistry = nullptr; perspRegistry = nullptr; introRegistry = nullptr; } WorkbenchPlugin::~WorkbenchPlugin() { delete presentationFactory; delete editorRegistry; delete viewRegistry; delete perspRegistry; delete introRegistry; inst = nullptr; } bool WorkbenchPlugin::HasExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { if (!element->GetAttribute(extensionName).isNull()) return true; QString elementText = element->GetValue(); if (!elementText.isEmpty()) return true; QList children(element->GetChildren(extensionName)); if (children.size() == 1) { if (!(children[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isNull())) return true; } return false; } bool WorkbenchPlugin::IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { QSharedPointer plugin = WorkbenchPlugin::GetBundleForExecutableExtension(element, extensionName); if (plugin.isNull()) return true; return plugin->getState() == ctkPlugin::ACTIVE; } QSharedPointer WorkbenchPlugin::GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { // this code is derived heavily from // ConfigurationElement.createExecutableExtension. QString prop; QString executable; QString contributorName; int i = 0; if (!extensionName.isNull()) prop = element->GetAttribute(extensionName); else { // property not specified, try as element value prop = element->GetValue(); if (!prop.isNull()) { prop = prop.trimmed(); if (prop.isEmpty()) prop = QString(); } } if (prop.isNull()) { // property not defined, try as a child element QList exec(element->GetChildren(extensionName)); if (!exec.isEmpty()) contributorName = exec[0]->GetAttribute("plugin"); } else { // simple property or element value, parse it into its components i = prop.indexOf(':'); if (i != -1) executable = prop.left(i).trimmed(); else executable = prop; i = executable.indexOf('/'); if (i != -1) contributorName = executable.left(i).trimmed(); } if (contributorName.isNull()) contributorName = element->GetContributor()->GetName(); return Platform::GetPlugin(contributorName); } WorkbenchPlugin* WorkbenchPlugin::GetDefault() { return inst; } std::size_t WorkbenchPlugin::GetBundleCount() { // TODO BundleContext GetBundles //return bundleContext->GetBundles().size(); return 0; } IPerspectiveRegistry* WorkbenchPlugin::GetPerspectiveRegistry() { if (perspRegistry == nullptr) { perspRegistry = new PerspectiveRegistry(); // the load methods can touch on WorkbenchImages if an image is // missing so we need to wrap the call in // a startup block for the case where a custom descriptor exists on // startup that does not have an image // associated with it. See bug 196352. //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { perspRegistry->Load(); // } //}); } return perspRegistry; } // PreferenceManager getPreferenceManager() { // if (preferenceManager == null) { // preferenceManager = new WorkbenchPreferenceManager( // PREFERENCE_PAGE_CATEGORY_SEPARATOR); // // //Get the pages from the registry // PreferencePageRegistryReader registryReader = new PreferencePageRegistryReader( // getWorkbench()); // registryReader // .loadFromRegistry(Platform.getExtensionRegistry()); // preferenceManager.addPages(registryReader.getTopLevelNodes()); // // } // return preferenceManager; // } IIntroRegistry* WorkbenchPlugin::GetIntroRegistry() { if (introRegistry == nullptr) { introRegistry = new IntroRegistry(); } return introRegistry; } IViewRegistry* WorkbenchPlugin::GetViewRegistry() { if (!viewRegistry) viewRegistry = new ViewRegistry(); return viewRegistry; } IEditorRegistry* WorkbenchPlugin::GetEditorRegistry() { if (!editorRegistry) editorRegistry = new EditorRegistry(); return editorRegistry; } IElementFactory* WorkbenchPlugin::GetElementFactory(const QString& targetID) const { // Get the extension point registry. IExtensionPoint::Pointer extensionPoint = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_ELEMENT_FACTORY); IElementFactory* factory = nullptr; if (!extensionPoint) { WorkbenchPlugin::Log("Unable to find element factory. Extension point: " + WorkbenchRegistryConstants::PL_ELEMENT_FACTORY + " not found"); return factory; } // Loop through the config elements. IConfigurationElement::Pointer targetElement; QList configElements = extensionPoint->GetConfigurationElements(); for (int j = 0; j < configElements.size(); j++) { QString strID = configElements[j]->GetAttribute("id"); if (targetID == strID) { targetElement = configElements[j]; break; } } if (!targetElement) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to find element factory: " + targetID); return factory; } // Create the extension. try { factory = targetElement->CreateExecutableExtension("class"); } catch (const CoreException& e) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to create element factory.", e.GetStatus()); factory = nullptr; } return factory; } IPresentationFactory* WorkbenchPlugin::GetPresentationFactory() { if (presentationFactory != nullptr) return presentationFactory; QString targetID = Workbench::GetInstance()->GetPresentationId(); presentationFactory = this->CreateExtension( WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES, "factory", targetID); if (presentationFactory == nullptr) WorkbenchPlugin::Log("Error creating presentation factory: " + targetID + " -- class is not an IPresentationFactory"); return presentationFactory; } void WorkbenchPlugin::Log(const QString& message) { BERRY_INFO << "LOG: " << message << std::endl; //inst->GetLog().log(message); } void WorkbenchPlugin::Log(const ctkException &exc) { QString str; QDebug dbg(&str); dbg << exc.printStackTrace(); BERRY_INFO << "LOG: " << str << std::endl; //inst->GetLog().log(exc); } void WorkbenchPlugin::Log(const QString& message, const ctkException &t) { PlatformException exc(message, t); WorkbenchPlugin::Log(exc); } void WorkbenchPlugin::Log(const QString& clazz, const QString& methodName, const ctkException &t) { QString msg = QString("Exception in ") + clazz + "." + methodName + ": " + t.what(); WorkbenchPlugin::Log(msg, t); } void WorkbenchPlugin::Log(const QString& message, const SmartPointer& status) { //1FTUHE0: ITPCORE:ALL - API - Status & logging - loss of semantic info if (!message.isEmpty()) { GetDefault()->GetLog()->Log(StatusUtil::NewStatus(IStatus::ERROR_TYPE, message, BERRY_STATUS_LOC)); } GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::Log(const SmartPointer& status) { GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::start(ctkPluginContext* context) { //context.addBundleListener(getBundleListener()); AbstractUICTKPlugin::start(context); bundleContext = context; AbstractSourceProvider::DEBUG = Policy::DEBUG_SOURCES(); HandlerAuthority::DEBUG = Policy::DEBUG_HANDLERS(); HandlerAuthority::DEBUG_PERFORMANCE = Policy::DEBUG_HANDLERS_PERFORMANCE(); HandlerAuthority::DEBUG_VERBOSE = Policy::DEBUG_HANDLERS_VERBOSE(); HandlerAuthority::DEBUG_VERBOSE_COMMAND_ID = Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID(); BERRY_REGISTER_EXTENSION_CLASS(EditorIntroAdapterPart, context) BERRY_REGISTER_EXTENSION_CLASS(ExtensionFactory, context) BERRY_REGISTER_EXTENSION_CLASS(QtWidgetsTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPageTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPresentationFactory, context) BERRY_REGISTER_EXTENSION_CLASS(PerspectivesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QtStylePreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(HandlerServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(MenuServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(CommandServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(WorkbenchSourceProvider, context) BERRY_REGISTER_EXTENSION_CLASS(OpenPerspectivePropertyTester, context) BERRY_REGISTER_EXTENSION_CLASS(PerspectiveParameterValues, context) BERRY_REGISTER_EXTENSION_CLASS(HelpContentsHandler, context) BERRY_REGISTER_EXTENSION_CLASS(DynamicHelpHandler, context) BERRY_REGISTER_EXTENSION_CLASS(IntroHandler, context) BERRY_REGISTER_EXTENSION_CLASS(OpenInNewWindowHandler, context) BERRY_REGISTER_EXTENSION_CLASS(NewEditorHandler, context) BERRY_REGISTER_EXTENSION_CLASS(QuitHandler, context) BERRY_REGISTER_EXTENSION_CLASS(ShowPerspectiveHandler, context) BERRY_REGISTER_EXTENSION_CLASS(ShowViewHandler, context) BERRY_REGISTER_EXTENSION_CLASS(SavePerspectiveHandler, context) BERRY_REGISTER_EXTENSION_CLASS(ClosePerspectiveHandler, context) BERRY_REGISTER_EXTENSION_CLASS(CloseAllPerspectivesHandler, context) BERRY_REGISTER_EXTENSION_CLASS(ResetPerspectiveHandler, context) styleManager.reset(new QtStyleManager()); context->registerService(styleManager.data()); // The UI plugin needs to be initialized so that it can install the callback in PrefUtil, // which needs to be done as early as possible, before the workbench // accesses any API preferences. // Bundle uiBundle = Platform.getBundle(PlatformUI.PLUGIN_ID); // try // { // // Attempt to load the activator of the ui bundle. This will force lazy start // // of the ui bundle. Using the bundle activator class here because it is a // // class that needs to be loaded anyway so it should not cause extra classes // // to be loaded. // if(uiBundle != null) // uiBundle.loadClass(UI_BUNDLE_ACTIVATOR); // } // catch (ClassNotFoundException e) // { // WorkbenchPlugin.log("Unable to load UI activator", e); //$NON-NLS-1$ // } /* * DO NOT RUN ANY OTHER CODE AFTER THIS LINE. If you do, then you are * likely to cause a deadlock in class loader code. Please see Bug 86450 * for more information. */ } //const QList WorkbenchPlugin::GetBundles() //{ // return bundleContext.IsNull() ? QList() : bundleContext->GetBundles(); //} ctkPluginContext* WorkbenchPlugin::GetPluginContext() { return bundleContext; } void WorkbenchPlugin::stop(ctkPluginContext* context) { AbstractUICTKPlugin::stop(context); styleManager.reset(); delete perspRegistry; // avoid possible crash, see bug #18399 perspRegistry = nullptr; } QString WorkbenchPlugin::GetDataLocation() const { QFileInfo fileInfo = bundleContext->getDataFile(""); if (!fileInfo.isWritable()) return QString(); return fileInfo.absoluteFilePath(); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.h similarity index 98% rename from Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h rename to Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.h index da52edb5da..7e2bdd05e6 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h +++ b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.h @@ -1,474 +1,474 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHPLUGIN_H_ #define BERRYWORKBENCHPLUGIN_H_ #include #include #include #include #include #include "berryAbstractUICTKPlugin.h" #include "berryPlatformUI.h" #include "presentations/berryIPresentationFactory.h" -#include "berryViewRegistry.h" -#include "berryEditorRegistry.h" -#include "berryPerspectiveRegistry.h" -#include "intro/berryIntroRegistry.h" +#include "internal/berryViewRegistry.h" +#include "internal/berryEditorRegistry.h" +#include "internal/berryPerspectiveRegistry.h" +#include "internal/intro/berryIntroRegistry.h" namespace berry { class QtStyleManager; /** * \ingroup org_blueberry_ui_internal * * This class represents the TOP of the workbench UI world * A plugin class is effectively an application wrapper * for a plugin & its classes. This class should be thought * of as the workbench UI's application class. * * This class is responsible for tracking various registries * font, preference, graphics, dialog store. * * This class is explicitly referenced by the * workbench plugin's "plugin.xml" and places it * into the UI start extension point of the main * overall application harness * * When is this class started? * When the Application * calls createExecutableExtension to create an executable * instance of our workbench class. */ -class WorkbenchPlugin : public AbstractUICTKPlugin +class BERRY_UI_QT WorkbenchPlugin : public AbstractUICTKPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org_blueberry_ui_qt") Q_INTERFACES(ctkPluginActivator) private: //static const QString UI_BUNDLE_ACTIVATOR = "org.blueberry.ui.internal.UIPlugin"; //$NON-NLS-1$ // Default instance of the receiver static WorkbenchPlugin* inst; // The presentation factory IPresentationFactory* presentationFactory; // Manager that maps resources to descriptors of editors to use EditorRegistry* editorRegistry; // The context within which this plugin was started. ctkPluginContext* bundleContext; // Other data. //WorkbenchPreferenceManager preferenceManager; ViewRegistry* viewRegistry; PerspectiveRegistry* perspRegistry; IntroRegistry* introRegistry; //SharedImages sharedImages; QScopedPointer styleManager; public: /** * Global workbench ui plugin flag. Only workbench implementation is allowed to use this flag * All other plugins, examples, or test cases must *not* use this flag. */ static bool DEBUG; /** * The character used to separate preference page category ids */ static char PREFERENCE_PAGE_CATEGORY_SEPARATOR; /** * Create an instance of the WorkbenchPlugin. The workbench plugin is * effectively the "application" for the workbench UI. The entire UI * operates as a good plugin citizen. */ WorkbenchPlugin(); ~WorkbenchPlugin(); /* * Creates an extension. If the extension plugin has not * been loaded a busy cursor will be activated during the duration of * the load. * * @param element the config element defining the extension * @param classAttribute the name of the attribute carrying the class * @return the extension object * @throws CoreException if the extension cannot be created */ // template // static E* CreateExtension(IConfigurationElement::ConstPointer element, // const QString& classAttribute) { // try { // // If plugin has been loaded create extension. // // Otherwise, show busy cursor then create extension. // if (BundleUtility.isActivated(element.getDeclaringExtension() // .getNamespace())) { // return element.createExecutableExtension(classAttribute); // } // final Object[] ret = new Object[1]; // final CoreException[] exc = new CoreException[1]; // BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { // ret[0] = element // .createExecutableExtension(classAttribute); // } catch (CoreException e) { // exc[0] = e; // } // } // }); // if (exc[0] != null) { // throw exc[0]; // } // return ret[0]; // // } catch (CoreException core) { // throw core; // } catch (Exception e) { // throw new CoreException(new Status(IStatus.ERR, PI_WORKBENCH, // IStatus.ERR, WorkbenchMessages.WorkbenchPlugin_extension,e)); // } // } /** * Answers whether the provided element either has an attribute with the * given name or a child element with the given name with an attribute * called class. * * @param element * the element to test * @param extensionName * the name of the extension to test for * @return whether or not the extension is declared */ static bool HasExecutableExtension(const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Checks to see if the provided element has the syntax for an executable * extension with a given name that resides in a bundle that is already * active. Determining the bundle happens in one of two ways:
*
    *
  • The element has an attribute with the specified name or element text * in the form bundle.id/class.name[:optional attributes]
  • *
  • The element has a child element with the specified name that has a * plugin attribute
  • *
* * @param element * the element to test * @param extensionName * the name of the extension to test for * @return whether or not the bundle expressed by the above criteria is * active. If the bundle cannot be determined then the state of the * bundle that declared the element is returned. */ static bool IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Returns the bundle that contains the class referenced by an executable * extension. Determining the bundle happens in one of two ways:
*
    *
  • The element has an attribute with the specified name or element text * in the form bundle.id/class.name[:optional attributes]
  • *
  • The element has a child element with the specified name that has a * plugin attribute
  • *
* * @param element * the element to test * @param extensionName * the name of the extension to test for * @return the bundle referenced by the extension. If that bundle cannot be * determined the bundle that declared the element is returned. Note * that this may be null. */ static QSharedPointer GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Return the default instance of the receiver. This represents the runtime plugin. * @return WorkbenchPlugin * @see AbstractUICTKPlugin for the typical implementation pattern for plugin classes. */ static WorkbenchPlugin* GetDefault(); std::size_t GetBundleCount(); /** * Answer the manager that maps resource types to a the * description of the editor to use * @return IEditorRegistry the editor registry used * by this plug-in. */ IEditorRegistry* GetEditorRegistry(); /** * Answer the element factory for an id, or nullnull if not found. * @param targetID The id of the presentation factory to use. * @return IPresentationFactory or null * if not factory matches that id. */ IPresentationFactory* GetPresentationFactory(); private: /** * Looks up the configuration element with the given id on the given extension point * and instantiates the class specified by the class attributes. * * @param extensionPointId the extension point id (simple id) * @param elementName the name of the configuration element, or null * to match any element * @param targetID the target id * @return the instantiated extension object, or null if not found */ template C* CreateExtension(const QString& extensionPointId, const QString& elementName, const QString& targetID) { IExtensionPoint::Pointer extensionPoint = Platform::GetExtensionRegistry() ->GetExtensionPoint(PlatformUI::PLUGIN_ID() + "." + extensionPointId); if (extensionPoint == 0) { WorkbenchPlugin::Log("Unable to find extension. Extension point: " + extensionPointId + " not found"); return nullptr; } // Loop through the config elements. IConfigurationElement::Pointer targetElement(nullptr); QList elements( Platform::GetExtensionRegistry()->GetConfigurationElementsFor(PlatformUI::PLUGIN_ID() + "." + extensionPointId)); for (int j = 0; j < elements.size(); j++) { if (elementName == "" || elementName == elements[j]->GetName()) { QString strID = elements[j]->GetAttribute("id"); if (targetID == strID) { targetElement = elements[j]; break; } } } if (targetElement.IsNull()) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to find extension: " + targetID + " in extension point: " + extensionPointId); return nullptr; } // Create the extension. try { return targetElement->CreateExecutableExtension("class"); } catch (const CoreException& /*e*/) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to create extension: " + targetID + " in extension point: " + extensionPointId); } return nullptr; } public: /** * Return the perspective registry. * @return IPerspectiveRegistry. The registry for the receiver. */ IPerspectiveRegistry* GetPerspectiveRegistry(); /** * Returns the introduction registry. * * @return the introduction registry. */ IIntroRegistry* GetIntroRegistry(); /* * Get the preference manager. * @return PreferenceManager the preference manager for * the receiver. */ //PreferenceManager getPreferenceManager(); /** * Answer the view registry. * @return IViewRegistry the view registry for the * receiver. */ IViewRegistry* GetViewRegistry(); /** * Logs the given message to the platform log. * * If you have an exception in hand, call log(String, Throwable) instead. * * If you have a status object in hand call log(String, IStatus) instead. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. */ static void Log(const QString &message); /** * Log the throwable. * @param t */ static void Log(const ctkException& exc); /** * Logs the given message and throwable to the platform log. * * If you have a status object in hand call log(String, IStatus) instead. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. * @param t * The throwable from where the problem actually occurred. */ static void Log(const QString &message, const ctkException& t); /** * Logs the given throwable to the platform log, indicating the class and * method from where it is being logged (this is not necessarily where it * occurred). * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param clazz * The calling class. * @param methodName * The calling method name. * @param t * The throwable from where the problem actually occurred. */ static void Log(const QString &clazz, const QString &methodName, const ctkException& t); /** * Logs the given message and status to the platform log. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. * May be null. * @param status * The status describing the problem. Must not be null. */ static void Log(const QString& message, const SmartPointer& status); /** * Log the status to the default log. * @param status */ static void Log(const SmartPointer& status); /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ void start(ctkPluginContext* context) override; /* * Return an array of all bundles contained in this workbench. * * @return an array of bundles in the workbench or an empty array if none */ //const QList GetBundles(); /** * Returns the bundle context associated with the workbench plug-in. * * @return the bundle context */ ctkPluginContext* GetPluginContext(); /* (non-Javadoc) * @see org.blueberry.ui.plugin.AbstractUICTKPlugin#stop(org.osgi.framework.BundleContext) */ void stop(ctkPluginContext* context) override; /** * FOR INTERNAL WORKBENCH USE ONLY. * * Returns the path to a location in the file system that can be used * to persist/restore state between workbench invocations. * If the location did not exist prior to this call it will be created. * Returns null if no such location is available. * * @return path to a location in the file system where this plug-in can * persist data between sessions, or null if no such * location is available. */ QString GetDataLocation() const; }; } #endif /*BERRYWORKBENCHPLUGIN_H_*/ diff --git a/Plugins/org.blueberry.ui.qt/src/berryXMLMemento.cpp b/Plugins/org.blueberry.ui.qt/src/berryXMLMemento.cpp index 3fd3a6c8a9..0d84435d1b 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryXMLMemento.cpp +++ b/Plugins/org.blueberry.ui.qt/src/berryXMLMemento.cpp @@ -1,434 +1,434 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryXMLMemento.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include const QString EMPTY_STRING; berry::XMLMemento::XMLMemento(Poco::XML::Document* document, Poco::XML::Element* elem) : factory(document), element(elem) { factory->duplicate(); element->duplicate(); } berry::XMLMemento::~XMLMemento() { element->release(); factory->release(); } berry::XMLMemento::Pointer berry::XMLMemento::CreateReadRoot( berry::XMLMemento::XMLByteInputStream& reader) { return CreateReadRoot(reader, ""); } berry::XMLMemento::Pointer berry::XMLMemento::CreateReadRoot( berry::XMLMemento::XMLByteInputStream& reader, const QString& baseDir) { QString errorMessage; Poco::Exception exception(""); try { Poco::XML::DOMParser parser; Poco::XML::InputSource source(reader); source.setSystemId(baseDir.toStdString()); Poco::XML::Document* doc = parser.parse(&source); Poco::XML::Element* elem = doc->documentElement(); XMLMemento::Pointer memento(new XMLMemento(doc, elem)); doc->release(); return memento; } catch (Poco::XML::SAXParseException& e) { errorMessage = QString("Could not parse content of XML file: ") + QString::fromStdString(e.displayText()); } QString problemText = QString::fromStdString(exception.message()); if (problemText.isEmpty()) { problemText = errorMessage.isEmpty() ? "Could not find root element node of XML file." : errorMessage; } throw WorkbenchException(problemText); } berry::XMLMemento::Pointer berry::XMLMemento::CreateWriteRoot( const QString& type) { // TODO // try{ auto doc = new Poco::XML::Document(); Poco::XML::Element* elem = doc->createElement(type.toStdString()); doc->appendChild(elem)->release(); XMLMemento::Pointer memento(new XMLMemento(doc, elem)); doc->release(); return memento; //}catch() //TODO: look for poco exceptions //{ //} } berry::IMemento::Pointer berry::XMLMemento::CreateChild( const QString& type) { Poco::XML::Element* child = factory->createElement(type.toStdString()); element->appendChild(child)->release(); IMemento::Pointer xmlChild(new XMLMemento(factory,child)); return xmlChild; } berry::IMemento::Pointer berry::XMLMemento::CreateChild( const QString& type, const QString& id) { Poco::XML::Element* child = factory->createElement(type.toStdString()); child->setAttribute(TAG_ID.toStdString(), id.toStdString()); element->appendChild(child)->release(); IMemento::Pointer xmlChild(new XMLMemento(factory,child)); return xmlChild; } berry::IMemento::Pointer berry::XMLMemento::CopyChild(IMemento::Pointer child) { //TODO check any casting errors Poco::XML::Element* elem = child.Cast ()->GetElement(); Poco::XML::Element* newElement = dynamic_cast (factory->importNode(elem, true)); element->appendChild(newElement)->release(); IMemento::Pointer xmlCopy(new XMLMemento(factory, newElement)); return xmlCopy; } berry::IMemento::Pointer berry::XMLMemento::GetChild(const QString& type) const { // Get the nodes. berry::XMLMemento::Pointer memento; Poco::XML::Element* child = element->getChildElement(type.toStdString()); // Find the first node which is a child of this node if (child) { memento = new berry::XMLMemento(factory, child); return memento; } // A child was not found. return memento; } QList berry::XMLMemento::GetChildren( const QString& type) const { QList mementos; Poco::XML::NodeList* elementList = element->getElementsByTagName(type.toStdString()); for (unsigned long i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast (elementList->item(i)); IMemento::Pointer child(new berry::XMLMemento(factory, elem)); mementos << child; } elementList->release(); return mementos; } bool berry::XMLMemento::GetFloat(const QString& key, double& value) const { if (!element->hasAttribute(key.toStdString())) return false; const std::string& attr = element->getAttribute(key.toStdString()); try { value = Poco::NumberParser::parseFloat(attr); } catch (const Poco::SyntaxException& /*e*/) { std::string _qnan = Poco::NumberFormatter::format(std::numeric_limits::quiet_NaN()); if (_qnan == attr) { value = std::numeric_limits::quiet_NaN(); return true; } std::string _inf = Poco::NumberFormatter::format(std::numeric_limits::infinity()); if (_inf == attr) { value = std::numeric_limits::infinity(); return true; } WorkbenchPlugin::Log("Memento problem - invalid float for key: " + key + " value: " + QString::fromStdString(attr)); return false; } return true; } QString berry::XMLMemento::GetType() const { return QString::fromStdString(element->nodeName()); } QString berry::XMLMemento::GetID() const { //TODO: make error handling! return QString::fromStdString(element->getAttribute(TAG_ID.toStdString())); } bool berry::XMLMemento::GetInteger(const QString& key, int& value) const { if (!element->hasAttribute(key.toStdString())) return false; const std::string& attr = element->getAttribute(key.toStdString()); try { value = Poco::NumberParser::parse(attr); } catch (const Poco::SyntaxException& /*e*/) { WorkbenchPlugin::Log("Memento problem - invalid integer for key: " + key + " value: " + QString::fromStdString(attr)); return false; } return true; } bool berry::XMLMemento::GetBoolean(const QString& key, bool& value) const { const std::string& attr = element->getAttribute(key.toStdString()); if (attr.empty()) return false; else if (attr == "true") { value = true; return true; } else { value = false; return true; } } bool berry::XMLMemento::GetString(const QString& key, QString& value) const { QString v = QString::fromStdString(element->getAttribute(key.toStdString())); if (v.isEmpty()) return false; value = v; return true; } QString berry::XMLMemento::GetTextData() const { Poco::XML::Text* textNode = GetTextNode(); if (textNode != nullptr) { return QString::fromStdString(textNode->getData()); } return EMPTY_STRING; } QList berry::XMLMemento::GetAttributeKeys() const { QList values; Poco::XML::NamedNodeMap* nnMap = element->attributes(); values.reserve(nnMap->length()); for (unsigned long i = 0; i < nnMap->length(); i++) { values[i] = QString::fromStdString(nnMap->item(i)->nodeName()); //TODO check if right } return values; } Poco::XML::Text* berry::XMLMemento::GetTextNode() const { //Get the nodes Poco::XML::NodeList* nodes = element->childNodes(); unsigned long size = nodes->length(); if (size == 0) return nullptr; //Search for the text node for (unsigned long index = 0; index < size; index++) { if (nodes->item(index)->nodeType() == Poco::XML::Node::TEXT_NODE) { return dynamic_cast (nodes->item(index)); } } // a Text node was not found return nullptr; } void berry::XMLMemento::PutElement(Poco::XML::Element* element, bool copyText) { Poco::XML::NamedNodeMap* nodeMap = element->attributes(); unsigned long size = nodeMap->length(); for (unsigned long index = 0; index < size; index++) { Poco::XML::Node* node = nodeMap->item(index); Poco::XML::Attr* attr = dynamic_cast (node); PutString(QString::fromStdString(attr->nodeName()), QString::fromStdString(attr->nodeValue())); } nodeMap->release(); bool needToCopyText = copyText; Poco::XML::Node* child = element->firstChild(); while (child) { unsigned short nodeType = child->nodeType(); switch (nodeType) { case Poco::XML::Node::ELEMENT_NODE: { Poco::XML::Element* elem = dynamic_cast (child); XMLMemento::Pointer child = CreateChild(QString::fromStdString(elem->nodeName())).Cast< berry::XMLMemento> (); child->PutElement(elem, true); } break; case Poco::XML::Node::TEXT_NODE: if (needToCopyText) { Poco::XML::Text* text = dynamic_cast (child); PutTextData(QString::fromStdString(text->getData())); needToCopyText = false; } break; default: break; } child = child->nextSibling(); } } void berry::XMLMemento::PutFloat(const QString& key, double value) { std::string xmlValue = Poco::NumberFormatter::format(value); element->setAttribute(key.toStdString(), xmlValue); } void berry::XMLMemento::PutInteger(const QString& key, int value) { std::string xmlValue = Poco::NumberFormatter::format(value); element->setAttribute(key.toStdString(), xmlValue); } void berry::XMLMemento::PutMemento(IMemento::Pointer memento) { // Do not copy the element's top level text node (this would overwrite the existing text). // Text nodes of children are copied. PutElement(memento.Cast ()->GetElement(), false); } void berry::XMLMemento::PutString(const QString& key, const QString& value) { element->setAttribute(key.toStdString(), value.toStdString()); //if (value == null) { // return;} //element.setAttribute(key, value); } void berry::XMLMemento::PutBoolean(const QString& key, bool value) { if (value) { element->setAttribute(key.toStdString(), "true"); } else { element->setAttribute(key.toStdString(), "false"); } } void berry::XMLMemento::PutTextData(const QString& data) { Poco::XML::Text* textNode = GetTextNode(); if (textNode == nullptr) { textNode = factory->createTextNode(data.toStdString()); element->insertBefore(textNode, element->firstChild())->release(); } else { textNode->setData(data.toStdString()); } } void berry::XMLMemento::Save(berry::XMLMemento::XMLByteOutputStream& writer) { if (writer.good()) { Poco::XML::DOMWriter out; out.setOptions(3); //write declaration and pretty print out.writeNode(writer, factory); } else { //TODO } } Poco::XML::Element* berry::XMLMemento::GetElement() const { return element; } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp.autosave b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp.autosave new file mode 100644 index 0000000000..520209821f --- /dev/null +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp.autosave @@ -0,0 +1,410 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "berryQtStyleManager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "berryQtPreferences.h" +#include "berryWorkbenchPlugin.h" + +namespace berry +{ + +QtStyleManager::QtStyleManager() +{ + AddDefaultStyle(); + AddDefaultFonts(); + ReadPreferences(); +} + +void QtStyleManager::ReadPreferences() +{ + IPreferencesService* prefService = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); + + QString paths = 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, ""); + // 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/defaultstyle.qss", "Default"); + AddStyle(":/org.blueberry.ui.qt/darkstyle.qss", "Dark"); + defaultStyle = styles[":/org.blueberry.ui.qt/defaultstyle.qss"]; +#endif +} + +void QtStyleManager::AddDefaultFonts() +{ + m_customFontNames.append(QString("<>")); + +// m_customFontNames.append(QString("Fira Sans")); +// QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/FiraSans/FiraSans.ttc"); + +// m_customFontNames.append(QString("Light Fira Sans")); +// QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/LightFiraSans/LightFiraSans.ttc"); + +// 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-Bold.ttf"); +// QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/OpenSans/OpenSans-BoldItalic.ttf"); +// QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/OpenSans/OpenSans-Italic.ttf"); +// QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/OpenSans/OpenSans-Light.ttf"); +// 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 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::GetIconThemes(IconThemeList& iconThemes) const +{ + iconThemes.clear(); + iconThemes.push_back(IconTheme(QString( "<>" ))); + + QStringList iconSearchPaths = QIcon::themeSearchPaths(); + + for(QStringList::Iterator pathIt = iconSearchPaths.begin(); pathIt != iconSearchPaths.end(); ++pathIt) + { + QDirIterator dirIt(*pathIt); + while (dirIt.hasNext()) + { + QString current = dirIt.next(); + QFileInfo info = dirIt.fileInfo(); + if (info.isDir() && info.isReadable()) + { + QFileInfo themeFile( info.filePath() + QString("/index.theme") ); + if( themeFile.exists() && themeFile.isFile() && themeFile.isReadable() ) + { + QString fileName = info.fileName(); + iconThemes.push_back( IconTheme(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) +{ + if( fontName == QString( "<>" ) || fontName == QString( "" )) + { + qApp->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont)); + } + else + { + QFont font; + font.setFamily(fontName); + font.setPointSize(11); + std::cout << "[FONT DEBUG] bold?: " << font.bold() << std::endl; + + QStringList foo = QFontDatabase::applicationFontFamilies(1); + for(size_t i = 0; i < foo.size(); ++i) + { + std::cout << "[FONT DEBUG]applicationFontFamilies?: " << foo[i] << std::endl; + } + + qApp->setFont(font); + } + currentFont = fontName; + qApp->setStyleSheet(currentStyle->stylesheet); + PlatformUI::GetWorkbench()->UpdateTheme(); +} + +void QtStyleManager::SetIconTheme(const QString& themeName) +{ + if( themeName == QString( "<>" ) ) + { + SetIconTheme( QString("tango"), true); + } + else + { + SetIconTheme(themeName, true); + } +} + +void QtStyleManager::SetIconTheme(const QString& themeName, bool /*update*/) +{ + QIcon::setThemeName( themeName ); +} + +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/internal/defaultpresentation/berryNativeTabFolder.cpp b/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp index 276609d53c..692745d73a 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp @@ -1,363 +1,363 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryNativeTabFolder.h" #include "berryNativeTabItem.h" #include "berryQCTabBar.h" #include -#include +#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(viewForm); layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); viewForm->setLayout(layout); connect(viewForm, SIGNAL(destroyed(QObject*)), this, SLOT(ViewFormDestroyed(QObject*))); auto topControls = new QWidget(viewForm); topControls->setMinimumSize(0, 24); topControls->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); layout->addWidget(topControls); auto topLayout = new QHBoxLayout(topControls); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->setSpacing(0); tabControl = new QCTabBar(topControls); tabControl->installEventFilter(this); tabControl->setMinimumSize(0, 25); tabControl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); topLayout->addWidget(tabControl); auto topRightControls = new QFrame(topControls); topRightControls->setObjectName("TabTopRightControls"); topRightControls->setMinimumSize(6, 25); topRightControls->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); topLayout->addWidget(topRightControls); 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); //contentFrame->setLayout(layout); 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&))); //std::cout << "Created: viewForm <-- " << qPrintable(parent->objectName()); //for (parent = parent->parentWidget(); parent != 0; parent = parent->parentWidget()) // std::cout << " <-- " << qPrintable(parent->objectName()); //std::cout << std::endl; //parent = viewForm; //std::cout << "Created control: QCTabBar <-- " << qPrintable(parent->objectName()); //for (parent = parent->parentWidget(); parent != 0; parent = parent->parentWidget()) // std::cout << " <-- " << qPrintable(parent->objectName()); //std::cout << std::endl; //attachListeners(control, false); // viewForm = new ViewForm(control, SWT.FLAT); // attachListeners(viewForm, false); // systemToolbar = new StandardSystemToolbar(viewForm, true, false, true, true, true); // systemToolbar.addListener(systemToolbarListener); // viewForm.setTopRight(systemToolbar.getControl()); // // topCenter = new ProxyControl(viewForm); // topCenterCache = new SizeCache(); // // title = new CLabel(viewForm, SWT.LEFT); // attachListeners(title, false); // viewForm.setTopLeft(title); 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::UpdateColors() { QString tabStyle = this->GetActive() == 1 ? skinManager->GetActiveTabStylesheet() : skinManager->GetTabStylesheet(); //tabControl->setStyleSheet(tabSkin); //contentFrame->setStyleSheet(tabSkin); viewForm->setStyleSheet(tabStyle); } void NativeTabFolder::SetActive(int activeState) { AbstractTabFolder::SetActive(activeState); this->UpdateColors(); } 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); // QRect rect1 = tabControl->geometry(); // QRect rect2 = viewForm->geometry(); // std::cout << "QCTabBar geometry is: x=" << rect1.x() << ", y=" << rect1.y() << ", width=" << rect1.width() << ", height=" << rect1.height() << std::endl; // std::cout << "ViewForm geometry is: " << rect2.x() << ", y=" << rect2.y() << ", width=" << rect2.width() << ", height=" << rect2.height() << std::endl; // Rectangle oldBounds = viewForm.getBounds(); // Rectangle newBounds = control.getClientArea(); // // viewForm.setBounds(newBounds); // // if (Util.equals(oldBounds, newBounds)) // { // viewForm.layout(flushCache); // } } QPoint NativeTabFolder::GetPaneMenuLocation() { return AbstractTabFolder::GetPaneMenuLocation(); //return systemToolbar.getPaneMenuLocation(); } void NativeTabFolder::SetState(int state) { AbstractTabFolder::SetState(state); //systemToolbar.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& /*info*/) { // if (!Util.equals(title.getText(), info.title)) // { // title.setText(info.title); // } // if (title.getImage() != info.image) // { // title.setImage(info.image); // } } QRect NativeTabFolder::GetTabArea() { return tabControl->geometry(); // Rectangle bounds = control.getBounds(); // // Rectangle clientArea = control.getClientArea(); // // bounds.x = 0; // bounds.y = 0; // Geometry.expand(bounds, 0, 0, -(clientArea.height + clientArea.y), 0); // // return Geometry.toDisplay(control.getParent(), bounds); } QWidget* NativeTabFolder::GetControl() { return viewForm; } bool NativeTabFolder::IsOnBorder(const QPoint& /*globalPos*/) { // Point localPos = getControl().toControl(globalPos); // // Rectangle clientArea = getClientArea(); // return localPos.y > clientArea.y && localPos.y < clientArea.y // + clientArea.height; return false; } AbstractTabItem* NativeTabFolder::GetSelection() { return tabControl->getCurrentTab(); } QWidget* NativeTabFolder::GetContentParent() { return contentFrame; } void NativeTabFolder::SetContent(QWidget* newContent) { //viewForm.setContent(newContent); if (content != nullptr) { contentFrame->layout()->removeWidget(content); disconnect(content); } content = newContent; content->installEventFilter(this); //((QBoxLayout*)contentFrame->layout())->addWidget(content, 1); contentFrame->layout()->addWidget(content); } QCTabBar* NativeTabFolder::GetTabFolder() { return tabControl; } void NativeTabFolder::SetSelectedTitle(const QString& /*newTitle*/) { //title.setText(newTitle); } void NativeTabFolder::SetSelectedImage(const QPixmap* /*image*/) { //title.setImage(image); } 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 /*enabled*/) { //systemToolbar.enablePaneMenu(enabled); } } 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 bff6cdb97e..5aefe230fe 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp @@ -1,288 +1,288 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "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 "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #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 (PerspectiveDescriptor::Pointer desc : 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/handlers/berryDynamicHelpHandler.cpp b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.cpp index 8f82fd7457..fb801e94c9 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.cpp @@ -1,76 +1,76 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryDynamicHelpHandler.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include #include namespace berry { Object::Pointer DynamicHelpHandler::Execute(const SmartPointer& /*event*/) { ctkPluginContext* context = WorkbenchPlugin::GetDefault()->GetPluginContext(); if (context == nullptr) { BERRY_WARN << "Plugin context not set, unable to open context help"; return Object::Pointer(); } // 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) { BERRY_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return Object::Pointer(); } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = nullptr; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == nullptr) { BERRY_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } return Object::Pointer(); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp index 3b63f9b8e6..6a4ea714bf 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp @@ -1,109 +1,109 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berrySavePerspectiveHandler.h" #include "berryHandlerUtil.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "internal/berryPerspectiveDescriptor.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include "internal/dialogs/berrySavePerspectiveDialog.h" #include #include namespace berry { Object::Pointer SavePerspectiveHandler::Execute(const SmartPointer& event) { IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); if (activeWorkbenchWindow.IsNotNull()) { IWorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage(); if (page.IsNotNull()) { PerspectiveDescriptor::Pointer descriptor(page->GetPerspective().Cast()); if (descriptor.IsNotNull()) { if (descriptor->IsSingleton()) { SaveSingleton(page); } else { SaveNonSingleton(page, descriptor); } } } } return Object::Pointer(); } void SavePerspectiveHandler::SaveSingleton(const IWorkbenchPage::Pointer& page) { QMessageBox::StandardButton btn = QMessageBox::question(page->GetWorkbenchWindow()->GetShell()->GetControl(), "Overwrite perspective", "The current perspective can only be opened once and cannot be saved using a new name. " "Do you want to overwrite?", QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); if (btn == QMessageBox::Ok) { page->SavePerspective(); } } void SavePerspectiveHandler::SaveNonSingleton(const IWorkbenchPage::Pointer& page, const PerspectiveDescriptor::Pointer& oldDesc) { // Get reg. PerspectiveRegistry* reg = static_cast( berry::WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); assert(reg != nullptr); // Get persp name. SavePerspectiveDialog dlg(*reg, page->GetWorkbenchWindow()->GetShell()->GetControl()); // Look up the descriptor by id again to ensure it is still valid. IPerspectiveDescriptor::Pointer description = reg->FindPerspectiveWithId(oldDesc->GetId()); dlg.SetInitialSelection(description); if (dlg.exec() != QDialog::Accepted) { return; } // Create descriptor. IPerspectiveDescriptor::Pointer newDesc = dlg.GetPersp(); if (newDesc.IsNull()) { QString name = dlg.GetPerspName(); newDesc = reg->CreatePerspective(name, description); if (newDesc.IsNull()) { QMessageBox::critical(&dlg, "Cannot Save Perspective", "Invalid Perspective Descriptor"); return; } } // Save state. page->SavePerspectiveAs(newDesc); } } 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 4f703d466e..463f822533 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp @@ -1,141 +1,141 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryShowPerspectiveHandler.h" #include #include #include #include #include #include "internal/berryPreferenceConstants.h" #include "internal/berryQtShowPerspectiveDialog.h" #include "internal/berryWorkbench.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #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.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp index e1aa446f07..0291b9b159 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp @@ -1,116 +1,116 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryShowViewHandler.h" #include "berryIWorkbenchCommandConstants.h" #include "berryHandlerUtil.h" #include "berryUIException.h" #include "berryIWorkbenchPage.h" #include "berryIViewDescriptor.h" #include "berryPlatformUI.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include "internal/berryQtShowViewDialog.h" #include #include namespace berry { ShowViewHandler::ShowViewHandler() { } Object::Pointer ShowViewHandler::Execute(const ExecutionEvent::ConstPointer& event) { IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); // Get the view identifier, if any. const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); ExecutionEvent::ParameterMap::const_iterator result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID); QString viewId = result != parameters.end() ? result.value() : QString::null; result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID); QString secondary = result != parameters.end() ? result.value() : QString::null; if (viewId.isEmpty()) { this->OpenOther(window); } else { try { this->OpenView(viewId, secondary, window); } catch (const PartInitException& e) { throw ExecutionException("Part could not be initialized", e); } } return Object::Pointer(nullptr); } void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window) { const IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } QtShowViewDialog dialog(window.GetPointer(), WorkbenchPlugin::GetDefault()->GetViewRegistry()); int returnCode = dialog.exec(); if (returnCode == QDialog::Rejected) { return; } const QList descriptors = dialog.GetSelection(); for (QString id : descriptors) { try { this->OpenView(id, QString(), window); } catch (const PartInitException& e) { BERRY_WARN << e.what(); // StatusUtil.handleStatus(e.getStatus(), // WorkbenchMessages.ShowView_errorTitle // + ": " + e.getMessage(), //$NON-NLS-1$ // StatusManager.SHOW); } } } void ShowViewHandler::OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::Pointer activeWorkbenchWindow) { const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); if (activePage.IsNull()) { return; } activePage->ShowView(viewId, secondaryId, IWorkbenchPage::VIEW_ACTIVATE); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp index a27a3389e0..fb60427eeb 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp @@ -1,141 +1,141 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryEditorIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" #include "internal/berryWorkbench.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" namespace berry { EditorIntroAdapterPart::EditorIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &EditorIntroAdapterPart::PropertyChange)) { } void EditorIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } void EditorIntroAdapterPart::CreatePartControl(QWidget* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } EditorIntroAdapterPart::~EditorIntroAdapterPart() { //setBarVisibility(true); if(introPart) { introPart->RemovePropertyListener(propChangeListener.data()); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } } QIcon EditorIntroAdapterPart::GetTitleImage() const { return introPart->GetTitleImage(); } QString EditorIntroAdapterPart::GetPartName() const { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? EditorPart::GetPartName() : introPart->GetPartName(); } void EditorIntroAdapterPart::Init(IEditorSite::Pointer site, IEditorInput::Pointer input) { Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager()->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener.data()); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, IMemento::Pointer(nullptr)); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro editor proxy.", e); } this->SetSite(site); this->SetInput(input); } void EditorIntroAdapterPart::DoSave(/*IProgressMonitor monitor*/) { } void EditorIntroAdapterPart::DoSaveAs() { } bool EditorIntroAdapterPart::IsDirty() const { return false; } bool EditorIntroAdapterPart::IsSaveAsAllowed() const { return false; } void EditorIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/, int propId) { FirePropertyChange(propId); } void EditorIntroAdapterPart::SetFocus() { introPart->SetFocus(); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp index 3765baca3f..70f3b3aa51 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp @@ -1,172 +1,172 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIntroRegistry.h" #include #include #include "berryIntroDescriptor.h" #include "internal/berryRegistryReader.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" namespace berry { const QString IntroRegistry::TAG_INTRO = "intro"; const QString IntroRegistry::TAG_INTROPRODUCTBINDING = "introProductBinding"; const QString IntroRegistry::ATT_INTROID = "introId"; const QString IntroRegistry::ATT_PRODUCTID = "productId"; QString IntroRegistry::GetIntroForProduct( const QString& targetProductId, const QList& extensions) const { for (int i = 0; i < extensions.size(); i++) { QList elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTROPRODUCTBINDING) { QString introId = elements[j]->GetAttribute(ATT_INTROID); QString productId = elements[j]->GetAttribute(ATT_PRODUCTID); if (introId.isEmpty() || productId.isEmpty()) { //TODO IStatus /* IStatus status = new Status( IStatus.ERROR, elements[j].getDeclaringExtension() .getNamespace(), IStatus.ERROR, "introId and productId must be defined.", new IllegalArgumentException()); WorkbenchPlugin.log("Invalid intro binding", status); */ WorkbenchPlugin::Log( elements[j]->GetDeclaringExtension()->GetNamespaceIdentifier() + ": Invalid intro binding. introId and productId must be defined"); continue; } if (targetProductId == productId) { return introId; } } } } return ""; } int IntroRegistry::GetIntroCount() const { return static_cast (GetIntros().size()); } QList IntroRegistry::GetIntros() const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return QList(); } QList extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QList list; for (int i = 0; i < extensions.size(); i++) { QList elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTRO) { try { IIntroDescriptor::Pointer descriptor(new IntroDescriptor(elements[j])); list.push_back(descriptor); } catch (const CoreException& e) { // log an error since its not safe to open a dialog here //TODO IStatus WorkbenchPlugin::Log("Unable to create intro descriptor", e); // e.getStatus()); } } } } return list; } IIntroDescriptor::Pointer IntroRegistry::GetIntroForProduct( const QString& targetProductId) const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return IIntroDescriptor::Pointer(); } QList extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QString targetIntroId = GetIntroForProduct(targetProductId, extensions); if (targetIntroId.isEmpty()) { return IIntroDescriptor::Pointer(); } IIntroDescriptor::Pointer descriptor; QList intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { if (intros[i]->GetId() == targetIntroId) { descriptor = intros[i]; break; } } return descriptor; } IIntroDescriptor::Pointer IntroRegistry::GetIntro(const QString& id) const { QList intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { IIntroDescriptor::Pointer desc = intros[i]; if (desc->GetId() == id) { return desc; } } return IIntroDescriptor::Pointer(); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp index f58e68715c..ab8f462892 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp @@ -1,121 +1,121 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" #include "internal/berryWorkbench.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" namespace berry { ViewIntroAdapterPart::ViewIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &ViewIntroAdapterPart::PropertyChange)) { } void ViewIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } void ViewIntroAdapterPart::CreatePartControl(QWidget* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } ViewIntroAdapterPart::~ViewIntroAdapterPart() { //setBarVisibility(true); introPart->RemovePropertyListener(propChangeListener.data()); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } QIcon ViewIntroAdapterPart::GetTitleImage() const { return introPart->GetTitleImage(); } QString ViewIntroAdapterPart::GetPartName() const { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? ViewPart::GetPartName() : introPart->GetPartName(); } void ViewIntroAdapterPart::Init(IViewSite::Pointer site, IMemento::Pointer memento) throw (PartInitException) { ViewPart::Init(site); Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager() ->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener.data()); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, memento); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro view proxy.", e); } } void ViewIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/, int propId) { FirePropertyChange(propId); } void ViewIntroAdapterPart::SetFocus() { introPart->SetFocus(); } void ViewIntroAdapterPart::SaveState(IMemento::Pointer memento) { introPart->SaveState(memento); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryWorkbenchIntroManager.cpp b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryWorkbenchIntroManager.cpp index 83ade142b2..a8fd270c2c 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/intro/berryWorkbenchIntroManager.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/intro/berryWorkbenchIntroManager.cpp @@ -1,345 +1,345 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchIntroManager.h" #include "berryIntroConstants.h" #include "internal/berryWorkbench.h" #include "internal/berryWorkbenchPage.h" -#include "internal/berryWorkbenchPlugin.h" +#include "berryWorkbenchPlugin.h" #include "internal/berryPerspective.h" #include "internal/berryNullEditorInput.h" namespace berry { void WorkbenchIntroManager::CreateIntro( SmartPointer preferredWindow) { IIntroDescriptor::Pointer descr = this->workbench->GetIntroDescriptor(); if (!descr) { return; } IWorkbenchPage::Pointer workbenchPage = preferredWindow->GetActivePage(); if (!workbenchPage) { return; } try { if (IntroIsView()) { workbenchPage->ShowView(IntroConstants::INTRO_VIEW_ID); } else { IEditorInput::Pointer input(new NullEditorInput()); workbenchPage->OpenEditor(input, IntroConstants::INTRO_EDITOR_ID); } } catch (PartInitException& e) { //TODO IStatus // WorkbenchPlugin::Log(IntroMessages.Intro_could_not_create_part, new Status( // IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, IStatus.ERROR, // IntroMessages.Intro_could_not_create_part, e)); WorkbenchPlugin::Log("Could not create intro part.", e); } } bool WorkbenchIntroManager::IntroIsView() const { IIntroDescriptor::Pointer descr = this->workbench->GetIntroDescriptor(); if (descr) { return descr->GetRole() == IntroConstants::INTRO_ROLE_VIEW; } return true; } WorkbenchIntroManager::WorkbenchIntroManager(Workbench* workbench) : workbench(workbench) { // workbench.getExtensionTracker().registerHandler(new IExtensionChangeHandler(){ // // /* (non-Javadoc) // * @see org.eclipse.core.runtime.dynamicHelpers.IExtensionChangeHandler#addExtension(org.eclipse.core.runtime.dynamicHelpers.IExtensionTracker, org.eclipse.core.runtime.IExtension) // */ // public void addExtension(IExtensionTracker tracker,IExtension extension) { // //Do nothing // } // // /* (non-Javadoc) // * @see org.eclipse.core.runtime.dynamicHelpers.IExtensionChangeHandler#removeExtension(org.eclipse.core.runtime.IExtension, java.lang.Object[]) // */ // public void removeExtension(IExtension source, Object[] objects) { // for (int i = 0; i < objects.length; i++) { // if (objects[i] instanceof IIntroPart) { // closeIntro((IIntroPart) objects[i]); // } // } // // }}, null); } bool WorkbenchIntroManager::CloseIntro(IIntroPart::Pointer part) { if (!introPart || introPart != part) { return false; } IWorkbenchPart::Pointer introView = GetIntroAdapterPart(); if (introView) { //assumption is that there is only ever one intro per workbench //if we ever support one per window then this will need revisiting IWorkbenchPage::Pointer page = introView->GetSite()->GetPage(); if (IntroIsView()) { IViewReference::Pointer reference = page->FindViewReference( IntroConstants::INTRO_VIEW_ID); page->HideView(introView.Cast()); if (!reference || reference->GetPart(false) == 0) { introPart = nullptr; return true; } return false; } else { QList references(page->FindEditors(IEditorInput::Pointer(nullptr), IntroConstants::INTRO_EDITOR_ID, IWorkbenchPage::MATCH_ID)); Q_ASSERT(references.size() < 2); if (references.empty()) return false; if (page->CloseEditors(references, false)) { introPart = nullptr; return true; } return false; } } // if there is no part then null our reference introPart = nullptr; return true; } IIntroPart::Pointer WorkbenchIntroManager::ShowIntro(SmartPointer< IWorkbenchWindow> preferredWindow, bool standby) { if (!preferredWindow) { preferredWindow = this->workbench->GetActiveWorkbenchWindow(); } if (!preferredWindow) { return IIntroPart::Pointer(nullptr); } IWorkbenchPart::Pointer part = GetIntroAdapterPart(); if (!part) { CreateIntro(preferredWindow); } else { try { IWorkbenchPage::Pointer page = part->GetSite()->GetPage(); IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow(); if (window != preferredWindow) { window->GetShell()->SetActive(); } if (IntroIsView()) { page->ShowView(IntroConstants::INTRO_VIEW_ID); } else { IEditorInput::Pointer input(new NullEditorInput()); page->OpenEditor(input, IntroConstants::INTRO_EDITOR_ID); } } catch (PartInitException& e) { //TODO IStatus // WorkbenchPlugin::Log("Could not open intro", new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, IStatus.ERROR, "Could not open intro", // e)); //$NON-NLS-1$ //$NON-NLS-2$ WorkbenchPlugin::Log("Could not open intro", e); } } SetIntroStandby(introPart, standby); return introPart; } bool WorkbenchIntroManager::IsIntroInWindow( SmartPointer testWindow) const { IWorkbenchPart::Pointer part = GetIntroAdapterPart(); if (!part) { return false; } IWorkbenchWindow::Pointer window = part->GetSite()->GetWorkbenchWindow(); if (window == testWindow) { return true; } return false; } void WorkbenchIntroManager::SetIntroStandby(IIntroPart::Pointer part, bool /*standby*/) { if (!introPart || introPart != part) { return; } IWorkbenchPart::Pointer introPart = GetIntroAdapterPart(); if (!introPart) { return; } // PartPane::Pointer pane = viewIntroAdapterPart->GetSite().Cast()->GetPane(); // if (standby == !pane.isZoomed()) // { // // the zoom state is already correct - just update the part's state. // viewIntroAdapterPart.setStandby(standby); // return; // } // // viewIntroAdapterPart.getSite().getPage().toggleZoom(pane.getPartReference()); } bool WorkbenchIntroManager::IsIntroStandby(IIntroPart::Pointer part) const { if (!introPart || introPart != part) { return false; } IWorkbenchPart::Pointer introPart = GetIntroAdapterPart(); if (!introPart) { return false; } //return !((PartSite) introPart.getSite()).getPane().isZoomed(); return false; } IIntroPart::Pointer WorkbenchIntroManager::GetIntro() const { return introPart; } IWorkbenchPart::Pointer WorkbenchIntroManager::GetIntroAdapterPart() const { QList windows(this->workbench->GetWorkbenchWindows()); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; WorkbenchPage::Pointer page = window->GetActivePage().Cast(); if (!page) { continue; } if (IntroIsView()) { QList perspDescs(page->GetOpenPerspectives()); for (int j = 0; j < perspDescs.size(); j++) { IPerspectiveDescriptor::Pointer descriptor = perspDescs[j]; IViewReference::Pointer reference = page->FindPerspective(descriptor)->FindView( IntroConstants::INTRO_VIEW_ID); if (reference) { return reference->GetView(false); } } } else { QList references(page->FindEditors(IEditorInput::Pointer(nullptr), IntroConstants::INTRO_EDITOR_ID, IWorkbenchPage::MATCH_ID)); Q_ASSERT(references.size() < 2); if (references.size() == 1) return references.front()->GetEditor(false); } } return IWorkbenchPart::Pointer(nullptr); } IIntroPart::Pointer WorkbenchIntroManager::CreateNewIntroPart() { IntroDescriptor::Pointer introDescriptor(workbench->GetIntroDescriptor()); introPart = (introDescriptor == 0 ? IIntroPart::Pointer(nullptr) : introDescriptor->CreateIntro()); // if (introPart) // { // workbench.getExtensionTracker().registerObject( // introDescriptor.getConfigurationElement() .getDeclaringExtension(), // introPart, IExtensionTracker.REF_WEAK); // } return introPart; } bool WorkbenchIntroManager::HasIntro() const { return workbench->GetIntroDescriptor() != 0; } bool WorkbenchIntroManager::IsNewContentAvailable() { IntroDescriptor::Pointer introDescriptor = workbench->GetIntroDescriptor(); if (!introDescriptor) { return false; } try { IntroContentDetector::Pointer contentDetector = introDescriptor->GetIntroContentDetector(); if (contentDetector) { return contentDetector->IsNewContentAvailable(); } } catch (CoreException& ex) { //TODO IStatus // WorkbenchPlugin.log(new Status(IStatus.WARNING, // WorkbenchPlugin.PI_WORKBENCH, IStatus.WARNING, // "Could not load intro content detector", ex)); //$NON-NLS-1$ WorkbenchPlugin::Log("Could not load intro content detector", ex); } return false; } } diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.measurementtoolbox/manifest_headers.cmake index b318b8aca8..bea2c215a4 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/manifest_headers.cmake +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/manifest_headers.cmake @@ -1,5 +1,8 @@ set(Plugin-Name "MITK Measurement") -set(Plugin-Version "1.0.0") +set(Plugin-Version "1.0.1") set(Plugin-Vendor "DKFZ, Medical and Biological Informatics") set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.mitk.gui.qt.common) +set(Require-Plugin + org.mitk.gui.qt.common + org.blueberry.ui.qt + ) \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp index 866bc036cd..96cb80d89e 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp @@ -1,1361 +1,1390 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkImageStatisticsView.h" // Qt includes #include #include #include // berry includes #include // mitk includes #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateOr.h" #include "mitkPlanarFigureInteractor.h" // itk includes #include "itksys/SystemTools.hxx" #include #include #include +//blueberry includes +#include +#include + const std::string QmitkImageStatisticsView::VIEW_ID = "org.mitk.views.imagestatistics"; const int QmitkImageStatisticsView::STAT_TABLE_BASE_HEIGHT = 180; QmitkImageStatisticsView::QmitkImageStatisticsView(QObject* /*parent*/, const char* /*name*/) : m_Controls( NULL ), m_TimeStepperAdapter( NULL ), m_SelectedImage( NULL ), m_SelectedImageMask( NULL ), m_SelectedPlanarFigure( NULL ), m_ImageObserverTag( -1 ), m_ImageMaskObserverTag( -1 ), m_PlanarFigureObserverTag( -1 ), m_TimeObserverTag( -1 ), m_CurrentStatisticsValid( false ), m_StatisticsUpdatePending( false ), m_DataNodeSelectionChanged ( false ), m_Visible(false) { this->m_CalculationThread = new QmitkImageStatisticsCalculationThread; } QmitkImageStatisticsView::~QmitkImageStatisticsView() { if ( m_SelectedImage != NULL ) m_SelectedImage->RemoveObserver( m_ImageObserverTag ); if ( m_SelectedImageMask != NULL ) m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); if ( m_SelectedPlanarFigure != NULL ) m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); while(this->m_CalculationThread->isRunning()) // wait until thread has finished { itksys::SystemTools::Delay(100); } delete this->m_CalculationThread; } + void QmitkImageStatisticsView::CreateQtPartControl(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new Ui::QmitkImageStatisticsViewControls; m_Controls->setupUi(parent); CreateConnections(); m_Controls->m_ErrorMessageLabel->hide(); - m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); + m_Controls->m_StatisticsWidgetStack->setCurrentIndex(0); m_Controls->m_BinSizeFrame->setVisible(false); } } +void QmitkImageStatisticsView::OnPageSuccessfullyLoaded() +{ + berry::IPreferencesService* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); + m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); + + QString styleName = m_StylePref->Get(berry::QtPreferences::QT_STYLE_NAME, ""); + + if (styleName == ":/org.blueberry.ui.qt/darkstyle.qss") + { + this->m_Controls->m_JSHistogram->SendCommand( + "changeTheme('dark')"); + } + else + { + this->m_Controls->m_JSHistogram->SendCommand( + "changeTheme(default)"); + } +} + void QmitkImageStatisticsView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(this->m_Controls->m_ButtonCopyHistogramToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(OnClipboardHistogramButtonClicked()) ); connect( (QObject*)(this->m_Controls->m_ButtonCopyStatisticsToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(OnClipboardStatisticsButtonClicked()) ); connect( (QObject*)(this->m_Controls->m_IgnoreZerosCheckbox), SIGNAL(clicked()),(QObject*) this, SLOT(OnIgnoreZerosCheckboxClicked()) ); connect( (QObject*) this->m_CalculationThread, SIGNAL(finished()),this, SLOT( OnThreadedStatisticsCalculationEnds()),Qt::QueuedConnection); connect( (QObject*) this, SIGNAL(StatisticsUpdate()),this, SLOT( RequestStatisticsUpdate()), Qt::QueuedConnection); connect( (QObject*) this->m_Controls->m_StatisticsTable, SIGNAL(cellDoubleClicked(int,int)),this, SLOT( JumpToCoordinates(int,int)) ); connect((QObject*)(this->m_Controls->m_barRadioButton), SIGNAL(clicked()), (QObject*)(this), SLOT(OnBarRadioButtonSelected())); connect((QObject*)(this->m_Controls->m_lineRadioButton), SIGNAL(clicked()), (QObject*)(this), SLOT(OnLineRadioButtonSelected())); connect( (QObject*) (this->m_Controls->m_HistogramBinSizeSpinbox), SIGNAL(editingFinished()), this, SLOT(OnHistogramBinSizeBoxValueChanged())); connect((QObject*)(this->m_Controls->m_UseDefaultBinSizeBox), SIGNAL(clicked()), (QObject*) this, SLOT(OnDefaultBinSizeBoxChanged())); connect((QObject*)(this->m_Controls->m_ShowSubchartCheckBox), SIGNAL(clicked()), (QObject*) this, SLOT(OnShowSubchartBoxChanged())); + connect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), (QObject*) this, SLOT(OnPageSuccessfullyLoaded())); } } void QmitkImageStatisticsView::OnDefaultBinSizeBoxChanged() { m_Controls->m_BinSizeFrame->setVisible(!m_Controls->m_UseDefaultBinSizeBox->isChecked()); if (m_CalculationThread != NULL){ m_Controls->m_HistogramBinSizeSpinbox->setValue(m_CalculationThread->GetHistogramBinSize()); m_CalculationThread->SetUseDefaultNBins(m_Controls->m_UseDefaultBinSizeBox->isChecked()); } this->UpdateStatistics(); } void QmitkImageStatisticsView::OnShowSubchartBoxChanged() { this->m_Controls->m_JSHistogram->SetAppearance( this->m_Controls->m_lineRadioButton->isChecked(), this->m_Controls->m_ShowSubchartCheckBox->isChecked()); QString useLineChart = "false"; if (this->m_Controls->m_lineRadioButton->isChecked()) useLineChart = "true"; QString showSubchart = "false"; if (this->m_Controls->m_ShowSubchartCheckBox->isChecked()) showSubchart = "true"; this->m_Controls->m_JSHistogram->SendCommand( "ReloadChart(" + useLineChart + "," + showSubchart + ")"); } void QmitkImageStatisticsView::OnBarRadioButtonSelected() { this->m_Controls->m_JSHistogram->TransformView("bar"); } void QmitkImageStatisticsView::OnLineRadioButtonSelected() { this->m_Controls->m_JSHistogram->TransformView("line"); } void QmitkImageStatisticsView::PartClosed(const berry::IWorkbenchPartReference::Pointer& ) { } void QmitkImageStatisticsView::OnTimeChanged(const itk::EventObject& e) { if (this->m_SelectedDataNodes.isEmpty() || this->m_SelectedImage == NULL) return; const mitk::SliceNavigationController::GeometryTimeEvent* timeEvent = dynamic_cast(&e); assert(timeEvent != NULL); unsigned int timestep = timeEvent->GetPos(); if (this->m_SelectedImage->GetTimeSteps() > 1) { for (int x = 0; x < this->m_Controls->m_StatisticsTable->columnCount(); x++) { for (int y = 0; y < this->m_Controls->m_StatisticsTable->rowCount(); y++) { QTableWidgetItem* item = this->m_Controls->m_StatisticsTable->item(y, x); if (item == NULL) break; if (x == timestep) { item->setBackgroundColor(Qt::yellow); } else { if (y % 2 == 0) item->setBackground(this->m_Controls->m_StatisticsTable->palette().base()); else item->setBackground(this->m_Controls->m_StatisticsTable->palette().alternateBase()); } } } this->m_Controls->m_StatisticsTable->viewport()->update(); } if ((this->m_SelectedImage->GetTimeSteps() == 1 && timestep == 0) || this->m_SelectedImage->GetTimeSteps() > 1) { // display histogram for selected timestep this->m_Controls->m_JSHistogram->ClearHistogram(); QmitkImageStatisticsCalculationThread::HistogramType::Pointer histogram = this->m_CalculationThread->GetTimeStepHistogram(timestep); if (histogram.IsNotNull()) { bool closedFigure = this->m_CalculationThread->GetStatisticsUpdateSuccessFlag(); if ( closedFigure ) { this->m_Controls->m_JSHistogram->ComputeHistogram( - histogram.GetPointer(), this->m_Controls->m_lineRadioButton->isChecked(), this->m_Controls->m_ShowSubchartCheckBox->isChecked() ); + histogram.GetPointer(), this->m_Controls->m_lineRadioButton->isChecked(), this->m_Controls->m_ShowSubchartCheckBox->isChecked()); } //this->m_Controls->m_JSHistogram->ComputeHistogram(histogram.GetPointer()); /*else { m_Controls->m_JSHistogram->ComputeIntensityProfile(timestep, true); }*/ // this->m_Controls->m_JSHistogram->SignalGraphChanged(); // hacky way to make sure the protected SignalGraphChanged() is called //if (this->m_Controls->m_JSHistogram->GetUseLineGraph()) //{ //this->m_Controls->m_JSHistogram->OnBarRadioButtonSelected(); //this->m_Controls->m_JSHistogram->OnLineRadioButtonSelected(); //} //else //{ //this->m_Controls->m_JSHistogram->OnLineRadioButtonSelected(); //this->m_Controls->m_JSHistogram->OnBarRadioButtonSelected(); //} } } } void QmitkImageStatisticsView::JumpToCoordinates(int row ,int col) { if(m_SelectedDataNodes.isEmpty()) { MITK_WARN("QmitkImageStatisticsView") << "No data node selected for statistics calculation." ; return; } mitk::Point3D world; if (row==4 && !m_WorldMinList.empty()) world = m_WorldMinList[col]; else if (row==3 && !m_WorldMaxList.empty()) world = m_WorldMaxList[col]; else return; mitk::IRenderWindowPart* part = this->GetRenderWindowPart(); if (part) { part->GetQmitkRenderWindow("axial")->GetSliceNavigationController()->SelectSliceByPoint(world); part->GetQmitkRenderWindow("sagittal")->GetSliceNavigationController()->SelectSliceByPoint(world); part->GetQmitkRenderWindow("coronal")->GetSliceNavigationController()->SelectSliceByPoint(world); mitk::SliceNavigationController::GeometryTimeEvent timeEvent(this->m_SelectedImage->GetTimeGeometry(), col); part->GetQmitkRenderWindow("axial")->GetSliceNavigationController()->SetGeometryTime(timeEvent); } } void QmitkImageStatisticsView::OnIgnoreZerosCheckboxClicked() { emit StatisticsUpdate(); } void QmitkImageStatisticsView::OnClipboardHistogramButtonClicked() { if ( m_CurrentStatisticsValid && !( m_SelectedPlanarFigure != NULL)) { const unsigned int t = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->GetPos(); typedef mitk::ImageStatisticsCalculator::HistogramType HistogramType; const HistogramType *histogram = this->m_CalculationThread->GetTimeStepHistogram(t).GetPointer(); QString clipboard( "Measurement \t Frequency\n" ); for ( HistogramType::ConstIterator it = histogram->Begin(); it != histogram->End(); ++it ) { if( m_Controls->m_HistogramBinSizeSpinbox->value() == 1.0) { clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( it.GetMeasurementVector()[0], 0, 'f', 0 ) .arg( it.GetFrequency() ); } else { clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( it.GetMeasurementVector()[0], 0, 'f', 2 ) .arg( it.GetFrequency() ); } } QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); } // If a (non-closed) PlanarFigure is selected, display a line profile widget else if ( m_CurrentStatisticsValid && (m_SelectedPlanarFigure != NULL )) { /*auto intensity = m_Controls->m_JSHistogram->GetFrequency(); auto pixel = m_Controls->m_JSHistogram->GetMeasurement(); QString clipboard( "Pixel \t Intensity\n" ); auto j = pixel.begin(); for (auto i = intensity.begin(); i < intensity.end(); i++) { assert(j != pixel.end()); clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( (*j).toString()) .arg( (*i).toString()); j++; } QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); */ } else { QApplication::clipboard()->clear(); } } void QmitkImageStatisticsView::OnClipboardStatisticsButtonClicked() { QLocale tempLocal; QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); if ( m_CurrentStatisticsValid && !( m_SelectedPlanarFigure != NULL)) { const std::vector &statistics = this->m_CalculationThread->GetStatisticsData(); // Set time borders for for loop ;) unsigned int startT, endT; if(this->m_Controls->m_CheckBox4dCompleteTable->checkState()==Qt::CheckState::Unchecked) { startT = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()-> GetPos(); endT = startT+1; } else { startT = 0; endT = statistics.size(); } QVector< QVector > statisticsTable; QStringList headline; // Create Headline headline << " " << "Mean" << "Median" << "StdDev" << "RMS" << "Max" << "Min" << "NumberOfVoxels" << "Skewness" << "Kurtosis" << "Uniformity" << "Entropy" << "MPP" << "UPP" << "V [mm³]"; for(int i=0;i row; row.append(headline.at(i)); statisticsTable.append(row); } // Fill Table for(unsigned int t=startT;tGetMean()) << QString::number(statistics[t]->GetMedian()) << QString::number(statistics[t]->GetStd()) << QString::number(statistics[t]->GetRMS()) << QString::number(statistics[t]->GetMax()) << QString::number(statistics[t]->GetMin()) << QString::number(statistics[t]->GetN()) << QString::number(statistics[t]->GetSkewness()) << QString::number(statistics[t]->GetKurtosis()) << QString::number(statistics[t]->GetUniformity()) << QString::number(statistics[t]->GetEntropy()) << QString::number(statistics[t]->GetMPP()) << QString::number(statistics[t]->GetUPP()) << QString::number(m_Controls->m_StatisticsTable->item(7, 0)->data(Qt::DisplayRole).toDouble()); for(int z=0;zsetText(clipboard, QClipboard::Clipboard); } else { QApplication::clipboard()->clear(); } QLocale::setDefault(tempLocal); } void QmitkImageStatisticsView::OnSelectionChanged( berry::IWorkbenchPart::Pointer /*part*/, const QList &selectedNodes ) { if (this->m_Visible) { this->SelectionChanged( selectedNodes ); } else { this->m_DataNodeSelectionChanged = true; } } void QmitkImageStatisticsView::SelectionChanged(const QList &selectedNodes) { if( this->m_StatisticsUpdatePending ) { this->m_DataNodeSelectionChanged = true; return; // not ready for new data now! } if (selectedNodes.size() == this->m_SelectedDataNodes.size()) { int i = 0; for (; i < selectedNodes.size(); ++i) { if (selectedNodes.at(i) != this->m_SelectedDataNodes.at(i)) { break; } } // node selection did not change if (i == selectedNodes.size()) return; } //reset the feature image and image mask field m_Controls->m_SelectedFeatureImageLabel->setText("None"); m_Controls->m_SelectedMaskLabel->setText("None"); this->ReinitData(); if (selectedNodes.isEmpty()) { m_Controls->m_JSHistogram->ClearHistogram(); m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); // m_Controls->m_HistogramBinSizeLabel->setEnabled(true); m_Controls->m_InfoLabel->setText(QString("")); // m_Controls->horizontalLayout_3->setEnabled(false); m_Controls->groupBox->setEnabled(false); m_Controls->groupBox_3->setEnabled(false); } else { // m_Controls->horizontalLayout_3->setEnabled(true); m_Controls->groupBox->setEnabled(true); m_Controls->groupBox_3->setEnabled(true); } if(selectedNodes.size() == 1 || selectedNodes.size() == 2) { bool isBinary = false; selectedNodes.value(0)->GetBoolProperty("binary",isBinary); mitk::NodePredicateDataType::Pointer isLabelSet = mitk::NodePredicateDataType::New("LabelSetImage"); isBinary |= isLabelSet->CheckNode(selectedNodes.value(0)); if(isBinary) { m_Controls->m_JSHistogram->ClearHistogram(); m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); // m_Controls->m_HistogramBinSizeLabel->setEnabled(true); m_Controls->m_InfoLabel->setText(QString("")); } for (int i= 0; i< selectedNodes.size(); ++i) { this->m_SelectedDataNodes.push_back(selectedNodes.at(i)); } this->m_DataNodeSelectionChanged = false; this->m_Controls->m_ErrorMessageLabel->setText( "" ); this->m_Controls->m_ErrorMessageLabel->hide(); emit StatisticsUpdate(); } else { this->m_DataNodeSelectionChanged = false; } } void QmitkImageStatisticsView::ReinitData() { while( this->m_CalculationThread->isRunning()) // wait until thread has finished { itksys::SystemTools::Delay(100); } if(this->m_SelectedImage != NULL) { this->m_SelectedImage->RemoveObserver( this->m_ImageObserverTag); this->m_SelectedImage = NULL; } if(this->m_SelectedImageMask != NULL) { this->m_SelectedImageMask->RemoveObserver( this->m_ImageMaskObserverTag); this->m_SelectedImageMask = NULL; } if(this->m_SelectedPlanarFigure != NULL) { this->m_SelectedPlanarFigure->RemoveObserver( this->m_PlanarFigureObserverTag); this->m_SelectedPlanarFigure = NULL; } this->m_SelectedDataNodes.clear(); this->m_StatisticsUpdatePending = false; m_Controls->m_ErrorMessageLabel->setText( "" ); m_Controls->m_ErrorMessageLabel->hide(); this->InvalidateStatisticsTableView(); m_Controls->m_JSHistogram->ClearHistogram(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); } void QmitkImageStatisticsView::OnThreadedStatisticsCalculationEnds() { std::stringstream message; message << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->hide(); this->WriteStatisticsToGUI(); } void QmitkImageStatisticsView::UpdateStatistics() { mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if ( renderPart == NULL ) { this->m_StatisticsUpdatePending = false; return; } m_WorldMinList.clear(); m_WorldMaxList.clear(); // classify selected nodes mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image"); mitk::NodePredicateDataType::Pointer isLabelSet = mitk::NodePredicateDataType::New("LabelSetImage"); mitk::NodePredicateOr::Pointer imagePredicate = mitk::NodePredicateOr::New(isImage, isLabelSet); std::string maskName = std::string(); std::string maskType = std::string(); std::string featureImageName = std::string(); unsigned int maskDimension = 0; // reset data from last run ITKCommandType::Pointer changeListener = ITKCommandType::New(); changeListener->SetCallbackFunction( this, &QmitkImageStatisticsView::SelectedDataModified ); mitk::DataNode::Pointer planarFigureNode; for( int i= 0 ; i < this->m_SelectedDataNodes.size(); ++i) { mitk::PlanarFigure::Pointer planarFig = dynamic_cast(this->m_SelectedDataNodes.at(i)->GetData()); if( imagePredicate->CheckNode(this->m_SelectedDataNodes.at(i)) ) { bool isMask = false; this->m_SelectedDataNodes.at(i)->GetPropertyValue("binary", isMask); isMask |= isLabelSet->CheckNode(this->m_SelectedDataNodes.at(i)); if( this->m_SelectedImageMask == NULL && isMask) { this->m_SelectedImageMask = dynamic_cast(this->m_SelectedDataNodes.at(i)->GetData()); this->m_ImageMaskObserverTag = this->m_SelectedImageMask->AddObserver(itk::ModifiedEvent(), changeListener); maskName = this->m_SelectedDataNodes.at(i)->GetName(); maskType = m_SelectedImageMask->GetNameOfClass(); maskDimension = 3; } else if( !isMask ) { if(this->m_SelectedImage == NULL) { this->m_SelectedImage = static_cast(this->m_SelectedDataNodes.at(i)->GetData()); this->m_ImageObserverTag = this->m_SelectedImage->AddObserver(itk::ModifiedEvent(), changeListener); } featureImageName = this->m_SelectedDataNodes.at(i)->GetName(); } } else if (planarFig.IsNotNull()) { if(this->m_SelectedPlanarFigure == NULL) { this->m_SelectedPlanarFigure = planarFig; this->m_PlanarFigureObserverTag = this->m_SelectedPlanarFigure->AddObserver(mitk::EndInteractionPlanarFigureEvent(), changeListener); maskName = this->m_SelectedDataNodes.at(i)->GetName(); maskType = this->m_SelectedPlanarFigure->GetNameOfClass(); maskDimension = 2; planarFigureNode = m_SelectedDataNodes.at(i); } } else { std::stringstream message; message << "" << "Invalid data node type!" << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); } } if(maskName == "") { maskName = "None"; maskType = ""; maskDimension = 0; } if(featureImageName == "") { featureImageName = "None"; } if (m_SelectedPlanarFigure != NULL && m_SelectedImage == NULL) { mitk::DataStorage::SetOfObjects::ConstPointer parentSet = this->GetDataStorage()->GetSources(planarFigureNode); for (int i=0; iSize(); i++) { mitk::DataNode::Pointer node = parentSet->ElementAt(i); if( imagePredicate->CheckNode(node) ) { bool isMask = false; node->GetPropertyValue("binary", isMask); isMask |= isLabelSet->CheckNode(node); if( !isMask ) { if(this->m_SelectedImage == NULL) { this->m_SelectedImage = static_cast(node->GetData()); this->m_ImageObserverTag = this->m_SelectedImage->AddObserver(itk::ModifiedEvent(), changeListener); } } } } } unsigned int timeStep = renderPart->GetTimeNavigationController()->GetTime()->GetPos(); if ( m_SelectedImage != NULL && m_SelectedImage->IsInitialized()) { // Check if a the selected image is a multi-channel image. If yes, statistics // cannot be calculated currently. if ( m_SelectedImage->GetPixelType().GetNumberOfComponents() > 1 ) { std::stringstream message; message << "Multi-component images not supported."; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_Controls->m_JSHistogram->ClearHistogram(); m_CurrentStatisticsValid = false; this->m_StatisticsUpdatePending = false; m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); // m_Controls->m_HistogramBinSizeLabel->setEnabled(true); m_Controls->m_InfoLabel->setText(QString("")); return; } std::stringstream maskLabel; maskLabel << maskName; if ( maskDimension > 0 ) { maskLabel << " [" << maskDimension << "D " << maskType << "]"; } m_Controls->m_SelectedMaskLabel->setText( maskLabel.str().c_str() ); m_Controls->m_SelectedFeatureImageLabel->setText(featureImageName.c_str()); // check time step validity if(m_SelectedImage->GetDimension() <= 3 && timeStep > m_SelectedImage->GetDimension(3)-1) { timeStep = m_SelectedImage->GetDimension(3)-1; } // Add the used mask time step to the mask label so the user knows which mask time step was used // if the image time step is bigger than the total number of mask time steps (see // ImageStatisticsCalculator::ExtractImageAndMask) if (m_SelectedImageMask != NULL) { unsigned int maskTimeStep = timeStep; if (maskTimeStep >= m_SelectedImageMask->GetTimeSteps()) { maskTimeStep = m_SelectedImageMask->GetTimeSteps() - 1; } m_Controls->m_SelectedMaskLabel->setText(m_Controls->m_SelectedMaskLabel->text() + QString(" (t=") + QString::number(maskTimeStep) + QString(")")); } //// initialize thread and trigger it this->m_CalculationThread->SetIgnoreZeroValueVoxel( m_Controls->m_IgnoreZerosCheckbox->isChecked() ); this->m_CalculationThread->Initialize( m_SelectedImage, m_SelectedImageMask, m_SelectedPlanarFigure ); this->m_CalculationThread->SetTimeStep( timeStep ); std::stringstream message; message << "Calculating statistics..."; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); try { // Compute statistics // this->m_CalculationThread->SetUseDefaultBinSize(m_Controls->m_UseDefaultBinSizeBox->isChecked()); this->m_CalculationThread->start(); } catch ( const mitk::Exception& e) { std::stringstream message; message << "" << e.GetDescription() << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->m_StatisticsUpdatePending = false; } catch ( const std::runtime_error &e ) { // In case of exception, print error message on GUI std::stringstream message; message << "" << e.what() << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->m_StatisticsUpdatePending = false; } catch ( const std::exception &e ) { MITK_ERROR << "Caught exception: " << e.what(); // In case of exception, print error message on GUI std::stringstream message; message << "Error! Unequal Dimensions of Image and Segmentation. No recompute possible "; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->m_StatisticsUpdatePending = false; } } else { this->m_StatisticsUpdatePending = false; } } void QmitkImageStatisticsView::SelectedDataModified() { if( !m_StatisticsUpdatePending ) { emit StatisticsUpdate(); } } void QmitkImageStatisticsView::NodeRemoved(const mitk::DataNode *node) { while(this->m_CalculationThread->isRunning()) // wait until thread has finished { itksys::SystemTools::Delay(100); } if (node->GetData() == m_SelectedImage) { m_SelectedImage = NULL; } } void QmitkImageStatisticsView::RequestStatisticsUpdate() { if ( !m_StatisticsUpdatePending ) { if(this->m_DataNodeSelectionChanged) { this->SelectionChanged(this->GetCurrentSelection()); } else { this->m_StatisticsUpdatePending = true; this->UpdateStatistics(); } } if (this->GetRenderWindowPart()) this->GetRenderWindowPart()->RequestUpdate(); } void QmitkImageStatisticsView::OnHistogramBinSizeBoxValueChanged() { if (m_Controls->m_HistogramBinSizeSpinbox->value() != m_HistogramBinSize) { m_HistogramBinSize = m_Controls->m_HistogramBinSizeSpinbox->value(); this->m_CalculationThread->SetHistogramBinSize(m_Controls->m_HistogramBinSizeSpinbox->value()); this->UpdateStatistics(); } } void QmitkImageStatisticsView::WriteStatisticsToGUI() { disconnect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), 0, 0); + connect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), (QObject*) this, SLOT(OnPageSuccessfullyLoaded())); m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); // m_Controls->m_HistogramBinSizeLabel->setEnabled(true); m_Controls->m_InfoLabel->setText(QString("")); if(m_DataNodeSelectionChanged) { this->m_StatisticsUpdatePending = false; this->RequestStatisticsUpdate(); return; // stop visualization of results and calculate statistics of new selection } if ( this->m_CalculationThread->GetStatisticsUpdateSuccessFlag()) { if ( this->m_CalculationThread->GetStatisticsChangedFlag() ) { // Do not show any error messages m_Controls->m_ErrorMessageLabel->hide(); m_CurrentStatisticsValid = true; } if (m_Controls->m_barRadioButton->isChecked()) { //m_Controls->m_JSHistogram->OnBarRadioButtonSelected(); } m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_Controls->m_HistogramBinSizeSpinbox->setValue( this->m_CalculationThread->GetHistogramBinSize() ); //m_Controls->m_JSHistogram->ComputeHistogram( this->m_CalculationThread->GetTimeStepHistogram(this->m_CalculationThread->GetTimeStep()).GetPointer() ); this->FillStatisticsTableView( this->m_CalculationThread->GetStatisticsData(), this->m_CalculationThread->GetStatisticsImage()); m_CurrentStatisticsValid = true; } else { m_Controls->m_SelectedMaskLabel->setText( "None" ); m_Controls->m_ErrorMessageLabel->setText( m_CalculationThread->GetLastErrorMessage().c_str() ); m_Controls->m_ErrorMessageLabel->show(); // Clear statistics and histogram this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); //m_Controls->m_JSHistogram->clearHistogram(); m_CurrentStatisticsValid = false; // If a (non-closed) PlanarFigure is selected, display a line profile widget if ( m_SelectedPlanarFigure != NULL ) { // Check if the (closed) planar figure is out of bounds and so no image mask could be calculated--> Intensity Profile can not be calculated bool outOfBounds = false; if ( m_SelectedPlanarFigure->IsClosed() && m_SelectedImageMask == NULL) { outOfBounds = true; std::stringstream message; message << "Planar figure is on a rotated image plane or outside the image bounds."; m_Controls->m_InfoLabel->setText(message.str().c_str()); } // check whether PlanarFigure is initialized const mitk::PlaneGeometry *planarFigurePlaneGeometry = m_SelectedPlanarFigure->GetPlaneGeometry(); if ( !(planarFigurePlaneGeometry == NULL || outOfBounds)) { unsigned int timeStep = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->GetPos(); m_Controls->m_JSHistogram->SetImage(this->m_CalculationThread->GetStatisticsImage()); m_Controls->m_JSHistogram->SetPlanarFigure(m_SelectedPlanarFigure); connect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), (QObject*) this, SLOT(OnLineRadioButtonSelected())); m_Controls->m_JSHistogram->ComputeIntensityProfile(timeStep, true); //m_Controls->m_JSHistogram->ComputeIntensityProfile(timeStep); //this->ComputeIntensityProfile(m_SelectedPlanarFigure, this->m_CalculationThread->GetStatisticsImage(), timeStep, true); m_Controls->m_lineRadioButton->setChecked(true); m_Controls->m_lineRadioButton->setEnabled(false); m_Controls->m_barRadioButton->setEnabled(false); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(false); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(false); // m_Controls->m_HistogramBinSizeLabel->setEnabled(false); this->FillLinearProfileStatisticsTableView( this->m_CalculationThread->GetStatisticsImage() ); std::stringstream message; message << "Only linegraph available for an intensity profile!"; m_Controls->m_InfoLabel->setText(message.str().c_str()); m_CurrentStatisticsValid = true; } else { // Clear statistics, histogram, and GUI this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_Controls->m_JSHistogram->ClearHistogram(); m_CurrentStatisticsValid = false; m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_SelectedMaskLabel->setText( "None" ); this->m_StatisticsUpdatePending = false; m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); // m_Controls->m_HistogramBinSizeLabel->setEnabled(true); if (!outOfBounds) m_Controls->m_InfoLabel->setText(QString("")); return; // Sebastian Wirkert: would suggest to remove this return, since it is an artifact of previous // code architecture. However, removing it will cause m_StatisticsUpdatePending to be set to false // in case of invalid statistics which it previously was not. } } } + berry::IPreferencesService* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); + m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); + this->m_StatisticsUpdatePending = false; } void QmitkImageStatisticsView::FillStatisticsTableView( const std::vector &s, const mitk::Image *image ) { this->m_Controls->m_StatisticsTable->setColumnCount(image->GetTimeSteps()); this->m_Controls->m_StatisticsTable->horizontalHeader()->setVisible(image->GetTimeSteps() > 1); // Set Checkbox for complete copy of statistic table if(image->GetTimeSteps()>1) { this->m_Controls->m_CheckBox4dCompleteTable->setEnabled(true); } else { this->m_Controls->m_CheckBox4dCompleteTable->setEnabled(false); this->m_Controls->m_CheckBox4dCompleteTable->setChecked(false); } int decimals = 2; mitk::PixelType doublePix = mitk::MakeScalarPixelType< double >(); mitk::PixelType floatPix = mitk::MakeScalarPixelType< float >(); if (image->GetPixelType()==doublePix || image->GetPixelType()==floatPix) { decimals = 5; } for (unsigned int t = 0; t < image->GetTimeSteps(); t++) { this->m_Controls->m_StatisticsTable->setHorizontalHeaderItem(t, new QTableWidgetItem(QString::number(t))); if (s[t]->GetMaxIndex().size()==3) { mitk::Point3D index, max, min; index[0] = s[t]->GetMaxIndex()[0]; index[1] = s[t]->GetMaxIndex()[1]; index[2] = s[t]->GetMaxIndex()[2]; m_SelectedImage->GetGeometry()->IndexToWorld(index, max); this->m_WorldMaxList.push_back(max); index[0] = s[t]->GetMinIndex()[0]; index[1] = s[t]->GetMinIndex()[1]; index[2] = s[t]->GetMinIndex()[2]; m_SelectedImage->GetGeometry()->IndexToWorld(index, min); this->m_WorldMinList.push_back(min); } typedef mitk::ImageStatisticsCalculator::StatisticsContainer::RealType RealType; RealType maxVal = std::numeric_limits::max(); this->m_Controls->m_StatisticsTable->setItem( 0, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetMean(), 0, 'f', decimals) ) ); this->m_Controls->m_StatisticsTable->setItem( 1, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetMedian(), 0, 'f', decimals) ) ); this->m_Controls->m_StatisticsTable->setItem( 2, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetStd(), 0, 'f', decimals) ) ); this->m_Controls->m_StatisticsTable->setItem( 3, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetRMS(), 0, 'f', decimals) ) ); QString max; max.append(QString("%1").arg(s[t]->GetMax(), 0, 'f', decimals)); max += " ("; for (int i=0; iGetMaxIndex().size(); i++) { max += QString::number(s[t]->GetMaxIndex()[i]); if (iGetMaxIndex().size()-1) max += ","; } max += ")"; this->m_Controls->m_StatisticsTable->setItem( 4, t, new QTableWidgetItem( max ) ); QString min; min.append(QString("%1").arg(s[t]->GetMin(), 0, 'f', decimals)); min += " ("; for (int i=0; iGetMinIndex().size(); i++) { min += QString::number(s[t]->GetMinIndex()[i]); if (iGetMinIndex().size()-1) min += ","; } min += ")"; this->m_Controls->m_StatisticsTable->setItem( 5, t, new QTableWidgetItem( min ) ); this->m_Controls->m_StatisticsTable->setItem( 6, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetN()) ) ); const mitk::BaseGeometry *geometry = image->GetGeometry(); if ( geometry != NULL ) { const mitk::Vector3D &spacing = image->GetGeometry()->GetSpacing(); double volume = spacing[0] * spacing[1] * spacing[2] * (double) s[t]->GetN(); this->m_Controls->m_StatisticsTable->setItem( 7, t, new QTableWidgetItem( QString("%1").arg(volume, 0, 'f', decimals) ) ); } else { this->m_Controls->m_StatisticsTable->setItem( 7, t, new QTableWidgetItem( "NA" ) ); } //statistics of higher order should have 5 decimal places because they used to be very small this->m_Controls->m_StatisticsTable->setItem( 8, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetSkewness(), 0, 'f', 5) ) ); this->m_Controls->m_StatisticsTable->setItem( 9, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetKurtosis(), 0, 'f', 5) ) ); this->m_Controls->m_StatisticsTable->setItem( 10, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetUniformity(), 0, 'f', 5) ) ); this->m_Controls->m_StatisticsTable->setItem( 11, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetEntropy(), 0, 'f', 5) ) ); this->m_Controls->m_StatisticsTable->setItem( 12, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetMPP(), 0, 'f', decimals) ) ); this->m_Controls->m_StatisticsTable->setItem( 13, t, new QTableWidgetItem( QString("%1").arg(s[t]->GetUPP(), 0, 'f', 5) ) ); } this->m_Controls->m_StatisticsTable->resizeColumnsToContents(); int height = STAT_TABLE_BASE_HEIGHT; if (this->m_Controls->m_StatisticsTable->horizontalHeader()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalHeader()->height(); if (this->m_Controls->m_StatisticsTable->horizontalScrollBar()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalScrollBar()->height(); this->m_Controls->m_StatisticsTable->setMinimumHeight(height); // make sure the current timestep's column is highlighted (and the correct histogram is displayed) unsigned int t = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()-> GetPos(); mitk::SliceNavigationController::GeometryTimeEvent timeEvent(this->m_SelectedImage->GetTimeGeometry(), t); this->OnTimeChanged(timeEvent); t = std::min(image->GetTimeSteps() - 1, t); // See bug 18340 /*QString hotspotMean; hotspotMean.append(QString("%1").arg(s[t].GetHotspotStatistics().GetMean(), 0, 'f', decimals)); hotspotMean += " ("; for (int i=0; im_Controls->m_StatisticsTable->setItem( 7, t, new QTableWidgetItem( hotspotMean ) ); QString hotspotMax; hotspotMax.append(QString("%1").arg(s[t].GetHotspotStatistics().GetMax(), 0, 'f', decimals)); hotspotMax += " ("; for (int i=0; im_Controls->m_StatisticsTable->setItem( 8, t, new QTableWidgetItem( hotspotMax ) ); QString hotspotMin; hotspotMin.append(QString("%1").arg(s[t].GetHotspotStatistics().GetMin(), 0, 'f', decimals)); hotspotMin += " ("; for (int i=0; im_Controls->m_StatisticsTable->setItem( 9, t, new QTableWidgetItem( hotspotMin ) );*/ } std::vector QmitkImageStatisticsView::CalculateStatisticsForPlanarFigure( const mitk::Image *image) { std::vector result; int decimals = 2; mitk::PixelType doublePix = mitk::MakeScalarPixelType< double >(); mitk::PixelType floatPix = mitk::MakeScalarPixelType< float >(); if (image->GetPixelType()==doublePix || image->GetPixelType()==floatPix) { decimals = 5; } mitk::ImageStatisticsCalculator::StatisticsContainer::Pointer stats = m_Controls->m_JSHistogram->GetStatistics(); typedef mitk::ImageStatisticsCalculator::StatisticsContainer::RealType RealType; RealType maxVal = std::numeric_limits::max(); if (stats->GetMean() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetMean(), 0, 'f', decimals)); } if (stats->GetMedian() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetMedian(), 0, 'f', decimals)); } if (stats->GetStd() == maxVal) { result.push_back(QString("NA")); } else { result.push_back( QString("%1").arg( stats->GetStd(), 0, 'f', decimals)); } if (stats->GetRMS() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg( stats->GetRMS(), 0, 'f', decimals)); } if (stats->GetMax() == maxVal) { result.push_back(QString("NA")); } else { QString max; max.append(QString("%1").arg(stats->GetMax(), 0, 'f', decimals)); result.push_back(max); } if (stats->GetMin() == maxVal) { result.push_back(QString("NA")); } else { QString min; min.append(QString("%1").arg(stats->GetMin(), 0, 'f', decimals)); result.push_back(min); } if (stats->GetN() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetN())); } result.push_back(QString("NA")); //statistics of higher order should have 5 decimal places because they used to be very small if (stats->GetSkewness() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetSkewness(), 0, 'f', 5 )); } if (stats->GetKurtosis() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetKurtosis(), 0, 'f', 5) ); } if (stats->GetUniformity() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetUniformity(), 0, 'f', 5) ); } if (stats->GetEntropy() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetEntropy(), 0, 'f', 5) ); } if (stats->GetMPP() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetMPP(), 0, 'f', decimals) ); } if (stats->GetUPP() == maxVal) { result.push_back(QString("NA")); } else { result.push_back(QString("%1").arg(stats->GetUPP(), 0, 'f', 5) ); } return result; } void QmitkImageStatisticsView::FillLinearProfileStatisticsTableView( const mitk::Image *image ) { this->m_Controls->m_StatisticsTable->setColumnCount(1); this->m_Controls->m_StatisticsTable->horizontalHeader()->setVisible(false); m_PlanarFigureStatistics = this->CalculateStatisticsForPlanarFigure(image); for (int i = 0; i< m_PlanarFigureStatistics.size(); i++) { this->m_Controls->m_StatisticsTable->setItem( i, 0, new QTableWidgetItem(m_PlanarFigureStatistics[i] )); } this->m_Controls->m_StatisticsTable->resizeColumnsToContents(); int height = STAT_TABLE_BASE_HEIGHT; if (this->m_Controls->m_StatisticsTable->horizontalHeader()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalHeader()->height(); if (this->m_Controls->m_StatisticsTable->horizontalScrollBar()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalScrollBar()->height(); this->m_Controls->m_StatisticsTable->setMinimumHeight(height); } void QmitkImageStatisticsView::InvalidateStatisticsTableView() { this->m_Controls->m_StatisticsTable->horizontalHeader()->setVisible(false); this->m_Controls->m_StatisticsTable->setColumnCount(1); for ( unsigned int i = 0; i < this->m_Controls->m_StatisticsTable->rowCount(); ++i ) { { this->m_Controls->m_StatisticsTable->setItem( i, 0, new QTableWidgetItem( "NA" ) ); } } this->m_Controls->m_StatisticsTable->setMinimumHeight(STAT_TABLE_BASE_HEIGHT); } void QmitkImageStatisticsView::Activated() { } void QmitkImageStatisticsView::Deactivated() { } void QmitkImageStatisticsView::Visible() { m_Visible = true; mitk::IRenderWindowPart* renderWindow = GetRenderWindowPart(); if (renderWindow) { itk::ReceptorMemberCommand::Pointer cmdTimeEvent = itk::ReceptorMemberCommand::New(); cmdTimeEvent->SetCallbackFunction(this, &QmitkImageStatisticsView::OnTimeChanged); // It is sufficient to add the observer to the axial render window since the GeometryTimeEvent // is always triggered by all views. m_TimeObserverTag = renderWindow->GetQmitkRenderWindow("axial")-> GetSliceNavigationController()-> AddObserver(mitk::SliceNavigationController::GeometryTimeEvent(NULL, 0), cmdTimeEvent); } if (m_DataNodeSelectionChanged) { if (this->IsCurrentSelectionValid()) { this->SelectionChanged(this->GetCurrentSelection()); } else { this->SelectionChanged(this->GetDataManagerSelection()); } m_DataNodeSelectionChanged = false; } } void QmitkImageStatisticsView::Hidden() { m_Visible = false; // The slice navigation controller observer is removed here instead of in the destructor. // If it was called in the destructor, the application would freeze because the view's // destructor gets called after the render windows have been destructed. if ( m_TimeObserverTag != NULL ) { mitk::IRenderWindowPart* renderWindow = GetRenderWindowPart(); if (renderWindow) { renderWindow->GetQmitkRenderWindow("axial")->GetSliceNavigationController()-> RemoveObserver( m_TimeObserverTag ); } m_TimeObserverTag = NULL; } } void QmitkImageStatisticsView::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h index 2770e2a0ac..c5ab3a3cd5 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h @@ -1,197 +1,203 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkImageStatisticsView_H__INCLUDED #define QmitkImageStatisticsView_H__INCLUDED #include "ui_QmitkImageStatisticsViewControls.h" // Qmitk includes #include #include "QmitkStepperAdapter.h" #include "QmitkImageStatisticsCalculationThread.h" #include // mitk includes #include "mitkImageStatisticsCalculator.h" #include "mitkILifecycleAwarePart.h" #include "mitkPlanarLine.h" +#include + /*! \brief QmitkImageStatisticsView is a bundle that allows statistics calculation from images. Three modes are supported: 1. Statistics of one image, 2. Statistics of an image and a segmentation, 3. Statistics of an image and a Planar Figure. The statistics calculation is realized in a seperate thread to keep the gui accessable during calculation. \ingroup Plugins/org.mitk.gui.qt.measurementtoolbox */ class QmitkImageStatisticsView : public QmitkAbstractView, public mitk::ILifecycleAwarePart, public berry::IPartListener { Q_OBJECT private: /*! \ Convenient typedefs */ typedef mitk::DataStorage::SetOfObjects ConstVector; typedef ConstVector::ConstPointer ConstVectorPointer; typedef ConstVector::ConstIterator ConstVectorIterator; typedef std::map< mitk::Image *, mitk::ImageStatisticsCalculator::Pointer > ImageStatisticsMapType; typedef QList SelectedDataNodeVectorType; typedef itk::SimpleMemberCommand< QmitkImageStatisticsView > ITKCommandType; public: /*! \brief default constructor */ QmitkImageStatisticsView(QObject *parent=nullptr, const char *name=nullptr); /*! \brief default destructor */ virtual ~QmitkImageStatisticsView(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent) override; /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief not implemented*/ //bool IsExclusiveFunctionality() const; /*! \brief Is called from the selection mechanism once the data manager selection has changed*/ void OnSelectionChanged( berry::IWorkbenchPart::Pointer part, const QList &nodes ) override; static const std::string VIEW_ID; static const int STAT_TABLE_BASE_HEIGHT; public slots: /** \brief Called when the statistics update is finished, sets the results to GUI.*/ void OnThreadedStatisticsCalculationEnds(); /** \brief Update bin size for histogram resolution. */ void OnHistogramBinSizeBoxValueChanged(); protected slots: /** \brief Saves the histogram to the clipboard */ void OnClipboardHistogramButtonClicked(); /** \brief Saves the statistics to the clipboard */ void OnClipboardStatisticsButtonClicked(); /** \brief Indicates if zeros should be excluded from statistics calculation */ void OnIgnoreZerosCheckboxClicked( ); /** \brief Checks if update is possible and calls StatisticsUpdate() possible */ void RequestStatisticsUpdate(); /** \brief Jump to coordinates stored in the double clicked cell */ void JumpToCoordinates(int row, int col); /** \brief Toogle GUI elements if histogram default bin size checkbox value changed. */ void OnDefaultBinSizeBoxChanged(); void OnShowSubchartBoxChanged(); void OnBarRadioButtonSelected(); void OnLineRadioButtonSelected(); + void OnPageSuccessfullyLoaded(); + signals: /** \brief Method to set the data to the member and start the threaded statistics update */ void StatisticsUpdate(); protected: /** \brief Writes the calculated statistics to the GUI */ void FillStatisticsTableView(const std::vector &s, const mitk::Image *image ); std::vector CalculateStatisticsForPlanarFigure( const mitk::Image *image); void FillLinearProfileStatisticsTableView( const mitk::Image *image ); /** \brief Removes statistics from the GUI */ void InvalidateStatisticsTableView(); /** \brief Recalculate statistics for currently selected image and mask and * update the GUI. */ void UpdateStatistics(); /** \brief Listener for progress events to update progress bar. */ void UpdateProgressBar(); /** \brief Removes any cached images which are no longer referenced elsewhere. */ void RemoveOrphanImages(); /** \brief Computes an Intensity Profile along line and updates the histogram widget with it. */ void ComputeIntensityProfile( mitk::PlanarLine* line ); /** \brief Removes all Observers to images, masks and planar figures and sets corresponding members to zero */ void ClearObservers(); void Activated() override; void Deactivated() override; void Visible() override; void Hidden() override; void SetFocus() override; /** \brief Method called when itkModifiedEvent is called by selected data. */ void SelectedDataModified(); /** \brief Method called when the data manager selection changes */ void SelectionChanged(const QList &selectedNodes); /** \brief Method called to remove old selection when a new selection is present */ void ReinitData(); /** \brief writes the statistics to the gui*/ void WriteStatisticsToGUI(); void NodeRemoved(const mitk::DataNode *node) override; /** \brief Is called right before the view closes (before the destructor) */ virtual void PartClosed(const berry::IWorkbenchPartReference::Pointer& ) override; /** \brief Is called from the image navigator once the time step has changed */ void OnTimeChanged( const itk::EventObject& ); /** \brief Required for berry::IPartListener */ virtual Events::Types GetPartEventTypes() const override { return Events::CLOSED; } // member variables Ui::QmitkImageStatisticsViewControls *m_Controls; // if you have a planar figure selected, the statistics values will be saved in this one. std::vector m_PlanarFigureStatistics; QmitkImageStatisticsCalculationThread* m_CalculationThread; QmitkStepperAdapter* m_TimeStepperAdapter; unsigned int m_CurrentTime; QString m_Clipboard; // Image and mask data mitk::Image* m_SelectedImage; mitk::Image* m_SelectedImageMask; mitk::PlanarFigure* m_SelectedPlanarFigure; // observer tags long m_ImageObserverTag; long m_ImageMaskObserverTag; long m_PlanarFigureObserverTag; long m_TimeObserverTag; SelectedDataNodeVectorType m_SelectedDataNodes; bool m_CurrentStatisticsValid; bool m_StatisticsUpdatePending; bool m_StatisticsIntegrationPending; bool m_DataNodeSelectionChanged; bool m_Visible; double m_HistogramBinSize; std::vector m_WorldMinList; std::vector m_WorldMaxList; + + berry::IPreferences::Pointer m_StylePref; }; #endif // QmitkImageStatisticsView_H__INCLUDED diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsViewControls.ui.autosave b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsViewControls.ui.autosave new file mode 100644 index 0000000000..2d4b3edae3 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsViewControls.ui.autosave @@ -0,0 +1,643 @@ + + + QmitkImageStatisticsViewControls + + + true + + + + 0 + 0 + 548 + 800 + + + + Form + + + + + + + + + 0 + 0 + + + + Qt::LeftToRight + + + Feature Image: + + + + + + + + 0 + 0 + + + + None + + + + + + + + 0 + 0 + + + + Mask: + + + + + + + + 0 + 0 + + + + None + + + -1 + + + + + + + + 0 + 0 + + + + color: rgb(255, 0, 0); + + + Error Message + + + Qt::AutoText + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + Ignore zero-valued voxels + + + + + + + false + + + Statistics + + + + 9 + + + 9 + + + 9 + + + + + + 100 + 180 + + + + + 16777215 + 16777215 + + + + Qt::ScrollBarAsNeeded + + + Qt::ScrollBarAsNeeded + + + true + + + QAbstractItemView::NoEditTriggers + + + true + + + true + + + Qt::DotLine + + + false + + + 14 + + + 1 + + + false + + + false + + + 80 + + + true + + + 80 + + + false + + + true + + + true + + + false + + + 25 + + + 25 + + + false + + + false + + + + Mean + + + + + Median + + + + + StdDev + + + + + RMS + + + + + Max + + + + + Min + + + + + N + + + + + V (mm³) + + + + + Skewness + + + + + Kurtosis + + + + + Uniformity + + + + + Entropy + + + + + MPP + + + + + UPP + + + + + 0 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Copy to Clipboard + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + false + + + copy complete table + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + false + + + + 400 + 450 + + + + Histogram + + + false + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Plot + + + + + + + + + 0 + 0 + + + + + + + Barchart + + + true + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Linegraph + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Use default bin size + + + true + + + + + + + Show Subchart + + + true + + + + + + + QFrame::NoFrame + + + QFrame::Raised + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 60 + 0 + + + + + 100 + 16777215 + + + + Bin size: + + + + + + + Press enter to recalculate statistics with new bin size. + + + true + + + 5 + + + 0.000010000000000 + + + 1000000.000000000000000 + + + 100.000000000000000 + + + + + + + + + + + + + + 0 + 0 + + + + 0 + + + + + 0 + 0 + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Copy to Clipboard + + + + + + + Qt::Horizontal + + + + 413 + 17 + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + QmitkC3jsWidget + QWidget +
QmitkC3jsWidget.h
+
+
+ + +