diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp b/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp index 55db6af9cd..e4eb4d59ef 100755 --- a/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp +++ b/Plugins/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp @@ -1,58 +1,56 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtWorkbenchAdvisor.h" #include "internal/berryQtGlobalEventFilter.h" #include "berryWorkbenchPlugin.h" #include #include #include #include #include #include #include #include -#include #include namespace berry { void QtWorkbenchAdvisor::Initialize(IWorkbenchConfigurer::Pointer configurer) { WorkbenchAdvisor::Initialize(configurer); - auto* prefService = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - auto* prefs = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences()->Node(QtPreferences::QT_STYLES_NODE); auto styleName = QString::fromStdString(prefs->Get(QtPreferences::QT_STYLE_NAME, "")); auto fontName = QString::fromStdString(prefs->Get(QtPreferences::QT_FONT_NAME, "Open Sans")); auto fontSize = QString::fromStdString(prefs->Get(QtPreferences::QT_FONT_SIZE, "9")); ctkServiceReference serviceRef = WorkbenchPlugin::GetDefault()->GetPluginContext()->getServiceReference(); if (serviceRef) { IQtStyleManager* styleManager = WorkbenchPlugin::GetDefault()->GetPluginContext()->getService(serviceRef); styleManager->SetStyle(styleName); styleManager->SetFont(fontName); styleManager->SetFontSize(fontSize.toInt()); styleManager->UpdateWorkbenchFont(); } QObject* eventFilter = new QtGlobalEventFilter(qApp); qApp->installEventFilter(eventFilter); } } diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp index 4899d5b439..86b26b6aa1 100644 --- a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp @@ -1,141 +1,140 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryWorkbenchWindowAdvisor.h" #include #include #include #include #include #include "internal/berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchPlugin.h" -#include #include namespace berry { IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer() { return windowConfigurer; } WorkbenchWindowAdvisor::WorkbenchWindowAdvisor( const IWorkbenchWindowConfigurer::Pointer& configurer) { poco_assert(configurer.IsNotNull()); this->windowConfigurer = configurer; } WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor() { } void WorkbenchWindowAdvisor::PreWindowOpen() { // do nothing } ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor( IActionBarConfigurer::Pointer configurer) { ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer)); return actionBarAdvisor; } void WorkbenchWindowAdvisor::PostWindowRestore() { // do nothing } void WorkbenchWindowAdvisor::OpenIntro() { // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call // introOpened flag needs to be global IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer(); QString key = "introOpened"; //$NON-NLS-1$ ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast(); if (introOpened && introOpened->GetValue()) { return; } wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true))); - auto* workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); + auto* workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferences(); 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/internal/berryPartSashContainer.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp index 6a8ec00702..3f870e0625 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp @@ -1,1270 +1,1269 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPartSashContainer.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryPartStack.h" #include "berryPageLayout.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryDragUtil.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPreferenceConstants.h" #include "berryGeometry.h" #include "berryPartPane.h" #include "berryQtTracker.h" #include "berryConstants.h" -#include #include namespace berry { bool PartSashContainer::leftToRight = true; PartSashContainer::ControlListener::ControlListener( PartSashContainer* container) : partSashContainer(container) { } GuiTk::IControlListener::Events::Types PartSashContainer::ControlListener::GetEventTypes() const { return Events::RESIZED; } void PartSashContainer::ControlListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { partSashContainer->ResizeSashes(); } PartSashContainer::SashContainerDropTarget::SashContainerDropTarget( PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) : partSashContainer(partSashContainer) { this->SetTarget(sourcePart, side, cursor, targetPart); } void PartSashContainer::SashContainerDropTarget::SetTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { this->side = side; this->targetPart = targetPart; this->sourcePart = sourcePart; this->cursor = cursor; } void PartSashContainer::SashContainerDropTarget::Drop() { if (side != Constants::NONE) { LayoutPart::Pointer visiblePart = sourcePart.Cast (); if (sourcePart.Cast () != 0) { visiblePart = partSashContainer->GetVisiblePart(sourcePart.Cast< ILayoutContainer> ()); } partSashContainer->DropObject( partSashContainer->GetVisibleParts(sourcePart), visiblePart, targetPart, side); } } void PartSashContainer::DropObject(const QList& toDrop, LayoutPart::Pointer visiblePart, Object::Pointer targetPart, int side) { //getControl().setRedraw(false); // Targetpart is null if there isn't a part under the cursor (all the parts are // hidden or the container is empty). In this case, the actual side doesn't really // since we'll be the only visible container and will fill the entire space. However, // we can't leave it as Constants::CENTER since we can't stack if we don't have something // to stack on. In this case, we pick Constants::BOTTOM -- this will insert the new pane // below any currently-hidden parts. if (targetPart == 0 && side == Constants::CENTER) { side = Constants::BOTTOM; } PartStack::Pointer targetStack = targetPart.Cast (); if (targetStack == 0 && targetPart.Cast() != 0) { targetStack = targetPart.Cast ()->GetStack(); } LayoutPart::Pointer targetLayoutPart = targetStack; // if targetLayoutPart == 0 then we normally got a EditorSashContainer if (targetLayoutPart == 0) targetLayoutPart = targetPart.Cast(); if (side == Constants::CENTER) { if (this->IsStackType(targetStack)) { for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, targetStack); } } } else { PartStack::Pointer newPart = this->CreateStack(); // if the toDrop array has 1 item propagate the stack // appearance if (toDrop.size() == 1 && toDrop[0]->GetStack() != 0) { toDrop[0]->GetStack()->CopyAppearanceProperties(newPart); } for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, newPart); } this->AddEnhanced(newPart, side, this->GetDockingRatio(newPart, targetStack), targetLayoutPart); } if (visiblePart != 0) { this->SetVisiblePart(visiblePart->GetContainer(), visiblePart.Cast ()); } //getControl().setRedraw(true); if (visiblePart != 0) { visiblePart->SetFocus(); } } CursorType PartSashContainer::SashContainerDropTarget::GetCursor() { return QtDragManager::PositionToCursorType(cursor); } QRect PartSashContainer::SashContainerDropTarget::GetSnapRectangle() { QRect targetBounds; if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else { targetBounds = DragUtil::GetDisplayBounds(partSashContainer->GetParent()); } if (side == Constants::CENTER || side == Constants::NONE) { return targetBounds; } int distance = Geometry::GetDimension(targetBounds, !Geometry::IsHorizontal( side)); ILayoutContainer::Pointer stack = targetPart.Cast (); if (stack == 0 && targetPart.Cast () != 0) { stack = targetPart.Cast ()->GetContainer(); } return Geometry::GetExtrudedEdge(targetBounds, (int) (distance * partSashContainer->GetDockingRatio(sourcePart, stack)), side); } PartSashContainer::PartSashContainer(const QString& id, WorkbenchPage* _page, QWidget* _parentWidget) : LayoutPart(id), parentWidget(_parentWidget), parent(nullptr), page(_page), active( false), layoutDirty(false) { resizeListener = new ControlListener(this); - auto layout = WorkbenchPlugin::GetDefault()->GetPreferencesService()-> - GetSystemPreferences()->Get(WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, - WorkbenchPreferenceConstants::LEFT); + auto layout = WorkbenchPlugin::GetDefault()->GetPreferences()->Get( + WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, WorkbenchPreferenceConstants::LEFT); + if (layout == WorkbenchPreferenceConstants::RIGHT) { leftToRight = false; } } QList PartSashContainer::GetVisibleParts( Object::Pointer pane) { QList parts; if (pane.Cast ().IsNotNull()) { parts.push_back(pane.Cast ()); } else if (pane.Cast ().IsNotNull()) { PartStack::Pointer stack = pane.Cast (); QList children = stack->GetChildren(); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () != 0) { parts.push_back(iter->Cast ()); } } } return parts; } PartSashContainer::~PartSashContainer() { } void PartSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { if (root == 0) { return; } LayoutTree::Pointer part = root->Find(pane); if (part == 0) { return; } part->FindSashes(sashes); } void PartSashContainer::Add(LayoutPart::Pointer child) { if (child.IsNull()) { return; } this->AddEnhanced(child, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddPart(LayoutPart::Pointer child) { if (child.IsNull()) { return; } PartStack::Pointer newFolder = this->CreateStack(); newFolder->Add(child); this->AddEnhanced(newFolder, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddEnhanced(LayoutPart::Pointer child, int directionConstant, float ratioForNewPart, LayoutPart::Pointer relative) { int relativePosition = PageLayout::ConstantToLayoutPosition(directionConstant); float ratioForUpperLeftPart; if (relativePosition == IPageLayout::RIGHT || relativePosition == IPageLayout::BOTTOM) { ratioForUpperLeftPart = 1.0f - ratioForNewPart; } else { ratioForUpperLeftPart = ratioForNewPart; } this->Add(child, relativePosition, ratioForUpperLeftPart, relative); } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative) { bool isHorizontal = (relationship == IPageLayout::LEFT || relationship == IPageLayout::RIGHT); LayoutTree::Pointer node; if (root != 0 && relative != 0) { node = root->Find(relative); } QRect bounds; if (this->GetParent() == nullptr) { QWidget* control = this->GetPage()->GetClientComposite(); if (control != nullptr) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(control); } else { bounds = QRect(0, 0, 800, 600); } bounds.setX(0); bounds.setY(0); } else { bounds = this->GetBounds(); } int totalSize = this->MeasureTree(bounds, node, isHorizontal); int left = (int) (totalSize * ratio); int right = totalSize - left; this->Add(child, relationship, left, right, relative); } int PartSashContainer::MeasureTree(const QRect& outerBounds, LayoutTree::ConstPointer toMeasure, bool horizontal) { if (toMeasure == 0) { return Geometry::GetDimension(outerBounds, horizontal); } LayoutTreeNode* parent = toMeasure->GetParent(); if (parent == nullptr) { return Geometry::GetDimension(outerBounds, horizontal); } if (parent->GetSash()->IsHorizontal() == horizontal) { return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } bool isLeft = parent->IsLeftChild(toMeasure); LayoutTree::Pointer otherChild = parent->GetChild(!isLeft); if (otherChild->IsVisible()) { int left = parent->GetSash()->GetLeft(); int right = parent->GetSash()->GetRight(); int childSize = isLeft ? left : right; int bias = parent->GetCompressionBias(); // Normalize bias: 1 = we're fixed, -1 = other child is fixed if (isLeft) { bias = -bias; } if (bias == 1) { // If we're fixed, return the fixed size return childSize; } else if (bias == -1) { // If the other child is fixed, return the size of the parent minus the fixed size of the // other child return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) - (left + right - childSize); } // Else return the size of the parent, scaled appropriately return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) * childSize / (left + right); } return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } void PartSashContainer::AddChild(const RelationshipInfo& info) { LayoutPart::Pointer child = info.part; children.push_back(child); if (root == 0) { root = new LayoutTree(child); } else { //Add the part to the tree. int vertical = (info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::RIGHT) ? Constants::VERTICAL : Constants::HORIZONTAL; bool left = info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::TOP; LayoutPartSash::Pointer sash(new LayoutPartSash(this, vertical)); sash->SetSizes(info.left, info.right); if ((parent != nullptr) && child.Cast ().IsNull()) { sash->CreateControl(parent); } LayoutTree::Pointer newroot = root->Insert(child, left, sash, info.relative); root = newroot; } this->ChildAdded(child); if (active) { child->CreateControl(parent); child->SetVisible(true); child->SetContainer(ILayoutContainer::Pointer(this)); this->ResizeChild(child); } } void PartSashContainer::AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder) { RelationshipInfo newRelationshipInfo; newRelationshipInfo.part = child; if (root != 0) { newRelationshipInfo.relationship = IPageLayout::RIGHT; newRelationshipInfo.relative = root->FindBottomRight(); newRelationshipInfo.left = 200; newRelationshipInfo.right = 200; } // find the relationship info for the placeholder QList relationships = this->ComputeRelation(); for (int i = 0; i < relationships.size(); i++) { RelationshipInfo info = relationships[i]; if (info.part == placeholder) { newRelationshipInfo.left = info.left; newRelationshipInfo.right = info.right; newRelationshipInfo.relationship = info.relationship; newRelationshipInfo.relative = info.relative; } } this->AddChild(newRelationshipInfo); this->FlushLayout(); } bool PartSashContainer::AllowsBorder() { return true; } void PartSashContainer::ChildAdded(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(true); } } void PartSashContainer::ChildRemoved(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(false); } } QList PartSashContainer::ComputeRelation() { LayoutTree::Pointer treeRoot = root; QList list; if (treeRoot == 0) { return QList(); } RelationshipInfo r; r.part = treeRoot->ComputeRelation(list); list.push_front(r); return list; } void PartSashContainer::SetActive(bool isActive) { if (isActive == active) { return; } active = isActive; ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast ().IsNotNull()) { PartStack::Pointer stack = childIter->Cast (); stack->SetActive(isActive); } } if (isActive) { this->CreateControl(parentWidget); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(parent, resizeListener); DragUtil::AddDragTarget(parent, this); DragUtil::AddDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer child = *childIter; child->SetContainer(ILayoutContainer::Pointer(this)); child->SetVisible(true); //zoomedPart == null || child == zoomedPart); if (child.Cast ().IsNull()) { if (root != 0) { LayoutTree::Pointer node = root->Find(child); if (node != 0) { node->FlushCache(); } } } } if (root != 0) { //root.flushChildren(); //if (!isZoomed()) { root->CreateControl(parent); } } this->ResizeSashes(); } else { DragUtil::RemoveDragTarget(parent, this); DragUtil::RemoveDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); // remove all Listeners if (resizeListener != 0 && parent != nullptr) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(parent, resizeListener); } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer child = *iter; child->SetContainer(ILayoutContainer::Pointer(nullptr)); if (child.Cast ().IsNotNull()) { child->SetVisible(false); } } this->DisposeSashes(); //dispose(); } } void PartSashContainer::CreateControl(QWidget* parentWidget) { if (this->parent != nullptr) { return; } parent = this->CreateParent(parentWidget); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->CreateControl(parent); } } void PartSashContainer::Dispose() { if (parent == nullptr) { return; } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { // In PartSashContainer dispose really means deactivate, so we // only dispose PartTabFolders. if (iter->Cast() != 0) { (*iter)->Dispose(); } } this->DisposeParent(); this->parent = nullptr; } void PartSashContainer::DisposeSashes() { if (root != 0) { root->DisposeSashes(); } } void PartSashContainer::SetVisible(bool makeVisible) { if (makeVisible == this->GetVisible()) { return; } //if (!SwtUtil.isDisposed(this.parent)) //{ Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(this->parent, makeVisible); //} LayoutPart::SetVisible(makeVisible); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->SetVisible(makeVisible); // && (zoomedPart == null || child == zoomedPart)); } } LayoutPart::Pointer PartSashContainer::FindBottomRight() { if (root == 0) { return LayoutPart::Pointer(nullptr); } return root->FindBottomRight(); } QRect PartSashContainer::GetBounds() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->parent); } ILayoutContainer::ChildrenType PartSashContainer::GetChildren() const { return children; } QWidget* PartSashContainer::GetControl() { return this->parent; } LayoutTree::Pointer PartSashContainer::GetLayoutTree() { return root; } WorkbenchPage::Pointer PartSashContainer::GetPage() { return WorkbenchPage::Pointer(page); } QWidget* PartSashContainer::GetParent() { return parent; } bool PartSashContainer::IsChild(LayoutPart::Pointer part) { return std::find(children.begin(), children.end(), part) != children.end(); } void PartSashContainer::ResizeChild(LayoutPart::Pointer childThatChanged) { if (root != 0) { LayoutTree::Pointer tree = root->Find(childThatChanged); if (tree != 0) { tree->FlushCache(); } } this->FlushLayout(); } void PartSashContainer::Remove(LayoutPart::Pointer child) { // if (child == getZoomedPart()) // { // childRequestZoomOut(); // } if (!this->IsChild(child)) { return; } children.removeAll(child); if (root != 0) { root = root->Remove(child); } this->ChildRemoved(child); if (active) { child->SetVisible(false); child->SetContainer(ILayoutContainer::Pointer(nullptr)); this->FlushLayout(); } } void PartSashContainer::FlushLayout() { layoutDirty = true; LayoutPart::FlushLayout(); if (layoutDirty) { this->ResizeSashes(); } } void PartSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // if (oldChild == getZoomedPart()) // { // if (newChild.Cast ().IsNotNull()) // { // childRequestZoomOut(); // } // else // { // zoomedPart.setZoomed(false); // zoomedPart = newChild; // zoomedPart.setZoomed(true); // } // } children.erase(std::find(children.begin(), children.end(), oldChild)); children.push_back(newChild); this->ChildAdded(newChild); if (root != 0) { LayoutTree::Pointer leaf; leaf = root->Find(oldChild); if (leaf != 0) { leaf->SetPart(newChild); } } this->ChildRemoved(oldChild); if (active) { oldChild->SetVisible(false); oldChild->SetContainer(ILayoutContainer::Pointer(nullptr)); newChild->CreateControl(parent); newChild->SetContainer(ILayoutContainer::Pointer(this)); newChild->SetVisible(true); //zoomedPart == null || zoomedPart == newChild); this->ResizeChild(newChild); } } void PartSashContainer::ResizeSashes() { layoutDirty = false; if (!active) { return; } // if (isZoomed()) // { // getZoomedPart().setBounds(parent.getClientArea()); // } // else { if (root != 0) { root->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea( parent)); } } } int PartSashContainer::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { // if (isZoomed()) // { // return getZoomedPart().computePreferredSize(width, availableParallel, // availablePerpendicular, preferredParallel); // } if (root != 0) { return root->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } return preferredParallel; } int PartSashContainer::GetSizeFlags(bool width) { // if (isZoomed()) // { // return getZoomedPart().getSizeFlags(width); // } if (root != 0) { return root->GetSizeFlags(width); } return 0; } void PartSashContainer::SetBounds(const QRect& r) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(this->parent, r); } IDropTarget::Pointer PartSashContainer::Drag(QWidget* /*currentControl*/, const Object::Pointer& draggedObject, const QPoint& position, const QRect& /*dragRectangle*/) { if (!(draggedObject.Cast () != 0 || draggedObject.Cast () != 0)) { return IDropTarget::Pointer(nullptr); } PartPane::Pointer sourcePart = draggedObject.Cast (); PartStack::Pointer sourceContainer = draggedObject.Cast (); if (sourceContainer == 0) { sourceContainer = sourcePart->GetStack(); } if (!this->IsStackType(sourceContainer) && !this->IsPaneType(sourcePart)) { return IDropTarget::Pointer(nullptr); } IWorkbenchWindow::Pointer window = sourcePart ? sourcePart->GetWorkbenchWindow() : sourceContainer->GetWorkbenchWindow(); bool differentWindows = window != this->GetWorkbenchWindow(); bool editorDropOK = ((sourceContainer->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) && window->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(nullptr); } QRect containerBounds = DragUtil::GetDisplayBounds(parent); LayoutPart::Pointer targetPart; // If this container has no visible children if (this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) == 0) { return this->CreateDropTarget(draggedObject, Constants::CENTER, Constants::CENTER, Object::Pointer(nullptr)); } if (containerBounds.contains(position)) { if (root != 0) { targetPart = root->FindPart( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(parent, position)); } if (targetPart != 0) { QWidget* targetControl = targetPart->GetControl(); QRect targetBounds = DragUtil::GetDisplayBounds(targetControl); int side = Geometry::GetClosestSide(targetBounds, position); int distance = Geometry::GetDistanceFromEdge(targetBounds, position, side); // is the source coming from a standalone part bool standalone = (this->IsStackType(sourceContainer) && sourceContainer->IsStandalone()) || (this->IsPaneType(sourcePart) && sourcePart->GetStack()->IsStandalone()); // Only allow dropping onto an existing stack from different windows if (differentWindows && targetPart.Cast () != 0 && targetPart.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) { IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); return target; } // Reserve the 5 pixels around the edge of the part for the drop-on-edge cursor if (distance >= 5 && !standalone) { // Otherwise, ask the part if it has any special meaning for this drop location IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); if (target != 0) { return target; } } if (distance > 30 && this->IsStackType(targetPart.Cast ()) && !standalone) { PartStack::Pointer targetContainer = targetPart.Cast (); if (targetContainer->AllowsAdd(sourcePart)) { side = Constants::CENTER; } } // If the part doesn't want to override this drop location then drop on the edge // A "pointless drop" would be one that will put the dragged object back where it started. // Note that it should be perfectly valid to drag an object back to where it came from -- however, // the drop should be ignored. bool pointlessDrop = false; // = isZoomed(); if (!sourcePart && sourceContainer == targetPart) { pointlessDrop = true; } if ((sourceContainer != 0) && (sourceContainer == targetPart) && this->GetVisibleChildrenCount(sourceContainer.Cast()) <= 1) { pointlessDrop = true; } if (side == Constants::CENTER && sourceContainer == targetPart) { pointlessDrop = true; } int cursor = side; if (pointlessDrop) { side = Constants::NONE; cursor = Constants::CENTER; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, targetPart); else return this->CreateDropTarget(sourceContainer, side, cursor, targetPart); } } else { // We only allow dropping into a stack, not creating one if (differentWindows) return IDropTarget::Pointer(nullptr); int side = Geometry::GetClosestSide(containerBounds, position); bool pointlessDrop = false; // = isZoomed(); if (/*(this->IsStackType(sourceContainer) && sourceContainer == this) ||*/ (this->IsPaneType(sourcePart) && this->GetVisibleChildrenCount( sourceContainer.Cast()) <= 1) && sourceContainer->GetContainer() == this) { if (root == 0 || this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) <= 1) { pointlessDrop = true; } } int cursor = Geometry::GetOppositeSide(side); if (pointlessDrop) { side = Constants::NONE; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, Object::Pointer(nullptr)); else return this->CreateDropTarget(sourceContainer, side, cursor, Object::Pointer(nullptr)); } return IDropTarget::Pointer(nullptr); } PartSashContainer::SashContainerDropTarget::Pointer PartSashContainer::CreateDropTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { if (dropTarget == 0) { dropTarget = new SashContainerDropTarget(this, sourcePart, side, cursor, targetPart); } else { dropTarget->SetTarget(sourcePart, side, cursor, targetPart); } return dropTarget; } void PartSashContainer::Stack(LayoutPart::Pointer newPart, ILayoutContainer::Pointer container) { //this->GetControl().setRedraw(false); // Only deref the part if it is being referenced in -this- perspective Perspective::Pointer persp = page->GetActivePerspective(); PerspectiveHelper* pres = (persp != 0) ? persp->GetPresentation() : nullptr; if (pres != nullptr && container.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { IWorkbenchPartReference::Pointer newPartRef = newPart.Cast ()->GetPartReference(); IViewReference::Pointer vRef = newPartRef.Cast (); if (vRef != 0) { LayoutPart::Pointer fpp = pres->FindPart(vRef->GetId(), vRef->GetSecondaryId()); if (fpp != 0) { // Remove the part from old container. this->DerefPart(newPart); } } } else { // Remove the part from old container. this->DerefPart(newPart); } // Reparent part and add it to the workbook newPart->Reparent(this->GetParent()); container->Add(newPart); //getControl().setRedraw(true); } void PartSashContainer::DerefPart(LayoutPart::Pointer sourcePart) { ILayoutContainer::Pointer container = sourcePart->GetContainer(); if (container != 0) { container->Remove(sourcePart); if (this->IsStackType(container) && container.Cast () != 0) { if (container->GetChildren().size() == 0) { LayoutPart::Pointer stack = container.Cast (); this->Remove(stack); stack->Dispose(); } } } } std::size_t PartSashContainer::GetVisibleChildrenCount( ILayoutContainer::Pointer container) { // Treat null as an empty container if (container == 0) { return 0; } ILayoutContainer::ChildrenType children = container->GetChildren(); std::size_t count = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { count++; } } return count; } float PartSashContainer::GetDockingRatio(Object::Pointer /*dragged*/, ILayoutContainer::Pointer /*target*/) { return 0.5f; } void PartSashContainer::DescribeLayout(QString& buf) const { if (root == 0) { return; } // if (isZoomed()) // { // buf.append("zoomed "); //$NON-NLS-1$ // root.describeLayout(buf); // } // else { buf.append("layout "); //$NON-NLS-1$ root->DescribeLayout(buf); } } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative) { if (child == 0) { return; } if (relative != 0 && !this->IsChild(relative)) { return; } if (relationship < IPageLayout::LEFT || relationship > IPageLayout::BOTTOM) { relationship = IPageLayout::LEFT; } // store info about relative positions RelationshipInfo info; info.part = child; info.relationship = relationship; info.left = left; info.right = right; info.relative = relative; this->AddChild(info); } bool PartSashContainer::AllowsAutoFocus() { return true; } void PartSashContainer::StartDeferringEvents() { LayoutPart::StartDeferringEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(true); } } void PartSashContainer::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(false); } } void PartSashContainer::TestInvariants() { LayoutPart::TestInvariants(); // If we have a parent container, ensure that we are displaying the zoomed appearance iff // our parent is zoomed in on us // if (this->GetContainer() != 0) // { // Assert.isTrue((getZoomedPart() != null) == (getContainer().childIsZoomed( // this))); // } ILayoutContainer::ChildrenType childArray = this->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = childArray.begin(); iter != childArray.end(); ++iter) { (*iter)->TestInvariants(); } // If we're zoomed, ensure that we're actually zoomed into one of our children // if (isZoomed()) // { // Assert.isTrue(children.contains(zoomedPart)); // } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp index 83403abed2..751fefc86b 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp @@ -1,628 +1,624 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryPerspectiveRegistry.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" #include "berryPreferenceConstants.h" #include "berryPerspective.h" #include "berryPerspectiveRegistryReader.h" #include "berryPlatformUI.h" #include "handlers/berryClosePerspectiveHandler.h" #include "berryIExtension.h" #include "berryIExtensionTracker.h" -#include #include namespace berry { const QString PerspectiveRegistry::EXT = "_persp.xml"; const QString PerspectiveRegistry::ID_DEF_PERSP = "PerspectiveRegistry.DEFAULT_PERSP"; const QString PerspectiveRegistry::PERSP = "_persp"; const char PerspectiveRegistry::SPACE_DELIMITER = ' '; class PerspectiveRegistry::PreferenceChangeListener { PerspectiveRegistry* m_Registry; public: PreferenceChangeListener(PerspectiveRegistry* registry) : m_Registry(registry) {} void PropertyChange(const mitk::IPreferences::ChangeEvent& event) { /* * To ensure that no custom perspective definitions are * deleted when preferences are imported, merge old and new * values */ if (QString::fromStdString(event.GetProperty()).endsWith(PERSP)) { /* A Perspective is being changed, merge */ this->MergePerspectives(event); } else if (event.GetProperty() == PreferenceConstants::PERSPECTIVES) { /* The list of perpsectives is being changed, merge */ UpdatePreferenceList(event.GetSource()); } } void MergePerspectives(const mitk::IPreferences::ChangeEvent& event) { auto* store = event.GetSource(); if (event.GetNewValue().empty()) { /* * Perpsective is being removed; if the user has deleted or * reverted a custom perspective, let the change pass * through. Otherwise, restore the custom perspective entry */ // Find the matching descriptor in the registry QList perspectiveList = m_Registry->GetPerspectives(); for (int i = 0; i < perspectiveList.size(); i++) { QString id = perspectiveList[i]->GetId(); const auto property = QString::fromStdString(event.GetProperty()); if (property == id + PERSP) { // found // descriptor // see if the perspective has been flagged for // reverting or deleting if (!m_Registry->perspToRemove.contains(id)) { // restore store->Put((id + PERSP).toStdString(), event.GetOldValue()); } else { // remove element from the list m_Registry->perspToRemove.removeAll(id); } } } } else if (event.GetOldValue().empty()) { /* * New perspective is being added, update the * perspectiveRegistry to contain the new custom perspective */ auto property = QString::fromStdString(event.GetProperty()); QString id = property.left(property.lastIndexOf(PERSP)); if (m_Registry->FindPerspectiveWithId(id).IsNull()) { // perspective does not already exist in registry, add // it PerspectiveDescriptor::Pointer desc(new PerspectiveDescriptor( QString::null, QString::null, PerspectiveDescriptor::Pointer())); std::stringstream reader; std::string xmlStr = event.GetNewValue(); reader.str(xmlStr); try { XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(reader); desc->RestoreState(memento); m_Registry->AddPerspective(desc); } catch (const WorkbenchException& e) { //m_Registry->UnableToLoadPerspective(e.getStatus()); m_Registry->UnableToLoadPerspective(e.what()); } } } /* If necessary, add to the list of perspectives */ this->UpdatePreferenceList(store); } void UpdatePreferenceList(mitk::IPreferences* store) { QList perspectiveList = m_Registry->GetPerspectives(); QStringList perspBuffer; for (int i = 0; i < perspectiveList.size(); i++) { PerspectiveDescriptor::Pointer desc = perspectiveList[i].Cast(); if (m_Registry->HasCustomDefinition(desc)) { perspBuffer.push_back(desc->GetId()); } } store->Put(PreferenceConstants::PERSPECTIVES, perspBuffer.join(QString(SPACE_DELIMITER)).toStdString()); } }; PerspectiveRegistry::PerspectiveRegistry() : preferenceListener(new PreferenceChangeListener(this)) { IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker(); tracker->RegisterHandler(this, QString("org.blueberry.ui.perspectives")); - mitk::IPreferences* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); + mitk::IPreferences* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); prefs->OnPropertyChanged += mitk::MessageDelegate1( preferenceListener.data(), &PreferenceChangeListener::PropertyChange); } void PerspectiveRegistry::AddPerspective(PerspectiveDescriptor::Pointer desc) { if (desc == 0) { return; } this->Add(desc); } void PerspectiveRegistry::RevertPerspectives( const QList& perspToRevert) { // indicate that the user is removing these perspectives for (QList::const_iterator iter = perspToRevert.begin(); iter != perspToRevert.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } } void PerspectiveRegistry::DeletePerspectives( const QList& perspToDelete) { for (QList::const_iterator iter = perspToDelete.begin(); iter != perspToDelete.end(); ++iter) { this->DeletePerspective(*iter); } } void PerspectiveRegistry::DeletePerspective(IPerspectiveDescriptor::Pointer in) { PerspectiveDescriptor::Pointer desc = in.Cast(); // Don't delete predefined perspectives if (!desc->IsPredefined()) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } } void PerspectiveRegistry::Load() { // Load the registries. this->LoadPredefined(); this->LoadCustom(); // Get default perspective. // Get it from the R1.0 dialog settings first. Fixes bug 17039 // IDialogSettings dialogSettings = // WorkbenchPlugin.getDefault() .getDialogSettings(); // QString str = dialogSettings.get(ID_DEF_PERSP); // if (str != null && str.length() > 0) // { // this->SetDefaultPerspective(str); // dialogSettings.put(ID_DEF_PERSP, ""); //$NON-NLS-1$ // } this->VerifyDefaultPerspective(); } void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc, XMLMemento* memento) { - auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); // Save it to the preference store. std::stringstream ss; memento->Save(ss); - prefs->GetSystemPreferences()->Put((desc->GetId() + PERSP).toStdString(), ss.str()); + prefs->Put((desc->GetId() + PERSP).toStdString(), ss.str()); } IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& id) { std::stringstream ss; - auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - const auto xmlString = prefs->GetSystemPreferences()->Get((id + PERSP).toStdString(), ""); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + const auto xmlString = prefs->Get((id + PERSP).toStdString(), ""); if (!xmlString.empty()) { // defined in store ss.str(xmlString); } XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); return memento; } bool PerspectiveRegistry::ValidateLabel(const QString& label) { return !label.trimmed().isEmpty(); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithId(const QString& id) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetId() == id) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return null; // } return desc; } } return IPerspectiveDescriptor::Pointer(nullptr); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithLabel( const QString& label) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetLabel() == label) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return 0; // } return desc; } } return IPerspectiveDescriptor::Pointer(nullptr); } QString PerspectiveRegistry::GetDefaultPerspective() { return defaultPerspID; } QList PerspectiveRegistry::GetPerspectives() { // Collection descs = WorkbenchActivityHelper.restrictCollection(perspectives, // new ArrayList()); // return (IPerspectiveDescriptor[]) descs.toArray( // new IPerspectiveDescriptor[descs.size()]); QList result; for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { result.push_back(iter->Cast()); } return result; } void PerspectiveRegistry::SetDefaultPerspective(const QString& id) { IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { defaultPerspID = id; //TODO Preferences // PrefUtil.getAPIPreferenceStore().setValue( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id); } } IPerspectiveDescriptor::Pointer PerspectiveRegistry::CreatePerspective(const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Sanity check to avoid invalid or duplicate labels. if (!this->ValidateLabel(label)) { return IPerspectiveDescriptor::Pointer(nullptr); } if (this->FindPerspectiveWithLabel(label) != 0) { return IPerspectiveDescriptor::Pointer(nullptr); } // Calculate ID. QString id(label); id = id.replace(' ', '_').trimmed(); // Create descriptor. PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, label, originalDescriptor.Cast())); this->Add(desc); return IPerspectiveDescriptor::Pointer(static_cast(desc.GetPointer())); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Check for invalid labels if (label == "" || label.trimmed().isEmpty()) { throw Poco::InvalidArgumentException(); } // Check for duplicates IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { throw Poco::InvalidArgumentException(); } // Create descriptor. desc = new PerspectiveDescriptor(id, label, originalDescriptor.Cast()); this->Add(desc.Cast()); return desc; } void PerspectiveRegistry::RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) { PerspectiveDescriptor::Pointer desc = perspToRevert.Cast(); perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } PerspectiveRegistry::~PerspectiveRegistry() { // PlatformUI::GetWorkbench()->GetExtensionTracker()->UnregisterHandler(this); -// WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences()->RemovePropertyChangeListener( -// preferenceListener); +// WorkbenchPlugin::GetDefault()->GetPreferences()->RemovePropertyChangeListener(preferenceListener); } void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc) { // remove the entry from the preference store. - auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - - store->GetSystemPreferences()->Remove((desc->GetId() + PERSP).toStdString()); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + prefs->Remove((desc->GetId() + PERSP).toStdString()); } bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const { - auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - const auto keys = store->GetSystemPreferences()->Keys(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + const auto keys = prefs->Keys(); return std::find(keys.begin(), keys.end(), (desc->GetId() + PERSP).toStdString()) != keys.end(); } void PerspectiveRegistry::Add(PerspectiveDescriptor::Pointer desc) { perspectives.push_back(desc); IConfigurationElement::Pointer element = desc->GetConfigElement(); if (element.IsNotNull()) { PlatformUI::GetWorkbench()->GetExtensionTracker()->RegisterObject( element->GetDeclaringExtension(), desc, IExtensionTracker::REF_WEAK); } } void PerspectiveRegistry::InternalDeletePerspective(PerspectiveDescriptor::Pointer desc) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } void PerspectiveRegistry::LoadCustom() { QScopedPointer reader; /* Get the entries from the Preference store */ - auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - auto* prefs = store->GetSystemPreferences(); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); /* Get the space-delimited list of custom perspective ids */ QString customPerspectives = QString::fromStdString(prefs->Get(PreferenceConstants::PERSPECTIVES, "")); QStringList perspectivesList = customPerspectives.split(' ', QString::SkipEmptyParts); for (int i = 0; i < perspectivesList.size(); i++) { try { const auto xmlString = prefs->Get((perspectivesList[i] + PERSP).toStdString(), ""); if (!xmlString.empty()) { reader.reset(new std::stringstream(xmlString)); //reader->exceptions(std::ios_base::failbit); } else { throw WorkbenchException(QString("Description of '%1' perspective could not be found.").arg(perspectivesList[i])); } // Restore the layout state. XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(*reader); PerspectiveDescriptor::Pointer newPersp(new PerspectiveDescriptor( QString::null, QString::null, PerspectiveDescriptor::Pointer(nullptr))); newPersp->RestoreState(memento); QString id = newPersp->GetId(); IPerspectiveDescriptor::Pointer oldPersp = FindPerspectiveWithId(id); if (oldPersp.IsNull()) { Add(newPersp); } } catch (const std::ios_base::failure&) { UnableToLoadPerspective(QString::null); } catch (const WorkbenchException& e) { UnableToLoadPerspective(e.message()); } } // // Get the entries from files, if any // // if -data @noDefault specified the state location may not be // // initialized // IPath path = WorkbenchPlugin.getDefault().getDataLocation(); // if (path == null) // { // return; // } // File folder = path.toFile(); // if (folder.isDirectory()) // { // File[] fileList = folder.listFiles(); // int nSize = fileList.length; // for (int nX = 0; nX < nSize; nX++) // { // File file = fileList[nX]; // if (file.getName().endsWith(EXT)) // { // // get the memento // InputStream stream = null; // try // { // stream = new FileInputStream(file); // reader = new BufferedReader(new InputStreamReader(stream, "utf-8")); //$NON-NLS-1$ // // Restore the layout state. // XMLMemento memento = XMLMemento.createReadRoot(reader); // PerspectiveDescriptor newPersp = // new PerspectiveDescriptor(null, null, null); // newPersp.restoreState(memento); // IPerspectiveDescriptor oldPersp = findPerspectiveWithId( // newPersp .getId()); // if (oldPersp == null) // { // add(newPersp); // } // // save to the preference store // saveCustomPersp(newPersp, memento); // // delete the file // file.delete(); // reader.close(); // stream.close(); // } catch (IOException e) // { // unableToLoadPerspective(null); // } catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // } // } } void PerspectiveRegistry::UnableToLoadPerspective(const QString& status) { QString msg = "Unable to load perspective"; if (status == "") { WorkbenchPlugin::Log(msg); //IStatus errStatus = // new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } else { WorkbenchPlugin::Log(status + ": " + msg); //IStatus errStatus = StatusUtil.newStatus(status, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } } void PerspectiveRegistry::LoadPredefined() { PerspectiveRegistryReader reader(this); reader.ReadPerspectives(Platform::GetExtensionRegistry()); } void PerspectiveRegistry::VerifyDefaultPerspective() { // Step 1: Try current defPerspId value. IPerspectiveDescriptor::Pointer desc; if (defaultPerspID != "") { desc = this->FindPerspectiveWithId(defaultPerspID); } if (desc != 0) { return; } // Step 2. Read default value. //TODO Preferences // QString str = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID); // if (str != null && str.length() > 0) // { // desc = this->FindPerspectiveWithId(str); // } // if (desc != 0) // { // defaultPerspID = str; // return; // } // Step 3. Use application-specific default defaultPerspID = Workbench::GetInstance()->GetDefaultPerspectiveId(); } void PerspectiveRegistry::RemoveExtension(const IExtension::Pointer& /*source*/, const QList& objects) { for (int i = 0; i < objects.size(); i++) { if (PerspectiveDescriptor::Pointer desc = objects[i].Cast()) { // close the perspective in all windows QList windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (int w = 0; w < windows.size(); ++w) { IWorkbenchWindow::Pointer window = windows[w]; QList pages = window->GetPages(); for (int p = 0; p < pages.size(); ++p) { WorkbenchPage::Pointer page = pages[p].Cast(); ClosePerspectiveHandler::ClosePerspective(page, page->FindPerspective(desc)); } } // ((Workbench)PlatformUI.getWorkbench()).getPerspectiveHistory().removeItem(desc); this->InternalDeletePerspective(desc); } } } void PerspectiveRegistry::AddExtension(IExtensionTracker* /*tracker*/, const IExtension::Pointer& addedExtension) { QList addedElements = addedExtension->GetConfigurationElements(); for (int i = 0; i < addedElements.size(); i++) { PerspectiveRegistryReader reader(this); reader.ReadElement(addedElements[i]); } } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp index cd166d9ac2..489840defb 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp @@ -1,265 +1,272 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtStylePreferencePage.h" #include "berryWorkbenchPlugin.h" #include #include #include #include -#include #include +namespace +{ + mitk::IPreferences* GetPreferences() + { + return berry::WorkbenchPlugin::GetDefault()->GetPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); + } +} + namespace berry { QtStylePreferencePage::QtStylePreferencePage() { } void QtStylePreferencePage::Init(IWorkbench::Pointer ) { } void QtStylePreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); - auto* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); - ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext(); ctkServiceReference styleManagerRef = context->getServiceReference(); if (styleManagerRef) { styleManager = context->getService(styleManagerRef); } - m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); - Update(); connect(controls.m_StylesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(StyleChanged(int))); connect(controls.m_FontComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(FontChanged(int))); connect(controls.m_FontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(FontChanged(int))); connect(controls.m_PathList, SIGNAL(itemSelectionChanged()), this, SLOT(UpdatePathListButtons())); connect(controls.m_AddButton, SIGNAL(clicked(bool)), this, SLOT(AddPathClicked(bool))); connect(controls.m_EditButton, SIGNAL(clicked(bool)), this, SLOT(EditPathClicked(bool))); connect(controls.m_RemoveButton, SIGNAL(clicked(bool)), this, SLOT(RemovePathClicked(bool))); } void QtStylePreferencePage::FillStyleCombo(const berry::IQtStyleManager::Style& currentStyle) { controls.m_StylesCombo->clear(); styles.clear(); styleManager->GetStyles(styles); qSort(styles); for (int i = 0; i < styles.size(); ++i) { controls.m_StylesCombo->addItem(styles.at(i).name, QVariant(styles.at(i).fileName)); } controls.m_StylesCombo->setCurrentIndex(styles.indexOf(currentStyle)); } void QtStylePreferencePage::FillFontCombo(const QString& currentFont) { controls.m_FontComboBox->clear(); QStringList fonts; styleManager->GetFonts(fonts); for (int i = 0; i < fonts.size(); ++i) { controls.m_FontComboBox->addItem(fonts.at(i)); } controls.m_FontComboBox->setCurrentIndex(fonts.indexOf(currentFont)); if (currentFont == QString("<>")) { controls.m_FontSizeSpinBox->setEnabled(false); } else { controls.m_FontSizeSpinBox->setEnabled(true); } } void QtStylePreferencePage::AddPath(const QString& path, bool updateCombo) { if (!controls.m_PathList->findItems(path, Qt::MatchCaseSensitive).isEmpty()) return; new QListWidgetItem(path, controls.m_PathList); styleManager->AddStyles(path); if (updateCombo) FillStyleCombo(oldStyle); } void QtStylePreferencePage::StyleChanged(int /*index*/) { QString fileName = controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString(); styleManager->SetStyle(fileName); } void QtStylePreferencePage::FontChanged(int /*index*/) { QString fontName = controls.m_FontComboBox->currentText(); int fontSize = controls.m_FontSizeSpinBox->value(); if (fontName == QString("<>")) { controls.m_FontSizeSpinBox->setEnabled(false); } else { controls.m_FontSizeSpinBox->setEnabled(true); } styleManager->SetFont(fontName); styleManager->SetFontSize(fontSize); styleManager->UpdateWorkbenchFont(); } void QtStylePreferencePage::AddPathClicked(bool /*checked*/) { QListWidgetItem* item = controls.m_PathList->currentItem(); QString initialDir; if (item) initialDir = item->text(); QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir); if (!dir.isEmpty()) this->AddPath(dir, true); } void QtStylePreferencePage::RemovePathClicked(bool /*checked*/) { QList selection = controls.m_PathList->selectedItems(); QListIterator it(selection); while (it.hasNext()) { QListWidgetItem* item = it.next(); QString dir = item->text(); controls.m_PathList->takeItem(controls.m_PathList->row(item)); delete item; styleManager->RemoveStyles(dir); } if (!styleManager->Contains(oldStyle.fileName)) { oldStyle = styleManager->GetDefaultStyle(); } FillStyleCombo(oldStyle); } void QtStylePreferencePage::EditPathClicked(bool checked) { QListWidgetItem* item = controls.m_PathList->currentItem(); QString initialDir = item->text(); QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir); if (!dir.isEmpty()) { this->RemovePathClicked(checked); this->AddPath(dir, true); } } void QtStylePreferencePage::UpdatePathListButtons() { int s = controls.m_PathList->selectedItems().size(); if (s == 0) { controls.m_EditButton->setEnabled(false); controls.m_RemoveButton->setEnabled(false); } else if (s == 1) { controls.m_EditButton->setEnabled(true); controls.m_RemoveButton->setEnabled(true); } else { controls.m_EditButton->setEnabled(false); controls.m_RemoveButton->setEnabled(true); } } QWidget* QtStylePreferencePage::GetQtControl() const { return mainWidget; } bool QtStylePreferencePage::PerformOk() { - m_StylePref->Put(berry::QtPreferences::QT_STYLE_NAME, controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString().toStdString()); + auto* prefs = GetPreferences(); + + prefs->Put(berry::QtPreferences::QT_STYLE_NAME, controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString().toStdString()); QString paths; for (int i = 0; i < controls.m_PathList->count(); ++i) { QString path = controls.m_PathList->item(i)->text() + ";"; paths += path; } - m_StylePref->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths.toStdString()); - m_StylePref->Put(berry::QtPreferences::QT_FONT_NAME, controls.m_FontComboBox->currentText().toStdString()); - m_StylePref->Put(berry::QtPreferences::QT_FONT_SIZE, std::to_string(controls.m_FontSizeSpinBox->value())); + prefs->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths.toStdString()); + prefs->Put(berry::QtPreferences::QT_FONT_NAME, controls.m_FontComboBox->currentText().toStdString()); + prefs->Put(berry::QtPreferences::QT_FONT_SIZE, std::to_string(controls.m_FontSizeSpinBox->value())); - m_StylePref->PutBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, + prefs->PutBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, controls.m_ToolbarCategoryCheckBox->isChecked()); return true; } void QtStylePreferencePage::PerformCancel() { Update(); } void QtStylePreferencePage::Update() { styleManager->RemoveStyles(); - auto paths = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, "")); + auto* prefs = GetPreferences(); + + auto paths = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, "")); QStringList pathList = paths.split(";", QString::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddPath(it.next(), false); } - auto styleName = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_STYLE_NAME, "")); + auto styleName = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_STYLE_NAME, "")); styleManager->SetStyle(styleName); oldStyle = styleManager->GetStyle(); FillStyleCombo(oldStyle); - auto fontName = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_FONT_NAME, "Open Sans")); + auto fontName = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_FONT_NAME, "Open Sans")); styleManager->SetFont(fontName); - auto fontSize = std::stoi(m_StylePref->Get(berry::QtPreferences::QT_FONT_SIZE, "9")); + auto fontSize = std::stoi(prefs->Get(berry::QtPreferences::QT_FONT_SIZE, "9")); styleManager->SetFontSize(fontSize); controls.m_FontSizeSpinBox->setValue(fontSize); styleManager->UpdateWorkbenchFont(); FillFontCombo(styleManager->GetFont()); controls.m_ToolbarCategoryCheckBox->setChecked( - m_StylePref->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true)); + prefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true)); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h index c0253f57d7..47ebbcfed4 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.h @@ -1,81 +1,75 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYQTSTYLEPREFERENCEPAGE_H_ #define BERRYQTSTYLEPREFERENCEPAGE_H_ #include #include #include #include -namespace mitk -{ - class IPreferences; -} - namespace berry { class QtStylePreferencePage : public QObject, public IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QtStylePreferencePage(); void Init(IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; protected: void AddPath(const QString& path, bool updateCombo); void FillStyleCombo(const berry::IQtStyleManager::Style& currentStyle); void FillFontCombo(const QString& currentFont); protected slots: void StyleChanged(int /*index*/); void FontChanged(int /*index*/); void AddPathClicked(bool /*checked*/); void RemovePathClicked(bool /*checked*/); void EditPathClicked(bool checked); void UpdatePathListButtons(); private: berry::IQtStyleManager* styleManager; Ui::QtStylePreferencePageUI controls; - mitk::IPreferences* m_StylePref; berry::IQtStyleManager::Style oldStyle; berry::IQtStyleManager::StyleList styles; QWidget* mainWidget; }; } #endif /* BERRYQTSTYLEPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp index 5eb5443c39..2118c1b969 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp @@ -1,1978 +1,1976 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryLog.h" #include "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbench.h" #include #include "berryPolicy.h" #include "berrySaveablesList.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryEditorHistory.h" #include "berryEditorHistoryItem.h" #include "berryServiceLocatorCreator.h" #include "berryWorkbenchPage.h" #include "berryPerspective.h" #include "berryPreferenceConstants.h" #include "berryUIExtensionTracker.h" #include "berryWorkbenchWindow.h" #include "berryDisplay.h" #include "services/berryIServiceFactory.h" #include "util/berrySafeRunnable.h" #include "berryWorkbenchServiceRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchMenuService.h" #include "berryEvaluationService.h" #include "berryCommandService.h" #include "berryCommandManager.h" #include "berryMenuManager.h" #include "berryParameterType.h" #include "berryQActionProperties.h" #include "berrySourceProviderService.h" #include "berryWorkbenchLocationService.h" #include #include #include #include #include #include #include #include #include #include #include #include -#include #include namespace berry { Workbench* Workbench::instance = nullptr; WorkbenchTestable::Pointer Workbench::testableObject; const unsigned int Workbench::VERSION_STRING_COUNT = 1; const QString Workbench::VERSION_STRING[Workbench::VERSION_STRING_COUNT] = { "1.0" }; const QString Workbench::DEFAULT_WORKBENCH_STATE_FILENAME = "workbench.xml"; class RestoreStateRunnable: public SafeRunnable { private: Workbench* workbench; Poco::File stateFile; bool& result; public: RestoreStateRunnable(Workbench* workbench, const QString& stateFile, bool& result) : SafeRunnable( "Unable to read workbench state. Workbench UI layout will be reset."), workbench(workbench), stateFile(stateFile.toStdString()), result(result) { } void Run() override { Poco::FileInputStream input(stateFile.path()); IMemento::Pointer memento = XMLMemento::CreateReadRoot(input); // Validate known version format QString version; memento->GetString(WorkbenchConstants::TAG_VERSION, version); bool valid = false; for (auto & elem : Workbench::VERSION_STRING) { if (elem == version) { valid = true; break; } } if (!valid) { input.close(); QString msg = "Invalid workbench state version. workbench.xml will be deleted"; QMessageBox::critical(nullptr, "Restoring Problems", msg); stateFile.remove(); // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result = false; return; } // // Validate compatible version format // // We no longer support the release 1.0 format // if (VERSION_STRING[0].equals(version)) // { // reader.close(); // QString msg = "The saved user interface layout is in an " // "obsolete format and cannot be preserved. Your projects and files " // "will not be affected. Press OK to convert to the new format. Press " // "Cancel to exit with no changes."; // QList dlgLabels; // dlgLabels.push_back("Ok"); // dlgLabels.push_back("Cancel"); // IDialog::Pointer dlg = MessageDialog::CreateDialog(Shell::Pointer(0), // "Cannot Preserve Layout", 0, msg, IDialog::WARNING, dlgLabels, 0); // IDialog::ReturnCode ignoreSavedState = dlg->Open(); // // OK is the default // if (ignoreSavedState == IDialog::OK) // { // stateFile.remove(); // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, // // null); // result = false; // } // else // { // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_EXIT, msg, // // null); // result = false; // } // return; // } // Restore the saved state //final IStatus restoreResult = restoreState(memento); /*bool restoreResult =*/ workbench->RestoreState(memento); input.close(); // if (restoreResult.getSeverity() == IStatus.ERROR) { // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // StatusManager.getManager().handle(restoreResult, StatusManager.LOG); // } // }); // // } } void HandleException(const ctkException& e) override { //StartupThreading.runWithoutExceptions(new StartupRunnable() { //public void runWithException() { Handle(e); // QString msg = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$ // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, e); result = false; stateFile.remove(); // }}); } private: void Handle(const ctkException& e) { SafeRunnable::HandleException(e); } }; int Workbench::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { // create the workbench instance Workbench workbench(display, advisor); // run the workbench event loop int returnCode = workbench.RunUI(); return returnCode; } Display* Workbench::CreateDisplay() { // create the display Display* newDisplay = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDisplay(); // workaround for 1GEZ9UR and 1GF07HN //newDisplay.setWarnings(false); // Set the priority higher than normal so as to be higher // than the JobManager. //Poco::Thread::current()->setPriority(Poco::Thread::PRIO_HIGH); //initializeImages(); return newDisplay; } Workbench::ServiceLocatorOwner::ServiceLocatorOwner(Workbench* wb) : workbench(wb) { } void Workbench::ServiceLocatorOwner::Dispose() { QMessageBox::information( nullptr, "Restart needed", "A required plug-in is no longer available and the Workbench needs " "to be restarted. You will be prompted to save if there is any unsaved work."); workbench->Close(PlatformUI::RETURN_RESTART, true); } Workbench::Workbench(Display* display, WorkbenchAdvisor* advisor) : commandManager(nullptr), progressCount(-1) , serviceLocatorOwner(new ServiceLocatorOwner(this)) , largeUpdates(0), introManager(nullptr), isStarting(true), isClosing(false) , activeWorkbenchWindow(nullptr) { poco_check_ptr(display) ; poco_check_ptr(advisor); // the reference count to the one and only workbench instance // is increased, so that temporary smart pointer to the workbench // do not delete it this->Register(); this->display = display; this->advisor = advisor; Workbench::instance = this; serviceLocatorCreator.reset(new ServiceLocatorCreator()); serviceLocatorCreator->Register(); this->serviceLocator = serviceLocatorCreator->CreateServiceLocator( nullptr, nullptr, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); serviceLocator->RegisterService(serviceLocatorCreator.data()); workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WORKBENCH_SCOPE, this, nullptr, nullptr, 0)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); returnCode = PlatformUI::RETURN_UNSTARTABLE; } Display* Workbench::GetDisplay() const { return display; } Workbench* Workbench::GetInstance() { return instance; } WorkbenchTestable::Pointer Workbench::GetWorkbenchTestable() { if (!testableObject) { testableObject = new WorkbenchTestable(); } return testableObject; } Workbench::~Workbench() { this->instance = nullptr; this->UnRegister(false); } Object* Workbench::GetService(const QString& key) { return serviceLocator->GetService(key); } bool Workbench::HasService(const QString& key) const { return serviceLocator->HasService(key); } bool Workbench::Init() { // // setup debug mode if required. // if (WorkbenchPlugin.getDefault().isDebugging()) { // WorkbenchPlugin.DEBUG = true; // ModalContext.setDebugMode(true); // } bool bail = false; // create workbench window manager //windowManager = new WindowManager(); IIntroRegistry* introRegistry = WorkbenchPlugin::GetDefault()->GetIntroRegistry(); if (introRegistry->GetIntroCount() > 0) { IProduct::Pointer product = Platform::GetProduct(); if (product.IsNotNull()) { introDescriptor = introRegistry->GetIntroForProduct(product->GetId()).Cast(); } } // TODO Correctly order service initialization // there needs to be some serious consideration given to // the services, and hooking them up in the correct order evaluationService.reset(new EvaluationService()); evaluationService->Register(); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { serviceLocator->RegisterService(evaluationService.data()); // } // }); // Initialize the activity support. //workbenchActivitySupport = new WorkbenchActivitySupport(); //activityHelper = ActivityPersistanceHelper.getInstance(); this->InitializeDefaultServices(); // initializeFonts(); // initializeColors(); // initializeApplicationColors(); // now that the workbench is sufficiently initialized, let the advisor // have a turn. advisor->InternalBasicInitialize(this->GetWorkbenchConfigurer()); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { StartSourceProviders(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // activateWorkbenchContext(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // createApplicationMenu(); // } // }); // attempt to restore a previous workbench state advisor->PreStartup(); if (!advisor->OpenWindows()) { bail = true; } if (bail) return false; //forceOpenPerspective(); return true; } bool Workbench::RestoreState() { //return false; if (!GetWorkbenchConfigurer()->GetSaveAndRestore()) { // QString msg = "This application does not save and restore previously saved state."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // Read the workbench state file. QString stateFile = GetWorkbenchStateFile(); // If there is no state file cause one to open. if (stateFile.isEmpty() || !QFile::exists(stateFile)) { // QString msg = "No previously saved state to restore."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // final IStatus result[] = { new Status(IStatus.OK, // WorkbenchPlugin.PI_WORKBENCH, IStatus.OK, "", null) }; //$NON-NLS-1$ bool result = true; ISafeRunnable::Pointer runnable(new RestoreStateRunnable(this, stateFile, result)); SafeRunner::Run(runnable); // ensure at least one window was opened //if (result[0].isOK() && windowManager.getWindows().length == 0) if (result && windowManager.GetWindowCount() == 0) { QString msg = "No windows restored."; // result[0] = new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result &= false; } return result; } bool Workbench::RestoreState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.Workbench_problemsRestoring, null); bool result = true; const bool showProgress = false; //TODO restore state progress // final boolean showProgress = PrefUtil.getAPIPreferenceStore() // .getBoolean( // IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); try { /* * Restored windows will be set in the createdWindows field to be * used by the openWindowsAfterRestore() method */ if (!showProgress) { DoRestoreState(memento, result); } else { // Retrieve how many plug-ins were loaded while restoring the // workbench int lastProgressCount = -1; memento->GetInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, lastProgressCount); // If we don't know how many plug-ins were loaded last time, // assume we are loading half of the installed plug-ins. /*const std::size_t expectedProgressCount = std::max(1, lastProgressCount == -1 ? WorkbenchPlugin::GetDefault()->GetBundleCount() / 2 : lastProgressCount);*/ //TODO restore state progress // RunStartupWithProgress(expectedProgressCount, new Runnable() { // public void Run() { // DoRestoreState(memento, result); // } // }); } } catch (...) { OpenWindowsAfterRestore(); throw; } OpenWindowsAfterRestore(); return result; } void Workbench::DoRestoreState(IMemento::Pointer memento, bool& status) // final MultiStatus status) { IMemento::Pointer childMem; try { // UIStats.start(UIStats.RESTORE_WORKBENCH, "MRUList"); //$NON-NLS-1$ IMemento::Pointer mruMemento = memento ->GetChild(WorkbenchConstants::TAG_MRU_LIST); if (mruMemento) { // TODO restore editor history //status.add(getEditorHistory().restoreState(mruMemento)); } //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ } catch (...) { //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ throw; } // Restore advisor state. IMemento::Pointer advisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); if (advisorState) { //status.add(getAdvisor().restoreState(advisorState)); status &= GetAdvisor()->RestoreState(advisorState); } // Get the child windows. QList children = memento ->GetChildren(WorkbenchConstants::TAG_WINDOW); createdWindows.clear(); // Read the workbench windows. for (int i = 0; i < children.size(); i++) { childMem = children[i]; WorkbenchWindow::Pointer newWindow; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow = NewWorkbenchWindow(); newWindow->Create(); // }}); createdWindows.push_back(newWindow); // allow the application to specify an initial perspective to open // @issue temporary workaround for ignoring initial perspective // String initialPerspectiveId = // getAdvisor().getInitialWindowPerspectiveId(); // if (initialPerspectiveId != null) { // IPerspectiveDescriptor desc = // getPerspectiveRegistry().findPerspectiveWithId(initialPerspectiveId); // result.merge(newWindow.restoreState(childMem, desc)); // } // add the window so that any work done in newWindow.restoreState // that relies on Workbench methods has windows to work with windowManager.Add(newWindow); // now that we've added it to the window manager we need to listen // for any exception that might hose us before we get a chance to // open it. If one occurs, remove the new window from the manager. // Assume that the new window is a phantom for now try { //status.merge(newWindow[0].restoreState(childMem, null)); status &= newWindow->RestoreState(childMem, IPerspectiveDescriptor::Pointer(nullptr)); try { newWindow->FireWindowRestored(); } catch (const WorkbenchException& /*e*/) { //status.add(e.getStatus()); status &= false; } // everything worked so far, don't close now } catch (...) { // null the window in newWindowHolder so that it won't be // opened later on createdWindows[i] = nullptr; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newWindow->Close(); // }}); } } } void Workbench::OpenWindowsAfterRestore() { if (createdWindows.empty()) { return; } // now open the windows (except the ones that were nulled because we // closed them above) for (int i = 0; i < createdWindows.size(); i++) { if (createdWindows[i]) { WorkbenchWindow::Pointer myWindow = createdWindows[i]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { try { myWindow->Open(); } catch (...) { myWindow->Close(); throw; } // }}); } } createdWindows.clear(); } void Workbench::InitializeDefaultServices() { // final IContributionService contributionService = new ContributionService( // getAdvisor()); // serviceLocator.registerService(IContributionService.class, // contributionService); // // // TODO Correctly order service initialization // // there needs to be some serious consideration given to // // the services, and hooking them up in the correct order // // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { saveablesList.reset(new SaveablesList()); saveablesList->Register(); serviceLocator->RegisterService(saveablesList.data()); // }}); // /* * Phase 1 of the initialization of commands. When this phase completes, * all the services and managers will exist, and be accessible via the * getService(Object) method. */ // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { Command::DEBUG_COMMAND_EXECUTION = Policy::DEBUG_COMMANDS(); Command::DEBUG_HANDLERS = Policy::DEBUG_HANDLERS_VERBOSE(); Command::DEBUG_HANDLERS_COMMAND_ID = Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID(); commandManager.reset(new CommandManager()); // }}); // // final CommandService [] commandService = new CommandService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { commandService.reset(new CommandService(commandManager.data())); commandService->Register(); commandService->ReadRegistry(); serviceLocator->RegisterService(commandService.data()); // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // ContextManager.DEBUG = Policy.DEBUG_CONTEXTS; // contextManager = new ContextManager(); // }}); // // final IContextService contextService = new ContextService( // contextManager); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // contextService.readRegistry(); // }}); // // serviceLocator.registerService(IContextService.class, contextService); // // // final IBindingService [] bindingService = new BindingService[1]; // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // BindingManager.DEBUG = Policy.DEBUG_KEY_BINDINGS; // bindingManager = new BindingManager(contextManager, commandManager); // bindingService[0] = new BindingService( // bindingManager, commandService[0], Workbench.this); // // }}); // // bindingService[0].readRegistryAndPreferences(commandService[0]); // serviceLocator.registerService(IBindingService.class, bindingService[0]); // // final CommandImageManager commandImageManager = new CommandImageManager(); // final CommandImageService commandImageService = new CommandImageService( // commandImageManager, commandService[0]); // commandImageService.readRegistry(); // serviceLocator.registerService(ICommandImageService.class, // commandImageService); auto wms = new WorkbenchMenuService(serviceLocator.GetPointer()); menuService.reset(wms); menuService->Register(); serviceLocator->RegisterService(menuService.data()); // the service must be registered before it is initialized - its // initialization uses the service locator to address a dependency on // the menu service //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { wms->ReadRegistry(); // }}); // the source providers are now initialized in phase 3, but source // priorities have to be set before handler initialization // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { InitializeSourcePriorities(); // } // }); /* * Phase 2 of the initialization of commands. This handles the creation * of wrappers for legacy APIs. By the time this phase completes, any * code trying to access commands through legacy APIs should work. */ //IHandlerService* handlerService = nullptr; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { /*handlerService = */serviceLocator->GetService(); // } // }); // workbenchContextSupport = new WorkbenchContextSupport(this, // contextManager); // workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, // commandManager, contextManager, handlerService[0]); // initializeCommandResolver(); this->AddWindowListener(this); // bindingManager.addBindingManagerListener(bindingManagerListener); // serviceLocator.registerService(ISelectionConversionService.class, // new SelectionConversionService()); } int Workbench::RunUI() { // initialize workbench and restore or open one window bool initOK = this->Init(); // let the advisor run its start up code if (initOK) { advisor->PostStartup(); // may trigger a close/restart } //TODO start eager plug-ins //startPlugins(); //addStartupRegistryListener(); isStarting = false; BERRY_INFO << "BlueBerry Workbench ready"; this->GetWorkbenchTestable()->Init(Display::GetDefault(), this); // spin event loop return display->RunEventLoop(); } QString Workbench::GetDefaultPerspectiveId() const { return this->GetAdvisor()->GetInitialWindowPerspectiveId(); } IAdaptable* Workbench::GetDefaultPageInput() const { return this->GetAdvisor()->GetDefaultPageInput(); } QString Workbench::GetPresentationId() const { if (factoryID != "") { return factoryID; } //factoryID = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID); // Workaround for bug 58975 - New preference mechanism does not properly // initialize defaults // Ensure that the UI plugin has started too. factoryID = WorkbenchConstants::DEFAULT_PRESENTATION_ID; return factoryID; } IElementFactory* Workbench::GetElementFactory(const QString& factoryId) const { return WorkbenchPlugin::GetDefault()->GetElementFactory(factoryId); } void Workbench::UpdateTheme() { WorkbenchPlugin::GetDefault()->GetPresentationFactory()->UpdateTheme(); } void Workbench::LargeUpdateStart() { if (largeUpdates++ == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(false); // workbenchContextSupport.setProcessing(false); QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateStart(); } } } } void Workbench::LargeUpdateEnd() { if (--largeUpdates == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(true); // workbenchContextSupport.setProcessing(true); // Perform window-specific blocking. QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateEnd(); } } } } IExtensionTracker*Workbench::GetExtensionTracker() const { if (tracker.isNull()) { tracker.reset(new UIExtensionTracker(this->GetDisplay())); } return tracker.data(); } void Workbench::OpenFirstTimeWindow() { try { IAdaptable* input; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { input = this->GetDefaultPageInput(); // }}); this->BusyOpenWorkbenchWindow(this->GetPerspectiveRegistry()->GetDefaultPerspective(), input); } catch (WorkbenchException& e) { // Don't use the window's shell as the dialog parent, // as the window is not open yet (bug 76724). //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Problems_Opening_Page, e.getMessage(), e // .getStatus()); // }}); BERRY_ERROR << "Error: Problems opening page. " << e.what() << std::endl; } } WorkbenchConfigurer::Pointer Workbench::GetWorkbenchConfigurer() { if (workbenchConfigurer.IsNull()) { workbenchConfigurer = new WorkbenchConfigurer(); } return workbenchConfigurer; } WorkbenchAdvisor* Workbench::GetAdvisor() const { return advisor; } IViewRegistry* Workbench::GetViewRegistry() const { return WorkbenchPlugin::GetDefault()->GetViewRegistry(); } IEditorRegistry* Workbench::GetEditorRegistry() const { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } EditorHistory* Workbench::GetEditorHistory() const { if (editorHistory.isNull()) { editorHistory.reset(new EditorHistory()); } return editorHistory.data(); } IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() const { return WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry(); } bool Workbench::Close() { return this->Close(PlatformUI::RETURN_OK, false); } bool Workbench::Close(int returnCode, bool force) { BERRY_INFO << "Closing workbench..."; this->returnCode = returnCode; bool ret; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(force); // } //}); return ret; } /** * Closes the workbench. Assumes that the busy cursor is active. * * @param force * true if the close is mandatory, and false if the close is * allowed to fail * @return true if the close succeeded, and false otherwise */ bool Workbench::BusyClose(bool force) { // notify the advisor of preShutdown and allow it to veto if not forced isClosing = advisor->PreShutdown(); if (!force && !isClosing) { return false; } // notify regular workbench clients of preShutdown and allow them to // veto if not forced isClosing = this->FirePreShutdown(force); if (!force && !isClosing) { return false; } // save any open editors if they are dirty isClosing = this->SaveAllEditors(!force); if (!force && !isClosing) { return false; } bool closeEditors = !force && false; // false is the default for the not yet implemented preference below // && PrefUtil.getAPIPreferenceStore().getBoolean( // IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT); if (closeEditors) { // SafeRunner.run(new SafeRunnable() { // public void run() { QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchPage::Pointer page = windows[i]->GetActivePage(); if (page) isClosing = isClosing && page->CloseAllEditors(false); } // } //}); if (!force && !isClosing) { return false; } } if (this->GetWorkbenchConfigurer()->GetSaveAndRestore()) { try { // SafeRunner.run(new SafeRunnable() { // public void run() { XMLMemento::Pointer mem = RecordWorkbenchState(); // Save the IMemento to a file. SaveMementoToFile(mem); // } } catch(const ctkException& e) { // public void handleException(Throwable e) { QString message; if (e.what() == nullptr) { message = "An error has occurred. See error log for more details. Do you want to exit?"; } else { message = QString("An error has occurred: ") + e.what() + ". See error log for more details. Do you want to exit?"; } if (QMessageBox::question(nullptr, "Error", message) != QMessageBox::Yes) { isClosing = false; } } // } // }); } if (!force && !isClosing) { return false; } //SafeRunner.run(new SafeRunnable(WorkbenchMessages.ErrorClosing) { // public void run() { if (isClosing || force) { isClosing = windowManager.Close(); } // } //}); if (!force && !isClosing) { return false; } this->Shutdown(); display->ExitEventLoop(0); return true; } QString Workbench::GetWorkbenchStateFile() const { QString path = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (path.isNull()) { return QString(); } return QDir::cleanPath(path + "/" + DEFAULT_WORKBENCH_STATE_FILENAME); } /* * Save the workbench UI in a persistence file. */ bool Workbench::SaveMementoToFile(XMLMemento::Pointer memento) { // Save it to a file. // XXX: nobody currently checks the return value of this method. QString stateFile = GetWorkbenchStateFile(); if (stateFile.isNull()) { return false; } //BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; try { Poco::FileOutputStream stream(stateFile.toStdString()); memento->Save(stream); } catch (const Poco::IOException& /*e*/) { QFile::remove(stateFile); QMessageBox::critical(nullptr, "Saving Problems", "Unable to store workbench state."); return false; } // Success ! return true; } IWorkbenchWindow::Pointer Workbench::GetActiveWorkbenchWindow() const { // Look for the window that was last known being // the active one WorkbenchWindow::Pointer win = this->GetActivatedWindow(); return win; } std::size_t Workbench::GetWorkbenchWindowCount() const { return windowManager.GetWindowCount(); } QList Workbench::GetWorkbenchWindows() const { QList windows = windowManager.GetWindows(); QList result; for (QList::iterator iter = windows.begin(); iter != windows.end(); ++iter) { result.push_back(iter->Cast()); } return result; } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Run op in busy cursor. //final Object[] result = new Object[1]; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { return this->BusyOpenWorkbenchWindow(perspID, input); // } catch (WorkbenchException e) { // result[0] = e; // } // } //}); } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow(IAdaptable* input) { return this->OpenWorkbenchWindow(this->GetPerspectiveRegistry() ->GetDefaultPerspective(), input); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& perspectiveId, IWorkbenchWindow::Pointer window) { // If the specified window has the requested perspective open, then the // window // is given focus and the perspective is shown. The page's input is // ignored. WorkbenchWindow::Pointer win = window.Cast (); if (win) { IWorkbenchPage::Pointer page = win->GetActivePage(); if (page) { QList perspectives(page ->GetOpenPerspectives()); for (int i = 0; i < perspectives.size(); i++) { IPerspectiveDescriptor::Pointer persp = perspectives[i]; if (perspectiveId == persp->GetId()) { win->MakeVisible(); page->SetPerspective(persp); return page; } } } } // If another window that has the workspace root as input and the // requested // perpective open and active, then the window is given focus. IAdaptable* input = GetDefaultPageInput(); QList windows(GetWorkbenchWindows()); for (int i = 0; i < windows.size(); i++) { win = windows[i].Cast(); if (window != win) { WorkbenchPage::Pointer page = win->GetActivePage().Cast(); if (page) { bool inputSame = false; if (input == nullptr) { inputSame = (page->GetInput() == nullptr); } else { inputSame = input == page->GetInput(); } if (inputSame) { Perspective::Pointer persp = page->GetActivePerspective(); if (persp) { IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc) { if (perspectiveId == desc->GetId()) { Shell::Pointer shell = win->GetShell(); shell->Open(); if (shell->GetMinimized()) { shell->SetMinimized(false); } return page; } } } } } } } // Otherwise the requested perspective is opened and shown in the // specified // window or in a new window depending on the current user preference // for opening // perspectives, and that window is given focus. win = window.Cast(); if (win) { - auto* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); - int mode = store->GetSystemPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, - PreferenceConstants::OPM_ACTIVE_PAGE); + auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + int mode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = win->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page) { persp = page->GetPerspective(); } // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp) { IWorkbenchWindow::Pointer newWindow = OpenWorkbenchWindow(perspectiveId, input); return newWindow->GetActivePage(); } IPerspectiveDescriptor::Pointer desc = GetPerspectiveRegistry() ->FindPerspectiveWithId(perspectiveId); if (desc == 0) { throw WorkbenchException( "Unable to create perspective \"" + perspectiveId + "\". There is no corresponding perspective extension."); } win->GetShell()->Open(); if (page == 0) { page = win->OpenPage(perspectiveId, input); } else { page->SetPerspective(desc); } return page; } // Just throw an exception.... throw WorkbenchException("Problems opening perspective \"" + perspectiveId + "\""); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& /*perspectiveId*/, IWorkbenchWindow::Pointer /*window*/, IAdaptable* /*input*/) { return IWorkbenchPage::Pointer(nullptr); // // If the specified window has the requested perspective open and the // // same requested // // input, then the window is given focus and the perspective is shown. // bool inputSameAsWindow = false; // WorkbenchWindow::Pointer win = window.Cast(); // if (win.IsNotNull()) { // WorkbenchPage::Pointer page = win->GetActiveWorkbenchPage(); // if (page.IsNotNull()) { // bool inputSame = false; // if (input == 0) { // inputSame = (page->GetInput() == 0); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // inputSameAsWindow = true; // IPerspectiveDescriptor perspectives[] = page // .getOpenPerspectives(); // for (int i = 0; i < perspectives.length; i++) { // IPerspectiveDescriptor persp = perspectives[i]; // if (perspectiveId.equals(persp.getId())) { // win.makeVisible(); // page.setPerspective(persp); // return page; // } // } // } // } // } // // // If another window has the requested input and the requested // // perpective open and active, then that window is given focus. // IWorkbenchWindow[] windows = getWorkbenchWindows(); // for (int i = 0; i < windows.length; i++) { // win = (WorkbenchWindow) windows[i]; // if (window != win) { // WorkbenchPage page = win.getActiveWorkbenchPage(); // if (page != null) { // boolean inputSame = false; // if (input == null) { // inputSame = (page.getInput() == null); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // Perspective persp = page.getActivePerspective(); // if (persp != null) { // IPerspectiveDescriptor desc = persp.getDesc(); // if (desc != null) { // if (perspectiveId.equals(desc.getId())) { // win.getShell().open(); // return page; // } // } // } // } // } // } // } // // // If the specified window has the same requested input but not the // // requested // // perspective, then the window is given focus and the perspective is // // opened and shown // // on condition that the user preference is not to open perspectives in // // a new window. // win = (WorkbenchWindow) window; // if (inputSameAsWindow && win != null) { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int mode = store.getInt(IPreferenceConstants.OPEN_PERSP_MODE); // // if (IPreferenceConstants.OPM_NEW_WINDOW != mode) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // If the specified window has no active perspective, then open the // // requested perspective and show the specified window. // if (win != null) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor persp = null; // if (page != null) { // persp = page.getPerspective(); // } // if (persp == null) { // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // Otherwise the requested perspective is opened and shown in a new // // window, and the // // window is given focus. // IWorkbenchWindow newWindow = openWorkbenchWindow(perspectiveId, input); // return newWindow.getActivePage(); } bool Workbench::SaveAllEditors(bool /*confirm*/) { return true; } IIntroManager* Workbench::GetIntroManager() const { return GetWorkbenchIntroManager(); } WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() const { if (introManager.isNull()) { introManager.reset(new WorkbenchIntroManager(const_cast(this))); } return introManager.data(); } IntroDescriptor::Pointer Workbench::GetIntroDescriptor() const { return introDescriptor; } void Workbench::SetIntroDescriptor(IntroDescriptor::Pointer descriptor) { if (GetIntroManager()->GetIntro()) { GetIntroManager()->CloseIntro(GetIntroManager()->GetIntro()); } introDescriptor = descriptor; } bool Workbench::IsRunning() const { return Tweaklets::Get(WorkbenchTweaklet::KEY)->IsRunning(); } bool Workbench::IsStarting() const { return isStarting; } bool Workbench::IsClosing() const { return isClosing; } WorkbenchWindow::Pointer Workbench::GetActivatedWindow() const { return activatedWindow; } /* * Sets the workbench window which was last known being the active one, or * null . */ void Workbench::SetActivatedWindow(WorkbenchWindow::Pointer window) { activatedWindow = window; } WorkbenchWindow::Pointer Workbench::NewWorkbenchWindow() { WorkbenchWindow::Pointer wbw(new WorkbenchWindow(this->GetNewWindowNumber())); return wbw; } int Workbench::GetNewWindowNumber() { // Get window list. QList windows = windowManager.GetWindows(); int count = static_cast(windows.size()); // Create an array of booleans (size = window count). // Cross off every number found in the window list. auto checkArray = new bool[count]; for (int nX = 0; nX < count; ++nX) { if (windows[nX].Cast ().IsNotNull()) { WorkbenchWindow::Pointer ww = windows[nX].Cast (); int index = ww->GetNumber() - 1; if (index >= 0 && index < count) { checkArray[index] = true; } } } // Return first index which is not used. // If no empty index was found then every slot is full. // Return next index. for (int index = 0; index < count; index++) { if (!checkArray[index]) { delete[] checkArray; return index + 1; } } delete[] checkArray; return static_cast(count + 1); } IWorkbenchWindow::Pointer Workbench::BusyOpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Create a workbench window (becomes active window) //final WorkbenchWindow newWindowArray[] = new WorkbenchWindow[1]; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { // newWindowArray[0] = newWorkbenchWindow(); WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); // } //}); //final WorkbenchWindow newWindow = newWindowArray[0]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Create(); // must be created before adding to window // manager // } //}); windowManager.Add(newWindow); //final WorkbenchException [] exceptions = new WorkbenchException[1]; // Create the initial page. if (perspID != "") { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { try { newWindow->BusyOpenPage(perspID, input); } catch (WorkbenchException& e) { windowManager.Remove(newWindow); throw e; } } // Open window after opening page, to avoid flicker. //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Open(); // } //}); return newWindow; } bool Workbench::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Workbench_problemsSaving, null); bool result = true; // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING[0]); // Save how many plug-ins were loaded while restoring the workbench if (progressCount != -1) { memento->PutInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, progressCount); } // Save the advisor state. IMemento::Pointer advisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); //result.add(getAdvisor().saveState(advisorState)); result &= GetAdvisor()->SaveState(advisorState); // Save the workbench windows. QList windows(GetWorkbenchWindows()); for (int nX = 0; nX < windows.size(); nX++) { WorkbenchWindow::Pointer window = windows[nX].Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_WINDOW); //result.merge(window.saveState(childMem)); result &= window->SaveState(childMem); } // result.add(getEditorHistory().saveState( // memento.createChild(IWorkbenchConstants.TAG_MRU_LIST))); return result; } XMLMemento::Pointer Workbench::RecordWorkbenchState() { XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_WORKBENCH); //final IStatus status = saveState(memento); bool status = SaveState(memento); //if (status.getSeverity() != IStatus.OK) { if (!status) { // // don't use newWindow as parent because it has not yet been opened // // (bug 76724) // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Workbench_problemsSaving, // WorkbenchMessages.Workbench_problemsSavingMsg, status); // }}); } return memento; } void Workbench::AddWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.AddListener(listener); } void Workbench::RemoveWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.RemoveListener(listener); } IWorkbenchListener::Events& Workbench::GetWorkbenchEvents() { return workbenchEvents; } void Workbench::AddWindowListener(IWindowListener* l) { windowEvents.AddListener(l); } void Workbench::RemoveWindowListener(IWindowListener* l) { windowEvents.RemoveListener(l); } IWindowListener::Events& Workbench::GetWindowEvents() { return windowEvents; } bool Workbench::FirePreShutdown(bool forced) { //SafeRunnable.run(new SafeRunnable() { // public void run() { typedef IWorkbenchListener::Events::PreShutdownEvent::ListenerList ListenerList; const ListenerList& listeners = workbenchEvents.preShutdown.GetListeners(); for ( auto iter = listeners.begin(); iter != listeners.end(); ++iter ) { // notify each listener if (! (*iter)->Execute(dynamic_cast(this), forced)) return false; } // } return true; } /** * Fire workbench postShutdown event. * * @since 3.2 */ void Workbench::FirePostShutdown() { // SafeRunnable.run(new SafeRunnable() { // public void run() { workbenchEvents.postShutdown(this); // } } void Workbench::FireWindowOpened(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowOpened(window); // } } void Workbench::FireWindowClosed(IWorkbenchWindow::Pointer window) { if (activatedWindow == window) { // Do not hang onto it so it can be GC'ed activatedWindow = nullptr; } // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowClosed(window); // } } void Workbench::FireWindowActivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowActivated(window); // } } void Workbench::FireWindowDeactivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowDeactivated(window); // } } IWorkbenchWindow::Pointer Workbench::RestoreWorkbenchWindow(IMemento::Pointer memento) { WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); //newWindow.create(); windowManager.Add(newWindow); // whether the window was opened bool opened = false; try { newWindow->RestoreState(memento, IPerspectiveDescriptor::Pointer(nullptr)); newWindow->FireWindowRestored(); newWindow->Open(); opened = true; } catch (...) { if (!opened) { newWindow->Close(); } } return newWindow; } void Workbench::Shutdown() { // shutdown application-specific portions first advisor->PostShutdown(); // notify regular workbench clients of shutdown, and clear the list when // done this->FirePostShutdown(); //workbenchListeners.clear(); //cancelEarlyStartup(); // for dynamic UI // Platform.getExtensionRegistry().removeRegistryChangeListener( // extensionEventHandler); // Platform.getExtensionRegistry().removeRegistryChangeListener( // startupRegistryListener); // ((GrabFocus) Tweaklets.get(GrabFocus.KEY)).dispose(); // Bring down all of the services. serviceLocator->Dispose(); // workbenchActivitySupport.dispose(); // WorkbenchHelpSystem.disposeIfNecessary(); // shutdown the rest of the workbench // WorkbenchColors.shutdown(); // activityHelper.shutdown(); // uninitializeImages(); // if (WorkbenchPlugin.getDefault() != null) { // WorkbenchPlugin.getDefault().reset(); // } // WorkbenchThemeManager.getInstance().dispose(); // PropertyPageContributorManager.getManager().dispose(); // ObjectActionContributorManager.getManager().dispose(); // if (tracker != null) { // tracker.close(); // } Tweaklets::Clear(); } void Workbench::InitializeSourcePriorities() { WorkbenchServiceRegistry::GetRegistry()->InitializeSourcePriorities(); } void Workbench::StartSourceProviders() { /* * Phase 3 of the initialization of commands. The source providers that * the workbench provides are creating and registered with the above * services. These source providers notify the services when particular * pieces of workbench state change. */ IEvaluationService* const evaluationService = serviceLocator->GetService(); //IContextService* const contextService = serviceLocator->GetService(); auto sps = new SourceProviderService(serviceLocator.GetPointer()); sourceProviderService.reset(sps); sourceProviderService->Register(); serviceLocator->RegisterService(sourceProviderService.data()); struct SafeSourceProviderRunnable : public ISafeRunnable { SafeSourceProviderRunnable(SourceProviderService* sps, IEvaluationService* es) : sps(sps), es(es) {} void Run() override { // this currently instantiates all players ... sigh sps->ReadRegistry(); QList sp = sps->GetSourceProviders(); for (int i = 0; i < sp.size(); i++) { es->AddSourceProvider(sp[i]); //if (!(sp[i] instanceof ActiveContextSourceProvider)) //{ // contextService.addSourceProvider(sp[i]); //} } } void HandleException(const ctkException& exception) override { WorkbenchPlugin::Log("Failed to initialize a source provider", exception); } private: SourceProviderService* sps; IEvaluationService* es; }; ISafeRunnable::Pointer sourceProviderRunnable( new SafeSourceProviderRunnable(sps, evaluationService)); SafeRunner::Run(sourceProviderRunnable); // SafeRunner.run(new ISafeRunnable() { // public void run() throws Exception { // // these guys are need to provide the variables they say // // they source // actionSetSourceProvider = (ActionSetSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_ACTION_SETS_NAME); // FocusControlSourceProvider focusControl = (FocusControlSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_FOCUS_CONTROL_ID_NAME); // serviceLocator.registerService(IFocusService.class, focusControl); // menuSourceProvider = (MenuSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_MENU_NAME); // } // public void handleException(Throwable exception) { // WorkbenchPlugin.log("Failed to initialize a source provider", exception); //$NON-NLS-1$ // } // }); } void Workbench::UpdateActiveWorkbenchWindowMenuManager(bool textOnly) { if (activeWorkbenchWindow != nullptr) { // if (actionSetSourceProvider != null) // { // activeWorkbenchWindow->RemoveActionSetsListener(actionSetSourceProvider); // } activeWorkbenchWindow = nullptr; } //bool actionSetsUpdated = false; IWorkbenchWindow::Pointer workbenchWindow = GetActiveWorkbenchWindow(); if (WorkbenchWindow::Pointer wbWnd = workbenchWindow.Cast()) { activeWorkbenchWindow = wbWnd.GetPointer(); if (activeWorkbenchWindow->IsClosing()) { return; } // Update the action sets. // Shell::Pointer windowShell = activeWorkbenchWindow->GetShell(); // Shell::Pointer activeShell = GetDisplay()->GetActiveShell(); // IContextService* service = GetService(); // if ((Util.equals(windowShell, activeShell) || service.getShellType(activeShell) == IContextService.TYPE_WINDOW) // && actionSetSourceProvider != null) // { // activeWorkbenchWindow->AddActionSetsListener(actionSetSourceProvider); // final WorkbenchPage page = activeWorkbenchWindow.getActiveWorkbenchPage(); // final IActionSetDescriptor[] newActionSets; // if (page != null) // { // newActionSets = page.getActionSets(); // final ActionSetsEvent event = new ActionSetsEvent(newActionSets); // actionSetSourceProvider.actionSetsChanged(event); // actionSetsUpdated = true; // } // } MenuManager* menuManager = activeWorkbenchWindow->GetMenuManager(); if (textOnly) { menuManager->Update(QActionProperties::TEXT); } else { menuManager->Update(true); } } // if (!actionSetsUpdated && actionSetSourceProvider != null) // { // ActionSetsEvent event = new ActionSetsEvent(null); // actionSetSourceProvider.actionSetsChanged(event); // } } void Workbench::WindowActivated(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } void Workbench::WindowDeactivated(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } void Workbench::WindowClosed(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } void Workbench::WindowOpened(const IWorkbenchWindow::Pointer&) { this->UpdateActiveWorkbenchWindowMenuManager(true); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp index 0713959c31..7b314e961f 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp @@ -1,285 +1,292 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryPerspectivesPreferencePage.h" #include "ui_berryPerspectivesPreferencePage.h" #include #include "internal/berryPerspective.h" #include "internal/berryPerspectiveRegistry.h" #include "internal/berryPreferenceConstants.h" #include "internal/berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" #include #include -#include #include +namespace +{ + mitk::IPreferences* GetPreferences() + { + return berry::WorkbenchPlugin::GetDefault()->GetPreferences(); + } +} + 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); + auto* prefs = GetPreferences(); + prefs->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); + auto* prefs = GetPreferences(); + openPerspMode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); ui->sameWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_ACTIVE_PAGE); ui->newWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_NEW_WINDOW); // Populate the perspectivesTable perspectives.clear(); perspToRevert.clear(); perspToDelete.clear(); QList persps = perspRegistry->GetPerspectives(); for (int i = 0; i < persps.size(); i++) { perspectives.push_back(persps[i].Cast()); } qSort(perspectives.begin(), perspectives.end(), PerspectiveComparator); defaultPerspectiveId = perspRegistry->GetDefaultPerspective(); UpdatePerspectivesTable(); } void PerspectivesPreferencePage::OpenPerspInSameWindow() { openPerspMode = PreferenceConstants::OPM_ACTIVE_PAGE; } void PerspectivesPreferencePage::OpenPerspInNewWindow() { openPerspMode = PreferenceConstants::OPM_NEW_WINDOW; } void PerspectivesPreferencePage::PerspectiveSelectionChanged() { UpdateButtons(); } void PerspectivesPreferencePage::RevertPerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToRevert.contains(desc)) { perspToRevert.push_back(desc); } UpdateButtons(); } void PerspectivesPreferencePage::DeletePerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToDelete.contains(desc)) { if (!FindOpenInstance(desc)) { perspToDelete.push_back(desc); perspToRevert.removeAll(desc); perspectives.removeAll(desc); UpdatePerspectivesTable(); } } UpdateButtons(); } void PerspectivesPreferencePage::MakeDefaultPerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToDelete.contains(desc)) { int row = perspectives.indexOf(desc); defaultPerspectiveId = desc->GetId(); UpdatePerspectivesTable(); ui->perspectivesListWidget->item(row)->setSelected(true); } UpdateButtons(); } void PerspectivesPreferencePage::UpdateButtons() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc) { ui->revertButton->setEnabled(desc->IsPredefined() && desc->HasCustomDefinition() && !perspToRevert.contains(desc)); ui->deleteButton->setEnabled(!desc->IsPredefined()); ui->makeDefaultButton->setEnabled(true); } else { ui->revertButton->setEnabled(false); ui->deleteButton->setEnabled(false); ui->makeDefaultButton->setEnabled(false); } } void PerspectivesPreferencePage::UpdatePerspectivesTable() { ui->perspectivesListWidget->clear(); for (const PerspectiveDescriptor::Pointer &desc : qAsConst(perspectives)) { NewPerspectivesTableItem(desc); } } void PerspectivesPreferencePage::NewPerspectivesTableItem(const SmartPointer& desc) { QString label = desc->GetLabel(); if (desc->GetId() == defaultPerspectiveId) { label += " (default)"; } new QListWidgetItem(desc->GetImageDescriptor(), label, ui->perspectivesListWidget); } bool PerspectivesPreferencePage::FindOpenInstance(const PerspectiveDescriptor::Pointer& desc) { QList windows = workbench->GetWorkbenchWindows(); //find all active perspectives currently for (int i = 0; i < windows.size(); i++) { QList pages = windows[i]->GetPages(); for (int j = 0; j < pages.size(); j++) { WorkbenchPage::Pointer page = pages[j].Cast(); if (page->FindPerspective(desc).IsNotNull()) { QMessageBox::StandardButton returnCode = QMessageBox::question(workbench->GetActiveWorkbenchWindow()->GetShell()->GetControl(), "Delete Perspective", QString("Are you sure you want to delete the \"%1\" perspective? It has open instances.").arg(desc->GetLabel()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); return (returnCode != QMessageBox::Yes); } } } return false; } SmartPointer PerspectivesPreferencePage::GetSelectedPerspective() const { PerspectiveDescriptor::Pointer desc; QList selection = ui->perspectivesListWidget->selectedItems(); if (!selection.isEmpty()) { int row = ui->perspectivesListWidget->row(selection.back()); if (row > -1) { desc = perspectives.at(row); } } return desc; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h index 630920adda..1efcf4e31d 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h @@ -1,86 +1,80 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYPERSPECTIVESPREFERENCEPAGE_H #define BERRYPERSPECTIVESPREFERENCEPAGE_H #include -namespace mitk -{ - class IPreferences; -} - namespace Ui { class PerspectivesPreferencePage; } namespace berry { class PerspectiveDescriptor; class PerspectiveRegistry; class PerspectivesPreferencePage : public QObject, public IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: PerspectivesPreferencePage(); ~PerspectivesPreferencePage() override; void Init(IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; private: Q_SLOT void OpenPerspInSameWindow(); Q_SLOT void OpenPerspInNewWindow(); Q_SLOT void PerspectiveSelectionChanged(); Q_SLOT void RevertPerspective(); Q_SLOT void DeletePerspective(); Q_SLOT void MakeDefaultPerspective(); void UpdateButtons(); void UpdatePerspectivesTable(); void NewPerspectivesTableItem(const SmartPointer& desc); bool FindOpenInstance(const SmartPointer& desc); SmartPointer GetSelectedPerspective() const; Ui::PerspectivesPreferencePage* ui; QWidget* pageWidget; int openPerspMode; - mitk::IPreferences* preferences; IWorkbench* workbench; PerspectiveRegistry* perspRegistry; QString defaultPerspectiveId; QList > perspectives; QList > perspToRevert; QList > perspToDelete; }; } #endif // BERRYPERSPECTIVESPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp index 5a648390b6..2d848122fd 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp @@ -1,75 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkGeneralPreferencePage.h" #include "QmitkDataNodeGlobalReinitAction.h" #include #include #include #include #include +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID.toStdString()); + } +} + QmitkGeneralPreferencePage::QmitkGeneralPreferencePage() : m_MainControl(nullptr) { // nothing here } void QmitkGeneralPreferencePage::Init(berry::IWorkbench::Pointer) { // nothing here } void QmitkGeneralPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID.toStdString()); - m_MainControl = new QWidget(parent); m_GlobalReinitOnNodeDelete = new QCheckBox; m_GlobalReinitOnNodeVisibilityChanged = new QCheckBox; auto formLayout = new QFormLayout; formLayout->addRow("&Call global reinit if node is deleted", m_GlobalReinitOnNodeDelete); formLayout->addRow("&Call global reinit if node visibility is changed", m_GlobalReinitOnNodeVisibilityChanged); m_MainControl->setLayout(formLayout); Update(); } QWidget* QmitkGeneralPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkGeneralPreferencePage::PerformOk() { - m_GeneralPreferencesNode->PutBool("Call global reinit if node is deleted", m_GlobalReinitOnNodeDelete->isChecked()); - m_GeneralPreferencesNode->PutBool("Call global reinit if node visibility is changed", m_GlobalReinitOnNodeVisibilityChanged->isChecked()); + auto* prefs = GetPreferences(); + + prefs->PutBool("Call global reinit if node is deleted", m_GlobalReinitOnNodeDelete->isChecked()); + prefs->PutBool("Call global reinit if node visibility is changed", m_GlobalReinitOnNodeVisibilityChanged->isChecked()); return true; } void QmitkGeneralPreferencePage::PerformCancel() { // nothing here } void QmitkGeneralPreferencePage::Update() { - m_GlobalReinitOnNodeDelete->setChecked(m_GeneralPreferencesNode->GetBool("Call global reinit if node is deleted", true)); - m_GlobalReinitOnNodeVisibilityChanged->setChecked(m_GeneralPreferencesNode->GetBool("Call global reinit if node visibility is changed", false)); + auto* prefs = GetPreferences(); + + m_GlobalReinitOnNodeDelete->setChecked(prefs->GetBool("Call global reinit if node is deleted", true)); + m_GlobalReinitOnNodeVisibilityChanged->setChecked(prefs->GetBool("Call global reinit if node visibility is changed", false)); } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h index 214837be68..1745da9c3f 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.h @@ -1,75 +1,68 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKGENERALPREFERENCEPAGE_H #define QMITKGENERALPREFERENCEPAGE_H #include "berryIQtPreferencePage.h" class QWidget; class QCheckBox; -namespace mitk -{ - class IPreferences; -} - class QmitkGeneralPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkGeneralPreferencePage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench) override; /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget) override; /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const override; /** * @see berry::IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @see berry::IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @see berry::IPreferencePage::Update() */ void Update() override; protected: QWidget* m_MainControl; QCheckBox* m_GlobalReinitOnNodeDelete; QCheckBox* m_GlobalReinitOnNodeVisibilityChanged; - - mitk::IPreferences* m_GeneralPreferencesNode; }; #endif // QMITKGENERALPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp index 0b26b41e8f..2a5eb434d6 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp @@ -1,259 +1,268 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "CommandLineModulesPreferencesPage.h" #include "CommandLineModulesViewConstants.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkDirectoryListWidget.h" #include "QmitkFileListWidget.h" +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(CommandLineModulesViewConstants::VIEW_ID); + } +} + //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::CommandLineModulesPreferencesPage() : m_MainControl(nullptr) , m_DebugOutput(nullptr) , m_ShowAdvancedWidgets(nullptr) , m_OutputDirectory(nullptr) , m_TemporaryDirectory(nullptr) , m_ModulesDirectories(nullptr) , m_ModulesFiles(nullptr) , m_GridLayoutForLoadCheckboxes(nullptr) , m_LoadFromHomeDir(nullptr) , m_LoadFromHomeDirCliModules(nullptr) , m_LoadFromCurrentDir(nullptr) , m_LoadFromCurrentDirCliModules(nullptr) , m_LoadFromApplicationDir(nullptr) , m_LoadFromApplicationDirCliModules(nullptr) , m_LoadFromAutoLoadPathDir(nullptr) , m_ValidationMode(nullptr) , m_MaximumNumberProcesses(nullptr) -, m_CLIPreferencesNode(nullptr) { } //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::~CommandLineModulesPreferencesPage() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::CreateQtControl(QWidget* parent) { mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); - const auto id = "/" + CommandLineModulesViewConstants::VIEW_ID; - m_CLIPreferencesNode = prefService->GetSystemPreferences()->Node(id); - m_MainControl = new QWidget(parent); m_TemporaryDirectory = new ctkDirectoryButton(m_MainControl); m_TemporaryDirectory->setCaption("Select a directory for temporary files ... "); m_OutputDirectory = new ctkDirectoryButton(m_MainControl); m_OutputDirectory->setCaption("Select a default directory for output files ... "); m_ModulesDirectories = new QmitkDirectoryListWidget(m_MainControl); m_ModulesDirectories->m_Label->setText("Select directories to scan:"); m_ModulesFiles = new QmitkFileListWidget(m_MainControl); m_ModulesFiles->m_Label->setText("Select additional executables:"); m_DebugOutput = new QCheckBox(m_MainControl); m_DebugOutput->setToolTip("Output debugging information to the console."); m_ShowAdvancedWidgets = new QCheckBox(m_MainControl); m_ShowAdvancedWidgets->setToolTip("If selected, additional widgets appear\nin front-end for advanced users."); m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl); m_LoadFromAutoLoadPathDir->setText("CTK_MODULE_LOAD_PATH"); m_LoadFromAutoLoadPathDir->setToolTip("Scan the directory specified by\nthe environment variable CTK_MODULE_LOAD_PATH."); m_LoadFromAutoLoadPathDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDir = new QCheckBox(m_MainControl); m_LoadFromApplicationDir->setText("install dir"); m_LoadFromApplicationDir->setToolTip("Scan the directory where\nthe application is installed."); m_LoadFromApplicationDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDirCliModules = new QCheckBox(m_MainControl); m_LoadFromApplicationDirCliModules->setText("install dir/cli-modules"); m_LoadFromApplicationDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the installation directory."); m_LoadFromApplicationDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDir = new QCheckBox(m_MainControl); m_LoadFromHomeDir->setText("home dir"); m_LoadFromHomeDir->setToolTip("Scan the users home directory."); m_LoadFromHomeDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDirCliModules = new QCheckBox(m_MainControl); m_LoadFromHomeDirCliModules->setText("home dir/cli-modules"); m_LoadFromHomeDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the users home directory."); m_LoadFromHomeDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDir = new QCheckBox(m_MainControl); m_LoadFromCurrentDir->setText("current dir"); m_LoadFromCurrentDir->setToolTip("Scan the current working directory\nfrom where the application was launched."); m_LoadFromCurrentDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDirCliModules = new QCheckBox(m_MainControl); m_LoadFromCurrentDirCliModules->setText("current dir/cli-modules"); m_LoadFromCurrentDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the current working directory \n from where the application was launched."); m_LoadFromCurrentDirCliModules->setLayoutDirection(Qt::RightToLeft); m_GridLayoutForLoadCheckboxes = new QGridLayout; m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDir, 0, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDirCliModules, 0, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDir, 1, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDirCliModules, 1, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDir, 2, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDirCliModules, 2, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromAutoLoadPathDir, 3, 1); m_ValidationMode = new QComboBox(m_MainControl); m_ValidationMode->addItem("strict", ctkCmdLineModuleManager::STRICT_VALIDATION); m_ValidationMode->addItem("none", ctkCmdLineModuleManager::SKIP_VALIDATION); m_ValidationMode->addItem("weak", ctkCmdLineModuleManager::WEAK_VALIDATION); m_ValidationMode->setCurrentIndex(0); m_MaximumNumberProcesses = new QSpinBox(m_MainControl); m_MaximumNumberProcesses->setMinimum(1); m_MaximumNumberProcesses->setMaximum(1000000); m_XmlTimeoutInSeconds = new QSpinBox(m_MainControl); m_XmlTimeoutInSeconds->setMinimum(1); m_XmlTimeoutInSeconds->setMaximum(3600); auto formLayout = new QFormLayout; formLayout->addRow("show debug output:", m_DebugOutput); formLayout->addRow("show advanced widgets:", m_ShowAdvancedWidgets); formLayout->addRow("XML time-out (secs):", m_XmlTimeoutInSeconds); formLayout->addRow("XML validation mode:", m_ValidationMode); formLayout->addRow("max. concurrent processes:", m_MaximumNumberProcesses); formLayout->addRow("scan:", m_GridLayoutForLoadCheckboxes); formLayout->addRow("additional module directories:", m_ModulesDirectories); formLayout->addRow("additional modules:", m_ModulesFiles); formLayout->addRow("temporary directory:", m_TemporaryDirectory); formLayout->addRow("default output directory:", m_OutputDirectory); m_MainControl->setLayout(formLayout); this->Update(); } //----------------------------------------------------------------------------- QWidget* CommandLineModulesPreferencesPage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- std::string CommandLineModulesPreferencesPage::ConvertToStdString(const QStringList& list) { std::string output; for (int i = 0; i < list.count(); i++) { QString path = list[i] + ";"; output += path.toStdString(); } return output; } //----------------------------------------------------------------------------- bool CommandLineModulesPreferencesPage::PerformOk() { - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory().toStdString()); - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory().toStdString()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, m_ShowAdvancedWidgets->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, m_LoadFromApplicationDirCliModules->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, m_LoadFromHomeDirCliModules->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, m_LoadFromCurrentDirCliModules->isChecked()); - m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); + auto* prefs = GetPreferences(); + + prefs->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory().toStdString()); + prefs->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory().toStdString()); + prefs->PutBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, m_ShowAdvancedWidgets->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, m_LoadFromApplicationDirCliModules->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, m_LoadFromHomeDirCliModules->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, m_LoadFromCurrentDirCliModules->isChecked()); + prefs->PutBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); const auto paths = m_ModulesDirectories->directories().join(";").toStdString(); - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, paths); + prefs->Put(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, paths); const auto modules = m_ModulesFiles->files().join(";").toStdString(); - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, modules); + prefs->Put(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, modules); - int currentValidationMode = m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2); + int currentValidationMode = prefs->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2); if (currentValidationMode != m_ValidationMode->currentIndex()) { QMessageBox msgBox; msgBox.setText("Changing the XML validation mode will require a restart of the application."); msgBox.exec(); } - m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, m_ValidationMode->currentIndex()); - m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, m_XmlTimeoutInSeconds->value()); - m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::MAX_CONCURRENT, m_MaximumNumberProcesses->value()); + prefs->PutInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, m_ValidationMode->currentIndex()); + prefs->PutInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, m_XmlTimeoutInSeconds->value()); + prefs->PutInt(CommandLineModulesViewConstants::MAX_CONCURRENT, m_MaximumNumberProcesses->value()); return true; } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::PerformCancel() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Update() { + auto* prefs = GetPreferences(); + const auto fallbackTmpDir = QDir::tempPath().toStdString(); - m_TemporaryDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir))); + m_TemporaryDirectory->setDirectory(QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir))); const auto fallbackOutputDir = QDir::homePath().toStdString(); - m_OutputDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir))); - - m_ShowAdvancedWidgets->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); - m_DebugOutput->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false)); - m_LoadFromApplicationDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false)); - m_LoadFromApplicationDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true)); - m_LoadFromHomeDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false)); - m_LoadFromHomeDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false)); - m_LoadFromCurrentDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false)); - m_LoadFromCurrentDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false)); - m_LoadFromAutoLoadPathDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); - - const auto paths = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); + m_OutputDirectory->setDirectory(QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir))); + + m_ShowAdvancedWidgets->setChecked(prefs->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); + m_DebugOutput->setChecked(prefs->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false)); + m_LoadFromApplicationDir->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false)); + m_LoadFromApplicationDirCliModules->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true)); + m_LoadFromHomeDir->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false)); + m_LoadFromHomeDirCliModules->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false)); + m_LoadFromCurrentDir->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false)); + m_LoadFromCurrentDirCliModules->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false)); + m_LoadFromAutoLoadPathDir->setChecked(prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); + + const auto paths = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); QStringList directoryList = paths.split(";", QString::SkipEmptyParts); m_ModulesDirectories->setDirectories(directoryList); - const auto files = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); + const auto files = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); QStringList fileList = files.split(";", QString::SkipEmptyParts); m_ModulesFiles->setFiles(fileList); - m_ValidationMode->setCurrentIndex(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2)); - m_XmlTimeoutInSeconds->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30)); // 30 secs = QProcess default timeout - m_MaximumNumberProcesses->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4)); + m_ValidationMode->setCurrentIndex(prefs->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2)); + m_XmlTimeoutInSeconds->setValue(prefs->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30)); // 30 secs = QProcess default timeout + m_MaximumNumberProcesses->setValue(prefs->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4)); } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h index 6fe94807f4..41f7aefb28 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h @@ -1,112 +1,105 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef COMMANDLINEMODULESPREFERENCESPAGE_H #define COMMANDLINEMODULESPREFERENCESPAGE_H #include "berryIQtPreferencePage.h" #include class QWidget; class QGridLayout; class QCheckBox; class QComboBox; class QSpinBox; class QmitkDirectoryListWidget; class QmitkFileListWidget; class ctkDirectoryButton; -namespace mitk -{ - class IPreferences; -} - /** * \class CommandLineModulesPreferencesPage * \brief Preference page for CommandLineModulesView * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ class CommandLineModulesPreferencesPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: CommandLineModulesPreferencesPage(); ~CommandLineModulesPreferencesPage() override; /** * \brief Called by framework to initialise this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: protected: QWidget *m_MainControl; QCheckBox *m_DebugOutput; QCheckBox *m_ShowAdvancedWidgets; ctkDirectoryButton *m_OutputDirectory; ctkDirectoryButton *m_TemporaryDirectory; QmitkDirectoryListWidget *m_ModulesDirectories; QmitkFileListWidget *m_ModulesFiles; QGridLayout *m_GridLayoutForLoadCheckboxes; QCheckBox *m_LoadFromHomeDir; QCheckBox *m_LoadFromHomeDirCliModules; QCheckBox *m_LoadFromCurrentDir; QCheckBox *m_LoadFromCurrentDirCliModules; QCheckBox *m_LoadFromApplicationDir; QCheckBox *m_LoadFromApplicationDirCliModules; QCheckBox *m_LoadFromAutoLoadPathDir; QComboBox *m_ValidationMode; QSpinBox *m_XmlTimeoutInSeconds; QSpinBox *m_MaximumNumberProcesses; - mitk::IPreferences* m_CLIPreferencesNode; - private: std::string ConvertToStdString(const QStringList& list); }; #endif // COMMANDLINEMODULESPREFERENCESPAGE_H diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h index 25be8da301..be48c78656 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h @@ -1,249 +1,244 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef CommandLineModulesView_h #define CommandLineModulesView_h #include #include #include #include class ctkCmdLineModuleBackendLocalProcess; class ctkCmdLineModuleDirectoryWatcher; class CommandLineModulesViewControls; class QmitkCmdLineModuleRunner; class QAction; class QVBoxLayout; -namespace mitk -{ - class IPreferences; -} - /*! * \class CommandLineModulesView * \brief Provides basic GUI interface to the CTK command line modules. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal * \sa QmitkAbstractView */ class CommandLineModulesView : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: CommandLineModulesView(); ~CommandLineModulesView() override; /** * \brief Main method, called by framework to create the GUI at the right time. * \param parent The parent QWidget, as this class itself is not a QWidget subclass. */ void CreateQtPartControl(QWidget *parent) override; /** * \brief Called by the framework to indicate that the preferences have changed. * \param prefs not used, as we call RetrievePreferenceValues(). */ void OnPreferencesChanged(const mitk::IPreferences* prefs) override; protected Q_SLOTS: /** * \brief Called when the ctkMenuComboBox has the menu selection changed, * and causes the corresponding GUI to be displayed. */ void OnActionChanged(QAction*); /** * \brief Slot that is called when the restore defaults button is pressed, * to reset the current GUI form to the default values, if the XML specifies defaults. */ void OnRestoreButtonPressed(); /** * \brief Slot that is called when the Run button is pressed to run the current module. */ void OnRunButtonPressed(); /** * \brief Alerts the user of any errors comming out of the directory watcher. */ void OnDirectoryWatcherErrorsDetected(const QString&); protected: /** * \brief Called by framework to set the focus on the right widget * when this view has focus, so currently, thats the ctkMenuCombo box. */ void SetFocus() override; private slots: /** * \brief Called when the user clicks to close a tab, and removes the front end from m_ListOfModules */ void OnTabCloseRequested(int tabNumber); /** * \brief Called from QmitkCmdLineModuleProgressWidget to indicate a job has started. */ void OnJobStarted(); /** * \brief Called from QmitkCmdLineModuleProgressWidget to indicate a job has finished. */ void OnJobFinished(); /** * \brief Called when the user hits the 'clear XML cache' button. */ void OnClearCache(); /** * \brief Called when the user hits the 'reload modules' button. */ void OnReloadModules(); private: /** * \brief Called on startup and by OnPreferencesChanged to load all * preferences except the temporary folder into member variables. */ void RetrieveAndStorePreferenceValues(); /** * \brief Called on startup and by OnPreferencesChanged to load the temporary folder * preference into member variable m_TemporaryDirectoryName. */ void RetrieveAndStoreTemporaryDirectoryPreferenceValues(); /** * \brief Called on startup and by OnPreferencesChanged to set the validation mode, but will require a restart. */ void RetrieveAndStoreValidationMode(); /** * \brief Called to get hold of the actual preferences node. */ mitk::IPreferences* RetrievePreferences() const; /** * \brief Search all modules for the one matching the given identifier. * \param fullName The "fullName" is the . from the XML. * \return ctkCmdLineModuleReference the reference corresponding to the fullName, or an invalid reference if non found. */ ctkCmdLineModuleReference GetReferenceByFullName(QString fullName); /** * \brief Raises a message box asking the user to select a module first. */ void AskUserToSelectAModule() const; /** * \brief Enables or Disables the Run Button. */ void UpdateRunButtonEnabledStatus(); /** * \brief The GUI controls contain a reset and run button, and a QWidget container, and the GUI component * for each command line module is added to the QWidget dynamically at run time. */ CommandLineModulesViewControls *m_Controls; /** * \brief We store the parent, passed in via CommandLineModulesView::CreateQtPartControl, * as this class itself is not a QWidget. */ QWidget *m_Parent; /** * \brief We keep a local layout, and arrange a display of QmitkCmdLineModuleProgressWidget, * where each QmitkCmdLineModuleProgressWidget represents a single running job. */ QVBoxLayout *m_Layout; /** * \brief The manager is responsible for loading and instantiating command line modules. */ ctkCmdLineModuleManager *m_ModuleManager; /** * \brief We are using a back-end that runs locally installed command line programs. */ ctkCmdLineModuleBackendLocalProcess *m_ModuleBackend; /** * \brief The ctkCmdLineModuleDirectoryWatcher maintains the list of directories * we are using to load modules, to provide automatic updates. */ ctkCmdLineModuleDirectoryWatcher *m_DirectoryWatcher; /** * \brief We store a temporary folder name, accessible via user preferences. */ QString m_TemporaryDirectoryName; /** * \brief We store an output folder name, accessible via user preferences for when * the file specified in a default output path is not within a writable directory. */ QString m_OutputDirectoryName; /** * \brief Cache the list of directory paths locally to avoid repeatedly trying to update Directory Watcher. */ QStringList m_DirectoryPaths; /** * \brief Cache the list of module/executable paths locally to avoid repeatedly trying to update Directory Watcher. */ QStringList m_ModulePaths; /** * \brief We store the validation mode, accessisble via user preferences. */ ctkCmdLineModuleManager::ValidationMode m_ValidationMode; /** * \brief We store the maximum number of concurrent processes, and disable the run button accordingly. */ int m_MaximumConcurrentProcesses; /** * \brief Counts the number of currently running processes. */ int m_CurrentlyRunningProcesses; /** * \brief Member variable, taken from preference page. */ bool m_DebugOutput; /** * \brief Member variable, taken from preferences page. */ int m_XmlTimeoutSeconds; /** * \brief We keep a list of front ends to match the m_TabWidget. */ QList<ctkCmdLineModuleFrontend*> m_ListOfModules; }; #endif // CommandLineModulesView_h diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp index f291ef224b..3acb39095b 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp @@ -1,136 +1,145 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDataManagerHotkeysPrefPage.h" // mitk qt widgets ext module #include <QmitkHotkeyLineEdit.h> // berry #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> // qt #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("DataManager/Hotkeys"); + } +} + QmitkDataManagerHotkeysPrefPage::QmitkDataManagerHotkeysPrefPage() : m_MainControl(nullptr) { } void QmitkDataManagerHotkeysPrefPage::Init(berry::IWorkbench::Pointer) { } void QmitkDataManagerHotkeysPrefPage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - auto* dataManagerHotkeysPreferencesNode = prefService->GetSystemPreferences()->Node("/DataManager/Hotkeys"); - m_DataManagerHotkeysPreferencesNode = dataManagerHotkeysPreferencesNode; - m_HotkeyEditors["Make all nodes invisible"] = new QmitkHotkeyLineEdit("Ctrl+V"); m_HotkeyEditors["Toggle visibility of selected nodes"] = new QmitkHotkeyLineEdit("V"); m_HotkeyEditors["Delete selected nodes"] = new QmitkHotkeyLineEdit("Del"); m_HotkeyEditors["Reinit selected nodes"] = new QmitkHotkeyLineEdit("R"); m_HotkeyEditors["Global reinit"] = new QmitkHotkeyLineEdit("Ctrl+R"); m_HotkeyEditors["Show node information"] = new QmitkHotkeyLineEdit("Ctrl+I"); m_MainControl = new QWidget(parent); auto layout = new QGridLayout; int i = 0; for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) { layout->addWidget(new QLabel(it->first), i, 0); layout->addWidget(it->second, i, 1); layout->setRowStretch(i, 0); ++i; } layout->setRowStretch(i + 1, 10); m_MainControl->setLayout(layout); Update(); } QWidget* QmitkDataManagerHotkeysPrefPage::GetQtControl() const { return m_MainControl; } bool QmitkDataManagerHotkeysPrefPage::PerformOk() { - if (m_DataManagerHotkeysPreferencesNode != nullptr) + auto* prefs = GetPreferences(); + + if (prefs != nullptr) { QString keyString; QString errString; for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) { keyString = it->second->GetKeySequenceAsString(); if (keyString.isEmpty()) { errString = QString("No valid key sequence for \"%1\"").arg(it->first); } if (errString.isEmpty()) { std::map<QString, QmitkHotkeyLineEdit*>::iterator it2; // search for duplicated key for (it2 = m_HotkeyEditors.begin(); it2 != m_HotkeyEditors.end(); ++it2) { if (it->first != it2->first && keyString == it2->second->GetKeySequenceAsString()) { errString = QString("Duplicate hot key for \"%1\" and \"%2\"").arg(it->first).arg(it2->first); break; } } } if (!errString.isEmpty()) { QMessageBox::critical(QApplication::activeWindow(), "Error", errString); return false; } } // no errors -> save all values and flush to file for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) { QString keySequence = it->second->GetKeySequenceAsString(); - m_DataManagerHotkeysPreferencesNode->Put(it->first.toStdString(), it->second->GetKeySequenceAsString().toStdString()); + prefs->Put(it->first.toStdString(), it->second->GetKeySequenceAsString().toStdString()); } - m_DataManagerHotkeysPreferencesNode->Flush(); + prefs->Flush(); return true; } return false; } void QmitkDataManagerHotkeysPrefPage::PerformCancel() { } void QmitkDataManagerHotkeysPrefPage::Update() { - if (m_DataManagerHotkeysPreferencesNode != nullptr) + auto* prefs = GetPreferences(); + + if (prefs != nullptr) { for (auto it = m_HotkeyEditors.begin(); it != m_HotkeyEditors.end(); ++it) - it->second->setText(QString::fromStdString(m_DataManagerHotkeysPreferencesNode->Get(it->first.toStdString(), it->second->text().toStdString()))); + it->second->setText(QString::fromStdString(prefs->Get(it->first.toStdString(), it->second->text().toStdString()))); } } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h index 586c5cff0a..c372058f90 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h @@ -1,78 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERHOTKEYSPREFPAGE_H #define QMITKDATAMANAGERHOTKEYSPREFPAGE_H #include <org_mitk_gui_qt_datamanager_Export.h> // blueberry ui qt plugin #include <berryIQtPreferencePage.h> // qt #include <QWidget> // c++ #include <map> -namespace mitk -{ - class IPreferences; -} - class QmitkHotkeyLineEdit; struct MITK_QT_DATAMANAGER QmitkDataManagerHotkeysPrefPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDataManagerHotkeysPrefPage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; /** * @brief \see IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @brief \see IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @brief \see IPreferencePage::Update() */ void Update() override; protected: - /** - * @brief The node from which the properties are taken (will be catched from the preferences service in ctor) - * - * - */ - mitk::IPreferences* m_DataManagerHotkeysPreferencesNode; /** * @brief Maps a label to hotkey lineedit, e.g. "Toggle Visibility of selected nodes" => QmitkHotkeyLineEdit * * */ std::map<QString, QmitkHotkeyLineEdit*> m_HotkeyEditors; QWidget* m_MainControl; }; #endif // QMITKDATAMANAGERHOTKEYSPREFPAGE_H diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp index 9db87ead55..852c9deee8 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp @@ -1,89 +1,98 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDataManagerPreferencePage.h" #include "QmitkDataManagerView.h" #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QCheckBox> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(QmitkDataManagerView::VIEW_ID.toStdString()); + } +} + QmitkDataManagerPreferencePage::QmitkDataManagerPreferencePage() : m_MainControl(nullptr) { // nothing here } void QmitkDataManagerPreferencePage::Init(berry::IWorkbench::Pointer ) { // nothing here } void QmitkDataManagerPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_DataManagerPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataManagerView::VIEW_ID.toStdString()); - m_MainControl = new QWidget(parent); m_EnableSingleEditing = new QCheckBox; m_PlaceNewNodesOnTop = new QCheckBox; m_ShowHelperObjects = new QCheckBox; m_ShowNodesContainingNoData = new QCheckBox; m_AllowParentChange = new QCheckBox; auto formLayout = new QFormLayout; formLayout->addRow("&Single click property editing:", m_EnableSingleEditing); formLayout->addRow("&Place new nodes on top:", m_PlaceNewNodesOnTop); formLayout->addRow("&Show helper objects:", m_ShowHelperObjects); formLayout->addRow("&Show nodes containing no data", m_ShowNodesContainingNoData); formLayout->addRow("&Allow changing of parent node:", m_AllowParentChange); m_MainControl->setLayout(formLayout); Update(); } QWidget* QmitkDataManagerPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkDataManagerPreferencePage::PerformOk() { - m_DataManagerPreferencesNode->PutBool("Single click property editing", m_EnableSingleEditing->isChecked()); - m_DataManagerPreferencesNode->PutBool("Place new nodes on top", m_PlaceNewNodesOnTop->isChecked()); - m_DataManagerPreferencesNode->PutBool("Show helper objects", m_ShowHelperObjects->isChecked()); - m_DataManagerPreferencesNode->PutBool("Show nodes containing no data", m_ShowNodesContainingNoData->isChecked()); - m_DataManagerPreferencesNode->PutBool("Allow changing of parent node", m_AllowParentChange->isChecked()); + auto* prefs = GetPreferences(); + + prefs->PutBool("Single click property editing", m_EnableSingleEditing->isChecked()); + prefs->PutBool("Place new nodes on top", m_PlaceNewNodesOnTop->isChecked()); + prefs->PutBool("Show helper objects", m_ShowHelperObjects->isChecked()); + prefs->PutBool("Show nodes containing no data", m_ShowNodesContainingNoData->isChecked()); + prefs->PutBool("Allow changing of parent node", m_AllowParentChange->isChecked()); return true; } void QmitkDataManagerPreferencePage::PerformCancel() { // nothing here } void QmitkDataManagerPreferencePage::Update() { - m_EnableSingleEditing->setChecked(m_DataManagerPreferencesNode->GetBool("Single click property editing", true)); - m_PlaceNewNodesOnTop->setChecked(m_DataManagerPreferencesNode->GetBool("Place new nodes on top", true)); - m_ShowHelperObjects->setChecked(m_DataManagerPreferencesNode->GetBool("Show helper objects", false)); - m_ShowNodesContainingNoData->setChecked(m_DataManagerPreferencesNode->GetBool("Show nodes containing no data", false)); - m_AllowParentChange->setChecked(m_DataManagerPreferencesNode->GetBool("Allow changing of parent node", false)); + auto* prefs = GetPreferences(); + + m_EnableSingleEditing->setChecked(prefs->GetBool("Single click property editing", true)); + m_PlaceNewNodesOnTop->setChecked(prefs->GetBool("Place new nodes on top", true)); + m_ShowHelperObjects->setChecked(prefs->GetBool("Show helper objects", false)); + m_ShowNodesContainingNoData->setChecked(prefs->GetBool("Show nodes containing no data", false)); + m_AllowParentChange->setChecked(prefs->GetBool("Allow changing of parent node", false)); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h index 6f3d31983c..c285096316 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h @@ -1,67 +1,61 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKDATAMANAGERPREFERENCEPAGE_H_ #define QMITKDATAMANAGERPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include <org_mitk_gui_qt_datamanager_Export.h> class QWidget; class QCheckBox; -namespace mitk -{ - class IPreferences; -} - struct MITK_QT_DATAMANAGER QmitkDataManagerPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDataManagerPreferencePage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected: QWidget* m_MainControl; QCheckBox* m_EnableSingleEditing; QCheckBox* m_PlaceNewNodesOnTop; QCheckBox* m_ShowHelperObjects; QCheckBox* m_ShowNodesContainingNoData; QCheckBox* m_AllowParentChange; - mitk::IPreferences* m_DataManagerPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp index 01aec2ee1e..23e017ba55 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp @@ -1,114 +1,124 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkNodeTableViewKeyFilter.h" #include "../QmitkDataManagerView.h" // mitk gui qt application plugin #include <QmitkDataNodeGlobalReinitAction.h> #include <QmitkDataNodeHideAllAction.h> #include <QmitkDataNodeReinitAction.h> #include <QmitkDataNodeRemoveAction.h> #include <QmitkDataNodeShowDetailsAction.h> #include <QmitkDataNodeToggleVisibilityAction.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> // qt #include <QKeyEvent> #include <QKeySequence> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("DataManager/Hotkeys"); + } +} + QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter(QObject *dataManagerView, mitk::DataStorage *dataStorage) : QObject(dataManagerView), m_DataStorage(dataStorage) { - m_Preferences = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/DataManager/Hotkeys"); } bool QmitkNodeTableViewKeyFilter::eventFilter(QObject *obj, QEvent *event) { auto dataStorage = m_DataStorage.Lock(); if (dataStorage.IsNull()) { // standard event processing return QObject::eventFilter(obj, event); } QmitkDataManagerView *dataManagerView = qobject_cast<QmitkDataManagerView *>(this->parent()); if (event->type() == QEvent::KeyPress && dataManagerView) { - QKeySequence makeAllInvisible = QKeySequence(QString::fromStdString(m_Preferences->Get("Make all nodes invisible", "Ctrl+V"))); - QKeySequence toggleVisibility = QKeySequence(QString::fromStdString(m_Preferences->Get("Toggle visibility of selected nodes", "V"))); - QKeySequence deleteSelectedNodes = QKeySequence(QString::fromStdString(m_Preferences->Get("Delete selected nodes", "Del"))); - QKeySequence reinit = QKeySequence(QString::fromStdString(m_Preferences->Get("Reinit selected nodes", "R"))); - QKeySequence globalReinit = QKeySequence(QString::fromStdString(m_Preferences->Get("Global reinit", "Ctrl+R"))); - QKeySequence showInfo = QKeySequence(QString::fromStdString(m_Preferences->Get("Show node information", "Ctrl+I"))); + auto* prefs = GetPreferences(); + + QKeySequence makeAllInvisible = QKeySequence(QString::fromStdString(prefs->Get("Make all nodes invisible", "Ctrl+V"))); + QKeySequence toggleVisibility = QKeySequence(QString::fromStdString(prefs->Get("Toggle visibility of selected nodes", "V"))); + QKeySequence deleteSelectedNodes = QKeySequence(QString::fromStdString(prefs->Get("Delete selected nodes", "Del"))); + QKeySequence reinit = QKeySequence(QString::fromStdString(prefs->Get("Reinit selected nodes", "R"))); + QKeySequence globalReinit = QKeySequence(QString::fromStdString(prefs->Get("Global reinit", "Ctrl+R"))); + QKeySequence showInfo = QKeySequence(QString::fromStdString(prefs->Get("Show node information", "Ctrl+I"))); QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); QKeySequence keySequence = QKeySequence(keyEvent->modifiers() + keyEvent->key()); // if no modifier was pressed the sequence is now empty if (keySequence.isEmpty()) { keySequence = QKeySequence(keyEvent->key()); } auto selectedNodes = AbstractDataNodeAction::GetSelectedNodes(dataManagerView->GetSite()); if (keySequence == makeAllInvisible) { if (selectedNodes.empty()) { // if no nodes are selected, hide all nodes of the data storage auto nodeset = dataStorage->GetAll(); for (auto it = nodeset->Begin(); it != nodeset->End(); ++it) { mitk::DataNode* node = it->Value(); if (nullptr != node) { selectedNodes.push_back(node); } } } HideAllAction::Run(selectedNodes); return true; } if (keySequence == deleteSelectedNodes) { RemoveAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes); return true; } if (keySequence == toggleVisibility) { ToggleVisibilityAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes); return true; } if (keySequence == reinit) { ReinitAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes); return true; } if (keySequence == globalReinit) { GlobalReinitAction::Run(dataManagerView->GetSite(), dataStorage); return true; } if (keySequence == showInfo) { ShowDetailsAction::Run(selectedNodes); return true; } } // standard event processing return QObject::eventFilter(obj, event); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h index 4caf9db86a..c51cff01ab 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h @@ -1,47 +1,40 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKNODETABLEVIEWKEYFILTER_H #define QMITKNODETABLEVIEWKEYFILTER_H // mitk core #include <mitkDataStorage.h> #include <mitkWeakPointer.h> #include <QObject> -namespace mitk -{ - class IPreferences; -} - /** * @brief A small class which receives key-pressed events on the node table. */ class QmitkNodeTableViewKeyFilter : public QObject { Q_OBJECT public: QmitkNodeTableViewKeyFilter(QObject *dataManagerView, mitk::DataStorage *dataStorage); protected: bool eventFilter(QObject *obj, QEvent *event) override; - mitk::IPreferences* m_Preferences; - mitk::WeakPointer<mitk::DataStorage> m_DataStorage; }; #endif // QMITKNODETABLEVIEWKEYFILTER_H diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp index b26e541db8..5fac8f48ec 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.cpp @@ -1,114 +1,122 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkDicomPreferencePage.h" #include "mitkPluginActivator.h" #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QCheckBox> #include <QGroupBox> #include <QRadioButton> #include <QMessageBox> #include <QDoubleSpinBox> #include <QLineEdit> #include <QFileDialog> -static QString CreateDefaultPath() +namespace { - QString path = mitk::PluginActivator::getContext()->getDataFile("").absolutePath(); - path.append("/database"); - return path; + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("org.mitk.views.dicomreader"); + } + + QString CreateDefaultPath() + { + QString path = mitk::PluginActivator::getContext()->getDataFile("").absolutePath(); + path.append("/database"); + return path; + } } QmitkDicomPreferencePage::QmitkDicomPreferencePage() : m_MainControl(nullptr) { } QmitkDicomPreferencePage::~QmitkDicomPreferencePage() { } void QmitkDicomPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkDicomPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_DicomPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader"); - m_MainControl = new QWidget(parent); auto formLayout = new QFormLayout; formLayout->setHorizontalSpacing(8); formLayout->setVerticalSpacing(24); auto displayOptionsLayout = new QHBoxLayout; m_PathEdit = new QLineEdit(m_MainControl); displayOptionsLayout->addWidget(m_PathEdit); m_PathSelect = new QPushButton("Select Path",m_MainControl); displayOptionsLayout->addWidget(m_PathSelect); m_PathDefault = new QPushButton("Default",m_MainControl); displayOptionsLayout->addWidget(m_PathDefault); formLayout->addRow("Local database path:",displayOptionsLayout); m_MainControl->setLayout(formLayout); connect(m_PathDefault, SIGNAL(clicked()), this, SLOT(DefaultButtonPushed())); connect(m_PathSelect, SIGNAL(clicked()), this, SLOT(PathSelectButtonPushed())); this->Update(); } QWidget* QmitkDicomPreferencePage::GetQtControl() const { return m_MainControl; } void QmitkDicomPreferencePage::PerformCancel() { } bool QmitkDicomPreferencePage::PerformOk() { - m_DicomPreferencesNode->Put("default dicom path",m_PathEdit->text().toStdString()); + auto* prefs = GetPreferences(); + prefs->Put("default dicom path",m_PathEdit->text().toStdString()); return true; } void QmitkDicomPreferencePage::Update() { - const auto path = QString::fromStdString(m_DicomPreferencesNode->Get("default dicom path", CreateDefaultPath().toStdString())); + auto* prefs = GetPreferences(); + const auto path = QString::fromStdString(prefs->Get("default dicom path", CreateDefaultPath().toStdString())); m_PathEdit->setText(path); } void QmitkDicomPreferencePage::DefaultButtonPushed() { m_PathEdit->setText(CreateDefaultPath()); } void QmitkDicomPreferencePage::PathSelectButtonPushed() { QString path = QFileDialog::getExistingDirectory(m_MainControl,"Folder for Dicom directory","dir"); if (!path.isEmpty()) { m_PathEdit->setText(path); } } diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h index 06d9e4e697..23aca60627 100644 --- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkDicomPreferencePage.h @@ -1,75 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkDicomPreferencePage_h #define QmitkDicomPreferencePage_h #include <QString> #include <QStringList> #include "berryIQtPreferencePage.h" #include <org_mitk_gui_qt_dicombrowser_Export.h> -namespace mitk -{ - class IPreferences; -} - class QWidget; class QCheckBox; class QLineEdit; class QPushButton; class DICOM_EXPORT QmitkDicomPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDicomPreferencePage(); ~QmitkDicomPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected: QWidget* m_MainControl; - mitk::IPreferences* m_DicomPreferencesNode; QLineEdit* m_PathEdit; QPushButton* m_PathSelect; QPushButton* m_PathDefault; protected slots: void DefaultButtonPushed(); void PathSelectButtonPushed(); }; #endif // QmitkQmitkDicomPreferencePage_h diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp index a7f6081662..09d2646799 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.cpp @@ -1,388 +1,397 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "DoseVisualizationPreferencePage.h" #include "mitkRTUIConstants.h" #include <QWidget> #include <QMessageBox> #include <QInputDialog> #include <QMenu> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <QmitkDoseColorDelegate.h> #include <QmitkDoseValueDelegate.h> #include <QmitkDoseVisualStyleDelegate.h> #include <QmitkIsoDoseLevelSetModel.h> #include "mitkIsoLevelsGenerator.h" #include "org_mitk_gui_qt_dosevisualization_Activator.h" +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); + } +} + DoseVisualizationPreferencePage::DoseVisualizationPreferencePage() : m_MainControl(nullptr), m_Controls(nullptr), m_referenceDoseChanged(false), m_presetMapChanged(false), m_globalVisChanged(false) { } DoseVisualizationPreferencePage::~DoseVisualizationPreferencePage() { delete m_LevelSetModel; delete m_DoseColorDelegate; delete m_DoseValueDelegate; delete m_DoseVisualDelegate; delete m_Controls; } void DoseVisualizationPreferencePage::Init(berry::IWorkbench::Pointer ) { } void DoseVisualizationPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_DoseVisNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID); - m_LevelSetModel = new QmitkIsoDoseLevelSetModel(this); m_DoseColorDelegate = new QmitkDoseColorDelegate(this); m_DoseValueDelegate = new QmitkDoseValueDelegate(this); m_DoseVisualDelegate = new QmitkDoseVisualStyleDelegate(this); m_MainControl = new QWidget(parent); m_Controls = new Ui::DoseVisualizationPreferencePageControls; m_Controls->setupUi( m_MainControl ); this->m_Controls->isoLevelSetView->setModel(m_LevelSetModel); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(0,m_DoseColorDelegate); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(1,m_DoseValueDelegate); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(2,m_DoseVisualDelegate); this->m_Controls->isoLevelSetView->setItemDelegateForColumn(3,m_DoseVisualDelegate); this->m_Controls->isoLevelSetView->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_Controls->spinReferenceDose, SIGNAL(valueChanged(double)), m_LevelSetModel, SLOT(setReferenceDose(double))); connect(m_Controls->spinReferenceDose, SIGNAL(valueChanged(double)), this, SLOT(OnReferenceDoseChanged(double))); connect(m_Controls->checkGlobalSync, SIGNAL(toggled(bool)), m_Controls->spinReferenceDose, SLOT(setEnabled(bool))); connect(m_Controls->radioAbsDose, SIGNAL(toggled(bool)), m_LevelSetModel, SLOT(setShowAbsoluteDose(bool))); connect(m_Controls->isoLevelSetView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(OnShowContextMenuIsoSet(const QPoint&))); connect(m_Controls->listPresets, SIGNAL(currentItemChanged ( QListWidgetItem *, QListWidgetItem *)), this, SLOT(OnCurrentItemChanged ( QListWidgetItem *, QListWidgetItem *))); connect(m_Controls->btnAddPreset, SIGNAL(clicked(bool)), this, SLOT(OnAddPresetClicked(bool))); connect(m_Controls->btnDelPreset, SIGNAL(clicked(bool)), this, SLOT(OnDelPresetClicked(bool))); connect(m_Controls->btnResetPreset, SIGNAL(clicked(bool)), this, SLOT(OnResetPresetClicked(bool))); connect(m_Controls->btnDelLevel, SIGNAL(clicked(bool)), this, SLOT(OnDelLevelClicked(bool))); connect(m_Controls->btnAddLevel, SIGNAL(clicked(bool)), this, SLOT(OnAddLevelClicked(bool))); connect(m_Controls->checkGlobalVisColorWash, SIGNAL(toggled(bool)), this, SLOT(OnGlobalVisChanged(bool))); connect(m_Controls->checkGlobalVisIsoLine, SIGNAL(toggled(bool)), this, SLOT(OnGlobalVisChanged(bool))); this->Update(); } QWidget* DoseVisualizationPreferencePage::GetQtControl() const { return m_MainControl; } bool DoseVisualizationPreferencePage::PerformOk() { - m_DoseVisNode->PutBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID,m_Controls->radioAbsDose->isChecked()); - m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID,m_Controls->checkGlobalVisColorWash->isChecked()); - m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID,m_Controls->checkGlobalVisIsoLine->isChecked()); - m_DoseVisNode->PutDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID,m_Controls->spinReferenceDose->value()); - m_DoseVisNode->PutBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, m_Controls->checkGlobalSync->isChecked()); + auto* prefs = GetPreferences(); + + prefs->PutBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID,m_Controls->radioAbsDose->isChecked()); + prefs->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID,m_Controls->checkGlobalVisColorWash->isChecked()); + prefs->PutBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID,m_Controls->checkGlobalVisIsoLine->isChecked()); + prefs->PutDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID,m_Controls->spinReferenceDose->value()); + prefs->PutBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, m_Controls->checkGlobalSync->isChecked()); mitk::StorePresetsMap(this->m_Presets); if (this->m_Presets.find(this->m_selectedPresetName)==this->m_Presets.end()) { //the preset currently selected in the application is not available any more. Change it to a valid one. mitk::SetSelectedPresetName(this->m_Presets.begin()->first); } if (this->m_LevelSetModel->isModified()) { this->m_presetMapChanged = true; } if (m_referenceDoseChanged) { mitk::SignalReferenceDoseChange(m_Controls->checkGlobalSync->isChecked(), m_Controls->spinReferenceDose->value(), mitk::org_mitk_gui_qt_dosevisualization_Activator::GetContext()); } if (m_presetMapChanged) { mitk::SignalPresetMapChange(mitk::org_mitk_gui_qt_dosevisualization_Activator::GetContext()); } if(m_globalVisChanged) { mitk::SignalGlobalVisChange(m_Controls->checkGlobalSync->isChecked(), m_Controls->checkGlobalVisIsoLine->isChecked(), m_Controls->checkGlobalVisColorWash->isChecked(), mitk::org_mitk_gui_qt_dosevisualization_Activator::GetContext()); } return true; } void DoseVisualizationPreferencePage::PerformCancel() { } void DoseVisualizationPreferencePage::Update() { - m_Controls->checkGlobalVisColorWash->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID, true)); - m_Controls->checkGlobalVisIsoLine->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID, true)); - m_Controls->radioAbsDose->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, true)); - m_Controls->radioRelDose->setChecked(!(m_DoseVisNode->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, false))); - m_Controls->spinReferenceDose->setValue(m_DoseVisNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID, mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE)); - m_Controls->checkGlobalSync->setChecked(m_DoseVisNode->GetBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, true)); + auto* prefs = GetPreferences(); + + m_Controls->checkGlobalVisColorWash->setChecked(prefs->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID, true)); + m_Controls->checkGlobalVisIsoLine->setChecked(prefs->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_ISOLINES_ID, true)); + m_Controls->radioAbsDose->setChecked(prefs->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, true)); + m_Controls->radioRelDose->setChecked(!(prefs->GetBool(mitk::RTUIConstants::DOSE_DISPLAY_ABSOLUTE_ID, false))); + m_Controls->spinReferenceDose->setValue(prefs->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID, mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE)); + m_Controls->checkGlobalSync->setChecked(prefs->GetBool(mitk::RTUIConstants::GLOBAL_REFERENCE_DOSE_SYNC_ID, true)); m_referenceDoseChanged = false; m_presetMapChanged = false; m_globalVisChanged = false; this->m_Presets = mitk::LoadPresetsMap(); if(m_Presets.empty()) return; this->m_selectedPresetName = mitk::GetSelectedPresetName(); UpdatePresetsWidgets(); } mitk::IsoDoseLevelSet* DoseVisualizationPreferencePage::GetSelectedIsoLevelSet() { QListWidgetItem* selectedItem = m_Controls->listPresets->currentItem(); mitk::IsoDoseLevelSet::Pointer result; if (selectedItem) { result = m_Presets[selectedItem->text().toStdString()]; } return result; } void DoseVisualizationPreferencePage::UpdateLevelSetWidgets() { this->m_Controls->btnAddLevel->setEnabled(this->GetSelectedIsoLevelSet()!=nullptr); QModelIndex selectedIndex = m_Controls->isoLevelSetView->currentIndex(); this->m_Controls->btnDelLevel->setEnabled(this->GetSelectedIsoLevelSet()!=nullptr && selectedIndex.isValid()); } void DoseVisualizationPreferencePage::UpdatePresetsWidgets() { m_Controls->listPresets->clear(); QListWidgetItem* selectedItem = nullptr; for (PresetMapType::iterator pos = m_Presets.begin(); pos != m_Presets.end(); ++pos) { QListWidgetItem* item = new QListWidgetItem(QString::fromStdString(pos->first)); if (!selectedItem) { selectedItem = item; } m_Controls->listPresets->addItem(item); } if (selectedItem) { m_Controls->listPresets->setCurrentItem(selectedItem); } if (this->m_LevelSetModel->isModified()) { this->m_presetMapChanged = true; } this->m_LevelSetModel->setIsoDoseLevelSet(this->GetSelectedIsoLevelSet()); m_Controls->btnDelPreset->setEnabled((m_Controls->listPresets->currentItem() != nullptr) && (m_Controls->listPresets->count()>1)); } void DoseVisualizationPreferencePage::OnCurrentItemChanged (QListWidgetItem*, QListWidgetItem*) { this->m_LevelSetModel->setIsoDoseLevelSet(this->GetSelectedIsoLevelSet()); } void DoseVisualizationPreferencePage::OnShowContextMenuIsoSet(const QPoint& pos) { QPoint globalPos = m_Controls->isoLevelSetView->viewport()->mapToGlobal(pos); QModelIndex selectedIndex = m_Controls->isoLevelSetView->currentIndex(); QMenu viewMenu; QAction* addLevelAct = viewMenu.addAction("Add new level"); QAction* delLevelAct = viewMenu.addAction("Delete selected level"); delLevelAct->setEnabled(selectedIndex.isValid()); viewMenu.addSeparator(); QAction* invertIsoLineAct = viewMenu.addAction("Invert iso line visibility"); QAction* activateIsoLineAct = viewMenu.addAction("Activate all iso lines"); QAction* deactivateIsoLineAct = viewMenu.addAction("Deactivate all iso lines"); viewMenu.addSeparator(); QAction* invertColorWashAct = viewMenu.addAction("Invert color wash visibility"); QAction* activateColorWashAct = viewMenu.addAction("Activate all color wash levels"); QAction* deactivateColorWashAct = viewMenu.addAction("Deactivate all color wash levels"); viewMenu.addSeparator(); QAction* swapAct = viewMenu.addAction("Swap iso line/color wash visibility"); QAction* selectedItem = viewMenu.exec(globalPos); if (selectedItem == invertIsoLineAct) { this->m_LevelSetModel->invertVisibilityIsoLines(); } else if (selectedItem == activateIsoLineAct) { this->m_LevelSetModel->switchVisibilityIsoLines(true); } else if (selectedItem == deactivateIsoLineAct) { this->m_LevelSetModel->switchVisibilityIsoLines(false); } else if (selectedItem == invertColorWashAct) { this->m_LevelSetModel->invertVisibilityColorWash(); } else if (selectedItem == activateColorWashAct) { this->m_LevelSetModel->switchVisibilityColorWash(true); } else if (selectedItem == deactivateColorWashAct) { this->m_LevelSetModel->switchVisibilityColorWash(false); } else if (selectedItem == swapAct) { this->m_LevelSetModel->swapVisibility(); } else if (selectedItem == addLevelAct) { this->m_LevelSetModel->addLevel(); } else if (selectedItem == delLevelAct) { this->m_LevelSetModel->deleteLevel(selectedIndex); } } void DoseVisualizationPreferencePage::OnAddPresetClicked(bool) { bool done = false; QString name = tr("new_preset"); while (!done) { bool ok; name = QInputDialog::getText(m_MainControl, tr("Define name of new preset."), tr("Preset name:"), QLineEdit::Normal, name, &ok); if (!ok) { return; //cancled by user; } bool uniqueName = m_Presets.find(name.toStdString()) == m_Presets.end(); if (!uniqueName) { QMessageBox box; box.setText(tr("New preset name is not unique. Please, choose another one.")); box.exec(); } bool validName = name.indexOf(tr("/")) ==-1; if (!validName) { QMessageBox box; box.setText(tr("New preset name is not valid. Please don't use \"/\".")); box.exec(); } done = uniqueName && validName; } mitk::IsoDoseLevelSet::Pointer newSet = mitk::GenerateIsoLevels_Virtuos(); m_Presets.insert(std::make_pair(name.toStdString(),newSet)); m_presetMapChanged = true; UpdatePresetsWidgets(); } void DoseVisualizationPreferencePage::OnDelPresetClicked(bool) { QListWidgetItem* selectedItem = m_Controls->listPresets->currentItem(); if (selectedItem) { if (m_Controls->listPresets->count() > 1) { m_Presets.erase(selectedItem->text().toStdString()); m_presetMapChanged = true; this->UpdatePresetsWidgets(); } } } void DoseVisualizationPreferencePage::OnResetPresetClicked(bool) { QMessageBox box; box.setText("Do you want to reset the presets?"); box.setInformativeText("If you reset the presets. All user defined presets will be removed and the default presets will be loaded."); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); box.setDefaultButton(QMessageBox::No); int ret = box.exec(); if (ret == QMessageBox::Yes) { mitk::IsoDoseLevelSet::Pointer newSet = mitk::GenerateIsoLevels_Virtuos(); m_Presets.clear(); m_Presets.insert(std::make_pair("Virtuos",newSet)); m_presetMapChanged = true; UpdatePresetsWidgets(); } } void DoseVisualizationPreferencePage::OnAddLevelClicked(bool) { this->m_LevelSetModel->addLevel(); } void DoseVisualizationPreferencePage::OnDelLevelClicked(bool) { QModelIndex selectedIndex = m_Controls->isoLevelSetView->currentIndex(); if (!selectedIndex.isValid()) { selectedIndex = m_Controls->isoLevelSetView->indexAt(QPoint(1,1)); } this->m_LevelSetModel->deleteLevel(selectedIndex); } void DoseVisualizationPreferencePage::OnReferenceDoseChanged(double) { this->m_referenceDoseChanged = true; } void DoseVisualizationPreferencePage::OnGlobalVisChanged(bool) { this->m_globalVisChanged = true; } diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h index 4f36d50552..b030921bad 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/DoseVisualizationPreferencePage.h @@ -1,125 +1,118 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __DOSE_VISUALIZATION_PREFERENCE_PAGE_H #define __DOSE_VISUALIZATION_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" #include "ui_DoseVisualizationPreferencePageControls.h" #include <mitkIsoDoseLevelCollections.h> #include "mitkDoseVisPreferenceHelper.h" /*forward declarations*/ class QmitkIsoDoseLevelSetModel; class QmitkDoseColorDelegate; class QmitkDoseValueDelegate; class QmitkDoseVisualStyleDelegate; class QWidget; -namespace mitk -{ - class IPreferences; -} - /** * \class DoseVisualizationPreferencePage * \brief Preference page for RT Dose visualization */ class DoseVisualizationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: DoseVisualizationPreferencePage(); ~DoseVisualizationPreferencePage() override; /** * \brief Called by framework to initialize this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: void OnCurrentItemChanged ( QListWidgetItem * currentItem, QListWidgetItem * previousItem); void OnShowContextMenuIsoSet(const QPoint& pos); void OnAddPresetClicked(bool checked); void OnDelPresetClicked(bool checked); void OnResetPresetClicked(bool checked); void OnAddLevelClicked(bool checked); void OnDelLevelClicked(bool checked); void OnReferenceDoseChanged(double dose); void OnGlobalVisChanged(bool vis); protected: /** Method updates the presets widgets according to the internal members*/ void UpdatePresetsWidgets(); /** Method actualizes the level set model and edit buttons according to the currently selected item in the presets list view*/ void UpdateLevelSetWidgets(); /** Method returns the iso dose level set selected in the preset lists. May return nullptr if no preset is selected.*/ mitk::IsoDoseLevelSet* GetSelectedIsoLevelSet(); QWidget *m_MainControl; Ui::DoseVisualizationPreferencePageControls* m_Controls; - mitk::IPreferences* m_DoseVisNode; - typedef mitk::PresetMapType PresetMapType; PresetMapType m_Presets; std::string m_selectedPresetName; bool m_referenceDoseChanged; bool m_presetMapChanged; bool m_globalVisChanged; QmitkIsoDoseLevelSetModel* m_LevelSetModel; QmitkDoseColorDelegate* m_DoseColorDelegate; QmitkDoseValueDelegate* m_DoseValueDelegate; QmitkDoseVisualStyleDelegate* m_DoseVisualDelegate; }; #endif diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp index aa96a9d5fe..e54c60dcc4 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.cpp @@ -1,112 +1,121 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "RTUIPreferencePage.h" #include "mitkRTUIConstants.h" #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_PREFERENCE_NODE_ID); + } +} + //----------------------------------------------------------------------------- RTUIPreferencePage::RTUIPreferencePage() : m_MainControl(nullptr), m_Controls(nullptr) { } //----------------------------------------------------------------------------- RTUIPreferencePage::~RTUIPreferencePage() { delete m_Controls; } //----------------------------------------------------------------------------- void RTUIPreferencePage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void RTUIPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_PreferencesNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_PREFERENCE_NODE_ID); - m_MainControl = new QWidget(parent); m_Controls = new Ui::RTUIPreferencePageControls; m_Controls->setupUi( m_MainControl ); connect(m_Controls->radioDefault, SIGNAL(toggled(bool)), m_Controls->spinDefault, SLOT(setEnabled(bool))); connect(m_Controls->radioRelativeToMax, SIGNAL(toggled(bool)), m_Controls->spinRelativeToMax, SLOT(setEnabled(bool))); this->Update(); } //----------------------------------------------------------------------------- QWidget* RTUIPreferencePage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- bool RTUIPreferencePage::PerformOk() { + auto* prefs = GetPreferences(); + bool useAsDefaultValue = m_Controls->radioDefault->isChecked(); - m_PreferencesNode->PutBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID, useAsDefaultValue); + prefs->PutBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID, useAsDefaultValue); if (useAsDefaultValue) { - m_PreferencesNode->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, m_Controls->spinDefault->value()); + prefs->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, m_Controls->spinDefault->value()); } else { - m_PreferencesNode->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, m_Controls->spinRelativeToMax->value()/100.0); + prefs->PutDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, m_Controls->spinRelativeToMax->value()/100.0); } return true; } //----------------------------------------------------------------------------- void RTUIPreferencePage::PerformCancel() { } //----------------------------------------------------------------------------- void RTUIPreferencePage::Update() { - bool useAsDefaultValue = m_PreferencesNode->GetBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID, true); - double doseValue = m_PreferencesNode->GetDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, 50.0); + auto* prefs = GetPreferences(); + + bool useAsDefaultValue = prefs->GetBool(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_AS_DEFAULT_ID, true); + double doseValue = prefs->GetDouble(mitk::RTUIConstants::UNKNOWN_PRESCRIBED_DOSE_HANDLING_VALUE_ID, 50.0); m_Controls->radioDefault->setChecked(useAsDefaultValue); m_Controls->radioRelativeToMax->setChecked(!useAsDefaultValue); m_Controls->spinDefault->setEnabled(useAsDefaultValue); m_Controls->spinRelativeToMax->setEnabled(!useAsDefaultValue); if (useAsDefaultValue) { m_Controls->spinDefault->setValue(doseValue); } else { m_Controls->spinRelativeToMax->setValue(doseValue*100.0); } } diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h index c4490a8270..82f43e0e80 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTUIPreferencePage.h @@ -1,85 +1,77 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __RT_UI_PREFERENCE_PAGE_H #define __RT_UI_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" #include "ui_RTUIPreferencePageControls.h" class QWidget; -namespace mitk -{ - class IPreferences; -} - /** * \class RTUIPreferencePage * \brief Preference page for general RT visualization settings. */ class RTUIPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: RTUIPreferencePage(); ~RTUIPreferencePage() override; /** * \brief Called by framework to initialize this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: protected: QWidget *m_MainControl; Ui::RTUIPreferencePageControls* m_Controls; - - mitk::IPreferences* m_PreferencesNode; - }; #endif diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp index c0777cf9c4..221f8f04a4 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.cpp @@ -1,77 +1,70 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkOpenDicomEditorAction.h" #include <QFileDialog> #include <QFileInfo> #include "mitkCoreObjectFactory.h" #include "mitkSceneIO.h" #include "mitkProgressBar.h" #include <mitkDataStorageEditorInput.h> #include <berryIEditorPart.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbench.h> #include <berryFileEditorInput.h> #include "mitkProperties.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" -#include <mitkCoreServices.h> -#include <mitkIPreferencesService.h> -#include <mitkIPreferences.h> QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenDicomEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl())); this->setText("&DICOM"); this->setToolTip("Open dicom browser"); - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); - this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenDicomEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } berry::IEditorInput::Pointer editorInput2(new berry::FileEditorInput(QString())); m_Window->GetActivePage()->OpenEditor(editorInput2, "org.mitk.editors.dicombrowser"); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h index 2423e8f75f..ead08a642e 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenDicomEditorAction.h @@ -1,47 +1,41 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENDICOMEDITORACTION_H_ #define QMITKOPENDICOMEDITORACTION_H_ #include <QAction> #include <QIcon> #include <org_mitk_gui_qt_ext_Export.h> #include <berryIWorkbenchWindow.h> -namespace mitk -{ - class IPreferences; -} - class MITK_QT_COMMON_EXT_EXPORT QmitkOpenDicomEditorAction : public QAction { Q_OBJECT public: QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init ( berry::IWorkbenchWindow::Pointer window ); berry::IWorkbenchWindow::Pointer m_Window; - mitk::IPreferences* m_GeneralPreferencesNode; }; #endif /*QMITKOPENDICOMEDITORACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp index eda7494553..e9b6b0b708 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp @@ -1,79 +1,72 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkOpenMxNMultiWidgetEditorAction.h" #include "mitkCoreObjectFactory.h" #include <berryIEditorPart.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbench.h> #include <mitkDataStorageEditorInput.h> -#include <mitkCoreServices.h> -#include <mitkIPreferencesService.h> -#include <mitkIPreferences.h> #include "internal/QmitkCommonExtPlugin.h" #include <mitkIDataStorageService.h> class ctkPluginContext; QmitkOpenMxNMultiWidgetEditorAction::QmitkOpenMxNMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenMxNMultiWidgetEditorAction::QmitkOpenMxNMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenMxNMultiWidgetEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl())); this->setText("MxN Display"); this->setToolTip("Open the mxn multi widget editor"); - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); - this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenMxNMultiWidgetEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>(); if (serviceRef) { mitk::IDataStorageService* dsService = context->getService<mitk::IDataStorageService>(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(dsRef)); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.mxnmultiwidget", true, berry::IWorkbenchPage::MATCH_ID); } } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h index 61ab084fd3..2b397bfad1 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.h @@ -1,56 +1,50 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENMXNMULTIWIDGETEDITORACTION_H #define QMITKOPENMXNMULTIWIDGETEDITORACTION_H #ifdef __MINGW32__ // We need to include winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwise they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include <QAction> #include <QIcon> #include <org_mitk_gui_qt_ext_Export.h> #include <berryIWorkbenchWindow.h> -namespace mitk -{ - class IPreferences; -} - class MITK_QT_COMMON_EXT_EXPORT QmitkOpenMxNMultiWidgetEditorAction : public QAction { Q_OBJECT public: QmitkOpenMxNMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenMxNMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init(berry::IWorkbenchWindow::Pointer window); berry::IWorkbenchWindow::Pointer m_Window; - mitk::IPreferences* m_GeneralPreferencesNode; }; #endif // QMITKOPENMXNMULTIWIDGETEDITORACTION_H diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp index 7114fb1969..a6aad97a05 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp @@ -1,79 +1,72 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkOpenStdMultiWidgetEditorAction.h" #include "mitkCoreObjectFactory.h" #include <berryIEditorPart.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbench.h> #include <mitkDataStorageEditorInput.h> -#include <mitkCoreServices.h> -#include <mitkIPreferencesService.h> -#include <mitkIPreferences.h> #include "internal/QmitkCommonExtPlugin.h" #include <mitkIDataStorageService.h> class ctkPluginContext; QmitkOpenStdMultiWidgetEditorAction::QmitkOpenStdMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenStdMultiWidgetEditorAction::QmitkOpenStdMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenStdMultiWidgetEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl())); this->setText("Standard Display"); this->setToolTip("Open the standard multi widget editor"); - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); - this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenStdMultiWidgetEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>(); if (serviceRef) { mitk::IDataStorageService* dsService = context->getService<mitk::IDataStorageService>(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(dsRef)); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.stdmultiwidget", true, berry::IWorkbenchPage::MATCH_ID); } } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h index f65b2b1db3..e0d1dbcf9f 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.h @@ -1,56 +1,50 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENSTDMULTIWIDGETEDITORACTION_H #define QMITKOPENSTDMULTIWIDGETEDITORACTION_H #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include <QAction> #include <QIcon> #include <org_mitk_gui_qt_ext_Export.h> #include <berryIWorkbenchWindow.h> -namespace mitk -{ - class IPreferences; -} - class MITK_QT_COMMON_EXT_EXPORT QmitkOpenStdMultiWidgetEditorAction : public QAction { Q_OBJECT public: QmitkOpenStdMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenStdMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init(berry::IWorkbenchWindow::Pointer window); berry::IWorkbenchWindow::Pointer m_Window; - mitk::IPreferences* m_GeneralPreferencesNode; }; #endif // QMITKOPENSTDMULTIWIDGETEDITORACTION_H diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp index aacfbc2ec1..25087c57ab 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp @@ -1,77 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkOpenXnatEditorAction.h" #include <berryIEditorPart.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbench.h> #include <berryFileEditorInput.h> -#include <mitkCoreServices.h> -#include <mitkIPreferencesService.h> -#include <mitkIPreferences.h> - QmitkOpenXnatEditorAction::QmitkOpenXnatEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->init(window); } QmitkOpenXnatEditorAction::QmitkOpenXnatEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) { this->setIcon(icon); this->init(window); } void QmitkOpenXnatEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl())); this->setText("&XNAT"); this->setToolTip("Open XNAT tool"); - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); - this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenXnatEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } QList<berry::IEditorReference::Pointer> editors = m_Window->GetActivePage()->FindEditors(berry::IEditorInput::Pointer(nullptr), "org.mitk.editors.xnat.browser", berry::IWorkbenchPage::MATCH_ID); if (editors.empty()) { // no XnatEditor is currently open, create a new one berry::IEditorInput::Pointer editorInput(new berry::FileEditorInput(QString())); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.xnat.browser"); } else { // reuse an existing editor berry::IEditorPart::Pointer reuseEditor = editors.front()->GetEditor(true); m_Window->GetActivePage()->Activate(reuseEditor); } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h index c40e613a4a..a9d8a61b90 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.h @@ -1,47 +1,41 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKOPENXNATEDITORACTION_H_ #define QMITKOPENXNATEDITORACTION_H_ #include <QAction> #include <QIcon> #include <org_mitk_gui_qt_ext_Export.h> #include <berryIWorkbenchWindow.h> -namespace mitk -{ - class IPreferences; -} - class MITK_QT_COMMON_EXT_EXPORT QmitkOpenXnatEditorAction : public QAction { Q_OBJECT public: QmitkOpenXnatEditorAction(berry::IWorkbenchWindow::Pointer window); QmitkOpenXnatEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init ( berry::IWorkbenchWindow::Pointer window ); berry::IWorkbenchWindow::Pointer m_Window; - mitk::IPreferences* m_GeneralPreferencesNode; }; #endif /*QMITKOPENXNATEDITORACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp index 566519241b..30b3422b74 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp @@ -1,64 +1,75 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAppInstancesPreferencePage.h" #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("General"); + } +} + QmitkAppInstancesPreferencePage::QmitkAppInstancesPreferencePage() { } void QmitkAppInstancesPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkAppInstancesPreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); - auto* prefService = mitk::CoreServices::GetPreferencesService(); - prefs = prefService->GetSystemPreferences()->Node("/General"); - Update(); } QWidget* QmitkAppInstancesPreferencePage::GetQtControl() const { return mainWidget; } bool QmitkAppInstancesPreferencePage::PerformOk() { + auto* prefs = GetPreferences(); + prefs->PutBool("newInstance.always", controls.newInstanceAlways->isChecked()); prefs->PutBool("newInstance.scene", controls.newInstanceScene->isChecked()); + return true; } void QmitkAppInstancesPreferencePage::PerformCancel() { } void QmitkAppInstancesPreferencePage::Update() { + auto* prefs = GetPreferences(); + bool always = prefs->GetBool("newInstance.always", false); bool scene = prefs->GetBool("newInstance.scene", true); controls.newInstanceAlways->setChecked(always); controls.newInstanceScene->setChecked(scene); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h index b9cd932254..77ba1fc4f9 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h @@ -1,55 +1,47 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKAPPINSTANCESPREFERENCEPAGE_H_ #define QMITKAPPINSTANCESPREFERENCEPAGE_H_ #include <berryIQtPreferencePage.h> #include <ui_QmitkAppInstancesPreferencePage.h> -namespace mitk -{ - class IPreferences; -} - class QmitkAppInstancesPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkAppInstancesPreferencePage(); QmitkAppInstancesPreferencePage(const QmitkAppInstancesPreferencePage& other); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; private: Ui::QmitkAppInstancesPreferencePage controls; - - mitk::IPreferences* prefs; - QWidget* mainWidget; }; #endif /* QMITKAPPINSTANCESPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp index 0c627d8b0a..cf26cce7b0 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp @@ -1,185 +1,183 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkExceptionMacro.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <QFileDialog> #include <QProcess> #include <QTextCodec> #include <ui_QmitkExternalProgramsPreferencePage.h> #include "QmitkExternalProgramsPreferencePage.h" -static mitk::IPreferences* GetPreferences() +namespace { - auto* preferencesService = mitk::CoreServices::GetPreferencesService(); - - if (preferencesService != nullptr) + mitk::IPreferences* GetPreferences() { - auto* systemPreferences = preferencesService->GetSystemPreferences(); - - if (systemPreferences != nullptr) - return systemPreferences->Node("/org.mitk.gui.qt.ext.externalprograms"); + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("org.mitk.gui.qt.ext.externalprograms"); } - - mitkThrow(); } QmitkExternalProgramsPreferencePage::QmitkExternalProgramsPreferencePage() - : m_Preferences(GetPreferences()), - m_Ui(new Ui::QmitkExternalProgramsPreferencePage), + : m_Ui(new Ui::QmitkExternalProgramsPreferencePage), m_Control(nullptr), m_FFmpegProcess(nullptr), m_GnuplotProcess(nullptr) { } QmitkExternalProgramsPreferencePage::~QmitkExternalProgramsPreferencePage() { } void QmitkExternalProgramsPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_FFmpegProcess = new QProcess(m_Control); m_GnuplotProcess = new QProcess(m_Control); m_Ui->setupUi(m_Control); connect(m_FFmpegProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnFFmpegProcessError(QProcess::ProcessError))); connect(m_FFmpegProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnFFmpegProcessFinished(int, QProcess::ExitStatus))); connect(m_Ui->ffmpegButton, SIGNAL(clicked()), this, SLOT(OnFFmpegButtonClicked())); connect(m_GnuplotProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnGnuplotProcessError(QProcess::ProcessError))); connect(m_GnuplotProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnGnuplotProcessFinished(int, QProcess::ExitStatus))); connect(m_Ui->gnuplotButton, SIGNAL(clicked()), this, SLOT(OnGnuplotButtonClicked())); this->Update(); } void QmitkExternalProgramsPreferencePage::OnFFmpegButtonClicked() { QString filter = "ffmpeg executable "; #if defined(WIN32) filter += "(ffmpeg.exe)"; #else filter += "(ffmpeg)"; #endif QString ffmpegPath = QFileDialog::getOpenFileName(m_Control, "FFmpeg", "", filter); if (!ffmpegPath.isEmpty()) { m_FFmpegPath = ffmpegPath; m_FFmpegProcess->start(ffmpegPath, QStringList() << "-version", QProcess::ReadOnly); } } void QmitkExternalProgramsPreferencePage::OnFFmpegProcessError(QProcess::ProcessError) { m_FFmpegPath.clear(); m_Ui->ffmpegLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnFFmpegProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::NormalExit && exitCode == 0) { QString output = QTextCodec::codecForName("UTF-8")->toUnicode(m_FFmpegProcess->readAllStandardOutput()); if (output.startsWith("ffmpeg")) { m_Ui->ffmpegLineEdit->setText(m_FFmpegPath); return; } } m_FFmpegPath.clear(); m_Ui->ffmpegLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnGnuplotButtonClicked() { QString filter = "gnuplot executable "; #if defined(WIN32) filter += "(gnuplot.exe)"; #else filter += "(gnuplot)"; #endif QString gnuplotPath = QFileDialog::getOpenFileName(m_Control, "Gnuplot", "", filter); if (!gnuplotPath.isEmpty()) { m_GnuplotPath = gnuplotPath; m_GnuplotProcess->start(gnuplotPath, QStringList() << "--version", QProcess::ReadOnly); } } void QmitkExternalProgramsPreferencePage::OnGnuplotProcessError(QProcess::ProcessError) { m_GnuplotPath.clear(); m_Ui->gnuplotLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnGnuplotProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::NormalExit && exitCode == 0) { QString output = QTextCodec::codecForName("UTF-8")->toUnicode(m_GnuplotProcess->readAllStandardOutput()); if (output.startsWith("gnuplot")) { m_Ui->gnuplotLineEdit->setText(m_GnuplotPath); return; } } m_GnuplotPath.clear(); m_Ui->gnuplotLineEdit->clear(); } QWidget* QmitkExternalProgramsPreferencePage::GetQtControl() const { return m_Control; } void QmitkExternalProgramsPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkExternalProgramsPreferencePage::PerformCancel() { } bool QmitkExternalProgramsPreferencePage::PerformOk() { - m_Preferences->Put("ffmpeg", m_FFmpegPath.toStdString()); - m_Preferences->Put("gnuplot", m_GnuplotPath.toStdString()); + auto* prefs = GetPreferences(); + + prefs->Put("ffmpeg", m_FFmpegPath.toStdString()); + prefs->Put("gnuplot", m_GnuplotPath.toStdString()); + return true; } void QmitkExternalProgramsPreferencePage::Update() { - m_FFmpegPath = QString::fromStdString(m_Preferences->Get("ffmpeg", "")); + auto* prefs = GetPreferences(); + + m_FFmpegPath = QString::fromStdString(prefs->Get("ffmpeg", "")); if (!m_FFmpegPath.isEmpty()) m_FFmpegProcess->start(m_FFmpegPath, QStringList() << "-version", QProcess::ReadOnly); - m_GnuplotPath = QString::fromStdString(m_Preferences->Get("gnuplot", "")); + m_GnuplotPath = QString::fromStdString(prefs->Get("gnuplot", "")); if (!m_GnuplotPath.isEmpty()) m_GnuplotProcess->start(m_GnuplotPath, QStringList() << "--version", QProcess::ReadOnly); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h index 2ec515e341..a27574642b 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.h @@ -1,67 +1,61 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkExternalProgramsPreferencePage_h #define QmitkExternalProgramsPreferencePage_h #include <berryIQtPreferencePage.h> #include <QProcess> #include <QScopedPointer> -namespace mitk -{ - class IPreferences; -} - namespace Ui { class QmitkExternalProgramsPreferencePage; } class QmitkExternalProgramsPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkExternalProgramsPreferencePage(); ~QmitkExternalProgramsPreferencePage() override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; void Init(berry::IWorkbench::Pointer) override; void PerformCancel() override; bool PerformOk() override; void Update() override; private slots: void OnFFmpegButtonClicked(); void OnFFmpegProcessError(QProcess::ProcessError error); void OnFFmpegProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); void OnGnuplotButtonClicked(); void OnGnuplotProcessError(QProcess::ProcessError error); void OnGnuplotProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); private: - mitk::IPreferences* m_Preferences; QScopedPointer<Ui::QmitkExternalProgramsPreferencePage> m_Ui; QWidget* m_Control; QProcess* m_FFmpegProcess; QString m_FFmpegPath; QProcess* m_GnuplotProcess; QString m_GnuplotPath; }; #endif diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp index a6078e571a..ad4632cd6a 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp @@ -1,185 +1,186 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkInputDevicesPrefPage.h" #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QCheckBox> #include <QHashIterator> #include <QMessageBox> #include <mitkIInputDeviceRegistry.h> #include <mitkIInputDeviceDescriptor.h> #include <mitkCoreExtConstants.h> #include "QmitkCommonExtPlugin.h" +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(mitk::CoreExtConstants::INPUTDEVICE_PREFERENCES.toStdString()); + } +} QmitkInputDevicesPrefPage::QmitkInputDevicesPrefPage() : m_MainControl(nullptr) { - // gets the old setting of the preferences and loads them into the preference node - auto* prefService = mitk::CoreServices::GetPreferencesService(); - this->m_InputDevicesPrefNode = prefService->GetSystemPreferences()->Node(mitk::CoreExtConstants::INPUTDEVICE_PREFERENCES.toStdString()); } void QmitkInputDevicesPrefPage::Init(berry::IWorkbench::Pointer ) { } void QmitkInputDevicesPrefPage::CreateQtControl(QWidget* parent) { m_MainControl = new QWidget(parent); auto layout = new QVBoxLayout; QList<mitk::IInputDeviceDescriptor::Pointer> temp(GetInputDeviceRegistry()->GetInputDevices()); for(QList<mitk::IInputDeviceDescriptor::Pointer>::const_iterator it = temp.begin(); it != temp.end();++it) { QString inputDeviceName((*it)->GetName()); auto checkBox = new QCheckBox((inputDeviceName),m_MainControl); layout->addWidget(checkBox); m_InputDevices.insert(checkBox,(*it)->GetID()); if(inputDeviceName == "WiiMote") { m_WiiMoteModes = new QGroupBox("WiiMote Modus"); m_WiiMoteHeadTracking = new QRadioButton(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING); m_WiiMoteSurfaceInteraction = new QRadioButton(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION); m_WiiMoteHeadTracking->setChecked(true); auto vBoxLayout = new QVBoxLayout; vBoxLayout->addWidget(m_WiiMoteHeadTracking); vBoxLayout->addWidget(m_WiiMoteSurfaceInteraction); m_WiiMoteModes->setLayout(vBoxLayout); layout->addWidget(m_WiiMoteModes); } } layout->addStretch(); m_MainControl->setLayout(layout); this->Update(); } QWidget* QmitkInputDevicesPrefPage::GetQtControl() const { return m_MainControl; } bool QmitkInputDevicesPrefPage::PerformOk() { + auto* prefs = GetPreferences(); bool result = true; mitk::IInputDeviceRegistry* inputDeviceRegistry = GetInputDeviceRegistry(); QHashIterator<QCheckBox*, QString> it(m_InputDevices); while (it.hasNext()) { it.next(); mitk::IInputDeviceDescriptor::Pointer inputdevice(inputDeviceRegistry->Find(it.value())); if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { const auto headTracking(m_WiiMoteHeadTracking->text().toStdString()); const auto surfaceInteraction(m_WiiMoteSurfaceInteraction->text().toStdString()); - this->m_InputDevicesPrefNode->PutBool - (headTracking, m_WiiMoteHeadTracking->isChecked()); - this->m_InputDevicesPrefNode->PutBool - (surfaceInteraction, m_WiiMoteSurfaceInteraction->isChecked()); + prefs->PutBool(headTracking, m_WiiMoteHeadTracking->isChecked()); + prefs->PutBool(surfaceInteraction, m_WiiMoteSurfaceInteraction->isChecked()); // forced flush of the preferences is needed // because otherwise the mitk::WiiMoteActivator class // cannot distinguish the two different modes without // changing the interface for all input devices - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - if (prefService != nullptr) - { - prefService->GetSystemPreferences()->Flush(); - } + prefs->Flush(); } if(it.key()->isChecked()) { result &= inputdevice->CreateInputDevice()->RegisterInputDevice(); } else { result &= inputdevice->CreateInputDevice()->UnRegisterInputDevice(); // temporary fix, unclean solution: // e.g. user activates SpaceNavigator and leaves the // the wiimote deactivated, the user will get the warning // despite the fact that it has never been activated if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { // until now 2010-09-06 there were some unfixed problems // with reconnecting the wiimote after disconnecting it. // It was suggested that it might have something to do // with the type of stack, that is used for the pairing. // MS-Stack for example does not work properly. QMessageBox::information(nullptr,"WiiMote supportproblem", "A reconnect of the WiiMote is not yet supported! " "Please restart the application, if you want to " "activate the Wii remote/s again."); } } if(result) { - this->m_InputDevicesPrefNode->PutBool(it.value().toStdString(), it.key()->isChecked()); + prefs->PutBool(it.value().toStdString(), it.key()->isChecked()); } } return result; } void QmitkInputDevicesPrefPage::PerformCancel() { } void QmitkInputDevicesPrefPage::Update() { + auto* prefs = GetPreferences(); QHashIterator<QCheckBox*, QString> it(m_InputDevices); + while (it.hasNext()) { it.next(); - it.key()->setChecked(this->m_InputDevicesPrefNode->GetBool(it.value().toStdString(), false)); + it.key()->setChecked(prefs->GetBool(it.value().toStdString(), false)); if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { m_WiiMoteHeadTracking->setChecked( - this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING.toStdString(), false)); + prefs->GetBool(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING.toStdString(), false)); m_WiiMoteSurfaceInteraction->setChecked - (this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION.toStdString(), false)); + (prefs->GetBool(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION.toStdString(), false)); } } } mitk::IInputDeviceRegistry *QmitkInputDevicesPrefPage::GetInputDeviceRegistry() const { ctkServiceReference serviceRef = QmitkCommonExtPlugin::getContext()->getServiceReference<mitk::IInputDeviceRegistry>(); if (!serviceRef) return nullptr; return QmitkCommonExtPlugin::getContext()->getService<mitk::IInputDeviceRegistry>(serviceRef); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h index 354bbde14d..cc4e3fd161 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h @@ -1,90 +1,87 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITK_INPUTDEVICESPREFPAGE_H_ #define QMITK_INPUTDEVICESPREFPAGE_H_ #include "berryIQtPreferencePage.h" #include <QHash> #include <QGroupBox> #include <QRadioButton> class QWidget; class QCheckBox; namespace mitk { struct IInputDeviceRegistry; -class IPreferences; } class QmitkInputDevicesPrefPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: /** * Default constructor */ QmitkInputDevicesPrefPage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench) override; /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget) override; /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const override; /** * @see berry::IPreferencePage::PerformOk() */ bool PerformOk() override; /** * @see berry::IPreferencePage::PerformCancel() */ void PerformCancel() override; /** * @see berry::IPreferencePage::Update() */ void Update() override; protected: QWidget* m_MainControl; QHash<QCheckBox*,QString> m_InputDevices; // specific for Wiimote QGroupBox* m_WiiMoteModes; QRadioButton* m_WiiMoteHeadTracking; QRadioButton* m_WiiMoteSurfaceInteraction; - mitk::IPreferences* m_InputDevicesPrefNode; - mitk::IInputDeviceRegistry* GetInputDeviceRegistry() const; }; #endif // QMITK_INPUTDEVICESPREFPAGE_H_ diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp index f5e91ecde4..9cf5ee61c5 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.cpp @@ -1,78 +1,86 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMitkWorkbenchIntroPreferencePage.h" #include "QmitkMitkWorkbenchIntroPart.h" #include <berryPlatformUI.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <ui_QmitkMitkWorkbenchIntroPreferencePage.h> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("org.mitk.qt.extapplicationintro"); + } +} + QmitkMitkWorkbenchIntroPreferencePage::QmitkMitkWorkbenchIntroPreferencePage() : m_Ui(new Ui::QmitkMitkWorkbenchIntroPreferencePage), m_Control(nullptr) { } QmitkMitkWorkbenchIntroPreferencePage::~QmitkMitkWorkbenchIntroPreferencePage() { } void QmitkMitkWorkbenchIntroPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkMitkWorkbenchIntroPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_MitkWorkbenchIntroPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.qt.extapplicationintro"); - m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); this->Update(); } QWidget* QmitkMitkWorkbenchIntroPreferencePage::GetQtControl() const { return m_Control; } bool QmitkMitkWorkbenchIntroPreferencePage::PerformOk() { - m_MitkWorkbenchIntroPreferencesNode->PutBool("show tips", m_Ui->showTipsCheckBox->isChecked()); + auto* prefs = GetPreferences(); + prefs->PutBool("show tips", m_Ui->showTipsCheckBox->isChecked()); auto intro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->GetIntro(); if (intro.IsNotNull()) { auto* workbenchIntro = dynamic_cast<QmitkMitkWorkbenchIntroPart*>(intro.GetPointer()); if (workbenchIntro != nullptr) workbenchIntro->ReloadPage(); } return true; } void QmitkMitkWorkbenchIntroPreferencePage::PerformCancel() { } void QmitkMitkWorkbenchIntroPreferencePage::Update() { - m_Ui->showTipsCheckBox->setChecked(m_MitkWorkbenchIntroPreferencesNode->GetBool("show tips", true)); + auto* prefs = GetPreferences(); + m_Ui->showTipsCheckBox->setChecked(prefs->GetBool("show tips", true)); } diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h index 0e125b12ca..371d2bec76 100644 --- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/src/internal/QmitkMitkWorkbenchIntroPreferencePage.h @@ -1,51 +1,44 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkMitkWorkbenchIntroPreferencePage_h #define QmitkMitkWorkbenchIntroPreferencePage_h #include <berryIQtPreferencePage.h> -namespace mitk -{ - class IPreferences; -} - namespace Ui { class QmitkMitkWorkbenchIntroPreferencePage; } class QmitkMitkWorkbenchIntroPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkMitkWorkbenchIntroPreferencePage(); ~QmitkMitkWorkbenchIntroPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; private: - mitk::IPreferences* m_MitkWorkbenchIntroPreferencesNode; - Ui::QmitkMitkWorkbenchIntroPreferencePage* m_Ui; QWidget* m_Control; }; #endif diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp index c822da0243..35428e8d45 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.cpp @@ -1,101 +1,111 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkMxNMultiWidgetEditorPreferencePage.h" #include <QmitkMxNMultiWidgetEditor.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(QmitkMxNMultiWidgetEditor::EDITOR_ID.toStdString()); + } +} + QmitkMxNMultiWidgetEditorPreferencePage::QmitkMxNMultiWidgetEditorPreferencePage() - : m_Preferences(nullptr) { // nothing here } QmitkMxNMultiWidgetEditorPreferencePage::~QmitkMxNMultiWidgetEditorPreferencePage() { //nothing here } void QmitkMxNMultiWidgetEditorPreferencePage::Init(berry::IWorkbench::Pointer) { // nothing here } void QmitkMxNMultiWidgetEditorPreferencePage::CreateQtControl(QWidget* parent) { m_MainControl = new QWidget(parent); m_Ui.setupUi(m_MainControl); - auto* preferenceService = mitk::CoreServices::GetPreferencesService(); - Q_ASSERT(preferenceService); - m_Preferences = preferenceService->GetSystemPreferences()->Node(QmitkMxNMultiWidgetEditor::EDITOR_ID.toStdString()); - connect(m_Ui.m_ColormapComboBox, SIGNAL(activated(int)), SLOT(ChangeColormap(int))); connect(m_Ui.m_ResetButton, SIGNAL(clicked()), SLOT(ResetPreferencesAndGUI())); Update(); } QWidget* QmitkMxNMultiWidgetEditorPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkMxNMultiWidgetEditorPreferencePage::PerformOk() { - m_Preferences->PutBool("Use constrained zooming and panning", m_Ui.m_EnableFlexibleZooming->isChecked()); - m_Preferences->PutBool("Show level/window widget", m_Ui.m_ShowLevelWindowWidget->isChecked()); - m_Preferences->PutBool("PACS like mouse interaction", m_Ui.m_PACSLikeMouseMode->isChecked()); - m_Preferences->PutInt("Render window widget colormap", m_Ui.m_ColormapComboBox->currentIndex()); - m_Preferences->PutBool("Render window individual decorations", m_Ui.m_IndividualDecorations->isChecked()); + auto* prefs = GetPreferences(); + + prefs->PutBool("Use constrained zooming and panning", m_Ui.m_EnableFlexibleZooming->isChecked()); + prefs->PutBool("Show level/window widget", m_Ui.m_ShowLevelWindowWidget->isChecked()); + prefs->PutBool("PACS like mouse interaction", m_Ui.m_PACSLikeMouseMode->isChecked()); + prefs->PutInt("Render window widget colormap", m_Ui.m_ColormapComboBox->currentIndex()); + prefs->PutBool("Render window individual decorations", m_Ui.m_IndividualDecorations->isChecked()); - m_Preferences->PutInt("crosshair gap size", m_Ui.m_CrosshairGapSize->value()); + prefs->PutInt("crosshair gap size", m_Ui.m_CrosshairGapSize->value()); return true; } void QmitkMxNMultiWidgetEditorPreferencePage::PerformCancel() { // nothing here } void QmitkMxNMultiWidgetEditorPreferencePage::Update() { - m_Ui.m_EnableFlexibleZooming->setChecked(m_Preferences->GetBool("Use constrained zooming and panning", true)); - m_Ui.m_ShowLevelWindowWidget->setChecked(m_Preferences->GetBool("Show level/window widget", true)); - m_Ui.m_PACSLikeMouseMode->setChecked(m_Preferences->GetBool("PACS like mouse interaction", false)); + auto* prefs = GetPreferences(); - int colormap = m_Preferences->GetInt("Render window widget colormap", 0); + m_Ui.m_EnableFlexibleZooming->setChecked(prefs->GetBool("Use constrained zooming and panning", true)); + m_Ui.m_ShowLevelWindowWidget->setChecked(prefs->GetBool("Show level/window widget", true)); + m_Ui.m_PACSLikeMouseMode->setChecked(prefs->GetBool("PACS like mouse interaction", false)); + + int colormap = prefs->GetInt("Render window widget colormap", 0); m_Ui.m_ColormapComboBox->setCurrentIndex(colormap); - m_Ui.m_IndividualDecorations->setChecked(m_Preferences->GetBool("Render window individual decorations", false)); + m_Ui.m_IndividualDecorations->setChecked(prefs->GetBool("Render window individual decorations", false)); - m_Ui.m_CrosshairGapSize->setValue(m_Preferences->GetInt("crosshair gap size", 32)); + m_Ui.m_CrosshairGapSize->setValue(prefs->GetInt("crosshair gap size", 32)); } void QmitkMxNMultiWidgetEditorPreferencePage::ResetPreferencesAndGUI() { - m_Preferences->Clear(); + auto* prefs = GetPreferences(); + + prefs->Clear(); Update(); } void QmitkMxNMultiWidgetEditorPreferencePage::ChangeColormap(int i) { if (0 == i) { m_CurrentColormap = "Black and white"; } } diff --git a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h index ae2e247ab2..d820b8b50d 100644 --- a/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.mxnmultiwidgeteditor/src/internal/QmitkMxNMultiWidgetEditorPreferencePage.h @@ -1,69 +1,59 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKMXNMULTIWIDGETEDITORPREFERENCEPAGE_H #define QMITKMXNMULTIWIDGETEDITORPREFERENCEPAGE_H #include "ui_QmitkMxNMultiWidgetEditorPreferencePage.h" #include <berryIQtPreferencePage.h> #include <QProcess> #include <QScopedPointer> #include <QPushButton> -namespace mitk -{ - class IPreferences; -} - class QmitkMxNMultiWidgetEditorPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkMxNMultiWidgetEditorPreferencePage(); ~QmitkMxNMultiWidgetEditorPreferencePage() override; void Init(berry::IWorkbench::Pointer) override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; public slots: /** * @brief ResetColors set default colors and refresh the GUI. */ void ResetPreferencesAndGUI(); void ChangeColormap(int i); protected: std::string m_CurrentColormap; - /** - * @brief m_Preferences the berry preferences. - */ - mitk::IPreferences* m_Preferences; - private: Ui::QmitkMxNMultiWidgetEditorPreferencePage m_Ui; QWidget* m_MainControl; }; #endif // QMITKMXNMULTIWIDGETEDITORPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp index 7e5541808f..823a33fedb 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp @@ -1,146 +1,156 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkSegmentationPreferencePage.h" #include <mitkBaseApplication.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <QFileDialog> #include <ui_QmitkSegmentationPreferencePageControls.h> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node("org.mitk.views.segmentation"); + } +} + QmitkSegmentationPreferencePage::QmitkSegmentationPreferencePage() : m_Ui(new Ui::QmitkSegmentationPreferencePageControls), m_Control(nullptr), m_Initializing(false) { } QmitkSegmentationPreferencePage::~QmitkSegmentationPreferencePage() { } void QmitkSegmentationPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkSegmentationPreferencePage::CreateQtControl(QWidget* parent) { m_Initializing = true; - mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); - - m_SegmentationPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); connect(m_Ui->labelSetPresetToolButton, SIGNAL(clicked()), this, SLOT(OnLabelSetPresetButtonClicked())); connect(m_Ui->suggestionsToolButton, SIGNAL(clicked()), this, SLOT(OnSuggestionsButtonClicked())); this->Update(); m_Initializing = false; } QWidget* QmitkSegmentationPreferencePage::GetQtControl() const { return m_Control; } bool QmitkSegmentationPreferencePage::PerformOk() { - m_SegmentationPreferencesNode->PutBool("slim view", m_Ui->slimViewCheckBox->isChecked()); - m_SegmentationPreferencesNode->PutBool("draw outline", m_Ui->outlineRadioButton->isChecked()); - m_SegmentationPreferencesNode->PutBool("selection mode", m_Ui->selectionModeCheckBox->isChecked()); - m_SegmentationPreferencesNode->Put("label set preset", m_Ui->labelSetPresetLineEdit->text().toStdString()); - m_SegmentationPreferencesNode->PutBool("default label naming", m_Ui->defaultNameRadioButton->isChecked()); - m_SegmentationPreferencesNode->Put("label suggestions", m_Ui->suggestionsLineEdit->text().toStdString()); - m_SegmentationPreferencesNode->PutBool("replace standard suggestions", m_Ui->replaceStandardSuggestionsCheckBox->isChecked()); - m_SegmentationPreferencesNode->PutBool("suggest once", m_Ui->suggestOnceCheckBox->isChecked()); + auto* prefs = GetPreferences(); + + prefs->PutBool("slim view", m_Ui->slimViewCheckBox->isChecked()); + prefs->PutBool("draw outline", m_Ui->outlineRadioButton->isChecked()); + prefs->PutBool("selection mode", m_Ui->selectionModeCheckBox->isChecked()); + prefs->Put("label set preset", m_Ui->labelSetPresetLineEdit->text().toStdString()); + prefs->PutBool("default label naming", m_Ui->defaultNameRadioButton->isChecked()); + prefs->Put("label suggestions", m_Ui->suggestionsLineEdit->text().toStdString()); + prefs->PutBool("replace standard suggestions", m_Ui->replaceStandardSuggestionsCheckBox->isChecked()); + prefs->PutBool("suggest once", m_Ui->suggestOnceCheckBox->isChecked()); return true; } void QmitkSegmentationPreferencePage::PerformCancel() { } void QmitkSegmentationPreferencePage::Update() { - m_Ui->slimViewCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("slim view", false)); + auto* prefs = GetPreferences(); + + m_Ui->slimViewCheckBox->setChecked(prefs->GetBool("slim view", false)); - if (m_SegmentationPreferencesNode->GetBool("draw outline", true)) + if (prefs->GetBool("draw outline", true)) { m_Ui->outlineRadioButton->setChecked(true); } else { m_Ui->overlayRadioButton->setChecked(true); } - m_Ui->selectionModeCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("selection mode", false)); + m_Ui->selectionModeCheckBox->setChecked(prefs->GetBool("selection mode", false)); auto labelSetPreset = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), ""); bool isOverriddenByCmdLineArg = !labelSetPreset.empty(); if (!isOverriddenByCmdLineArg) - labelSetPreset = m_SegmentationPreferencesNode->Get("label set preset", ""); + labelSetPreset = prefs->Get("label set preset", ""); m_Ui->labelSetPresetLineEdit->setDisabled(isOverriddenByCmdLineArg); m_Ui->labelSetPresetToolButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->labelSetPresetCmdLineArgLabel->setVisible(isOverriddenByCmdLineArg); m_Ui->labelSetPresetLineEdit->setText(QString::fromStdString(labelSetPreset)); - if (m_SegmentationPreferencesNode->GetBool("default label naming", true)) + if (prefs->GetBool("default label naming", true)) { m_Ui->defaultNameRadioButton->setChecked(true); } else { m_Ui->askForNameRadioButton->setChecked(true); } auto labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), ""); isOverriddenByCmdLineArg = !labelSuggestions.empty(); if (!isOverriddenByCmdLineArg) - labelSuggestions = m_SegmentationPreferencesNode->Get("label suggestions", ""); + labelSuggestions = prefs->Get("label suggestions", ""); m_Ui->defaultNameRadioButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->askForNameRadioButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsLineEdit->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsToolButton->setDisabled(isOverriddenByCmdLineArg); m_Ui->suggestionsCmdLineArgLabel->setVisible(isOverriddenByCmdLineArg); m_Ui->suggestionsLineEdit->setText(QString::fromStdString(labelSuggestions)); - m_Ui->replaceStandardSuggestionsCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("replace standard suggestions", true)); - m_Ui->suggestOnceCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("suggest once", true)); + m_Ui->replaceStandardSuggestionsCheckBox->setChecked(prefs->GetBool("replace standard suggestions", true)); + m_Ui->suggestOnceCheckBox->setChecked(prefs->GetBool("suggest once", true)); } void QmitkSegmentationPreferencePage::OnLabelSetPresetButtonClicked() { const auto filename = QFileDialog::getOpenFileName(m_Control, QStringLiteral("Load Label Set Preset"), QString(), QStringLiteral("Label set preset (*.lsetp)")); if (!filename.isEmpty()) m_Ui->labelSetPresetLineEdit->setText(filename); } void QmitkSegmentationPreferencePage::OnSuggestionsButtonClicked() { const auto filename = QFileDialog::getOpenFileName(m_Control, QStringLiteral("Load Label Suggestions"), QString(), QStringLiteral("Label suggestions (*.json)")); if (!filename.isEmpty()) m_Ui->suggestionsLineEdit->setText(filename); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h index 48384f06df..a3f9789ce4 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h @@ -1,69 +1,62 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSEGMENTATIONPREFERENCEPAGE_H #define QMITKSEGMENTATIONPREFERENCEPAGE_H #include "org_mitk_gui_qt_segmentation_Export.h" #include <berryIQtPreferencePage.h> class QWidget; -namespace mitk -{ - class IPreferences; -} - namespace Ui { class QmitkSegmentationPreferencePageControls; } class MITK_QT_SEGMENTATION QmitkSegmentationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkSegmentationPreferencePage(); ~QmitkSegmentationPreferencePage() override; void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; bool PerformOk() override; void PerformCancel() override; void Update() override; protected Q_SLOTS: void OnLabelSetPresetButtonClicked(); void OnSuggestionsButtonClicked(); protected: Ui::QmitkSegmentationPreferencePageControls* m_Ui; QWidget* m_Control; bool m_Initializing; - - mitk::IPreferences* m_SegmentationPreferencesNode; }; #endif // QMITKSEGMENTATIONPREFERENCEPAGE_H diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h index 95fe0399b0..141edd83b0 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h @@ -1,130 +1,125 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKSTDMULTIWIDGETEDITOR_H #define QMITKSTDMULTIWIDGETEDITOR_H // mitk gui qt common plugin #include <QmitkAbstractMultiWidgetEditor.h> #include <mitkILinkedRenderWindowPart.h> #include <org_mitk_gui_qt_stdmultiwidgeteditor_Export.h> // c++ #include <memory> class QmitkStdMultiWidget; class QmitkStdMultiWidgetEditorPrivate; -namespace mitk -{ - class IPreferences; -} - /** * @brief */ class ORG_MITK_GUI_QT_STDMULTIWIDGETEDITOR QmitkStdMultiWidgetEditor final : public QmitkAbstractMultiWidgetEditor, public mitk::ILinkedRenderWindowPart { Q_OBJECT public: static const QString EDITOR_ID; QmitkStdMultiWidgetEditor(); virtual ~QmitkStdMultiWidgetEditor() override; virtual QmitkLevelWindowWidget* GetLevelWindowWidget() const override; /** * @brief Overridden from mitk::ILinkedRenderWindowPart */ virtual void EnableSlicingPlanes(bool enable) override; /** * @brief Overridden from mitk::ILinkedRenderWindowPart */ virtual bool IsSlicingPlanesEnabled() const override; /** * @brief Overridden from berry::IPartListener */ virtual berry::IPartListener::Events::Types GetPartEventTypes() const override; /** * @brief Overridden from berry::IPartListener */ virtual void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) override; /** * @brief Overridden from berry::IPartListener */ virtual void PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) override; void OnInteractionSchemeChanged(mitk::InteractionSchemeSwitcher::InteractionScheme scheme) override; void ShowLevelWindowWidget(bool show); private: /** * @brief Overridden from QmitkAbstractRenderEditor */ virtual void SetFocus() override; /** * @brief Overridden from QmitkAbstractRenderEditor */ virtual void CreateQtPartControl(QWidget* parent) override; /** * @brief Overridden from QmitkAbstractRenderEditor */ virtual void OnPreferencesChanged(const mitk::IPreferences* preferences) override; /** * @brief InitializePreferences Internal helper method to set default preferences. * This method is used to show the current preferences in the first call of * the preference page (the GUI). * * @param preferences berry preferences. */ void InitializePreferences(mitk::IPreferences *preferences); /** * @brief GetPreferenceDecorations Getter to fill internal members with values of preferences. * @param preferences The berry preferences. * * If a preference is set, the value will overwrite the current value. If it does not exist, * the value will not change. */ void GetPreferenceDecorations(const mitk::IPreferences *preferences); /** * @brief GetColorForWidget helper method to convert a saved color string to mitk::Color. * @param hexColor color in hex format (#12356) where each digit is in the form (0-F). * @return the color in mitk format. */ mitk::Color HexColorToMitkColor(const std::string& hexColor); /** * @brief MitkColorToHex Convert an mitk::Color to hex string. * @param color mitk format. * @return String in hex (#RRGGBB). */ std::string MitkColorToHex(const mitk::Color& color); struct Impl; std::unique_ptr<Impl> m_Impl; }; #endif // QMITKSTDMULTIWIDGETEDITOR_H diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp index 04d9e7ef59..d4e6d3e6b4 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp @@ -1,245 +1,255 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkStdMultiWidgetEditorPreferencePage.h" #include <ui_QmitkStdMultiWidgetEditorPreferencePage.h> #include <QmitkStdMultiWidgetEditor.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include <QColorDialog> +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(QmitkStdMultiWidgetEditor::EDITOR_ID.toStdString()); + } +} + QmitkStdMultiWidgetEditorPreferencePage::QmitkStdMultiWidgetEditorPreferencePage() - : m_Preferences(nullptr), - m_Ui(new Ui::QmitkStdMultiWidgetEditorPreferencePage), + : m_Ui(new Ui::QmitkStdMultiWidgetEditorPreferencePage), m_Control(nullptr) { } QmitkStdMultiWidgetEditorPreferencePage::~QmitkStdMultiWidgetEditorPreferencePage() { } void QmitkStdMultiWidgetEditorPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); - mitk::CoreServicePointer prefService(mitk::CoreServices::GetPreferencesService()); - - m_Preferences = prefService->GetSystemPreferences()->Node(QmitkStdMultiWidgetEditor::EDITOR_ID.toStdString()); - QObject::connect( m_Ui->m_ColorButton1, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_ColorButton2, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_ResetButton, SIGNAL( clicked() ) , this, SLOT( ResetPreferencesAndGUI() ) ); QObject::connect( m_Ui->m_RenderWindowDecorationColor, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_RenderWindowChooser, SIGNAL(activated(int) ) , this, SLOT( OnWidgetComboBoxChanged(int) ) ); QObject::connect( m_Ui->m_RenderWindowDecorationText, SIGNAL(textChanged(QString) ) , this, SLOT( AnnotationTextChanged(QString) ) ); this->Update(); } QWidget* QmitkStdMultiWidgetEditorPreferencePage::GetQtControl() const { return m_Control; } void QmitkStdMultiWidgetEditorPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkStdMultiWidgetEditorPreferencePage::PerformCancel() { } bool QmitkStdMultiWidgetEditorPreferencePage::PerformOk() { - m_Preferences->Put("stdmulti.widget0 corner annotation", m_WidgetAnnotation[0].toStdString()); - m_Preferences->Put("stdmulti.widget1 corner annotation", m_WidgetAnnotation[1].toStdString()); - m_Preferences->Put("stdmulti.widget2 corner annotation", m_WidgetAnnotation[2].toStdString()); - m_Preferences->Put("stdmulti.widget3 corner annotation", m_WidgetAnnotation[3].toStdString()); - - m_Preferences->Put("stdmulti.widget0 decoration color", m_WidgetDecorationColor[0].toStdString()); - m_Preferences->Put("stdmulti.widget1 decoration color", m_WidgetDecorationColor[1].toStdString()); - m_Preferences->Put("stdmulti.widget2 decoration color", m_WidgetDecorationColor[2].toStdString()); - m_Preferences->Put("stdmulti.widget3 decoration color", m_WidgetDecorationColor[3].toStdString()); - - m_Preferences->Put("stdmulti.widget0 first background color", m_WidgetBackgroundColor1[0].toStdString()); - m_Preferences->Put("stdmulti.widget1 first background color", m_WidgetBackgroundColor1[1].toStdString()); - m_Preferences->Put("stdmulti.widget2 first background color", m_WidgetBackgroundColor1[2].toStdString()); - m_Preferences->Put("stdmulti.widget3 first background color", m_WidgetBackgroundColor1[3].toStdString()); - m_Preferences->Put("stdmulti.widget0 second background color", m_WidgetBackgroundColor2[0].toStdString()); - m_Preferences->Put("stdmulti.widget1 second background color", m_WidgetBackgroundColor2[1].toStdString()); - m_Preferences->Put("stdmulti.widget2 second background color", m_WidgetBackgroundColor2[2].toStdString()); - m_Preferences->Put("stdmulti.widget3 second background color", m_WidgetBackgroundColor2[3].toStdString()); - m_Preferences->PutInt("crosshair gap size", m_Ui->m_CrosshairGapSize->value()); - - m_Preferences->PutBool("Use constrained zooming and panning" + auto* prefs = GetPreferences(); + + prefs->Put("stdmulti.widget0 corner annotation", m_WidgetAnnotation[0].toStdString()); + prefs->Put("stdmulti.widget1 corner annotation", m_WidgetAnnotation[1].toStdString()); + prefs->Put("stdmulti.widget2 corner annotation", m_WidgetAnnotation[2].toStdString()); + prefs->Put("stdmulti.widget3 corner annotation", m_WidgetAnnotation[3].toStdString()); + + prefs->Put("stdmulti.widget0 decoration color", m_WidgetDecorationColor[0].toStdString()); + prefs->Put("stdmulti.widget1 decoration color", m_WidgetDecorationColor[1].toStdString()); + prefs->Put("stdmulti.widget2 decoration color", m_WidgetDecorationColor[2].toStdString()); + prefs->Put("stdmulti.widget3 decoration color", m_WidgetDecorationColor[3].toStdString()); + + prefs->Put("stdmulti.widget0 first background color", m_WidgetBackgroundColor1[0].toStdString()); + prefs->Put("stdmulti.widget1 first background color", m_WidgetBackgroundColor1[1].toStdString()); + prefs->Put("stdmulti.widget2 first background color", m_WidgetBackgroundColor1[2].toStdString()); + prefs->Put("stdmulti.widget3 first background color", m_WidgetBackgroundColor1[3].toStdString()); + prefs->Put("stdmulti.widget0 second background color", m_WidgetBackgroundColor2[0].toStdString()); + prefs->Put("stdmulti.widget1 second background color", m_WidgetBackgroundColor2[1].toStdString()); + prefs->Put("stdmulti.widget2 second background color", m_WidgetBackgroundColor2[2].toStdString()); + prefs->Put("stdmulti.widget3 second background color", m_WidgetBackgroundColor2[3].toStdString()); + prefs->PutInt("crosshair gap size", m_Ui->m_CrosshairGapSize->value()); + + prefs->PutBool("Use constrained zooming and panning" , m_Ui->m_EnableFlexibleZooming->isChecked()); - m_Preferences->PutBool("Show level/window widget", m_Ui->m_ShowLevelWindowWidget->isChecked()); - m_Preferences->PutBool("PACS like mouse interaction", m_Ui->m_PACSLikeMouseMode->isChecked()); + prefs->PutBool("Show level/window widget", m_Ui->m_ShowLevelWindowWidget->isChecked()); + prefs->PutBool("PACS like mouse interaction", m_Ui->m_PACSLikeMouseMode->isChecked()); return true; } void QmitkStdMultiWidgetEditorPreferencePage::Update() { + auto* prefs = GetPreferences(); + //Note: there should be default preferences already defined in the //QmitkStdMultiWidgetEditor::InitializePreferences(). Therefore, //all default values here are not relevant. //gradient background colors - m_WidgetBackgroundColor1[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 first background color", "#000000")); - m_WidgetBackgroundColor2[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 second background color", "#000000")); - m_WidgetBackgroundColor1[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 first background color", "#000000")); - m_WidgetBackgroundColor2[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 second background color", "#000000")); - m_WidgetBackgroundColor1[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 first background color", "#000000")); - m_WidgetBackgroundColor2[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 second background color", "#000000")); - m_WidgetBackgroundColor1[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 first background color", "#191919")); - m_WidgetBackgroundColor2[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 second background color", "#7F7F7F")); + m_WidgetBackgroundColor1[0] = QString::fromStdString(prefs->Get("stdmulti.widget0 first background color", "#000000")); + m_WidgetBackgroundColor2[0] = QString::fromStdString(prefs->Get("stdmulti.widget0 second background color", "#000000")); + m_WidgetBackgroundColor1[1] = QString::fromStdString(prefs->Get("stdmulti.widget1 first background color", "#000000")); + m_WidgetBackgroundColor2[1] = QString::fromStdString(prefs->Get("stdmulti.widget1 second background color", "#000000")); + m_WidgetBackgroundColor1[2] = QString::fromStdString(prefs->Get("stdmulti.widget2 first background color", "#000000")); + m_WidgetBackgroundColor2[2] = QString::fromStdString(prefs->Get("stdmulti.widget2 second background color", "#000000")); + m_WidgetBackgroundColor1[3] = QString::fromStdString(prefs->Get("stdmulti.widget3 first background color", "#191919")); + m_WidgetBackgroundColor2[3] = QString::fromStdString(prefs->Get("stdmulti.widget3 second background color", "#7F7F7F")); //decoration colors - m_WidgetDecorationColor[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 decoration color", "#c00000")); - m_WidgetDecorationColor[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 decoration color", "#00b000")); - m_WidgetDecorationColor[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 decoration color", "#0080ff")); - m_WidgetDecorationColor[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 decoration color", "#ffff00")); + m_WidgetDecorationColor[0] = QString::fromStdString(prefs->Get("stdmulti.widget0 decoration color", "#c00000")); + m_WidgetDecorationColor[1] = QString::fromStdString(prefs->Get("stdmulti.widget1 decoration color", "#00b000")); + m_WidgetDecorationColor[2] = QString::fromStdString(prefs->Get("stdmulti.widget2 decoration color", "#0080ff")); + m_WidgetDecorationColor[3] = QString::fromStdString(prefs->Get("stdmulti.widget3 decoration color", "#ffff00")); //annotation text - m_WidgetAnnotation[0] = QString::fromStdString(m_Preferences->Get("stdmulti.widget0 corner annotation", "Axial")); - m_WidgetAnnotation[1] = QString::fromStdString(m_Preferences->Get("stdmulti.widget1 corner annotation", "Sagittal")); - m_WidgetAnnotation[2] = QString::fromStdString(m_Preferences->Get("stdmulti.widget2 corner annotation", "Coronal")); - m_WidgetAnnotation[3] = QString::fromStdString(m_Preferences->Get("stdmulti.widget3 corner annotation", "3D")); + m_WidgetAnnotation[0] = QString::fromStdString(prefs->Get("stdmulti.widget0 corner annotation", "Axial")); + m_WidgetAnnotation[1] = QString::fromStdString(prefs->Get("stdmulti.widget1 corner annotation", "Sagittal")); + m_WidgetAnnotation[2] = QString::fromStdString(prefs->Get("stdmulti.widget2 corner annotation", "Coronal")); + m_WidgetAnnotation[3] = QString::fromStdString(prefs->Get("stdmulti.widget3 corner annotation", "3D")); //Ui stuff int index = m_Ui->m_RenderWindowChooser->currentIndex(); QColor firstBackgroundColor(m_WidgetBackgroundColor1[index]); QColor secondBackgroundColor(m_WidgetBackgroundColor2[index]); QColor widgetColor(m_WidgetDecorationColor[index]); this->SetStyleSheetToColorChooserButton(firstBackgroundColor, m_Ui->m_ColorButton1); this->SetStyleSheetToColorChooserButton(secondBackgroundColor, m_Ui->m_ColorButton2); this->SetStyleSheetToColorChooserButton(widgetColor, m_Ui->m_RenderWindowDecorationColor); m_Ui->m_RenderWindowDecorationText->setText(m_WidgetAnnotation[index]); - m_Ui->m_EnableFlexibleZooming->setChecked(m_Preferences->GetBool("Use constrained zooming and panning", true)); - m_Ui->m_ShowLevelWindowWidget->setChecked(m_Preferences->GetBool("Show level/window widget", true)); - m_Ui->m_PACSLikeMouseMode->setChecked(m_Preferences->GetBool("PACS like mouse interaction", false)); - m_Ui->m_CrosshairGapSize->setValue(m_Preferences->GetInt("crosshair gap size", 32)); + m_Ui->m_EnableFlexibleZooming->setChecked(prefs->GetBool("Use constrained zooming and panning", true)); + m_Ui->m_ShowLevelWindowWidget->setChecked(prefs->GetBool("Show level/window widget", true)); + m_Ui->m_PACSLikeMouseMode->setChecked(prefs->GetBool("PACS like mouse interaction", false)); + m_Ui->m_CrosshairGapSize->setValue(prefs->GetInt("crosshair gap size", 32)); } void QmitkStdMultiWidgetEditorPreferencePage::ColorChooserButtonClicked() { unsigned int widgetIndex = m_Ui->m_RenderWindowChooser->currentIndex(); if(widgetIndex > 3) { MITK_ERROR << "Selected index for unknown."; return; } QObject *senderObj = sender(); // This will give Sender button //find out last used color and set it QColor initialColor; if( senderObj->objectName() == m_Ui->m_ColorButton1->objectName()) { initialColor = QColor(m_WidgetBackgroundColor1[widgetIndex]); }else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) { initialColor = QColor(m_WidgetBackgroundColor2[widgetIndex]); }else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) { initialColor = QColor(m_WidgetDecorationColor[widgetIndex]); } //get the new color QColor newcolor = QColorDialog::getColor(initialColor); if(!newcolor.isValid()) { newcolor = initialColor; } this->SetStyleSheetToColorChooserButton(newcolor, static_cast<QPushButton*>(senderObj)); //convert it to std string and apply it if( senderObj->objectName() == m_Ui->m_ColorButton1->objectName()) { m_WidgetBackgroundColor1[widgetIndex] = newcolor.name(); } else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) { m_WidgetBackgroundColor2[widgetIndex] = newcolor.name(); } else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) { m_WidgetDecorationColor[widgetIndex] = newcolor.name(); } } void QmitkStdMultiWidgetEditorPreferencePage::SetStyleSheetToColorChooserButton(QColor backgroundcolor, QPushButton* button) { button->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(backgroundcolor.red())); styleSheet.append(","); styleSheet.append(QString::number(backgroundcolor.green())); styleSheet.append(","); styleSheet.append(QString::number(backgroundcolor.blue())); styleSheet.append(")"); button->setStyleSheet(styleSheet); } void QmitkStdMultiWidgetEditorPreferencePage::AnnotationTextChanged(QString text) { unsigned int widgetIndex = m_Ui->m_RenderWindowChooser->currentIndex(); if( widgetIndex > 3) { MITK_INFO << "Selected index for unknown widget."; return; } m_WidgetAnnotation[widgetIndex] = text; } void QmitkStdMultiWidgetEditorPreferencePage::ResetPreferencesAndGUI() { - m_Preferences->Clear(); + auto* prefs = GetPreferences(); + + prefs->Clear(); this->Update(); } void QmitkStdMultiWidgetEditorPreferencePage::OnWidgetComboBoxChanged(int i) { if( i > 3) { MITK_ERROR << "Selected unknown widget."; return; } QColor widgetColor(m_WidgetDecorationColor[i]); QColor gradientBackground1(m_WidgetBackgroundColor1[i]); QColor gradientBackground2(m_WidgetBackgroundColor2[i]); this->SetStyleSheetToColorChooserButton(widgetColor, m_Ui->m_RenderWindowDecorationColor); this->SetStyleSheetToColorChooserButton(gradientBackground1, m_Ui->m_ColorButton1); this->SetStyleSheetToColorChooserButton(gradientBackground2, m_Ui->m_ColorButton2); m_Ui->m_RenderWindowDecorationText->setText(m_WidgetAnnotation[i]); } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h index db30fd9535..58932874a5 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h @@ -1,112 +1,102 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkStdMultiWidgetEditorPreferencePage_h #define QmitkStdMultiWidgetEditorPreferencePage_h #include <berryIQtPreferencePage.h> #include <QScopedPointer> #include <QString> #include <array> class QPushButton; -namespace mitk -{ - class IPreferences; -} - namespace Ui { class QmitkStdMultiWidgetEditorPreferencePage; } class QmitkStdMultiWidgetEditorPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkStdMultiWidgetEditorPreferencePage(); ~QmitkStdMultiWidgetEditorPreferencePage() override; void CreateQtControl(QWidget* parent) override; QWidget* GetQtControl() const override; void Init(berry::IWorkbench::Pointer) override; void PerformCancel() override; bool PerformOk() override; void Update() override; public slots: /** * @brief ResetColors set default colors and refresh the GUI. */ void ResetPreferencesAndGUI(); /** * @brief OnWidgetComboBoxChanged slot called when the QComboBox to chose the widget was modified. * @param i index of the combobox to select the widget (1-4). */ void OnWidgetComboBoxChanged(int i); /** * @brief AnnotationTextChanged called when QLineEdit for the annotation was changed. * @param text The new text. */ void AnnotationTextChanged(QString text); protected: /** * @brief m_WidgetBackgroundColor1 the background colors. * * If two different colors are chosen, a gradient background appears. */ std::array<QString, 4> m_WidgetBackgroundColor1; std::array<QString, 4> m_WidgetBackgroundColor2; /** * @brief m_WidgetDecorationColor the decoration color. * * The rectangle prop, the crosshair, the 3D planes and the corner annotation use this. */ std::array<QString, 4> m_WidgetDecorationColor; /** * @brief m_Widget1Annotation the text of the corner annotation. */ std::array<QString, 4> m_WidgetAnnotation; - /** - * @brief m_Preferences the berry preferences. - */ - mitk::IPreferences* m_Preferences; - /** * @brief SetStyleSheetToColorChooserButton colorize a button. * @param backgroundcolor color for the button. * @param button the button. */ void SetStyleSheetToColorChooserButton(QColor backgroundcolor, QPushButton* button); protected slots: /** * @brief ColorChooserButtonClicked slot called when a button to choose color was clicked. */ void ColorChooserButtonClicked(); private: QScopedPointer<Ui::QmitkStdMultiWidgetEditorPreferencePage> m_Ui; QWidget* m_Control; }; #endif //QmitkStdMultiWidgetEditorPreferencePage_h diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp index c97741b79b..30d9b3f565 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp @@ -1,286 +1,296 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkXnatConnectionPreferencePage.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include <QFileDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> #include <QMap> #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include <mitkIOUtil.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> using namespace berry; +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID.toStdString()); + } +} + QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(nullptr) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - m_XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID.toStdString()); - m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument&) { session = nullptr; } if (session != nullptr && session->isOpen()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green"); m_Controls.xnatTestConnectionLabel->setText("Already connected."); m_Controls.xnatTestConnectionButton->setEnabled(false); } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked())); m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { - if (m_XnatConnectionPreferencesNode != nullptr) + auto* prefs = GetPreferences(); + + if (prefs != nullptr) { - m_XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString()); + prefs->Put(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString()); + prefs->Put(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString()); + prefs->Put(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString()); + prefs->Put(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString()); + prefs->Put(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString()); // Network proxy settings - m_XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text().toStdString(), m_Controls.cbUseNetworkProxy->isChecked()); - m_XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString()); - m_XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString()); + prefs->PutBool(m_Controls.cbUseNetworkProxy->text().toStdString(), m_Controls.cbUseNetworkProxy->isChecked()); + prefs->Put(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString()); + prefs->Put(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString()); + prefs->Put(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString()); + prefs->Put(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString()); // Silent Mode - m_XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text().toStdString(), m_Controls.cbUseSilentMode->isChecked()); + prefs->PutBool(m_Controls.cbUseSilentMode->text().toStdString(), m_Controls.cbUseSilentMode->isChecked()); //Write - m_XnatConnectionPreferencesNode->Flush(); + prefs->Flush(); return true; } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { - if (m_XnatConnectionPreferencesNode != nullptr) + auto* prefs = GetPreferences(); + + if (prefs != nullptr) { - m_Controls.inXnatHostAddress->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString()))); - m_Controls.inXnatPort->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString()))); - m_Controls.inXnatUsername->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString()))); - m_Controls.inXnatPassword->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString()))); - m_Controls.inXnatDownloadPath->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString()))); + m_Controls.inXnatHostAddress->setText(QString::fromStdString(prefs->Get(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString()))); + m_Controls.inXnatPort->setText(QString::fromStdString(prefs->Get(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString()))); + m_Controls.inXnatUsername->setText(QString::fromStdString(prefs->Get(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString()))); + m_Controls.inXnatPassword->setText(QString::fromStdString(prefs->Get(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString()))); + m_Controls.inXnatDownloadPath->setText(QString::fromStdString(prefs->Get(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString()))); // Network proxy settings - m_Controls.cbUseNetworkProxy->setChecked(m_XnatConnectionPreferencesNode->GetBool(m_Controls.cbUseNetworkProxy->text().toStdString(), false)); - m_Controls.inProxyAddress->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString()))); - m_Controls.inProxyPort->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString()))); - m_Controls.inProxyUsername->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString()))); - m_Controls.inProxyPassword->setText(QString::fromStdString(m_XnatConnectionPreferencesNode->Get(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString()))); + m_Controls.cbUseNetworkProxy->setChecked(prefs->GetBool(m_Controls.cbUseNetworkProxy->text().toStdString(), false)); + m_Controls.inProxyAddress->setText(QString::fromStdString(prefs->Get(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString()))); + m_Controls.inProxyPort->setText(QString::fromStdString(prefs->Get(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString()))); + m_Controls.inProxyUsername->setText(QString::fromStdString(prefs->Get(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString()))); + m_Controls.inProxyPassword->setText(QString::fromStdString(prefs->Get(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString()))); // Silent Mode - m_Controls.cbUseSilentMode->setChecked(m_XnatConnectionPreferencesNode->GetBool(m_Controls.cbUseSilentMode->text().toStdString(), false)); + m_Controls.cbUseSilentMode->setChecked(prefs->GetBool(m_Controls.cbUseSilentMode->text().toStdString(), false)); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet(""); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("background-color: red"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet(""); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("background-color: red"); } } } void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status) { m_Controls.groupBoxProxySettings->setVisible(status); } void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked() { QString dir = QFileDialog::getExistingDirectory(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void QmitkXnatConnectionPreferencePage::TestConnection() { if(UserInformationEmpty()) { return; } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (const std::invalid_argument &) { if (!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green"); m_Controls.xnatTestConnectionLabel->setText("Connecting successful."); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkXnatAuthenticationException& auth) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Adress\nPossibly due to missing OpenSSL for HTTPS connections"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h index d4b5227294..d6a297992d 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.h @@ -1,87 +1,80 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKXNATCONNECTIONPREFERENCEPAGE_H_ #define QMITKXNATCONNECTIONPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include "ui_QmitkXnatConnectionPreferencePageControls.h" -namespace mitk -{ - class IPreferences; -} - class QWidget; class QLineEdit; struct QmitkXnatConnectionPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkXnatConnectionPreferencePage(); void Init(berry::IWorkbench::Pointer workbench) override; void CreateQtControl(QWidget* widget) override; QWidget* GetQtControl() const override; /// /// \see IPreferencePage::PerformOk() /// bool PerformOk() override; /// /// \see IPreferencePage::PerformCancel() /// void PerformCancel() override; /// /// \see IPreferencePage::Update() /// void Update() override; protected slots: virtual void UrlChanged(); virtual void DownloadPathChanged(); void OnDownloadPathButtonClicked(); /// /// Toggles the Connection in the Service Registry from opened to closed or the other way around. /// virtual void TestConnection(); virtual void onUseNetworkProxy(bool); protected: Ui::QmitkXnatConnectionPreferencePageControls m_Controls; QWidget* m_Control; - mitk::IPreferences* m_XnatConnectionPreferencesNode; - private: /// /// Checks if the entered user information is empty. /// virtual bool UserInformationEmpty(); }; #endif /* QMITKXNATCONNECTIONPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp index 8db8d026eb..e330be3d14 100644 --- a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp +++ b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp @@ -1,151 +1,158 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "MatchPointBrowserPreferencesPage.h" #include "MatchPointBrowserConstants.h" #include <QWidget> #include <QLabel> #include <QFormLayout> #include <QCheckBox> #include <QComboBox> #include <QMessageBox> #include <QSpinBox> #include <ctkDirectoryButton.h> #include <mitkCoreServices.h> #include <mitkIPreferencesService.h> #include <mitkIPreferences.h> #include "QmitkDirectoryListWidget.h" #include "QmitkFileListWidget.h" +namespace +{ + mitk::IPreferences* GetPreferences() + { + auto* preferencesService = mitk::CoreServices::GetPreferencesService(); + return preferencesService->GetSystemPreferences()->Node(MatchPointBrowserConstants::VIEW_ID); + } +} + //----------------------------------------------------------------------------- MatchPointBrowserPreferencesPage::MatchPointBrowserPreferencesPage() : m_MainControl(nullptr) , m_AlgDirectories(nullptr) , m_AlgFiles(nullptr) , m_LoadFromHomeDir(nullptr) , m_LoadFromCurrentDir(nullptr) , m_LoadFromApplicationDir(nullptr) , m_LoadFromAutoLoadPathDir(nullptr) -, m_BrowserPreferencesNode(nullptr) { } //----------------------------------------------------------------------------- MatchPointBrowserPreferencesPage::~MatchPointBrowserPreferencesPage() { } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::CreateQtControl(QWidget* parent) { - auto* prefService = mitk::CoreServices::GetPreferencesService(); - - const auto id = "/" + MatchPointBrowserConstants::VIEW_ID; - m_BrowserPreferencesNode = prefService->GetSystemPreferences()->Node(id); - m_MainControl = new QWidget(parent); m_AlgDirectories = new QmitkDirectoryListWidget(m_MainControl); m_AlgDirectories->m_Label->setText("Select directories to scan:"); m_AlgFiles = new QmitkFileListWidget(m_MainControl); m_AlgFiles->m_Label->setText("Select additional executables:"); m_DebugOutput = new QCheckBox(m_MainControl); m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl); m_LoadFromApplicationDir = new QCheckBox(m_MainControl); m_LoadFromHomeDir = new QCheckBox(m_MainControl); m_LoadFromCurrentDir = new QCheckBox(m_MainControl); QFormLayout *formLayout = new QFormLayout; formLayout->addRow("show debug output:", m_DebugOutput); formLayout->addRow("scan home directory:", m_LoadFromHomeDir); formLayout->addRow("scan current directory:", m_LoadFromCurrentDir); formLayout->addRow("scan installation directory:", m_LoadFromApplicationDir); formLayout->addRow("scan MAP_MDRA_LOAD_PATH:", m_LoadFromAutoLoadPathDir); formLayout->addRow("additional algorithm directories:", m_AlgDirectories); formLayout->addRow("additional algorithms:", m_AlgFiles); m_MainControl->setLayout(formLayout); this->Update(); } //----------------------------------------------------------------------------- QWidget* MatchPointBrowserPreferencesPage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- std::string MatchPointBrowserPreferencesPage::ConvertToString( const QStringList& list ) { return list.join(';').toStdString(); } //----------------------------------------------------------------------------- bool MatchPointBrowserPreferencesPage::PerformOk() { - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); - m_BrowserPreferencesNode->PutBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); + auto* prefs = GetPreferences(); + + prefs->PutBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); + prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); + prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); + prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); + prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); const auto paths = this->ConvertToString(m_AlgDirectories->directories()); - m_BrowserPreferencesNode->Put(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, paths); + prefs->Put(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, paths); const auto modules = this->ConvertToString(m_AlgFiles->files()); - m_BrowserPreferencesNode->Put(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, modules); + prefs->Put(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, modules); return true; } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::PerformCancel() { } //----------------------------------------------------------------------------- void MatchPointBrowserPreferencesPage::Update() { - m_DebugOutput->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, false)); - m_LoadFromApplicationDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, true)); - m_LoadFromHomeDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, false)); - m_LoadFromCurrentDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, false)); - m_LoadFromAutoLoadPathDir->setChecked(m_BrowserPreferencesNode->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); + auto* prefs = GetPreferences(); + + m_DebugOutput->setChecked(prefs->GetBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, false)); + m_LoadFromApplicationDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, true)); + m_LoadFromHomeDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, false)); + m_LoadFromCurrentDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, false)); + m_LoadFromAutoLoadPathDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); - QString paths = QString::fromStdString(m_BrowserPreferencesNode->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, "")); + QString paths = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, "")); QStringList directoryList = paths.split(";", QString::SkipEmptyParts); m_AlgDirectories->setDirectories(directoryList); - QString files = QString::fromStdString(m_BrowserPreferencesNode->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, "")); + QString files = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, "")); QStringList fileList = files.split(";", QString::SkipEmptyParts); m_AlgFiles->setFiles(fileList); } diff --git a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h index d2863268f4..92adc9a858 100644 --- a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h +++ b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.h @@ -1,97 +1,90 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __MATCHPOINT_BROWSER_PREFERENCE_PAGE_H #define __MATCHPOINT_BROWSER_PREFERENCE_PAGE_H #include "berryIQtPreferencePage.h" class QWidget; class QCheckBox; class QComboBox; class QSpinBox; class QmitkDirectoryListWidget; class QmitkFileListWidget; class ctkDirectoryButton; -namespace mitk -{ - class IPreferences; -} - /** * \class MatchPointBrowserPreferencesPage * \brief Preference page for the MatchPoint Browser plugin */ class MatchPointBrowserPreferencesPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: MatchPointBrowserPreferencesPage(); ~MatchPointBrowserPreferencesPage() override; /** * \brief Called by framework to initialise this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench) override; /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget) override; /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const override; /** * \see IPreferencePage::PerformOk */ bool PerformOk() override; /** * \see IPreferencePage::PerformCancel */ void PerformCancel() override; /** * \see IPreferencePage::Update */ void Update() override; public slots: protected: QWidget* m_MainControl; QCheckBox* m_DebugOutput; QmitkDirectoryListWidget* m_AlgDirectories; QmitkFileListWidget* m_AlgFiles; QCheckBox* m_LoadFromHomeDir; QCheckBox* m_LoadFromCurrentDir; QCheckBox* m_LoadFromApplicationDir; QCheckBox* m_LoadFromAutoLoadPathDir; - mitk::IPreferences* m_BrowserPreferencesNode; - private: std::string ConvertToString(const QStringList& list); }; #endif // COMMANDLINEMODULESPREFERENCESPAGE_H