diff --git a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp index 695c963ce2..446c3d8ee6 100755 --- a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp +++ b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp @@ -1,78 +1,77 @@ -/*========================================================================= +/*=================================================================== -Program: BlueBerry Platform -Language: C++ -Date: $Date$ -Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkCoreExtActivator.h" #include "mitkPicFileReader.h" #include #include "mitkCoreExtConstants.h" #include "mitkInputDeviceRegistry.h" #include #include #include namespace mitk { void CoreExtActivator::start(ctkPluginContext* context) { Q_UNUSED(context) // see bug 10816 // don't let the linker optimize the dependency away mitk::PicFileReader::New(); RegisterCoreExtObjectFactory(); this->StartInputDeviceModules(); } void CoreExtActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } void mitk::CoreExtActivator::StartInputDeviceModules() { IInputDeviceRegistry::Pointer inputDeviceRegistry(new mitk::InputDeviceRegistry()); berry::Platform::GetServiceRegistry().RegisterService( mitk::CoreExtConstants::INPUTDEVICE_SERVICE, inputDeviceRegistry); // Gets the last setting of the preferences; if a device was selected, // it will still be activated after a restart berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); berry::IPreferences::Pointer extPreferencesNode = prefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES); // Initializes the modules std::vector descriptors(inputDeviceRegistry->GetInputDevices()); for (std::vector::const_iterator it = descriptors.begin(); it != descriptors.end(); ++it) { if (extPreferencesNode->GetBool((*it)->GetID(), false)) { IInputDevice::Pointer temp = (*it)->CreateInputDevice(); temp->RegisterInputDevice(); } } } // end method StartInputDeviceModules } // end namespace mitk Q_EXPORT_PLUGIN2(org_mitk_core_ext, mitk::CoreExtActivator) diff --git a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h index 4e3d873dee..8e4af29c03 100755 --- a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h +++ b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.h @@ -1,64 +1,63 @@ -/*========================================================================= +/*=================================================================== -Program: MITK Platform -Language: C++ -Date: $Date$ -Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKCOREEXTACTIVATOR_H_ #define MITKCOREEXTACTIVATOR_H_ #include #include #include namespace mitk { /** * @brief The activator class for the org.mitk.core.ext plug-in. * @ingroup org_mitk_core_ext_internal * * When the plug-in is started by the framework, it calls a global function to initialize * the mitkCoreExt module. * */ class MITK_LOCAL CoreExtActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: /** * Starts this plug-in and registers object factories. * * @param context * The context for the plug-in. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: /** * Activates the input device modules. */ void StartInputDeviceModules(); }; // end class CoreExtActivator } //end namespace mitk #endif /* MITKCOREEXTACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.cpp b/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.cpp index f492b8291f..f3d2d2474f 100644 --- a/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.cpp +++ b/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.cpp @@ -1,31 +1,30 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include "mitkIInputDeviceRegistry.h" const std::string mitk::CoreExtConstants::INPUTDEVICE_SERVICE = "org.mitk.core.ext.services.inputdeviceregistry"; const std::string mitk::CoreExtConstants::INPUTDEVICE_PREFERENCES = "org.mitk.core.ext.preferences.inputdevices"; const std::string mitk::CoreExtConstants::INPUTDEVICE_EXTENSION_NAME = "org.mitk.core.ext.inputdevices"; const std::string mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_CLASS = "class"; const std::string mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_DESCRIPTION = "description"; const std::string mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_NAME = "name"; const std::string mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_ID = "id"; const std::string mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION = "Surface Interaction"; const std::string mitk::CoreExtConstants::WIIMOTE_HEADTRACKING = "Headtracking"; const std::string mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME = "org.mitk.inputdevices.wiimote"; diff --git a/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.h b/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.h index 4b7cae4abd..7c75b53d78 100644 --- a/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.h +++ b/Plugins/org.mitk.core.ext/src/mitkCoreExtConstants.h @@ -1,54 +1,53 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKCOREEXTCONSTANTS_H_ #define MITKCOREEXTCONSTANTS_H_ #include #include namespace mitk { /** * The CoreExt Constants contains a list of unique ids in the following form:
* "org.mitk.mybundle.mytype.propername"
* * This ids have the purpose of connecting the plugin.xml of each bundle to the * appropriate classes. * * Additionally it includes names of tags, which are used in XML files
* regarding any input device. * * @ingroup org_mitk_core_ext */ struct MITKCOREEXT_EXPORT CoreExtConstants { static const std::string INPUTDEVICE_SERVICE; static const std::string INPUTDEVICE_PREFERENCES; static const std::string INPUTDEVICE_EXTENSION_NAME; static const std::string INPUTDEVICE_XMLATTRIBUTE_CLASS; static const std::string INPUTDEVICE_XMLATTRIBUTE_DESCRIPTION; static const std::string INPUTDEVICE_XMLATTRIBUTE_NAME; static const std::string INPUTDEVICE_XMLATTRIBUTE_ID; static const std::string WIIMOTE_SURFACEINTERACTION; static const std::string WIIMOTE_HEADTRACKING; static const std::string WIIMOTE_XMLATTRIBUTE_NAME; }; } #endif /*MITKCOREEXTCONSTANTS_H_*/ diff --git a/Plugins/org.mitk.core.ext/src/mitkIInputDevice.h b/Plugins/org.mitk.core.ext/src/mitkIInputDevice.h index ca8ae7603a..18409df634 100644 --- a/Plugins/org.mitk.core.ext/src/mitkIInputDevice.h +++ b/Plugins/org.mitk.core.ext/src/mitkIInputDevice.h @@ -1,57 +1,56 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIINPUTDEVICE_H_ #define MITKIINPUTDEVICE_H_ #include #include #include namespace mitk { /** * An input device provides a method to register and unregister itself. Meaning
* for example adding listeners and instianciate classes necessary to use the input device. * * @noimplement This interface is not intended to be implemented by clients. * @ingroup org_mitk_core_ext */ struct IInputDevice : public berry::Object { berryInterfaceMacro(IInputDevice, mitk) /** * Register the input device at one or more instances. */ virtual bool RegisterInputDevice() = 0; /** * Unregister the input device at one or more instances. */ virtual bool UnRegisterInputDevice() = 0; virtual ~IInputDevice() {} }; // end struct IInputDevice } // end namespace mitk Q_DECLARE_INTERFACE(mitk::IInputDevice, "org.mitk.IInputDevice") #endif /*MITKIINPUTDEVICE_H_*/ diff --git a/Plugins/org.mitk.core.ext/src/mitkIInputDeviceDescriptor.h b/Plugins/org.mitk.core.ext/src/mitkIInputDeviceDescriptor.h index 25126d6239..a6fad2681c 100644 --- a/Plugins/org.mitk.core.ext/src/mitkIInputDeviceDescriptor.h +++ b/Plugins/org.mitk.core.ext/src/mitkIInputDeviceDescriptor.h @@ -1,95 +1,94 @@ -/*========================================================================= +/*=================================================================== -Program: BlueBerry Platform -Language: C++ -Date: $Date: 2010-01-16 19:57:43 +0100 (Sat, 16 Jan 2010) $ -Version: $Revision: 21070 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIINPUTDEVICEDESCRIPTOR_H_ #define MITKIINPUTDEVICEDESCRIPTOR_H_ #include #include #include #include #include "mitkIInputDevice.h" namespace mitk { /** * This is an input device descriptor. It provides a "description" of a given * input device, so that the input device can later be constructed and registered. *

* The input device registry provides facilities to map from an extension * to a IInputDeviceDescriptor. *

*

* This interface is not intended to be implemented by clients. *

* * @see mitk::IInputDeviceRegistry * @ingroup org_mitk_core_ext */ struct IInputDeviceDescriptor : public berry::Object { berryInterfaceMacro(IInputDeviceDescriptor, mitk); /** * Creates an instance of an input device defined in the descriptor. * * @return the input device */ virtual IInputDevice::Pointer CreateInputDevice() = 0; /** * Returns the description of this input device. * * @return the description */ virtual std::string GetDescription() const = 0; /** * Returns the id of this input device. * * @return the id */ virtual std::string GetID() const = 0; /** * Returns the name of this input device. * * @return the name */ virtual std::string GetName() const = 0; // /** // * Returns the descriptor for the icon to show for this view. // */ //virtual SmartPointer GetImageDescriptor() const = 0; /** * Equals this class with the given parameter. * * @param object * the object for the equation * @return true, if the objects are equal :: false, if they differ in any way */ virtual bool operator==(const Object* object) const = 0; }; // end struct IInputDeviceDescriptor } //end namespace mitk #endif /*MITKIINPUTDEVICEDESCRIPTOR_H_*/ diff --git a/Plugins/org.mitk.core.ext/src/mitkIInputDeviceRegistry.h b/Plugins/org.mitk.core.ext/src/mitkIInputDeviceRegistry.h index 2c02905d65..4c1f1e0bf9 100644 --- a/Plugins/org.mitk.core.ext/src/mitkIInputDeviceRegistry.h +++ b/Plugins/org.mitk.core.ext/src/mitkIInputDeviceRegistry.h @@ -1,77 +1,76 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIINPUTDEVICEREGISTRY_H_ #define MITKIINPUTDEVICEREGISTRY_H_ #include #include #include #include #include #include "mitkIInputDeviceDescriptor.h" namespace mitk { /** * * The input device registry maintains a list of input devices explicitly registered * against the view extension point. *

* The description of a given input device is kept in a IInputDeviceDescriptor. *

*

* This interface is not intended to be implemented by clients. *

* * @see mitk::IInputDeviceDescriptor * @noimplement This interface is not intended to be implemented by clients. * @ingroup org_mitk_core_ext */ struct MITKCOREEXT_EXPORT IInputDeviceRegistry: public berry::Service { berryInterfaceMacro(IInputDeviceRegistry, mitk) /** * Return an input device descriptor with the given extension id. If no input device exists, * with the id return null. * * @param id * the id to search for * @return the descriptor or null */ virtual IInputDeviceDescriptor::Pointer Find(const std::string& id) const = 0; /** * Return a list of input devices defined in the registry. * * @return the input devices. */ virtual std::vector GetInputDevices() const = 0; virtual ~IInputDeviceRegistry() {} }; // end struct IInputDeviceRegistry } // end namespace mitk Q_DECLARE_INTERFACE(mitk::IInputDeviceRegistry, "org.mitk.service.IInputDeviceRegistry") #endif /*MITKIINPUTDEVICEREGISTRY_H_*/ diff --git a/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.cpp b/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.cpp index d98d818f4b..3074328660 100644 --- a/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.cpp +++ b/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.cpp @@ -1,84 +1,83 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkInputDeviceDescriptor.h" #include "mitkCoreExtConstants.h" mitk::InputDeviceDescriptor::InputDeviceDescriptor(berry::IConfigurationElement::Pointer inputDeviceExtensionPoint) : IInputDeviceDescriptor(), m_InputDeviceExtensionPoint(inputDeviceExtensionPoint) { } mitk::InputDeviceDescriptor::~InputDeviceDescriptor() { } mitk::IInputDevice::Pointer mitk::InputDeviceDescriptor::CreateInputDevice() { if(this->m_InputDevice == 0) { // "class" refers to xml attribute in a xml tag this->m_InputDevice = this->m_InputDeviceExtensionPoint ->CreateExecutableExtension(mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_CLASS); if (this->m_InputDevice == 0) { // support legacy BlueBerry extensions this->m_InputDevice = this->m_InputDeviceExtensionPoint ->CreateExecutableExtension( mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_CLASS, IInputDevice::GetManifestName()); } } return this->m_InputDevice; } std::string mitk::InputDeviceDescriptor::GetID() const { std::string idOfExtensionPoint; this->m_InputDeviceExtensionPoint->GetAttribute(mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_ID,idOfExtensionPoint); return idOfExtensionPoint; } std::string mitk::InputDeviceDescriptor::GetDescription() const { std::vector descriptions(this->m_InputDeviceExtensionPoint->GetChildren(mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_DESCRIPTION)); if(!descriptions.empty()) { return descriptions[0]->GetValue(); } return ""; } std::string mitk::InputDeviceDescriptor::GetName() const { std::string name; this->m_InputDeviceExtensionPoint->GetAttribute(mitk::CoreExtConstants::INPUTDEVICE_XMLATTRIBUTE_NAME,name); return name; } bool mitk::InputDeviceDescriptor::operator==(const Object* object) const { if (const InputDeviceDescriptor* other = dynamic_cast(object)) { return this->GetID() == other->GetID(); } return false; } diff --git a/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.h b/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.h index ca40817db1..2b030df9f2 100644 --- a/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.h +++ b/Plugins/org.mitk.core.ext/src/mitkInputDeviceDescriptor.h @@ -1,88 +1,87 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKINPUTDEVICEDESCRIPTOR_H_ #define MITKINPUTDEVICEDESCRIPTOR_H_ #include #include #include "mitkIInputDeviceDescriptor.h" #include "mitkIInputDevice.h" namespace mitk { /** * Documentation in the interface. * * @see mitk::IInputDeviceDescriptor * @ingroup org_mitk_core_ext */ class InputDeviceDescriptor : public IInputDeviceDescriptor { public: /** * Initialize the Input Device Descriptor with the given extension point. * * @param inputDeviceExtensionPoint * element, that refers to a extension point (type, id, name, class) */ InputDeviceDescriptor(berry::IConfigurationElement::Pointer inputDeviceExtensionPoint); /** * Default destructor */ ~InputDeviceDescriptor(); /** * @see mitk::IInputDeviceDescriptor::CreateInputDevice() */ mitk::IInputDevice::Pointer CreateInputDevice(); /** * @see mitk::IInputDeviceDescriptor::GetDescription() */ std::string GetDescription() const; /** * @see mitk::IInputDeviceDescriptor::GetID() */ std::string GetID() const; /** * @see mitk::IInputDeviceDescriptor::GetName() */ std::string GetName() const; /** * @see mitk::IInputDeviceDescriptor::operator==(const Object* object) */ bool operator==(const Object* object) const; private: // IConfigurationElements are used to access xml files (here: plugin.xml) berry::IConfigurationElement::Pointer m_InputDeviceExtensionPoint; mitk::IInputDevice::Pointer m_InputDevice; }; // end class } // end namespace #endif /*MITKINPUTDEVICEDESCRIPTOR_H_*/ diff --git a/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.cpp b/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.cpp index 28966b038e..a062b8cabe 100644 --- a/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.cpp +++ b/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.cpp @@ -1,86 +1,85 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include #include #include #include "mitkCoreExtConstants.h" mitk::InputDeviceRegistry::InputDeviceRegistry() { //initialize the registry by copying all available extension points into a local variable berry::IExtensionPointService::Pointer extensionPointService = berry::Platform::GetExtensionPointService(); std::vector allExtensionsInputDevices = extensionPointService->GetConfigurationElementsFor(mitk::CoreExtConstants::INPUTDEVICE_EXTENSION_NAME); for(std::vector::const_iterator it = allExtensionsInputDevices.begin(); it != allExtensionsInputDevices.end();++it) { InputDeviceDescriptorPtr temp(new mitk::InputDeviceDescriptor(*it)); // The equation with the end means, that if there is no such element and // the pointer will be at end (not the last element, actually after it) if(this->m_ListRegisteredDevices.find(temp->GetID()) == this->m_ListRegisteredDevices.end()) { m_ListRegisteredDevices.insert(std::make_pair(temp->GetID(),temp)); } else { throw std::runtime_error("The Input Device ID: "+temp->GetID()+" is already registered."); } } } mitk::InputDeviceRegistry::~InputDeviceRegistry() { } mitk::InputDeviceRegistry::InputDeviceDescriptorPtr mitk::InputDeviceRegistry::Find(const std::string &id) const { Poco::HashMap::ConstIterator result = this->m_ListRegisteredDevices.find(id); // first = key, second = element or vice versa, if inserted different in the hash map if(result != this->m_ListRegisteredDevices.end()) return result->second; return InputDeviceDescriptorPtr(0); } std::vector mitk::InputDeviceRegistry::GetInputDevices() const { std::vector temp; for(Poco::HashMap::ConstIterator it = m_ListRegisteredDevices.begin(); it != m_ListRegisteredDevices.end();++it) { // first = key, second = element or vice versa, if inserted different in the hash map temp.push_back(it->second); } return temp; } bool mitk::InputDeviceRegistry::IsA(const std::type_info& type) const { std::string name(GetType().name()); return name == type.name() || berry::Service::IsA(type); } const std::type_info& mitk::InputDeviceRegistry::GetType() const { return typeid(IInputDeviceRegistry); } diff --git a/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.h b/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.h index 3e990240fd..775d107477 100644 --- a/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.h +++ b/Plugins/org.mitk.core.ext/src/mitkInputDeviceRegistry.h @@ -1,67 +1,66 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKSPACENAVIGATORREGISTRY_H_ #define MITKSPACENAVIGATORREGISTRY_H_ #include #include #include #include #include namespace mitk { /** * Documentation in the interface. * * @see mitk::IInputDeviceRegistry * @ingroup org_mitk_core_ext */ class InputDeviceRegistry : public IInputDeviceRegistry { public: bool IsA(const std::type_info& type) const; const std::type_info& GetType() const; // easier maintenance typedef IInputDeviceDescriptor::Pointer InputDeviceDescriptorPtr; InputDeviceRegistry(); ~InputDeviceRegistry(); /** * @see mitk::IInputDeviceRegistry::Find(const std::string& id) */ InputDeviceDescriptorPtr Find(const std::string& id) const; /** * @see mitk::IInputDeviceRegistry´::GetInputDevices() */ std::vector GetInputDevices() const; protected: private: Poco::HashMap m_ListRegisteredDevices; }; // end class InputDeviceRegistry } // end namespace mitk #endif /*MITKSPACENAVIGATORREGISTRY_H_*/ diff --git a/Plugins/org.mitk.core.jobs/src/internal/mitkDataStorageAccessRule.cpp b/Plugins/org.mitk.core.jobs/src/internal/mitkDataStorageAccessRule.cpp index d7160aa205..14929dfc76 100644 --- a/Plugins/org.mitk.core.jobs/src/internal/mitkDataStorageAccessRule.cpp +++ b/Plugins/org.mitk.core.jobs/src/internal/mitkDataStorageAccessRule.cpp @@ -1,197 +1,196 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18503 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataStorageAccessRule.h" #include mitk::DataStorageAccessRule ::DataStorageAccessRule (mitk::DataStorage::Pointer myDataStorage, mitk::DataNode::Pointer myDataNode, mitk::DataStorageAccessRule::RuleType myRule) :m_Rule(myRule), m_sptrMyDataStorage(myDataStorage), m_sptrMyDataNode(myDataNode) { mitk::DataStorage::SetOfObjects::ConstPointer sptr_parentsNodesFirstRule = m_sptrMyDataStorage->GetSources(m_sptrMyDataNode); // checks if the DataNode does exists within the specified DataTree, if not an // Poco NotFoundException is thrown since the rule is useless bool exsists = false ; for(mitk::DataStorage::SetOfObjects::const_iterator it = sptr_parentsNodesFirstRule->begin(); it != sptr_parentsNodesFirstRule->end(); ++ it) { if (*it == m_sptrMyDataNode ) exsists = true ; } if (exsists == false) throw Poco::NotFoundException() ; } bool mitk::DataStorageAccessRule ::Contains(berry::ISchedulingRule::Pointer rule) const { DataStorageAccessRule::Pointer sptr_temp = rule.Cast(); // test if the ISchedulingRule is a DataStorageAccessRule if( sptr_temp == 0 ) return false ; // test if the DataStorageAccessRule object is exactly the instance else { if ( this == sptr_temp.GetPointer() ) return true ; return false ; } } bool mitk::DataStorageAccessRule ::IsConflicting(berry::ISchedulingRule::Pointer sptr_otherISchedulingRule) const { // test if the stored dataNode // cast to check if the ISchedulingRule is a DataStorageAccessRule DataStorageAccessRule::Pointer sptr_DataStorageAccessRule = sptr_otherISchedulingRule.Cast(); // checks if the Rule of the type ISchedulingRule is a DataStorageAccessRule if(sptr_DataStorageAccessRule == 0) return false ; // the rule to be compared with is a DataStorageAccessRule else { // testing if both jobs holding each rule do operate on the same DataStorage if not false is returned if( !CompareDataStorages(sptr_DataStorageAccessRule->GetDataStorage()) ) return false ; // checks if to rules to be compared are two add rules if (m_Rule == ADD_RULE && m_Rule == sptr_DataStorageAccessRule->GetRuleType()) return CompareTwoAddorRemoveRules() ; // checks if to the two rules to be compared are two remove rules if(m_Rule == REMOVE_RULE && m_Rule == sptr_DataStorageAccessRule->GetRuleType()) return CompareTwoAddorRemoveRules() ; // an add and remove rule needs to be compared else { return CompareAddandRemoveRules(sptr_DataStorageAccessRule) ; } } } bool mitk::DataStorageAccessRule ::CompareAddandRemoveRules(mitk::DataStorageAccessRule::Pointer sptr_otherDataStorageAccessRule) const { mitk::DataStorage::SetOfObjects::ConstPointer sptr_parentsNodesFirstRule = m_sptrMyDataStorage->GetSources(m_sptrMyDataNode); // checks if the DataStorageNode of to be compared DataStorageAccessRule is a parent node // if so the job holding this DataStorageAccessRule need to wait until the operation on the parent node is performed for(mitk::DataStorage::SetOfObjects::const_iterator it = sptr_parentsNodesFirstRule->begin(); it != sptr_parentsNodesFirstRule->end(); ++ it) { if (*it == sptr_otherDataStorageAccessRule->GetDataNode()) return true ; } mitk::DataStorage::SetOfObjects::ConstPointer sptr_derivedNodesRule = m_sptrMyDataStorage->GetDerivations(m_sptrMyDataNode); // checks if the DataStorage node of to be compared DataStorageAccessRule is a child node // if so the job holding this DataStorageAccessRule needs to wait until the operation on the parent node is performed for(mitk::DataStorage::SetOfObjects::const_iterator it = sptr_derivedNodesRule->begin(); it != sptr_derivedNodesRule->end(); ++it) { if(*it == sptr_otherDataStorageAccessRule->GetDataNode()) return true ; } // jobs operating on nodes on different branches do not cause conflicts thus they can be performed in different // threads concurrently return false ; } bool mitk::DataStorageAccessRule ::CompareDataStorages(mitk::DataStorage::Pointer otherDataStorage) const { if(m_sptrMyDataStorage == otherDataStorage) return true ; else return false; } bool mitk::DataStorageAccessRule ::CompareTwoAddorRemoveRules() const { return false ; } bool mitk::DataStorageAccessRule ::TestDataNode(mitk::DataNode::Pointer /*dataTreeToBeStored*/) const { mitk::DataStorage::SetOfObjects::ConstPointer tempAllNodes = m_sptrMyDataStorage->GetAll(); for(mitk::DataStorage::SetOfObjects::const_iterator it = tempAllNodes->begin(); it !=tempAllNodes->end(); ++ it){ if (m_sptrMyDataNode == *it ) return true ; } return false ; } mitk::DataNode::Pointer mitk::DataStorageAccessRule ::GetDataNode() const { return mitk::DataStorageAccessRule::m_sptrMyDataNode ; } mitk::DataStorage::Pointer mitk::DataStorageAccessRule ::GetDataStorage() const { return mitk::DataStorageAccessRule::m_sptrMyDataStorage ; } mitk::DataStorageAccessRule::RuleType mitk::DataStorageAccessRule ::GetRuleType() const { if (m_Rule == ADD_RULE) return ( mitk::DataStorageAccessRule::ADD_RULE ) ; else { return ( mitk::DataStorageAccessRule::REMOVE_RULE ) ; } } diff --git a/Plugins/org.mitk.core.jobs/src/mitkDataStorageAccessRule.h b/Plugins/org.mitk.core.jobs/src/mitkDataStorageAccessRule.h index a77a81d62f..a6fd080021 100644 --- a/Plugins/org.mitk.core.jobs/src/mitkDataStorageAccessRule.h +++ b/Plugins/org.mitk.core.jobs/src/mitkDataStorageAccessRule.h @@ -1,159 +1,158 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDATASTORAGEACCESSRULE_H_HEADER_INCLUDED_ #define MITKDATASTORAGEACCESSRULE_H_HEADER_INCLUDED_ #include #include "berryISchedulingRule.h" #include "berryObject.h" #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "mitkStandaloneDataStorage.h" namespace mitk { /** *@class DataStorageAccessRule * *@brief The DataStorageAccessRule inherits from the ISchedulingRule class. DataStorageAccessRule are used to restrict the adding and * removing of DataStorage nodes in multi-threaded scenarios. Only DataStorageNodes within different branches can be modified * concurrently. The idea and its restrictions is explained in the sections and diagrams below. * *

the IsScheduling(...) method :

* returns true or false depending if conflictions with another rule are found * *

* *

*

the rule behavior if jobs holing add rules of an DataTree node

* * two add rules are always allowed since there are no conflictions when adding nodes concurrently. The final order the nodes are finally added has * to be checked by the programmer of the particular job * * *

the rule behavior when two jobs holding remove rules of a DataNode

* * two jobs holding remove rules can be executed concurrently since all removing scenarios do not cause conflictions. If two jobs are * trying to remove the same DataTree node the job by itself needs to check if the node is still available before executing the removing * command * * *

the rule behavior of a jobs that is holding an add rule compared with a job that is holding a remove rule on a * DataNode

* * adding and removing of DataTree nodes concurrently can cause serious errors and needs to be restricted. Performing add and remove * operations on different DataStorage branches can be done concurrently since no conflictions are expected. * the performing of add and remove operation on the same DataNode, its parent nodes or child nodes of the same branch * by different jobs is not allowed. Jobs holding rules that are trying to perform such operations are blocked until the running job is done. * *

* *

*

the Contains method (...) method :

* only necessary for a specific type of scheduling rules. Has to be used if IScheduling rules are composed into hierarchies. * In such scenarios the contains(...) method specifies the hierarchical relationships among the locks. For example if a method tries to acquire a specific * rule to lock a specific directory it needs to check if no job is holding a rule for one or more subdirectories. For all cases in which no composing of * IScheduling rules is needed the Contains(...) method only needs to check if two jobs are holding exactly the same IScheduling rule on the same object. * Normally this can be achieved by just calling the IsConflicting(...) method. *

* *@author Jan Woerner */ class MITK_JOBS_EXPORT DataStorageAccessRule : public berry::ISchedulingRule { public: enum RuleType {ADD_RULE = 0, REMOVE_RULE} ; RuleType m_Rule; berryObjectMacro(DataStorageAccessRule) DataStorageAccessRule (mitk::DataStorage::Pointer myDataStorage, mitk::DataNode::Pointer myDataNode, DataStorageAccessRule::RuleType myRule) ; bool Contains (berry::ISchedulingRule::Pointer otherISchedulingRule) const; bool IsConflicting (berry::ISchedulingRule::Pointer otherISchedulingRule) const; private: /** * Returns false, identifying no conflictions between two DataStorageAccessRules. * Two add and remove rules do work together. From importance is that jobs using this rule need to check if the * node operating on is still available or already deleted by another job. The DataStorageAccessRule only checks if conflictions could * occur if the removing or adding of nodes is performed currently. */ bool CompareTwoAddorRemoveRules() const ; /** * searches for conflictions of an add DataStorageAccessRule with a remove DataStorageAccess rule * if the add and remove rule do operate in different branches, no conflictions are expected and false is returned */ bool CompareAddandRemoveRules(mitk::DataStorageAccessRule::Pointer sptr_otherDataStorageAccessRule) const; /** * for internal use only, * checks if the jobs that are to be compared do hold DataStorageAccessRule on the same * DataStorage. Jobs that do operate on different DataStorage do not conflict and false is returned */ bool CompareDataStorages(mitk::DataStorage::Pointer otherDataStorage) const; /** * for internal use only * validates if the DataTree node of a particular DataStorageAccess rule belongs to the DataStorage specified within the particular rule. * if not the rule is invalid and false is returned. No conflictions can be expected */ bool TestDataNode(mitk::DataNode::Pointer dataTreeToBeStored) const; /** * returns a pointer to the specified DataStorage node */ mitk::DataNode::Pointer GetDataNode() const; /** * returns a pointer to the specified DataStorage */ mitk::DataStorage::Pointer GetDataStorage() const; mitk::DataStorageAccessRule::RuleType GetRuleType() const; DataStorage::Pointer m_sptrMyDataStorage ; DataNode::Pointer m_sptrMyDataNode ; }; } #endif /*MITKDATASTORAGEACCESSRULE_H_HEADER_INCLUDED_ */ diff --git a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.cpp b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.cpp index 939955f942..2841cde2aa 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.cpp +++ b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.cpp @@ -1,56 +1,55 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataStorageReference.h" namespace mitk { DataStorageReference::DataStorageReference(DataStorage::Pointer dataStorage, bool isDefault) : m_Default(isDefault), m_DataStorage(dataStorage) { } DataStorage::Pointer DataStorageReference::GetDataStorage() const { return m_DataStorage; } bool DataStorageReference::IsDefault() const { return m_Default; } QString DataStorageReference::GetLabel() const { return m_Label; } void DataStorageReference::SetLabel(const QString& label) { m_Label = label; } bool DataStorageReference::operator==(const berry::Object* o) const { const DataStorageReference* other = dynamic_cast(o); if (other == 0) return false; return (m_DataStorage == other->m_DataStorage); } } diff --git a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.h b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.h index 152e5c8615..63dfb82b99 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.h +++ b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageReference.h @@ -1,50 +1,49 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDATASTORAGEREFERENCE_H_ #define MITKDATASTORAGEREFERENCE_H_ #include "../mitkIDataStorageReference.h" namespace mitk { class DataStorageReference : public IDataStorageReference { public: DataStorageReference(DataStorage::Pointer dataStorage, bool isDefault = false); DataStorage::Pointer GetDataStorage() const; bool IsDefault() const; QString GetLabel() const; void SetLabel(const QString& label); bool operator==(const berry::Object* o) const; private: bool m_Default; QString m_Label; DataStorage::Pointer m_DataStorage; }; } #endif /*MITKDATASTORAGEREFERENCE_H_*/ diff --git a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.cpp b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.cpp index cbda248971..5268bf78a3 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.cpp +++ b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.cpp @@ -1,104 +1,103 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataStorageService.h" #include "mitkDataStorageReference.h" #include "mitkStandaloneDataStorage.h" namespace mitk { DataStorageService::DataStorageService() { m_DefaultDataStorageRef = this->CreateDataStorage("Default DataStorage"); m_ActiveDataStorageRef = m_DefaultDataStorageRef; } bool DataStorageService::IsA(const std::type_info& type) const { std::string name(GetType().name()); return name == type.name() || Service::IsA(type); } const std::type_info& DataStorageService::GetType() const { return typeid(IDataStorageService); } IDataStorageReference::Pointer DataStorageService::CreateDataStorage(const QString& label) { StandaloneDataStorage::Pointer dataStorage = mitk::StandaloneDataStorage::New(); DataStorageReference::Pointer ref(new DataStorageReference(dataStorage.GetPointer())); ref->SetLabel(label); m_DataStorageReferences.insert(ref); return ref; } std::vector DataStorageService::GetDataStorageReferences() const { std::vector res; res.reserve(m_DataStorageReferences.size()+1); res.push_back(m_DefaultDataStorageRef); res.insert(res.end(), m_DataStorageReferences.begin(), m_DataStorageReferences.end()); return res; } IDataStorageReference::Pointer DataStorageService::GetDefaultDataStorage() const { return m_DefaultDataStorageRef; } IDataStorageReference::Pointer DataStorageService::GetDataStorage() const { if (m_ActiveDataStorageRef.IsNotNull()) return m_ActiveDataStorageRef; return m_DefaultDataStorageRef; } IDataStorageReference::Pointer DataStorageService::GetActiveDataStorage() const { return m_ActiveDataStorageRef; } void DataStorageService::SetActiveDataStorage(IDataStorageReference::Pointer dataStorageRef) { if (dataStorageRef.IsNull()) m_ActiveDataStorageRef = m_DefaultDataStorageRef; else m_ActiveDataStorageRef = dataStorageRef; } void DataStorageService::AddDataStorageReference(IDataStorageReference::Pointer dataStorageRef) { if (dataStorageRef.IsNull() || dataStorageRef->IsDefault()) return; m_DataStorageReferences.insert(dataStorageRef); } bool DataStorageService::RemoveDataStorageReference(IDataStorageReference::Pointer dataStorageRef) { if (m_ActiveDataStorageRef == dataStorageRef) { m_ActiveDataStorageRef = 0; } return m_DataStorageReferences.erase(dataStorageRef); } } diff --git a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.h b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.h index a299807dc0..6fabb74a7a 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.h +++ b/Plugins/org.mitk.core.services/src/internal/mitkDataStorageService.h @@ -1,60 +1,59 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDATASTORAGESERVICE_H_ #define MITKDATASTORAGESERVICE_H_ #include "../mitkIDataStorageService.h" namespace mitk { class DataStorageService : public QObject, public IDataStorageService { Q_OBJECT Q_INTERFACES(mitk::IDataStorageService) public: DataStorageService(); bool IsA(const std::type_info& type) const; const std::type_info& GetType() const; IDataStorageReference::Pointer CreateDataStorage(const QString& label); std::vector GetDataStorageReferences() const; IDataStorageReference::Pointer GetDefaultDataStorage() const; IDataStorageReference::Pointer GetDataStorage() const; IDataStorageReference::Pointer GetActiveDataStorage() const; void SetActiveDataStorage(IDataStorageReference::Pointer dataStorageRef); void AddDataStorageReference(IDataStorageReference::Pointer dataStorageRef); bool RemoveDataStorageReference(IDataStorageReference::Pointer dataStorageRef); private: IDataStorageReference::Pointer m_ActiveDataStorageRef; IDataStorageReference::Pointer m_DefaultDataStorageRef; std::set m_DataStorageReferences; }; } #endif /*MITKDATASTORAGESERVICE_H_*/ diff --git a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp index 300dba3806..30d39d3ded 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp @@ -1,41 +1,40 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkPluginActivator.h" #include "internal/mitkDataStorageService.h" namespace mitk { const std::string org_mitk_core_services_Activator::PLUGIN_ID = "org.mitk.core.services"; void org_mitk_core_services_Activator::start(ctkPluginContext* context) { DataStorageService* service = new DataStorageService(); dataStorageService = IDataStorageService::Pointer(service); context->registerService(service); } void org_mitk_core_services_Activator::stop(ctkPluginContext* /*context*/) { dataStorageService = 0; } } Q_EXPORT_PLUGIN2(org_mitk_core_services, mitk::org_mitk_core_services_Activator) diff --git a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h index aad76afeff..2f80ac4e5e 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKCORESERVICESPLUGIN_H_ #define MITKCORESERVICESPLUGIN_H_ #include #include #include "mitkIDataStorageService.h" namespace mitk { class org_mitk_core_services_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: static const std::string PLUGIN_ID; void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: mitk::IDataStorageService::Pointer dataStorageService; }; typedef org_mitk_core_services_Activator PluginActivator; } #endif /*MITKCORESERVICESPLUGIN_H_*/ diff --git a/Plugins/org.mitk.core.services/src/mitkIDataStorageReference.h b/Plugins/org.mitk.core.services/src/mitkIDataStorageReference.h index 5a681dabf1..b2e7fd45fb 100644 --- a/Plugins/org.mitk.core.services/src/mitkIDataStorageReference.h +++ b/Plugins/org.mitk.core.services/src/mitkIDataStorageReference.h @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIDATASTORAGEREFERENCE_H_ #define MITKIDATASTORAGEREFERENCE_H_ #include #include #include #include namespace mitk { /** * \ingroup org_mitk_core_services */ struct MITK_CORE_SERVICES_PLUGIN IDataStorageReference : public berry::Object { berryInterfaceMacro(IDataStorageReference, mitk); virtual DataStorage::Pointer GetDataStorage() const = 0; virtual bool IsDefault() const = 0; virtual QString GetLabel() const = 0; virtual void SetLabel(const QString& label) = 0; virtual bool operator==(const berry::Object* o) const = 0; }; } #endif /*MITKIDATASTORAGEREFERENCE_H_*/ diff --git a/Plugins/org.mitk.core.services/src/mitkIDataStorageService.cpp b/Plugins/org.mitk.core.services/src/mitkIDataStorageService.cpp index 2cd8ea72e7..28d3441f0c 100644 --- a/Plugins/org.mitk.core.services/src/mitkIDataStorageService.cpp +++ b/Plugins/org.mitk.core.services/src/mitkIDataStorageService.cpp @@ -1,25 +1,24 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkIDataStorageService.h" namespace mitk { const std::string IDataStorageService::ID = "org.mitk.core.services.datastorage"; } diff --git a/Plugins/org.mitk.core.services/src/mitkIDataStorageService.h b/Plugins/org.mitk.core.services/src/mitkIDataStorageService.h index 254dade2f2..68a2fd41a6 100644 --- a/Plugins/org.mitk.core.services/src/mitkIDataStorageService.h +++ b/Plugins/org.mitk.core.services/src/mitkIDataStorageService.h @@ -1,60 +1,59 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIDATASTORAGESERVICE_H_ #define MITKIDATASTORAGESERVICE_H_ #include #include #include "mitkIDataStorageReference.h" #include #include namespace mitk { /** * \ingroup org_mitk_core_services */ struct MITK_CORE_SERVICES_PLUGIN IDataStorageService : public berry::Service { berryInterfaceMacro(IDataStorageService, berry); static const std::string ID; virtual IDataStorageReference::Pointer CreateDataStorage(const QString& label) = 0; virtual std::vector GetDataStorageReferences() const = 0; virtual IDataStorageReference::Pointer GetDefaultDataStorage() const = 0; virtual IDataStorageReference::Pointer GetDataStorage() const = 0; virtual IDataStorageReference::Pointer GetActiveDataStorage() const = 0; virtual void SetActiveDataStorage(IDataStorageReference::Pointer dataStorageRef) = 0; virtual void AddDataStorageReference(IDataStorageReference::Pointer dataStorageRef) = 0; virtual bool RemoveDataStorageReference(IDataStorageReference::Pointer dataStorageRef) = 0; }; } Q_DECLARE_INTERFACE(mitk::IDataStorageService, "org.mitk.service.IDataStorageService") #endif /*MITKIDATASTORAGESERVICE_H_*/ diff --git a/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.cpp b/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.cpp index 9608bb65d1..af97560c40 100644 --- a/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.cpp +++ b/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.cpp @@ -1,63 +1,62 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDiffusionImagingActivator.h" #include "mitkDiffusionImagingObjectFactory.h" #include "QmitkNodeDescriptorManager.h" #include "mitkNodePredicateDataType.h" #include void mitk::DiffusionImagingActivator::start(ctkPluginContext* context) { Q_UNUSED(context) RegisterDiffusionImagingObjectFactory(); QmitkNodeDescriptorManager* manager = QmitkNodeDescriptorManager::GetInstance(); mitk::NodePredicateDataType::Pointer isDiffusionImage = mitk::NodePredicateDataType::New("DiffusionImage"); QmitkNodeDescriptor* desc = new QmitkNodeDescriptor(QObject::tr("DiffusionImage"), QString(":/QmitkDiffusionImaging/QBallData24.png"), isDiffusionImage, manager); manager->AddDescriptor(desc); mitk::NodePredicateDataType::Pointer isTensorImage = mitk::NodePredicateDataType::New("TensorImage"); manager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("TensorImage"), QString(":/QmitkDiffusionImaging/recontensor.png"), isTensorImage, manager)); mitk::NodePredicateDataType::Pointer isQBallImage = mitk::NodePredicateDataType::New("QBallImage"); manager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("QBallImage"), QString(":/QmitkDiffusionImaging/reconodf.png"), isQBallImage, manager)); mitk::NodePredicateDataType::Pointer isFiberBundle = mitk::NodePredicateDataType::New("FiberBundle"); manager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("FiberBundle"), QString(":/QmitkDiffusionImaging/FiberBundle.png"), isFiberBundle, manager)); mitk::NodePredicateDataType::Pointer isFiberBundleX = mitk::NodePredicateDataType::New("FiberBundleX"); manager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("FiberBundleX"), QString(":/QmitkDiffusionImaging/FiberBundleX.png"), isFiberBundleX, manager)); mitk::NodePredicateDataType::Pointer isConnectomicsNetwork = mitk::NodePredicateDataType::New("ConnectomicsNetwork"); manager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("ConnectomicsNetwork"), QString(":/QmitkDiffusionImaging/ConnectomicsNetwork.png"), isConnectomicsNetwork, manager)); } void mitk::DiffusionImagingActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } Q_EXPORT_PLUGIN2(org_mitk_diffusionimaging, mitk::DiffusionImagingActivator) diff --git a/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.h b/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.h index ae4c4aada8..0c529b9035 100644 --- a/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.h +++ b/Plugins/org.mitk.diffusionimaging/src/internal/mitkDiffusionImagingActivator.h @@ -1,55 +1,54 @@ -/*========================================================================= +/*=================================================================== - Program: MITK Platform - Language: C++ - Date: $Date: 2009-05-19 15:45:39 +0200 (Di, 19 Mai 2009) $ - Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDIFFUSIONIMAGINGACTIVATOR_H_ #define MITKDIFFUSIONIMAGINGACTIVATOR_H_ #include #include namespace mitk { /** * \ingroup org_mitk_diffusionimaging_internal * * \brief The plug-in activator for the diffusion imaging module * * When the plug-in is started by the framework, it initialzes diffusion imaging * specific things. */ class MITK_LOCAL DiffusionImagingActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: /** * Registers diffusion imaging object factories. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; } #endif /* MITKDIFFUSIONIMAGINGACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.cpp b/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.cpp index fc603d63b6..e12bd11c2e 100644 --- a/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.cpp +++ b/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.cpp @@ -1,47 +1,46 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "org_mitk_gui_common_Activator.h" #include namespace mitk { ctkPluginContext* org_mitk_gui_common_Activator::m_Context = 0; void org_mitk_gui_common_Activator::start(ctkPluginContext* context) { m_Context = context; } void org_mitk_gui_common_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_Context = 0; } ctkPluginContext *org_mitk_gui_common_Activator::GetContext() { return m_Context; } } Q_EXPORT_PLUGIN2(org_mitk_gui_common, mitk::org_mitk_gui_common_Activator) diff --git a/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.h b/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.h index c5aa6faca9..cfdc1cd1dd 100644 --- a/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.h +++ b/Plugins/org.mitk.gui.common/src/internal/org_mitk_gui_common_Activator.h @@ -1,49 +1,48 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include namespace mitk { class org_mitk_gui_common_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static ctkPluginContext* GetContext(); private: static ctkPluginContext* m_Context; }; // org_mitk_gui_common_Activator typedef org_mitk_gui_common_Activator PluginActivator; } #endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.cpp b/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.cpp index 19a7c6263f..48efd5edd5 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.cpp @@ -1,50 +1,49 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataNodeObject.h" namespace mitk { DataNodeObject::DataNodeObject() : m_Node(0) { } DataNodeObject::DataNodeObject(DataNode::Pointer node) : m_Node(node) { } DataNode::Pointer DataNodeObject::GetDataNode() const { return m_Node; } bool DataNodeObject::operator==(const berry::Object* obj) const { if (const DataNodeObject* other = dynamic_cast(obj)) { return m_Node == other->m_Node; } return false; } } diff --git a/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.h b/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.h index 53f31c2c10..502647d67f 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.h +++ b/Plugins/org.mitk.gui.common/src/mitkDataNodeObject.h @@ -1,58 +1,57 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDATATREENODEOBJECT_H_ #define MITKDATATREENODEOBJECT_H_ #include #include #include #include namespace mitk { /** * \ingroup org_mitk_gui_common */ class MITK_GUI_COMMON_PLUGIN DataNodeObject : public berry::Object { public: berryObjectMacro(mitk::DataNodeObject) DataNodeObject(); DataNodeObject(DataNode::Pointer node); DataNode::Pointer GetDataNode() const; bool operator==(const berry::Object* obj) const; private: DataNode::Pointer m_Node; }; } #endif /* MITKDATATREENODEOBJECT_H_ */ diff --git a/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.cpp b/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.cpp index afe696f36f..718fa1dabb 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.cpp @@ -1,91 +1,90 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataNodeSelection.h" #include "mitkDataNodeObject.h" namespace mitk { DataNodeSelection::DataNodeSelection() : m_Selection(new ContainerType()) { } DataNodeSelection::DataNodeSelection(DataNode::Pointer node) : m_Selection(new ContainerType()) { DataNodeObject::Pointer obj(new DataNodeObject(node)); m_Selection->push_back(obj); } DataNodeSelection::DataNodeSelection(const std::vector& nodes) : m_Selection(new ContainerType()) { for (std::vector::const_iterator i = nodes.begin(); i != nodes.end(); ++i) { DataNodeObject::Pointer obj(new DataNodeObject(*i)); m_Selection->push_back(obj); } } berry::Object::Pointer DataNodeSelection::GetFirstElement() const { if (m_Selection->empty()) return berry::Object::Pointer(); return *(m_Selection->begin()); } berry::IStructuredSelection::iterator DataNodeSelection::Begin() const { return m_Selection->begin(); } berry::IStructuredSelection::iterator DataNodeSelection::End() const { return m_Selection->end(); } int DataNodeSelection::Size() const { return m_Selection->size(); } berry::IStructuredSelection::ContainerType::Pointer DataNodeSelection::ToVector() const { return m_Selection; } bool DataNodeSelection::IsEmpty() const { return m_Selection->empty(); } bool DataNodeSelection::operator==(const berry::Object* obj) const { if (const berry::IStructuredSelection* other = dynamic_cast(obj)) { return m_Selection == other->ToVector(); } return false; } } diff --git a/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.h b/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.h index ebd5a3c66b..e01d30ce6c 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.h +++ b/Plugins/org.mitk.gui.common/src/mitkDataNodeSelection.h @@ -1,66 +1,65 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDATATREENODESELECTION_H_ #define MITKDATATREENODESELECTION_H_ #include #include #include namespace mitk { /** * \ingroup org_mitk_gui_common */ class MITK_GUI_COMMON_PLUGIN DataNodeSelection : public virtual berry::IStructuredSelection { public: berryObjectMacro(DataNodeSelection); DataNodeSelection(); DataNodeSelection(DataNode::Pointer node); DataNodeSelection(const std::vector& nodes); virtual Object::Pointer GetFirstElement() const; virtual iterator Begin() const; virtual iterator End() const; virtual int Size() const; virtual ContainerType::Pointer ToVector() const; /** * @see berry::ISelection::IsEmpty() */ bool IsEmpty() const; bool operator==(const berry::Object* obj) const; protected: ContainerType::Pointer m_Selection; }; } #endif /* MITKDATATREENODESELECTION_H_ */ diff --git a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp index 8f1acbe999..c30ab0fe88 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp @@ -1,72 +1,71 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataStorageEditorInput.h" #include #include namespace mitk { DataStorageEditorInput::DataStorageEditorInput() { } DataStorageEditorInput::DataStorageEditorInput(IDataStorageReference::Pointer ref) { m_DataStorageRef = ref; } bool DataStorageEditorInput::Exists() const { return true; } std::string DataStorageEditorInput::GetName() const { return "DataStorage Scene"; } std::string DataStorageEditorInput::GetToolTipText() const { return ""; } bool DataStorageEditorInput::operator==(const berry::Object* o) const { if (const DataStorageEditorInput* input = dynamic_cast(o)) return this->m_DataStorageRef == input->m_DataStorageRef; return false; } IDataStorageReference::Pointer DataStorageEditorInput::GetDataStorageReference() { if (m_DataStorageRef.IsNull()) { berry::ServiceRegistry& serviceRegistry = berry::Platform::GetServiceRegistry(); IDataStorageService::Pointer dataService = serviceRegistry.GetServiceById(IDataStorageService::ID); if (!dataService) return IDataStorageReference::Pointer(0); m_DataStorageRef = dataService->GetDefaultDataStorage(); } return m_DataStorageRef; } } diff --git a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h index aa7f239073..f9af03a772 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h +++ b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h @@ -1,60 +1,59 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKDATASTORAGEEDITORINPUT_H_ #define MITKDATASTORAGEEDITORINPUT_H_ #include #include #include namespace mitk { /** * \ingroup org_mitk_gui_common * * \brief An editor input based on a mitk::DataStorage. * * This editor input is usually used in render window editors inheriting from * QmitkAbstractRenderEditor. */ class MITK_GUI_COMMON_PLUGIN DataStorageEditorInput : public berry::IEditorInput { public: berryObjectMacro(DataStorageEditorInput); DataStorageEditorInput(); DataStorageEditorInput(IDataStorageReference::Pointer ref); bool Exists() const; std::string GetName() const; std::string GetToolTipText() const; IDataStorageReference::Pointer GetDataStorageReference(); bool operator==(const berry::Object*) const; private: IDataStorageReference::Pointer m_DataStorageRef; }; } #endif /*MITKDATASTORAGEEDITORINPUT_H_*/ diff --git a/Plugins/org.mitk.gui.common/src/mitkILifecycleAwarePart.h b/Plugins/org.mitk.gui.common/src/mitkILifecycleAwarePart.h index e53ded00d0..615b2fd83c 100644 --- a/Plugins/org.mitk.gui.common/src/mitkILifecycleAwarePart.h +++ b/Plugins/org.mitk.gui.common/src/mitkILifecycleAwarePart.h @@ -1,59 +1,58 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKILIFECYCLEAWAREPART_H #define MITKILIFECYCLEAWAREPART_H namespace mitk { /** * \ingroup org_mitk_gui_common * * \brief Interface for a MITK Workbench part which wants to be notified about lifecycle changes. * * This interface is intended to be implemented by subclasses of berry::IWorkbenchPart. MITK Workbench parts * implementing this interface will be notified about their lifecycle changes. The same effect could * be achieved by registering a custom berry::IPartListener. * * \note There are no "Closed()" or "Opened()" methods. These correspond to the constructor and * desctructor of the Workbench part class. * * \see berry::IPartListener * \see mitk::IZombieViewPart */ struct ILifecycleAwarePart { virtual ~ILifecycleAwarePart() {} /** \see berry::IPartListener::PartActivated */ virtual void Activated() = 0; /** \see berry::IPartListener::PartDeactivated */ virtual void Deactivated() = 0; /** \see berry::IPartListener::PartVisible */ virtual void Visible() = 0; /** \see berry::IPartListener::PartHidden */ virtual void Hidden() = 0; }; } #endif // MITKILIFECYCLEAWAREPART_H diff --git a/Plugins/org.mitk.gui.common/src/mitkILinkedRenderWindowPart.h b/Plugins/org.mitk.gui.common/src/mitkILinkedRenderWindowPart.h index 2cc427f485..911f82cf5e 100644 --- a/Plugins/org.mitk.gui.common/src/mitkILinkedRenderWindowPart.h +++ b/Plugins/org.mitk.gui.common/src/mitkILinkedRenderWindowPart.h @@ -1,91 +1,90 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKILINKEDRENDERWINDOWPART_H #define MITKILINKEDRENDERWINDOWPART_H #include "mitkIRenderWindowPart.h" namespace mitk { class SlicesRotator; class SlicesSwiveller; /** * \ingroup org_mitk_gui_common * * \brief Extends the IRenderWindowPart interface with methods for controlling linked * render windows. * * This inteface should be implemented by subclasses of berry::IWorkbenchPart if they * provided several linked QmitkRenderWindow instances. */ struct ILinkedRenderWindowPart : public virtual IRenderWindowPart { /** * Get the mitk::SlicesRotator. * * \return A mitk::SlicesRotator instance if rotating slices is supported; * NULL otherwise. */ virtual mitk::SlicesRotator* GetSlicesRotator() const = 0; /** * Get the mitk::SlicesSwiveller. * * \return A mitk::SlicesSwiveller instance if swivelling slices is supported; * NULL otherwise. */ virtual mitk::SlicesSwiveller* GetSlicesSwiveller() const = 0; /** * Enable or disable the slicing planes linking the QmitkRenderWindow instances. * * \param enable true if the slicing planes should be enabled; * false otherwise. */ virtual void EnableSlicingPlanes(bool enable) = 0; /** * Get the enabled status of the slicing planes. * * \return true if the slicing planes are enabled; false * otherwise. */ virtual bool IsSlicingPlanesEnabled() const = 0; /** * Enable or disalbe linked navigation. * * \param enable If true, setting the selected position in one QmitkRenderWindow * affects the positions in the linked windows. If false, linked navigation * is disabled. */ virtual void EnableLinkedNavigation(bool enable) = 0; /** * Get the enabled status of linked navigation. * * \return true if linked navigation is enabled; false * otherwise. */ virtual bool IsLinkedNavigationEnabled() const = 0; }; } #endif // MITKILINKEDRENDERWINDOWPART_H diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.cpp b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.cpp index 9e9677284c..c6d11755e2 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.cpp @@ -1,27 +1,26 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkIRenderWindowPart.h" namespace mitk { const QString IRenderWindowPart::DECORATION_BORDER = "border"; const QString IRenderWindowPart::DECORATION_LOGO = "logo"; const QString IRenderWindowPart::DECORATION_MENU = "menu"; const QString IRenderWindowPart::DECORATION_BACKGROUND = "background"; } diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h index cee4fc9374..b557f214bb 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h @@ -1,191 +1,190 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIRENDERWINDOWPART_H #define MITKIRENDERWINDOWPART_H #include #include #include #include #include #include #include class QmitkRenderWindow; namespace mitk { struct IRenderingManager; class SliceNavigationController; /** * \ingroup org_mitk_gui_common * * \brief Interface for a MITK Workbench Part providing a render window. * * This interface allows generic access to Workbench parts which provide some * kind of render window. The interface is intended to be implemented by * subclasses of berry::IWorkbenchPart. Usually, the interface is implemented * by a Workbench editor. * * A IRenderWindowPart provides zero or more QmitkRenderWindow instances which can * be controlled via this interface. QmitkRenderWindow instances have an associated * \e id, which is implementation specific. However, implementations should consider * to use one of the following ids for certain QmitkRenderWindow instances to maximize * reusability (they are free to map multiple ids to one QmitkRenderWindow internally): *
    *
  • transversal
  • *
  • sagittal
  • *
  • coronal
  • *
  • 3d
  • *
* * \see ILinkedRenderWindowPart * \see IRenderWindowPartListener * \see QmitkAbstractRenderEditor */ struct MITK_GUI_COMMON_PLUGIN IRenderWindowPart { static const QString DECORATION_BORDER; // = "border" static const QString DECORATION_LOGO; // = "logo" static const QString DECORATION_MENU; // = "menu" static const QString DECORATION_BACKGROUND; // = "background; virtual ~IRenderWindowPart() {} /** * Get the currently active (focused) render window. * Focus handling is implementation specific. * * \return The active QmitkRenderWindow instance; NULL * if no render window is active. */ virtual QmitkRenderWindow* GetActiveRenderWindow() const = 0; /** * Get all render windows with their ids. * * \return A hash map mapping the render window id to the QmitkRenderWindow instance. */ virtual QHash GetRenderWindows() const = 0; /** * Get a render window with a specific id. * * \param id The render window id. * \return The QmitkRenderWindow instance for id */ virtual QmitkRenderWindow* GetRenderWindow(const QString& id) const = 0; /** * Get the rendering manager used by this render window part. * * \return The current IRenderingManager instance or NULL * if no rendering manager is used. */ virtual mitk::IRenderingManager* GetRenderingManager() const = 0; /** * Request an update of all render windows. * * \param requestType Specifies the type of render windows for which an update * will be requested. */ virtual void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Force an immediate update of all render windows. * * \param requestType Specifies the type of render windows for which an immediate update * will be requested. */ virtual void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Get the SliceNavigationController for controlling time positions. * * \return A SliceNavigationController if the render window supports this * operation; otherwise returns NULL. */ virtual mitk::SliceNavigationController* GetTimeNavigationController() const = 0; /** * Get the selected position in the render window with id id * or in the active render window if id is NULL. * * \param id The render window id. * \return The currently selected position in world coordinates. */ virtual mitk::Point3D GetSelectedPosition(const QString& id = QString()) const = 0; /** * Set the selected position in the render window with id id * or in the active render window if id is NULL. * * \param pos The position in world coordinates which should be selected. * \param id The render window id in which the selection should take place. */ virtual void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()) = 0; /** * Enable \e decorations like colored borders, menu widgets, logos, text annotations, etc. * * Decorations are implementation specific. A set of standardized decoration names is listed * in GetDecorations(). * * \param enable If true enable the decorations specified in decorations, * otherwise disable them. * \param decorations A list of decoration names. If empty, all supported decorations are affected. * * \see GetDecorations() */ virtual void EnableDecorations(bool enable, const QStringList& decorations = QStringList()) = 0; /** * Return if a specific decoration is enabled. * * \return true if the decoration is enabled, false if it is disabled * or unknown. * * \see GetDecorations() */ virtual bool IsDecorationEnabled(const QString& decoration) const = 0; /** * Get a list of supported decorations. * * The following decoration names are standardized and should not be used for other decoration types: *
    *
  • \e DECORATION_BORDER Any border decorations like colored rectangles, etc. *
  • \e DECORATION_MENU Menus associated with render windows *
  • \e DECORATION_BACKGROUND All kinds of backgrounds (patterns, gradients, etc.) except for solid colored backgrounds *
  • \e DECORATION_LOGO Any kind of logo overlayed on the rendered scene *
* * \return A list of supported decoration names. */ virtual QStringList GetDecorations() const = 0; }; } Q_DECLARE_INTERFACE(mitk::IRenderWindowPart, "org.mitk.ui.IRenderWindowPart") #endif // MITKIRENDERWINDOWPART_H diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h index b7abf8b0a2..332e88bed9 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h @@ -1,59 +1,58 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIRENDERWINDOWPARTLISTENER_H #define MITKIRENDERWINDOWPARTLISTENER_H namespace mitk { struct IRenderWindowPart; /** * \ingroup org_mitk_gui_common * * \brief Interface for berry::IViewPart implementations to be notified about mitk::IRenderWindowPart lifecycle changes. * * This interface is intended to be implemented by subclasses of berry::IWorkbenchPart. If implemented, * the interface methods are called automatically if a Workbench part which implementes mitk::IRenderWindowPart * is activated or deactivated. * * The notion of activated and deactivated is slightly different from the usual Workbench part lifecycle. */ struct IRenderWindowPartListener { virtual ~IRenderWindowPartListener() {} /** * Called when a IRenderWindowPart is activated or if it becomes visible and no * other IRenderWindowPart was activated before. * * \param renderWindowPart The newly activated IRenderWindowPart. */ virtual void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) = 0; /** * Called when a IRenderWindowPart becomes invisible and if it was active before. * * \param renderWindowPart The deactivated IRenderWindowPart. */ virtual void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) = 0; }; } #endif // MITKIRENDERWINDOWPARTLISTENER_H diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.cpp b/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.cpp index 987637c780..7d20c87714 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.cpp @@ -1,190 +1,189 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkIRenderingManager.h" namespace mitk { struct RenderingManagerInterface : public IRenderingManager { RenderingManagerInterface(RenderingManager::Pointer manager) : m_RM(manager) {} QList GetAllRegisteredVtkRenderWindows() const { RenderingManager::RenderWindowVector vec(m_RM->GetAllRegisteredRenderWindows()); QList result; for (RenderingManager::RenderWindowVector::iterator i = vec.begin(); i != vec.end(); ++i) { result.append(*i); } return result; } void RequestUpdate( vtkRenderWindow *renderWindow ) { m_RM->RequestUpdate(renderWindow); } void ForceImmediateUpdate( vtkRenderWindow *renderWindow ) { m_RM->ForceImmediateUpdate(renderWindow); } void RequestUpdateAll( RenderingManager::RequestType type ) { m_RM->RequestUpdateAll(type); } void ForceImmediateUpdateAll( RenderingManager::RequestType type ) { m_RM->ForceImmediateUpdateAll(type); } bool InitializeViews( const Geometry3D *geometry, RenderingManager::RequestType type = RenderingManager::REQUEST_UPDATE_ALL, bool preserveRoughOrientationInWorldSpace = false ) { return m_RM->InitializeViews( geometry, type, preserveRoughOrientationInWorldSpace); } bool InitializeViews( RenderingManager::RequestType type ) { return m_RM->InitializeViews(type); } bool InitializeView( vtkRenderWindow *renderWindow, const Geometry3D *geometry, bool initializeGlobalTimeSNC = false) { return m_RM->InitializeView(renderWindow, geometry, initializeGlobalTimeSNC); } bool InitializeView( vtkRenderWindow *renderWindow ) { return m_RM->InitializeView(renderWindow); } const SliceNavigationController *GetTimeNavigationController() const { return m_RM->GetTimeNavigationController(); } SliceNavigationController *GetTimeNavigationController() { return m_RM->GetTimeNavigationController(); } bool IsRendering() const { return m_RM->IsRendering(); } void AbortRendering() { m_RM->AbortRendering(); } void SetLODIncreaseBlocked(bool blocked) { m_RM->SetLODIncreaseBlocked(blocked); } bool GetLODIncreaseBlocked() const { return m_RM->GetLODIncreaseBlocked(); } void SetLODAbortMechanismEnabled(bool abort) { m_RM->SetLODAbortMechanismEnabled(abort); } bool GetLODAbortMechanismEnabled() const { return m_RM->GetLODAbortMechanismEnabled(); } void SetDepthPeelingEnabled(bool enabled) { m_RM->SetDepthPeelingEnabled(enabled); } void SetMaxNumberOfPeels(int maxNumber) { m_RM->SetMaxNumberOfPeels(maxNumber); } int GetNextLOD( BaseRenderer* renderer ) const { return m_RM->GetNextLOD(renderer); } void SetMaximumLOD( unsigned int max ) { m_RM->SetMaximumLOD(max); } void SetShading( bool state, unsigned int lod ) { m_RM->SetShading(state, lod); } bool GetShading( unsigned int lod ) { return m_RM->GetShading(lod); } void SetClippingPlaneStatus( bool status ) { m_RM->SetClippingPlaneStatus(status); } bool GetClippingPlaneStatus() { return m_RM->GetClippingPlaneStatus(); } void SetShadingValues( float ambient, float diffuse, float specular, float specpower ) { m_RM->SetShadingValues(ambient, diffuse, specular, specpower); } QList GetShadingValues() const { RenderingManager::FloatVector vec(m_RM->GetShadingValues()); QList result; for (RenderingManager::FloatVector::iterator i = vec.begin(); i != vec.end(); ++i) { result.push_back(*i); } return result; } const RenderingManager::Pointer m_RM; }; IRenderingManager* MakeRenderingManagerInterface(RenderingManager::Pointer manager) { return new RenderingManagerInterface(manager); } } diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.h b/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.h index ef9ab0973b..f919b6d560 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderingManager.h @@ -1,159 +1,158 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIRENDERINGMANAGER_H #define MITKIRENDERINGMANAGER_H #include #include #include #include namespace mitk { /** * \ingroup org_mitk_gui_common * * \brief An interface for accessing a mitk::RenderingManager instance. * * This interface acts as a wrapper to a mitk::RenderingManager instance, hiding some * methods from the user. * * \see MakeRenderingManagerInterface */ struct IRenderingManager { virtual ~IRenderingManager() {} /** Get a list of all registered RenderWindows */ virtual QList GetAllRegisteredVtkRenderWindows() const = 0; /** * Requests an update for the specified RenderWindow, to be executed as * soon as the main loop is ready for rendering. */ virtual void RequestUpdate( vtkRenderWindow *renderWindow ) = 0; /** Immediately executes an update of the specified RenderWindow. */ virtual void ForceImmediateUpdate( vtkRenderWindow *renderWindow ) = 0; /** * Requests all currently registered RenderWindows to be updated. * If only 2D or 3D windows should be updated, this can be specified * via the parameter requestType. */ virtual void RequestUpdateAll( RenderingManager::RequestType type = RenderingManager::REQUEST_UPDATE_ALL ) = 0; /** * Immediately executes an update of all registered RenderWindows. * If only 2D or 3D windows should be updated, this can be specified * via the parameter requestType. */ virtual void ForceImmediateUpdateAll( RenderingManager::RequestType type = RenderingManager::REQUEST_UPDATE_ALL ) = 0; /** Initializes the windows specified by requestType to the given geometry. */ virtual bool InitializeViews( const Geometry3D *geometry, RenderingManager::RequestType type = RenderingManager::REQUEST_UPDATE_ALL, bool preserveRoughOrientationInWorldSpace = false ) = 0; /** * Initializes the windows to the default viewing direction * (geomtry information is NOT changed). */ virtual bool InitializeViews( RenderingManager::RequestType type = RenderingManager::REQUEST_UPDATE_ALL ) = 0; /** * Initializes the specified window to the given geometry. Set * "initializeGlobalTimeSNC" to true in order to use this geometry as * global TimeSlicedGeometry. */ virtual bool InitializeView( vtkRenderWindow *renderWindow, const Geometry3D *geometry, bool initializeGlobalTimeSNC = false) = 0; /** * Initializes the specified window to the default viewing direction * (geomtry information is NOT changed). */ virtual bool InitializeView( vtkRenderWindow *renderWindow ) = 0; /** Gets the SliceNavigationController responsible for time-slicing. */ virtual const SliceNavigationController *GetTimeNavigationController() const = 0; /** Gets the SliceNavigationController responsible for time-slicing. */ virtual SliceNavigationController *GetTimeNavigationController() = 0; virtual bool IsRendering() const = 0; virtual void AbortRendering() = 0; /** En-/Disable LOD increase globally. */ virtual void SetLODIncreaseBlocked(bool blocked) = 0; /** Get LOD blocked status. */ virtual bool GetLODIncreaseBlocked() const = 0; /** En-/Disable LOD abort mechanism. */ virtual void SetLODAbortMechanismEnabled(bool abort) = 0; /** Get LOD abort mechanism status. */ virtual bool GetLODAbortMechanismEnabled() const = 0; /** En-/Disable depth peeling for all renderers */ virtual void SetDepthPeelingEnabled(bool enabled) = 0; /** Set maximum number of peels for all renderers */ virtual void SetMaxNumberOfPeels(int maxNumber) = 0; virtual int GetNextLOD( BaseRenderer* renderer ) const = 0; /** Set current LOD (NULL means all renderers)*/ virtual void SetMaximumLOD( unsigned int max ) = 0; virtual void SetShading( bool state, unsigned int lod ) = 0; virtual bool GetShading( unsigned int lod ) = 0; virtual void SetClippingPlaneStatus( bool status ) = 0; virtual bool GetClippingPlaneStatus() = 0; virtual void SetShadingValues( float ambient, float diffuse, float specular, float specpower ) = 0; virtual QList GetShadingValues() const = 0; }; } Q_DECLARE_INTERFACE(mitk::IRenderingManager, "org.mitk.ui.IRenderingManager") namespace mitk { /** * Create a IRenderManager interface for a given RenderingManager. Ownership of the * returned pointer is transferred to the caller of this function. * * \param manager The RenderingManager instance for which to create a interface. * \return A pointer to the interface object. The caller is responsible for deleting the pointer. */ MITK_GUI_COMMON_PLUGIN IRenderingManager* MakeRenderingManagerInterface(RenderingManager::Pointer manager); } #endif // MITKIRENDERINGMANAGER_H diff --git a/Plugins/org.mitk.gui.common/src/mitkIZombieViewPart.h b/Plugins/org.mitk.gui.common/src/mitkIZombieViewPart.h index 0eedfbf4aa..3e43c0db76 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIZombieViewPart.h +++ b/Plugins/org.mitk.gui.common/src/mitkIZombieViewPart.h @@ -1,60 +1,59 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIZOMBIEVIEWPART_H #define MITKIZOMBIEVIEWPART_H #include "mitkILifecycleAwarePart.h" namespace mitk { /** * \ingroup org_mitk_gui_common * * \brief Interface for MITK Workbench Views with special \e Zombie state handling. * * Some MITK Views need to change the application state in a way which should not be affected * by this View's activated/deactivated state. Examples are setting special interactors or removing * the crosshair from a QmitkRenderWindow. Such MITK Views are called \emph{Zombie Views} because * they partially outlive their own deactivation. Zombie Views are usually mutually exclusive. * * To ease the handling of Zombie Views, this interface acts as a marker to declare the implementing * class being a Zombie View, meaning that it will change some application state when it is activated * but will not reset it when deactivated. * * If a Zombie View is activated, the previously active Zombie View is notified by calling its * ActivatedZombieView() method. It should then reset the application state. * * \see ILifecycleAwarePart */ struct IZombieViewPart : public virtual ILifecycleAwarePart { /** * Called when another Zombie View was activated. This usually means that this part * should clean up its Zombie state. * * \param zombieView The newly activate Zombie View. */ virtual void ActivatedZombieView(berry::IWorkbenchPartReference::Pointer zombieView) = 0; }; } #endif // MITKIZOMBIEVIEWPART_H diff --git a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp index 25acbd33ba..654fa26e1c 100644 --- a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp @@ -1,255 +1,254 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkWorkbenchUtil.h" #include #include #include #include #include "mitkIDataStorageService.h" #include "mitkDataStorageEditorInput.h" #include "mitkRenderingManager.h" #include "mitkIRenderWindowPart.h" #include "mitkIRenderingManager.h" #include "mitkProperties.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkIOUtil.h" #include "mitkWorkbenchUtil.h" #include #include #include #include "internal/org_mitk_gui_common_Activator.h" namespace mitk { struct WorkbenchUtilPrivate { /** * Get the editor descriptor for a given name using the editorDescriptor * passed in as a default as a starting point. * * @param name * The name of the element to open. * @param editorReg * The editor registry to do the lookups from. * @param defaultDescriptor * IEditorDescriptor or null * @return IEditorDescriptor * @throws PartInitException * if no valid editor can be found */ static berry::IEditorDescriptor::Pointer GetEditorDescriptor(const QString& name, berry::IEditorRegistry* editorReg, berry::IEditorDescriptor::Pointer defaultDescriptor) { if (defaultDescriptor.IsNotNull()) { return defaultDescriptor; } berry::IEditorDescriptor::Pointer editorDesc = defaultDescriptor; // next check the OS for in-place editor (OLE on Win32) if (editorReg->IsSystemInPlaceEditorAvailable(name.toStdString())) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_INPLACE_EDITOR_ID); } // next check with the OS for an external editor if (editorDesc.IsNull() && editorReg->IsSystemExternalEditorAvailable(name.toStdString())) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } // if no valid editor found, bail out if (editorDesc.IsNull()) { throw berry::PartInitException("No editor found"); } return editorDesc; } }; void WorkbenchUtil::LoadFiles(const QStringList &fileNames, berry::IWorkbenchWindow::Pointer window) { if (fileNames.empty()) return; mitk::IDataStorageReference::Pointer dataStorageRef; { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsRef = context->getServiceReference(); if (dsRef) { dss = context->getService(dsRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dataStorageRef = dss->GetDataStorage(); context->ungetService(dsRef); } mitk::DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); // Do the actual work of loading the data into the data storage std::vector fileNames2; ctk::qListToSTLVector(fileNames, fileNames2); const bool dsmodified = mitk::IOUtil::LoadFiles(fileNames2, *dataStorage); // Check if there is an open perspective. If not, open the default perspective. if (window->GetActivePage().IsNull()) { std::string defaultPerspId = window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); window->GetWorkbench()->ShowPerspective(defaultPerspId, window); } try { // Activate the editor using the same data storage or open the default editor mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(dataStorageRef)); berry::IEditorPart::Pointer editor = mitk::WorkbenchUtil::OpenEditor(window->GetActivePage(), input, true); mitk::IRenderWindowPart* renderEditor = dynamic_cast(editor.GetPointer()); mitk::IRenderingManager* renderingManager = renderEditor == 0 ? 0 : renderEditor->GetRenderingManager(); if(dsmodified && renderingManager) { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = dataStorage->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = dataStorage->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry renderingManager->InitializeViews(bounds); } } catch (const berry::PartInitException& e) { QString msg = "An error occurred when displaying the file(s): %1"; QMessageBox::warning(QApplication::activeWindow(), "Error displaying file", msg.arg(QString::fromStdString(e.message()))); } } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, berry::IEditorInput::Pointer input, const QString &editorId, bool activate) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be NULL"); } // open the editor on the input return page->OpenEditor(input, editorId.toStdString(), activate); } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, mitk::DataStorageEditorInput::Pointer input, bool activate, bool determineContentType) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be NULL"); } // open the editor on the data storage QString name = QString::fromStdString(input->GetName()) + ".mitk"; berry::IEditorDescriptor::Pointer editorDesc = WorkbenchUtilPrivate::GetEditorDescriptor(name, berry::PlatformUI::GetWorkbench()->GetEditorRegistry(), GetDefaultEditor(name, determineContentType)); return page->OpenEditor(input, editorDesc->GetId(), activate); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetEditorDescriptor( const QString& name, bool /*inferContentType*/) { if (name.isEmpty()) { throw std::invalid_argument("name argument must not be empty"); } // no used for now //IContentType contentType = inferContentType ? Platform // .getContentTypeManager().findContentTypeFor(name) : null; berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); return WorkbenchUtilPrivate::GetEditorDescriptor(name, editorReg, editorReg->GetDefaultEditor(name.toStdString() /*, contentType*/)); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetDefaultEditor(const QString& name, bool /*determineContentType*/) { // Try file specific editor. berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); try { QString editorID; // = file.getPersistentProperty(EDITOR_KEY); if (!editorID.isEmpty()) { berry::IEditorDescriptor::Pointer desc = editorReg->FindEditor(editorID.toStdString()); if (desc.IsNotNull()) { return desc; } } } catch (const berry::CoreException& e) { // do nothing } // IContentType contentType = null; // if (determineContentType) // { // contentType = getContentType(file); // } // Try lookup with filename return editorReg->GetDefaultEditor(name.toStdString()); //, contentType); } } // namespace mitk diff --git a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.h b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.h index f66e3f5ad0..d4583d7dc1 100644 --- a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.h +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.h @@ -1,175 +1,174 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKWORKBENCHUTIL_H #define MITKWORKBENCHUTIL_H #include #include "mitkDataStorageEditorInput.h" #include #include namespace mitk { /** * @ingroup org_mitk_gui_common * * @brief Utility class for loading data and opening editors in a MITK Workbench. * * @note Infering the content type is not yet supported (ignore the comments about it * in the method documentation). */ struct MITK_GUI_COMMON_PLUGIN WorkbenchUtil { /** * Loads the set of given files into the active data storage of the given Workbench window. * * If the window already has an editor open on the active datastorage then that editor * is activated; otherwise the default editor for the "mitk" extension is activated. * * @param fileNames * A list of file names with absolute path. * @param wnd * The Workbench window in which the data will be loaded. * * @see mitk::IDataNodeReader */ static void LoadFiles(const QStringList& fileNames, berry::IWorkbenchWindow::Pointer wnd); /** * Opens an editor on the given object. *

* If the page already has an editor open on the target object then that * editor is brought to front; otherwise, a new editor is opened. If * activate == true the editor will be activated. *

* * @param page * the page in which the editor will be opened * @param input * the editor input * @param editorId * the id of the editor extension to use * @param activate * if true the editor will be activated * @return an open editor or null if an external editor was * opened * @exception PartInitException * if the editor could not be initialized * @see IWorkbenchPage#OpenEditor(IEditorInput::Pointer, std::string, bool) */ static berry::IEditorPart::Pointer OpenEditor(berry::IWorkbenchPage::Pointer page, berry::IEditorInput::Pointer input, const QString& editorId, bool activate = false); /** * Opens an editor on the given file resource. This method will attempt to * resolve the editor based on content-type bindings as well as traditional * name/extension bindings if determineContentType is * true. *

* If the page already has an editor open on the target object then that * editor is brought to front; otherwise, a new editor is opened. If * activate == true the editor will be activated. *

* * @param page * the page in which the editor will be opened * @param input * the editor input * @param activate * if true the editor will be activated * @param determineContentType * attempt to resolve the content type for this file * @return an open editor or null if an external editor was * opened * @exception PartInitException * if the editor could not be initialized * @see IWorkbenchPage#OpenEditor(IEditorInput::Pointer,std::string,bool) */ static berry::IEditorPart::Pointer OpenEditor(berry::IWorkbenchPage::Pointer page, mitk::DataStorageEditorInput::Pointer input, bool activate = false, bool determineContentType = false); /** * Returns an editor descriptor appropriate for opening a file resource with * the given name. *

* The editor descriptor is determined using a multi-step process. This * method will attempt to infer the content type of the file if * inferContentType is true. *

*
    *
  1. The file is consulted for a persistent property named * IDE.EDITOR_KEY containing the preferred editor id to be * used.
  2. *
  3. The workbench editor registry is consulted to determine if an editor * extension has been registered for the file type. If so, an instance of * the editor extension is opened on the file. See * IEditorRegistry#GetDefaultEditor(std::string).
  4. *
  5. The operating system is consulted to determine if an in-place * component editor is available (e.g. OLE editor on Win32 platforms).
  6. *
  7. The operating system is consulted to determine if an external editor * is available.
  8. *
*

* * @param name * the file name * @param inferContentType * attempt to infer the content type from the file name if this * is true * @return an editor descriptor, appropriate for opening the file * @throws PartInitException * if no editor can be found */ static berry::IEditorDescriptor::Pointer GetEditorDescriptor( const QString& name, bool inferContentType = true); /** * Returns the default editor for a given file. This method will attempt to * resolve the editor based on content-type bindings as well as traditional * name/extension bindings if determineContentType is * true. *

* A default editor id may be registered for a specific file using * setDefaultEditor. If the given file has a registered * default editor id the default editor will derived from it. If not, the * default editor is determined by taking the file name for the file and * obtaining the default editor for that name. *

* * @param file * the file * @param determineContentType * determine the content type for the given file * @return the descriptor of the default editor, or null if * not found */ static berry::IEditorDescriptor::Pointer GetDefaultEditor(const QString& file, bool determineContentType); }; } #endif // MITKWORKBENCHUTIL_H diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp index fb9652c3f8..2d4ce1bc99 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp @@ -1,129 +1,128 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-10-07 16:14:59 +0200 (Mi, 07 Okt 2009) $ -Version: $Revision: 19343 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkCloseProjectAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include #include #include #include #include QmitkCloseProjectAction::QmitkCloseProjectAction(berry::IWorkbenchWindow::Pointer window) : QAction(0) { this->init(window); } QmitkCloseProjectAction::QmitkCloseProjectAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0) { this->setIcon(icon); this->init(window); } void QmitkCloseProjectAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&Close Project..."); this->setToolTip("Close Project will remove all data objects from the application. This will free up the memory that is used by the data."); m_Window = window; this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkCloseProjectAction::Run() { try { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsRef = context->getServiceReference(); if (dsRef) { dss = context->getService(dsRef); } if (!dss) { MITK_WARN << "IDataStorageService service not available. Unable to close project."; context->ungetService(dsRef); return; } mitk::IDataStorageReference::Pointer dataStorageRef = dss->GetActiveDataStorage(); if (dataStorageRef.IsNull()) { // No active data storage set (i.e. not editor with a DataStorageEditorInput is active). dataStorageRef = dss->GetDefaultDataStorage(); } mitk::DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); if (dataStorage.IsNull()) { MITK_WARN << "No data storage available. Cannot close project."; return; } //check if we got the default datastorage and if there is anything else then helper object in the storage if(dataStorageRef->IsDefault() && dataStorage->GetSubset(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true))))->empty()) { return; } /* Ask, if the user is sure about that */ QString msg = "Are you sure that you want to close the current project (%1)?\nThis will remove all data objects."; if (QMessageBox::question(NULL, "Remove all data?", msg.arg(dataStorageRef->GetLabel()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { return; } /* Remove everything */ mitk::DataStorage::SetOfObjects::ConstPointer nodesToRemove = dataStorage->GetAll(); dataStorage->Remove(nodesToRemove); // Remove the datastorage from the data storage service dss->RemoveDataStorageReference(dataStorageRef); // Close all editors with this data storage as input mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dataStorageRef)); std::vector dsEditors = m_Window->GetActivePage()->FindEditors(dsInput, std::string(), berry::IWorkbenchPage::MATCH_INPUT); if (!dsEditors.empty()) { std::list editorsToClose; editorsToClose.assign(dsEditors.begin(), dsEditors.end()); m_Window->GetActivePage()->CloseEditors(editorsToClose, false); } } catch (std::exception& e) { MITK_ERROR << "Exception caught during closing project: " << e.what(); QMessageBox::warning(NULL, "Error", QString("An error occurred during Close Project: %1").arg(e.what())); } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h index 5858850f4a..0b27ca5008 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-10-09 16:36:23 +0200 (Fr, 09 Okt 2009) $ -Version: $Revision: 19414 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkCloseProjectAction_H_ #define QmitkCloseProjectAction_H_ #ifdef __MINGW32__ // We need to include winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkCloseProjectAction : public QAction { Q_OBJECT public: QmitkCloseProjectAction(berry::IWorkbenchWindow::Pointer window); QmitkCloseProjectAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: void init(berry::IWorkbenchWindow::Pointer window); berry::IWorkbenchWindow::Pointer m_Window; }; #endif /*QmitkCloseProjectAction_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp index c21a8bda76..af185b2761 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp @@ -1,54 +1,53 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDefaultDropTargetListener.h" #include #include #include #include #include #include berry::IDropTargetListener::Events::Types QmitkDefaultDropTargetListener::GetDropTargetEventTypes() const { return Events::DROP; } void QmitkDefaultDropTargetListener::DropEvent(QDropEvent *event) { qDebug() << event->mimeData()->formats(); qDebug() << event->mimeData()->text(); QList fileNames = event->mimeData()->urls(); if (fileNames.empty()) return; QStringList fileNames2; //TODO Qt 4.7 API //fileNames2.reserve(fileNames.size()); foreach(QUrl url, fileNames) { fileNames2.push_back(url.toLocalFile()); } mitk::WorkbenchUtil::LoadFiles(fileNames2, berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); event->accept(); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h index bfefd59d52..9a26723dbb 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h @@ -1,39 +1,38 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDEFAULTDROPTARGETLISTENER_H #define QMITKDEFAULTDROPTARGETLISTENER_H #include #include /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkDefaultDropTargetListener : public berry::IDropTargetListener { public: Events::Types GetDropTargetEventTypes() const; void DropEvent(QDropEvent* event); }; #endif // QMITKDEFAULTDROPTARGETLISTENER_H diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp index 1b60840103..1013549b93 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp @@ -1,44 +1,43 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-08-26 18:11:29 +0200 (Mi, 26 Aug 2009) $ -Version: $Revision: 18726 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFileExitAction.h" #include #include #include #include #include #include #include QmitkFileExitAction::QmitkFileExitAction(berry::IWorkbenchWindow::Pointer window) : QAction(0) { m_Window = window.GetPointer(); this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&Exit"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkFileExitAction::Run() { berry::PlatformUI::GetWorkbench()->Close(); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.h b/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.h index 0a91fcb022..49258e4878 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.h @@ -1,48 +1,47 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-08-04 15:43:53 +0200 (Di, 04 Aug 2009) $ -Version: $Revision: 18435 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKFILEEXITACTION_H_ #define QMITKFILEEXITACTION_H_ #include #include #include /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkFileExitAction : public QAction { Q_OBJECT public: QmitkFileExitAction(berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: berry::IWorkbenchWindow* m_Window; }; #endif /*QMITKFILEOPENACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp index fc795fd08b..287e678551 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp @@ -1,121 +1,120 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFileOpenAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include #include #include #include #include #include #include #include class QmitkFileOpenActionPrivate { public: QmitkFileOpenActionPrivate() : m_PrefServiceTracker(mitk::PluginActivator::GetContext()) {} void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileOpenAction* action ) { m_PrefServiceTracker.open(); m_Window = window; action->setParent(static_cast(m_Window.Lock()->GetShell()->GetControl())); action->setText("&Open..."); action->setToolTip("Open data files (images, surfaces,...)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { berry::IPreferencesService* prefService = m_PrefServiceTracker.getService(); if (prefService) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileOpenPath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return QString::fromStdString(prefs->Get("LastFileOpenPath", "")); } return QString(); } void setLastFileOpenPath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { prefs->Put("LastFileOpenPath", path.toStdString()); prefs->Flush(); } } berry::IWorkbenchWindow::WeakPtr m_Window; ctkServiceTracker m_PrefServiceTracker; }; QmitkFileOpenAction::QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileOpenActionPrivate) { d->init(window, this); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileOpenActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileOpenAction::~QmitkFileOpenAction() { } void QmitkFileOpenAction::Run() { // Ask the user for a list of files to open QStringList fileNames = QFileDialog::getOpenFileNames(NULL, "Open", d->getLastFileOpenPath(), mitk::CoreObjectFactory::GetInstance()->GetFileExtensions()); if (fileNames.empty()) return; d->setLastFileOpenPath(fileNames.front()); mitk::WorkbenchUtil::LoadFiles(fileNames, d->m_Window.Lock()); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h index 20e6f8bc54..2b6c5648ce 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h @@ -1,63 +1,62 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKFILEOPENACTION_H_ #define QMITKFILEOPENACTION_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include #include #include class QmitkFileOpenActionPrivate; /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkFileOpenAction : public QAction { Q_OBJECT public: QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window); QmitkFileOpenAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); ~QmitkFileOpenAction(); protected slots: virtual void Run(); private: const QScopedPointer d; }; #endif /*QMITKFILEOPENACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp index ac320171e0..c2adbc1d42 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp @@ -1,444 +1,443 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPreferencesDialog.h" #include "berryPlatform.h" #include "berryIConfigurationElement.h" #include "berryIExtensionPointService.h" #include "berryIExtension.h" #include #include #include #include #include #include #include #include using namespace std; class QmitkPreferencesDialogPrivate : public Ui::QmitkPreferencesDialog { public: /// /// Just a stub class for holding information on prefpages (metadata) /// struct PrefPage { PrefPage(std::string _id, std::string _name, std::string _category , std::string _className, std::string _keywords, berry::IConfigurationElement::Pointer _confElem) : id(_id), name(_name), category(_category), className(_className), keywords(_keywords), prefPage(0), confElem(_confElem), treeWidgetItem(0) {} bool operator==(const PrefPage& other) { return id == other.id; } bool operator<(const PrefPage& other) { return name < other.name; } std::string id; std::string name; std::string category; std::string className; std::string keywords; berry::IQtPreferencePage* prefPage; berry::IConfigurationElement::Pointer confElem; QTreeWidgetItem* treeWidgetItem; }; QmitkPreferencesDialogPrivate() : m_CurrentPage(0) { // m_PreferencesService m_PreferencesService = berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); // m_PrefPages berry::IExtensionPointService::Pointer extensionPointService = berry::Platform::GetExtensionPointService(); berry::IConfigurationElement::vector prefPages(extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.preferencePages")); berry::IConfigurationElement::vector keywordExts(extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords")); berry::IConfigurationElement::vector::iterator prefPagesIt; std::string id; std::string name; std::string category; std::string className; std::vector keywords; vector keywordRefs; berry::IConfigurationElement::vector::iterator keywordRefsIt; berry::IConfigurationElement::vector::iterator keywordExtsIt; string keywordRefId; string keywordId; string keywordLabels; for (prefPagesIt = prefPages.begin(); prefPagesIt != prefPages.end(); ++prefPagesIt) { keywords.clear(); id.clear(); name.clear(); className.clear(); category.clear(); keywordRefId.clear(); keywordId.clear(); keywordLabels.clear(); if((*prefPagesIt)->GetAttribute("id", id) && (*prefPagesIt)->GetAttribute("name", name) && (*prefPagesIt)->GetAttribute("class", className)) { (*prefPagesIt)->GetAttribute("category", category); //# collect keywords keywordRefs = (*prefPagesIt)->GetChildren("keywordreference"); // get all keyword references for (keywordRefsIt = keywordRefs.begin() ; keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { (*keywordRefsIt)->GetAttribute("id", keywordRefId); // get referenced id for (keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) // iterate over all keywords { (*keywordExtsIt)->GetAttribute("id", keywordId); // get keyword id if(keywordId == keywordRefId) // if referenced id is equals the current keyword id { //# collect all keywords from label attribute with a tokenizer std::string currLabel; (*keywordExtsIt)->GetAttribute("label", currLabel); std::transform(currLabel.begin(), currLabel.end(), currLabel.begin(), ::tolower); if (!currLabel.empty()) keywordLabels += std::string(" ") + currLabel; //break; // break here; possibly search for other referenced keywords } } } // add information as PrefPage m_PrefPages.push_back(PrefPage(id, name, category, className, keywordLabels, berry::IConfigurationElement::Pointer(*prefPagesIt))); } } } /// /// The Preferences Service to retrieve and store preferences. /// berry::IPreferencesService::WeakPtr m_PreferencesService; /// /// Saves all treewidgetitems in a map, the key is the id of the preferencepage. /// std::vector m_PrefPages; std::size_t m_CurrentPage; }; QmitkPreferencesDialog::QmitkPreferencesDialog(QWidget * parent, Qt::WindowFlags f) : QDialog(parent, f), d(new QmitkPreferencesDialogPrivate) { d->setupUi(this); QObject::connect(d->m_Keyword, SIGNAL(editingFinished()), this, SLOT(OnKeywordEditingFinished())); QObject::connect(d->m_Keyword, SIGNAL(textChanged(QString)), this, SLOT(OnKeywordTextChanged(QString))); QObject::connect(d->m_PreferencesTree, SIGNAL(itemSelectionChanged()), this, SLOT(OnPreferencesTreeItemSelectionChanged())); QPushButton* importButton = d->buttonBox->addButton("Import...", QDialogButtonBox::ActionRole); QObject::connect(importButton, SIGNAL(clicked()), this, SLOT(OnImportButtonClicked())); QPushButton* exportButton = d->buttonBox->addButton("Export...", QDialogButtonBox::ActionRole); QObject::connect(exportButton, SIGNAL(clicked()), this, SLOT(OnExportButtonClicked())); QObject::connect(this, SIGNAL(accepted()), this, SLOT(OnDialogAccepted())); QObject::connect(this, SIGNAL(rejected()), this, SLOT(OnDialogRejected())); d->buttonBox->button(QDialogButtonBox::Cancel)->setDefault(true); this->UpdateTree(); } QmitkPreferencesDialog::~QmitkPreferencesDialog() { } void QmitkPreferencesDialog::SetSelectedPage(const std::string& id) { for(vector::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { if(it->id == id) { d->m_PreferencesTree->setCurrentItem(it->treeWidgetItem); break; } } } void QmitkPreferencesDialog::OnImportButtonClicked() { int answer = QMessageBox::question(this, "Importing Preferences" , "All existing preferences will be overwritten!\nAre you sure that you want to import other preferences?", QMessageBox::Yes | QMessageBox::No ); if(answer == QMessageBox::No) return; try { berry::IPreferencesService::Pointer prefService = d->m_PreferencesService.Lock(); if(prefService.IsNotNull()) { berry::IBerryPreferencesService::Pointer berryPrefService = prefService.Cast(); if(berryPrefService != 0) { static QString importDir = ""; QString fileName = QFileDialog::getOpenFileName(this, tr("Choose file to import preferences"), importDir, tr("XML files (*.xml)")); if(!fileName.isEmpty()) { importDir = QFileInfo(fileName).absoluteDir().path(); Poco::File f(fileName.toLocal8Bit().data()); berryPrefService->ImportPreferences(f, ""); berry::IQtPreferencePage* prefPage = d->m_PrefPages[d->m_CurrentPage].prefPage; if(prefPage) prefPage->Update(); MITK_INFO("QmitkPreferencesDialog") << "Preferences successfully imported from " << f.path(); } } } } catch (Poco::Exception& pe) { QMessageBox::critical(this, "Error Importing", pe.message().c_str()); MITK_ERROR("QmitkPreferencesDialog") << pe.what(); } catch (std::exception& e) { QMessageBox::critical(this, "Error Importing", e.what()); MITK_ERROR("QmitkPreferencesDialog") << e.what(); } } void QmitkPreferencesDialog::OnExportButtonClicked() { try { berry::IPreferencesService::Pointer prefService = d->m_PreferencesService.Lock(); if(prefService.IsNotNull()) { berry::IBerryPreferencesService::Pointer berryPrefService = prefService.Cast(); if(berryPrefService != 0) { SavePreferences(); static QString exportDir = ""; QString fileName = QFileDialog::getSaveFileName(this, tr("Choose file to export preferences"), exportDir, tr("XML files (*.xml)")); if(!fileName.isEmpty()) { if(QFileInfo(fileName).suffix() != ".xml") { fileName += ".xml"; } exportDir = QFileInfo(fileName).absoluteDir().path(); Poco::File f(fileName.toLocal8Bit().data()); berryPrefService->ExportPreferences(f, ""); MITK_INFO("QmitkPreferencesDialog") << "Preferences successfully exported to " << f.path(); } } } } catch (Poco::Exception& pe) { QMessageBox::critical(this, "Error Exporting", pe.message().c_str()); MITK_ERROR("QmitkPreferencesDialog") << pe.what(); } catch (std::exception& e) { QMessageBox::critical(this, "Error Exporting", e.what()); MITK_ERROR("QmitkPreferencesDialog") << e.what(); } } void QmitkPreferencesDialog::SavePreferences() { berry::IQtPreferencePage* prefPage = 0; for(vector::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { prefPage = it->prefPage; if(prefPage) { prefPage->PerformOk(); } } /** * Every preference page has its own preferences, which should stay the same after a system restart.
* Therefore this method flushes all the preferences, every time a change in the preferences is
* performed and confirmed. * */ berry::IPreferencesService::Pointer prefService = d->m_PreferencesService.Lock(); if (prefService) { prefService->GetSystemPreferences()->Flush(); } } void QmitkPreferencesDialog::OnDialogAccepted() { this->SavePreferences(); } void QmitkPreferencesDialog::OnDialogRejected() { berry::IQtPreferencePage* prefPage = d->m_PrefPages[d->m_CurrentPage].prefPage; if(prefPage) prefPage->PerformCancel(); } void QmitkPreferencesDialog::OnKeywordTextChanged(const QString & /*s*/) { // search for text this->UpdateTree(); } void QmitkPreferencesDialog::OnKeywordEditingFinished() { } //bool QmitkPreferencesDialog::eventFilter( QObject *obj, QEvent *event ) //{ // if(obj == d->m_Keyword) // { // if(event->type() == QEvent::FocusIn && d->m_Keyword->text() == "search ...") // { // d->m_Keyword->setText(""); // d->m_Keyword->setStyleSheet("color: black;"); // } // else if(event->type() == QEvent::FocusOut && d->m_Keyword->text() == "") // { // d->m_Keyword->setText("search ..."); // d->m_Keyword->setStyleSheet("color: gray;"); // } // } // return true; //} void QmitkPreferencesDialog::OnPreferencesTreeItemSelectionChanged() { if(d->m_PreferencesTree == 0) return; // TODO: create page and show it QList selectedItems = d->m_PreferencesTree->selectedItems(); if(selectedItems.size()>0) { d->m_CurrentPage = 0; for(vector::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it, ++d->m_CurrentPage) { if(it->treeWidgetItem == selectedItems.at(0)) { d->m_Headline->setText(QString::fromStdString(it->name)); if(it->prefPage == 0) { berry::IPreferencePage* page = it->confElem->CreateExecutableExtension("class"); if (page == 0) { // support legacy BlueBerry extensions page = it->confElem->CreateExecutableExtension("class", berry::IPreferencePage::GetManifestName()); } it->prefPage = dynamic_cast(page); it->prefPage->CreateQtControl(d->m_PreferencesPanel); d->m_PreferencesPanel->addWidget(it->prefPage->GetQtControl()); } d->m_PreferencesPanel->setCurrentWidget(it->prefPage->GetQtControl()); break; } } } } void QmitkPreferencesDialog::UpdateTree() { if(d->m_PreferencesTree == 0) return; //m_PreferencesTree->clear(); string keyword = d->m_Keyword->text().toLower().toStdString(); map items; for(vector::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { if(it->treeWidgetItem == 0) { if(it->category.empty()) { it->treeWidgetItem = new QTreeWidgetItem(d->m_PreferencesTree); } else { it->treeWidgetItem = new QTreeWidgetItem(items[it->category]); } it->treeWidgetItem->setText(0, QString::fromStdString(it->name)); items[it->id] = it->treeWidgetItem; } // hide treeWidgetItem if keyword not matches if(!keyword.empty()) { if( it->keywords.find(keyword) == string::npos ) it->treeWidgetItem->setHidden(true); else { //#make the whole branch visible QTreeWidgetItem* treeWidgetParent = it->treeWidgetItem->parent(); while(treeWidgetParent!=0) { treeWidgetParent->setHidden(false); treeWidgetParent->setExpanded(true); treeWidgetParent = treeWidgetParent->parent(); } it->treeWidgetItem->setHidden(false); QFont f = it->treeWidgetItem->font(0); f.setBold(true); it->treeWidgetItem->setFont(0, f); } } else { QFont f = it->treeWidgetItem->font(0); f.setBold(false); it->treeWidgetItem->setFont(0, f); it->treeWidgetItem->setHidden(false); } } if(d->m_PrefPages.size()>0) { if(d->m_PrefPages.front().treeWidgetItem != 0) d->m_PrefPages.front().treeWidgetItem->setSelected(true); } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h index 059c6a8486..cf46122e96 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h @@ -1,69 +1,68 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef BERRYQMITKPREFERENCESDIALOG_H_ #define BERRYQMITKPREFERENCESDIALOG_H_ #include #include #include class QmitkPreferencesDialogPrivate; /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkPreferencesDialog : public QDialog { Q_OBJECT public: QmitkPreferencesDialog(QWidget * parent = 0, Qt::WindowFlags f = 0); ~QmitkPreferencesDialog(); void SetSelectedPage(const std::string& id); protected slots: void OnImportButtonClicked(); void OnExportButtonClicked(); void OnDialogAccepted(); void OnDialogRejected(); void OnKeywordTextChanged(const QString & s); void OnKeywordEditingFinished(); void OnPreferencesTreeItemSelectionChanged(); protected: //bool eventFilter(QObject *obj, QEvent *event); void UpdateTree(); /// /// Saves all preferencepages. /// void SavePreferences(); QScopedPointer d; }; #endif /* BERRYQMITKPREFERENCESDIALOG_H_ */ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp index 2824b312ac..bc7ed0a150 100755 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp @@ -1,94 +1,93 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkStatusBar.h" #include #include #include #include #include #include /** * Display the text in the statusbar of the applikation */ void QmitkStatusBar::DisplayText(const char* t) { m_StatusBar->showMessage(t); // TODO bug #1357 //qApp->processEvents(); // produces crashes! } /** * Display the text in the statusbar of the applikation for ms seconds */ void QmitkStatusBar::DisplayText(const char* t, int ms) { m_StatusBar->showMessage(t, ms); // TODO bug #1357 //qApp->processEvents(); // produces crashes! } /** * Show the grey value text in the statusbar */ void QmitkStatusBar::DisplayGreyValueText(const char* t) { QString text(t); m_GreyValueLabel->setText(text); } /** * Clear the text in the StatusBar */ void QmitkStatusBar::Clear() { if (m_StatusBar != NULL) m_StatusBar->clearMessage(); // TODO bug #1357 //qApp->processEvents(); // produces crashes! } /** * enable or disable the QSizeGrip */ void QmitkStatusBar::SetSizeGripEnabled(bool enable) { if (m_StatusBar != NULL) m_StatusBar->setSizeGripEnabled(enable); } QmitkStatusBar::QmitkStatusBar(QStatusBar* instance) :StatusBarImplementation() { m_StatusBar = instance; m_GreyValueLabel = new QLabel(m_StatusBar,0); int xResolution = QApplication::desktop()->screenGeometry(0).width()-100; m_GreyValueLabel->setMaximumSize(QSize(xResolution,50)); m_GreyValueLabel->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Fixed); m_StatusBar->addPermanentWidget(m_GreyValueLabel); mitk::StatusBar::SetImplementation(this); } QmitkStatusBar::~QmitkStatusBar() { } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.h b/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.h index bb95f8c1da..ab6caf4972 100755 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.h @@ -1,85 +1,84 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKSTATUSBAR_H #define QMITKSTATUSBAR_H #include #include #include #include #include /** * \ingroup org_mitk_gui_qt_application * * \brief QT-Toolkit/GUI dependent class that provides to send a Message to the QT's StatusBar * * A delay time can be set. * * All mitk-classes will call this class for output: * mitk::StatusBar::GetInstance(); */ class MITK_QT_APP QmitkStatusBar : public mitk::StatusBarImplementation { public: mitkClassMacro(QmitkStatusBar, mitk::StatusBarImplementation); //##Documentation //##@brief Constructor; //## holds param instance internaly and connects this to the mitkStatusBar QmitkStatusBar(QStatusBar* instance); //##Documentation //##@brief Destructor virtual ~QmitkStatusBar(); //##Documentation //## @brief Send a string to the applications StatusBar (QStatusBar). virtual void DisplayText(const char* t); virtual void DisplayText(const char* t, int ms); //##Documentation //## @brief Send a string as an error message to StatusBar. //## The implementation calls DisplayText() virtual void DisplayErrorText(const char *t) { this->DisplayText(t); }; virtual void DisplayWarningText(const char *t) { this->DisplayText(t); }; virtual void DisplayWarningText(const char *t, int ms) { this->DisplayText(t, ms); }; virtual void DisplayGenericOutputText(const char *t) {this->DisplayText(t);} virtual void DisplayDebugText(const char *t) { this->DisplayText(t); }; virtual void DisplayGreyValueText(const char *t); //##Documentation //## @brief removes any temporary message being shown. virtual void Clear(); //##Documentation //## @brief Set the QSizeGrip of the window //## (the triangle in the lower right Windowcorner for changing the size) //## to enabled or disabled virtual void SetSizeGripEnabled(bool enable); private: //static Pointer m_Instance; QStatusBar* m_StatusBar; QLabel* m_GreyValueLabel; }; #endif /* define QMITKSTATUSBAR_H */ diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.cpp index 24a52130b2..1d7ebb74ea 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.cpp @@ -1,58 +1,57 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-07 16:57:15 +0200 (Di, 07 Jul 2009) $ -Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkEditorsPreferencePage.h" #include QmitkEditorsPreferencePage::QmitkEditorsPreferencePage() : m_MainControl(0) { } void QmitkEditorsPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkEditorsPreferencePage::CreateQtControl(QWidget* parent) { //empty page m_MainControl = new QWidget(parent); QVBoxLayout *layout = new QVBoxLayout; m_MainControl->setLayout(layout); this->Update(); } QWidget* QmitkEditorsPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkEditorsPreferencePage::PerformOk() { return true; } void QmitkEditorsPreferencePage::PerformCancel() { } void QmitkEditorsPreferencePage::Update() { } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h index f2fb32aea4..919e60d90c 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkEditorsPreferencePage.h @@ -1,75 +1,74 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ -Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEDITORSPREFERENCEPAGE_H_ #define QMITKEDITORSPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include class QWidget; class QmitkEditorsPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: /** * Default constructor */ QmitkEditorsPreferencePage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench); /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget); /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const; /** * @see berry::IPreferencePage::PerformOk() */ virtual bool PerformOk(); /** * @see berry::IPreferencePage::PerformCancel() */ virtual void PerformCancel(); /** * @see berry::IPreferencePage::Update() */ virtual void Update(); protected: QWidget* m_MainControl; }; #endif /* QMITKEDITORSPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp index 6df2a4f89f..9718f36ef7 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkGeneralPreferencePage.cpp @@ -1,58 +1,57 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-07 16:57:15 +0200 (Di, 07 Jul 2009) $ -Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkGeneralPreferencePage.h" #include QmitkGeneralPreferencePage::QmitkGeneralPreferencePage() : m_MainControl(0) { } void QmitkGeneralPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkGeneralPreferencePage::CreateQtControl(QWidget* parent) { //empty page m_MainControl = new QWidget(parent); QVBoxLayout *layout = new QVBoxLayout; m_MainControl->setLayout(layout); this->Update(); } QWidget* QmitkGeneralPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkGeneralPreferencePage::PerformOk() { return true; } void QmitkGeneralPreferencePage::PerformCancel() { } void QmitkGeneralPreferencePage::Update() { } 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 e4573d58b1..6b34c1039a 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,74 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ -Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKGENERALPREFERENCEPAGE_H_ #define QMITKGENERALPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include class QWidget; class QmitkGeneralPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: /** * Default constructor */ QmitkGeneralPreferencePage(); /** * @see berry::IPreferencePage::Init(berry::IWorkbench::Pointer workbench) */ void Init(berry::IWorkbench::Pointer workbench); /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget); /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const; /** * @see berry::IPreferencePage::PerformOk() */ virtual bool PerformOk(); /** * @see berry::IPreferencePage::PerformCancel() */ virtual void PerformCancel(); /** * @see berry::IPreferencePage::Update() */ virtual void Update(); protected: QWidget* m_MainControl; }; #endif /* QMITKGENERALPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp index 2a5b308f08..03bbad77f4 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp @@ -1,70 +1,69 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "org_mitk_gui_qt_application_Activator.h" #include "QmitkGeneralPreferencePage.h" #include "QmitkEditorsPreferencePage.h" #include #include #include namespace mitk { ctkPluginContext* org_mitk_gui_qt_application_Activator::m_Context = 0; void org_mitk_gui_qt_application_Activator::start(ctkPluginContext* context) { this->m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkGeneralPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkEditorsPreferencePage, context) QFile file(":/org.mitk.gui.qt.common/StateMachine.xml"); if(file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text) ) { QByteArray contents = file.readAll(); QString string(contents); file.close(); mitk::GlobalInteraction::GetInstance()->Initialize("global", string.toStdString()); } else throw std::exception(); QmitkRegisterClasses(); } void org_mitk_gui_qt_application_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) this->m_Context = 0; } ctkPluginContext* org_mitk_gui_qt_application_Activator::GetContext() { return m_Context; } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_application, mitk::org_mitk_gui_qt_application_Activator) diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h index 4bd05dfeca..6006f253fa 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h @@ -1,49 +1,48 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include namespace mitk { class org_mitk_gui_qt_application_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static ctkPluginContext* GetContext(); private: static ctkPluginContext* m_Context; }; // org_mitk_gui_common_Activator typedef org_mitk_gui_qt_application_Activator PluginActivator; } #endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp index 54aaa8e522..7c60e905b8 100644 --- a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp +++ b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp @@ -1,1054 +1,1053 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkBasicImageProcessingView.h" // QT includes (GUI) #include #include #include #include #include #include #include // Berry includes (selection service) #include #include // MITK includes (GUI) #include "QmitkStdMultiWidget.h" #include "QmitkDataNodeSelectionProvider.h" #include "mitkDataNodeObject.h" // MITK includes (general) #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateDimension.h" #include "mitkNodePredicateAnd.h" #include "mitkImageTimeSelector.h" #include "mitkVectorImageMapper2D.h" #include "mitkProperties.h" // Includes for image casting between ITK and MITK #include "mitkImageCast.h" #include "mitkITKImageImport.h" // ITK includes (general) #include // Morphological Operations #include #include #include #include #include // Smoothing #include #include #include // Threshold #include // Inversion #include // Derivatives #include #include #include // Resampling #include #include // Image Arithmetics #include #include #include #include // Boolean operations #include #include #include // Convenient Definitions typedef itk::Image ImageType; typedef itk::Image FloatImageType; typedef itk::Image, 3> VectorImageType; typedef itk::BinaryBallStructuringElement BallType; typedef itk::GrayscaleDilateImageFilter DilationFilterType; typedef itk::GrayscaleErodeImageFilter ErosionFilterType; typedef itk::GrayscaleMorphologicalOpeningImageFilter OpeningFilterType; typedef itk::GrayscaleMorphologicalClosingImageFilter ClosingFilterType; typedef itk::MedianImageFilter< ImageType, ImageType > MedianFilterType; typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType> GaussianFilterType; typedef itk::TotalVariationDenoisingImageFilter TotalVariationFilterType; typedef itk::TotalVariationDenoisingImageFilter VectorTotalVariationFilterType; typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > ThresholdFilterType; typedef itk::InvertIntensityImageFilter< ImageType, ImageType > InversionFilterType; typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, ImageType > GradientFilterType; typedef itk::LaplacianImageFilter< FloatImageType, FloatImageType > LaplacianFilterType; typedef itk::SobelEdgeDetectionImageFilter< FloatImageType, FloatImageType > SobelFilterType; typedef itk::ResampleImageFilter< ImageType, ImageType > ResampleImageFilterType; typedef itk::AddImageFilter< ImageType, ImageType, ImageType > AddFilterType; typedef itk::SubtractImageFilter< ImageType, ImageType, ImageType > SubtractFilterType; typedef itk::MultiplyImageFilter< ImageType, ImageType, ImageType > MultiplyFilterType; typedef itk::DivideImageFilter< ImageType, ImageType, FloatImageType > DivideFilterType; typedef itk::OrImageFilter< ImageType, ImageType > OrImageFilterType; typedef itk::AndImageFilter< ImageType, ImageType > AndImageFilterType; typedef itk::XorImageFilter< ImageType, ImageType > XorImageFilterType; QmitkBasicImageProcessing::QmitkBasicImageProcessing() : QmitkFunctionality(), m_Controls(NULL), m_SelectedImageNode(NULL), m_TimeStepperAdapter(NULL), m_SelectionListener(NULL) { } QmitkBasicImageProcessing::~QmitkBasicImageProcessing() { //berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); //if(s) // s->RemoveSelectionListener(m_SelectionListener); } void QmitkBasicImageProcessing::CreateQtPartControl(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new Ui::QmitkBasicImageProcessingViewControls; m_Controls->setupUi(parent); this->CreateConnections(); //setup predictaes for combobox mitk::NodePredicateDimension::Pointer dimensionPredicate = mitk::NodePredicateDimension::New(3); mitk::NodePredicateDataType::Pointer imagePredicate = mitk::NodePredicateDataType::New("Image"); m_Controls->m_ImageSelector2->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->m_ImageSelector2->SetPredicate(mitk::NodePredicateAnd::New(dimensionPredicate, imagePredicate)); } m_Controls->gbTwoImageOps->hide(); m_SelectedImageNode = mitk::DataStorageSelection::New(this->GetDefaultDataStorage(), false); } void QmitkBasicImageProcessing::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->cbWhat1), SIGNAL( activated(int) ), this, SLOT( SelectAction(int) ) ); connect( (QObject*)(m_Controls->btnDoIt), SIGNAL(clicked()),(QObject*) this, SLOT(StartButtonClicked())); connect( (QObject*)(m_Controls->cbWhat2), SIGNAL( activated(int) ), this, SLOT( SelectAction2(int) ) ); connect( (QObject*)(m_Controls->btnDoIt2), SIGNAL(clicked()),(QObject*) this, SLOT(StartButton2Clicked())); connect( (QObject*)(m_Controls->rBOneImOp), SIGNAL( clicked() ), this, SLOT( ChangeGUI() ) ); connect( (QObject*)(m_Controls->rBTwoImOp), SIGNAL( clicked() ), this, SLOT( ChangeGUI() ) ); } m_TimeStepperAdapter = new QmitkStepperAdapter((QObject*) m_Controls->sliceNavigatorTime, GetActiveStdMultiWidget()->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromBIP"); } void QmitkBasicImageProcessing::Activated() { QmitkFunctionality::Activated(); this->m_Controls->cbWhat1->clear(); this->m_Controls->cbWhat1->insertItem( NOACTIONSELECTED, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Please select operation", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( CATEGORY_DENOISING, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "--- Denoising ---", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( GAUSSIAN, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Gaussian", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( MEDIAN, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Median", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( TOTALVARIATION, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Total Variation", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( CATEGORY_MORPHOLOGICAL, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "--- Morphological ---", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( DILATION, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Dilation", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( EROSION, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Erosion", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( OPENING, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Opening", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( CLOSING, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Closing", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( CATEGORY_EDGE_DETECTION, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "--- Edge Detection ---", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( GRADIENT, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Gradient", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( LAPLACIAN, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Laplacian (2nd Derivative)", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( SOBEL, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Sobel Operator", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( CATEGORY_MISC, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "--- Misc ---", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( THRESHOLD, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Threshold", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( INVERSION, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Image Inversion", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat1->insertItem( DOWNSAMPLING, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Downsampling", 0, QApplication::UnicodeUTF8) )); this->m_Controls->cbWhat2->clear(); this->m_Controls->cbWhat2->insertItem( TWOIMAGESNOACTIONSELECTED, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Please select on operation", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( CATEGORY_ARITHMETIC, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "--- Arithmetric operations ---", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( ADD, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Add to Image 1:", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( SUBTRACT, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Subtract from Image 1:", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( MULTIPLY, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Multiply with Image 1:", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( DIVIDE, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "Divide Image 1 by:", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( CATEGORY_BOOLEAN, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "--- Boolean operations ---", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( AND, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "AND", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( OR, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "OR", 0, QApplication::UnicodeUTF8) ) ); this->m_Controls->cbWhat2->insertItem( XOR, QString( QApplication::translate("QmitkBasicImageProcessingViewControls", "XOR", 0, QApplication::UnicodeUTF8) ) ); } //datamanager selection changed void QmitkBasicImageProcessing::OnSelectionChanged(std::vector nodes) { //any nodes there? if (!nodes.empty()) { // reset GUI this->ResetOneImageOpPanel(); m_Controls->sliceNavigatorTime->setEnabled(false); m_Controls->leImage1->setText("Select an Image in Data Manager"); m_Controls->tlWhat1->setEnabled(false); m_Controls->cbWhat1->setEnabled(false); m_Controls->tlWhat2->setEnabled(false); m_Controls->cbWhat2->setEnabled(false); m_SelectedImageNode->RemoveAllNodes(); //get the selected Node mitk::DataNode* _DataNode = nodes.front(); *m_SelectedImageNode = _DataNode; //try to cast to image mitk::Image::Pointer tempImage = dynamic_cast(m_SelectedImageNode->GetNode()->GetData()); //no image if( tempImage.IsNull() || (tempImage->IsInitialized() == false) ) { m_Controls->leImage1->setText("Not an image."); return; } //2D image if( tempImage->GetDimension() < 3) { m_Controls->leImage1->setText("2D images are not supported."); return; } //image m_Controls->leImage1->setText(QString(m_SelectedImageNode->GetNode()->GetName().c_str())); // button coding if ( tempImage->GetDimension() > 3 ) { m_Controls->sliceNavigatorTime->setEnabled(true); m_Controls->tlTime->setEnabled(true); } m_Controls->tlWhat1->setEnabled(true); m_Controls->cbWhat1->setEnabled(true); m_Controls->tlWhat2->setEnabled(true); m_Controls->cbWhat2->setEnabled(true); } } void QmitkBasicImageProcessing::ChangeGUI() { if(m_Controls->rBOneImOp->isChecked()) { m_Controls->gbTwoImageOps->hide(); m_Controls->gbOneImageOps->show(); } else if(m_Controls->rBTwoImOp->isChecked()) { m_Controls->gbOneImageOps->hide(); m_Controls->gbTwoImageOps->show(); } } void QmitkBasicImageProcessing::ResetOneImageOpPanel() { m_Controls->tlParam1->setText("Param1"); m_Controls->tlParam2->setText("Param2"); m_Controls->cbWhat1->setCurrentIndex(0); m_Controls->tlTime->setEnabled(false); this->ResetParameterPanel(); m_Controls->btnDoIt->setEnabled(false); m_Controls->cbHideOrig->setEnabled(false); } void QmitkBasicImageProcessing::ResetParameterPanel() { m_Controls->tlParam->setEnabled(false); m_Controls->tlParam1->setEnabled(false); m_Controls->tlParam2->setEnabled(false); m_Controls->sbParam1->setEnabled(false); m_Controls->sbParam2->setEnabled(false); m_Controls->sbParam1->setValue(0); m_Controls->sbParam2->setValue(0); } void QmitkBasicImageProcessing::ResetTwoImageOpPanel() { m_Controls->cbWhat2->setCurrentIndex(0); m_Controls->tlImage2->setEnabled(false); m_Controls->m_ImageSelector2->setEnabled(false); m_Controls->btnDoIt2->setEnabled(false); } void QmitkBasicImageProcessing::SelectAction(int action) { if ( ! m_SelectedImageNode->GetNode() ) return; // Prepare GUI this->ResetParameterPanel(); m_Controls->btnDoIt->setEnabled(false); m_Controls->cbHideOrig->setEnabled(false); QString text1 = "No Parameters"; QString text2 = "No Parameters"; // check which operation the user has selected and set parameters and GUI accordingly switch (action) { case 2: { m_SelectedAction = GAUSSIAN; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Variance:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 2 ); break; } case 3: { m_SelectedAction = MEDIAN; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 4: { m_SelectedAction = TOTALVARIATION; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); m_Controls->tlParam2->setEnabled(true); m_Controls->sbParam2->setEnabled(true); text1 = "Number Iterations:"; text2 = "Regularization\n(Lambda/1000):"; m_Controls->sbParam1->setMinimum( 1 ); m_Controls->sbParam1->setMaximum( 1000 ); m_Controls->sbParam1->setValue( 40 ); m_Controls->sbParam2->setMinimum( 0 ); m_Controls->sbParam2->setMaximum( 100000 ); m_Controls->sbParam2->setValue( 1 ); break; } case 6: { m_SelectedAction = DILATION; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 7: { m_SelectedAction = EROSION; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 8: { m_SelectedAction = OPENING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 9: { m_SelectedAction = CLOSING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 11: { m_SelectedAction = GRADIENT; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "Sigma of Gaussian Kernel:\n(in Image Spacing Units)"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 2 ); break; } case 12: { m_SelectedAction = LAPLACIAN; break; } case 13: { m_SelectedAction = SOBEL; break; } case 15: { m_SelectedAction = THRESHOLD; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); m_Controls->tlParam2->setEnabled(true); m_Controls->sbParam2->setEnabled(true); text1 = "Lower threshold:"; text2 = "Upper threshold:"; m_Controls->sbParam1->setMinimum( -100000 ); m_Controls->sbParam1->setMaximum( 100000 ); m_Controls->sbParam1->setValue( 0 ); m_Controls->sbParam2->setMinimum( -100000 ); m_Controls->sbParam2->setMaximum( 100000 ); m_Controls->sbParam2->setValue( 300 ); break; } case 16: { m_SelectedAction = INVERSION; break; } case 17: { m_SelectedAction = DOWNSAMPLING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "Downsampling by Factor:"; m_Controls->sbParam1->setMinimum( 1 ); m_Controls->sbParam1->setMaximum( 100 ); m_Controls->sbParam1->setValue( 2 ); break; } default: return; } m_Controls->tlParam->setEnabled(true); m_Controls->tlParam1->setText(text1); m_Controls->tlParam2->setText(text2); m_Controls->btnDoIt->setEnabled(true); m_Controls->cbHideOrig->setEnabled(true); } void QmitkBasicImageProcessing::StartButtonClicked() { if(!m_SelectedImageNode->GetNode()) return; this->BusyCursorOn(); mitk::Image::Pointer newImage; try { newImage = dynamic_cast(m_SelectedImageNode->GetNode()->GetData()); } catch ( std::exception &e ) { QString exceptionString = "An error occured during image loading:\n"; exceptionString.append( e.what() ); QMessageBox::warning( NULL, "Basic Image Processing", exceptionString , QMessageBox::Ok, QMessageBox::NoButton ); this->BusyCursorOff(); return; } // check if input image is valid, casting does not throw exception when casting from 'NULL-Object' if ( (! newImage) || (newImage->IsInitialized() == false) ) { this->BusyCursorOff(); QMessageBox::warning( NULL, "Basic Image Processing", "Input image is broken or not initialized. Returning.", QMessageBox::Ok, QMessageBox::NoButton ); return; } // check if operation is done on 4D a image time step if(newImage->GetDimension() > 3) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(newImage); timeSelector->SetTimeNr( ((QmitkSliderNavigatorWidget*)m_Controls->sliceNavigatorTime)->GetPos() ); timeSelector->Update(); newImage = timeSelector->GetOutput(); } // check if image or vector image ImageType::Pointer itkImage = ImageType::New(); VectorImageType::Pointer itkVecImage = VectorImageType::New(); int isVectorImage = newImage->GetPixelType().GetNumberOfComponents(); if(isVectorImage > 1) { CastToItkImage( newImage, itkVecImage ); } else { CastToItkImage( newImage, itkImage ); } std::stringstream nameAddition(""); int param1 = m_Controls->sbParam1->value(); int param2 = m_Controls->sbParam2->value(); try{ switch (m_SelectedAction) { case GAUSSIAN: { GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New(); gaussianFilter->SetInput( itkImage ); gaussianFilter->SetVariance( param1 ); gaussianFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(gaussianFilter->GetOutput()); nameAddition << "_Gaussian_var_" << param1; std::cout << "Gaussian filtering successful." << std::endl; break; } case MEDIAN: { MedianFilterType::Pointer medianFilter = MedianFilterType::New(); MedianFilterType::InputSizeType size; size.Fill(param1); medianFilter->SetRadius( size ); medianFilter->SetInput(itkImage); medianFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(medianFilter->GetOutput()); nameAddition << "_Median_radius_" << param1; std::cout << "Median Filtering successful." << std::endl; break; } case TOTALVARIATION: { if(isVectorImage > 1) { VectorTotalVariationFilterType::Pointer TVFilter = VectorTotalVariationFilterType::New(); TVFilter->SetInput( itkVecImage.GetPointer() ); TVFilter->SetNumberIterations(param1); TVFilter->SetLambda(double(param2)/1000.); TVFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(TVFilter->GetOutput()); } else { FloatImageType::Pointer fImage = FloatImageType::New(); CastToItkImage( newImage, fImage ); TotalVariationFilterType::Pointer TVFilter = TotalVariationFilterType::New(); TVFilter->SetInput( fImage.GetPointer() ); TVFilter->SetNumberIterations(param1); TVFilter->SetLambda(double(param2)/1000.); TVFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(TVFilter->GetOutput()); } nameAddition << "_TV_Iter_" << param1 << "_L_" << param2; std::cout << "Total Variation Filtering successful." << std::endl; break; } case DILATION: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); DilationFilterType::Pointer dilationFilter = DilationFilterType::New(); dilationFilter->SetInput( itkImage ); dilationFilter->SetKernel( binaryBall ); dilationFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(dilationFilter->GetOutput()); nameAddition << "_Dilated_by_" << param1; std::cout << "Dilation successful." << std::endl; break; } case EROSION: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); ErosionFilterType::Pointer erosionFilter = ErosionFilterType::New(); erosionFilter->SetInput( itkImage ); erosionFilter->SetKernel( binaryBall ); erosionFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(erosionFilter->GetOutput()); nameAddition << "_Eroded_by_" << param1; std::cout << "Erosion successful." << std::endl; break; } case OPENING: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); OpeningFilterType::Pointer openFilter = OpeningFilterType::New(); openFilter->SetInput( itkImage ); openFilter->SetKernel( binaryBall ); openFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(openFilter->GetOutput()); nameAddition << "_Opened_by_" << param1; std::cout << "Opening successful." << std::endl; break; } case CLOSING: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); ClosingFilterType::Pointer closeFilter = ClosingFilterType::New(); closeFilter->SetInput( itkImage ); closeFilter->SetKernel( binaryBall ); closeFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(closeFilter->GetOutput()); nameAddition << "_Closed_by_" << param1; std::cout << "Closing successful." << std::endl; break; } case GRADIENT: { GradientFilterType::Pointer gradientFilter = GradientFilterType::New(); gradientFilter->SetInput( itkImage ); gradientFilter->SetSigma( param1 ); gradientFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(gradientFilter->GetOutput()); nameAddition << "_Gradient_sigma_" << param1; std::cout << "Gradient calculation successful." << std::endl; break; } case LAPLACIAN: { FloatImageType::Pointer fImage = FloatImageType::New(); CastToItkImage( newImage, fImage ); LaplacianFilterType::Pointer laplacianFilter = LaplacianFilterType::New(); laplacianFilter->SetInput( fImage ); laplacianFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(laplacianFilter->GetOutput()); nameAddition << "_Second_Derivative"; std::cout << "Laplacian filtering successful." << std::endl; break; } case SOBEL: { FloatImageType::Pointer fImage = FloatImageType::New(); CastToItkImage( newImage, fImage ); SobelFilterType::Pointer sobelFilter = SobelFilterType::New(); sobelFilter->SetInput( fImage ); sobelFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(sobelFilter->GetOutput()); nameAddition << "_Sobel"; std::cout << "Edge Detection successful." << std::endl; break; } case THRESHOLD: { ThresholdFilterType::Pointer thFilter = ThresholdFilterType::New(); thFilter->SetLowerThreshold(param1 < param2 ? param1 : param2); thFilter->SetUpperThreshold(param2 > param1 ? param2 : param1); thFilter->SetInsideValue(1); thFilter->SetOutsideValue(0); thFilter->SetInput(itkImage); thFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(thFilter->GetOutput()); nameAddition << "_Threshold"; std::cout << "Thresholding successful." << std::endl; break; } case INVERSION: { InversionFilterType::Pointer invFilter = InversionFilterType::New(); mitk::ScalarType min = newImage->GetScalarValueMin(); mitk::ScalarType max = newImage->GetScalarValueMax(); invFilter->SetMaximum( max + min ); invFilter->SetInput(itkImage); invFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(invFilter->GetOutput()); nameAddition << "_Inverted"; std::cout << "Image inversion successful." << std::endl; break; } case DOWNSAMPLING: { ResampleImageFilterType::Pointer downsampler = ResampleImageFilterType::New(); downsampler->SetInput( itkImage ); typedef itk::NearestNeighborInterpolateImageFunction< ImageType, double > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); downsampler->SetInterpolator( interpolator ); downsampler->SetDefaultPixelValue( 0 ); ResampleImageFilterType::SpacingType spacing = itkImage->GetSpacing(); spacing *= (double) param1; downsampler->SetOutputSpacing( spacing ); downsampler->SetOutputOrigin( itkImage->GetOrigin() ); downsampler->SetOutputDirection( itkImage->GetDirection() ); ResampleImageFilterType::SizeType size = itkImage->GetLargestPossibleRegion().GetSize(); for ( int i = 0; i < 3; ++i ) { size[i] /= param1; } downsampler->SetSize( size ); downsampler->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(downsampler->GetOutput()); nameAddition << "_Downsampled_by_" << param1; std::cout << "Downsampling successful." << std::endl; break; } default: this->BusyCursorOff(); return; } } catch (...) { this->BusyCursorOff(); QMessageBox::warning(NULL, "Warning", "Problem when applying filter operation. Check your input..."); return; } newImage->DisconnectPipeline(); // adjust level/window to new image mitk::LevelWindow levelwindow; levelwindow.SetAuto( newImage ); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); levWinProp->SetLevelWindow( levelwindow ); // compose new image name std::string name = m_SelectedImageNode->GetNode()->GetName(); if (name.find(".pic.gz") == name.size() -7 ) { name = name.substr(0,name.size() -7); } name.append( nameAddition.str() ); // create final result MITK data storage node mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "levelwindow", levWinProp ); result->SetProperty( "name", mitk::StringProperty::New( name.c_str() ) ); result->SetData( newImage ); // for vector images, a different mapper is needed if(isVectorImage > 1) { mitk::VectorImageMapper2D::Pointer mapper = mitk::VectorImageMapper2D::New(); result->SetMapper(1,mapper); } // reset GUI to ease further processing this->ResetOneImageOpPanel(); // add new image to data storage and set as active to ease further processing GetDefaultDataStorage()->Add( result, m_SelectedImageNode->GetNode() ); if ( m_Controls->cbHideOrig->isChecked() == true ) m_SelectedImageNode->GetNode()->SetProperty( "visible", mitk::BoolProperty::New(false) ); // TODO!! m_Controls->m_ImageSelector1->SetSelectedNode(result); // show the results mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->BusyCursorOff(); } void QmitkBasicImageProcessing::SelectAction2(int operation) { // check which operation the user has selected and set parameters and GUI accordingly switch (operation) { case 2: m_SelectedOperation = ADD; break; case 3: m_SelectedOperation = SUBTRACT; break; case 4: m_SelectedOperation = MULTIPLY; break; case 5: m_SelectedOperation = DIVIDE; break; case 7: m_SelectedOperation = AND; break; case 8: m_SelectedOperation = OR; break; case 9: m_SelectedOperation = XOR; break; default: this->ResetTwoImageOpPanel(); return; } m_Controls->tlImage2->setEnabled(true); m_Controls->m_ImageSelector2->setEnabled(true); m_Controls->btnDoIt2->setEnabled(true); } void QmitkBasicImageProcessing::StartButton2Clicked() { mitk::Image::Pointer newImage1 = dynamic_cast (m_SelectedImageNode->GetNode()->GetData()); mitk::Image::Pointer newImage2 = dynamic_cast (m_Controls->m_ImageSelector2->GetSelectedNode()->GetData()); // check if images are valid if( (!newImage1) || (!newImage2) || (newImage1->IsInitialized() == false) || (newImage2->IsInitialized() == false) ) { itkGenericExceptionMacro(<< "At least one of the input images are broken or not initialized. Returning"); return; } this->BusyCursorOn(); this->ResetTwoImageOpPanel(); // check if 4D image and use filter on correct time step int time = ((QmitkSliderNavigatorWidget*)m_Controls->sliceNavigatorTime)->GetPos(); if(time>=0) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(newImage1); timeSelector->SetTimeNr( time ); timeSelector->UpdateLargestPossibleRegion(); newImage1 = timeSelector->GetOutput(); newImage1->DisconnectPipeline(); timeSelector->SetInput(newImage2); timeSelector->SetTimeNr( time ); timeSelector->UpdateLargestPossibleRegion(); newImage2 = timeSelector->GetOutput(); newImage2->DisconnectPipeline(); } // reset GUI for better usability this->ResetTwoImageOpPanel(); ImageType::Pointer itkImage1 = ImageType::New(); ImageType::Pointer itkImage2 = ImageType::New(); CastToItkImage( newImage1, itkImage1 ); CastToItkImage( newImage2, itkImage2 ); // Remove temp image newImage2 = NULL; std::string nameAddition = ""; try { switch (m_SelectedOperation) { case ADD: { AddFilterType::Pointer addFilter = AddFilterType::New(); addFilter->SetInput1( itkImage1 ); addFilter->SetInput2( itkImage2 ); addFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(addFilter->GetOutput()); nameAddition = "_Added"; } break; case SUBTRACT: { SubtractFilterType::Pointer subFilter = SubtractFilterType::New(); subFilter->SetInput1( itkImage1 ); subFilter->SetInput2( itkImage2 ); subFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(subFilter->GetOutput()); nameAddition = "_Subtracted"; } break; case MULTIPLY: { MultiplyFilterType::Pointer multFilter = MultiplyFilterType::New(); multFilter->SetInput1( itkImage1 ); multFilter->SetInput2( itkImage2 ); multFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(multFilter->GetOutput()); nameAddition = "_Multiplied"; } break; case DIVIDE: { DivideFilterType::Pointer divFilter = DivideFilterType::New(); divFilter->SetInput1( itkImage1 ); divFilter->SetInput2( itkImage2 ); divFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(divFilter->GetOutput()); nameAddition = "_Divided"; } break; case AND: { AndImageFilterType::Pointer andFilter = AndImageFilterType::New(); andFilter->SetInput1( itkImage1 ); andFilter->SetInput2( itkImage2 ); andFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(andFilter->GetOutput()); nameAddition = "_AND"; break; } case OR: { OrImageFilterType::Pointer orFilter = OrImageFilterType::New(); orFilter->SetInput1( itkImage1 ); orFilter->SetInput2( itkImage2 ); orFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(orFilter->GetOutput()); nameAddition = "_OR"; break; } case XOR: { XorImageFilterType::Pointer xorFilter = XorImageFilterType::New(); xorFilter->SetInput1( itkImage1 ); xorFilter->SetInput2( itkImage2 ); xorFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(xorFilter->GetOutput()); nameAddition = "_XOR"; break; } default: std::cout << "Something went wrong..." << std::endl; this->BusyCursorOff(); return; } } catch (...) { this->BusyCursorOff(); QMessageBox::warning(NULL, "Warning", "Problem when applying arithmetic operation to two images. Check dimensions of input images."); return; } // disconnect pipeline; images will not be reused newImage1->DisconnectPipeline(); itkImage1 = NULL; itkImage2 = NULL; // adjust level/window to new image and compose new image name mitk::LevelWindow levelwindow; levelwindow.SetAuto( newImage1 ); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); levWinProp->SetLevelWindow( levelwindow ); std::string name = m_SelectedImageNode->GetNode()->GetName(); if (name.find(".pic.gz") == name.size() -7 ) { name = name.substr(0,name.size() -7); } // create final result MITK data storage node mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "levelwindow", levWinProp ); result->SetProperty( "name", mitk::StringProperty::New( (name + nameAddition ).c_str() )); result->SetData( newImage1 ); GetDefaultDataStorage()->Add( result, m_SelectedImageNode->GetNode() ); // show only the newly created image m_SelectedImageNode->GetNode()->SetProperty( "visible", mitk::BoolProperty::New(false) ); m_Controls->m_ImageSelector2->GetSelectedNode()->SetProperty( "visible", mitk::BoolProperty::New(false) ); // show the newly created image mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->BusyCursorOff(); } diff --git a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h index 410743505e..1885ba8a0c 100644 --- a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h +++ b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h @@ -1,185 +1,184 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QmitkBasicImageProcessingView_H__INCLUDED) #define QmitkBasicImageProcessingView_H__INCLUDED #include "QmitkFunctionality.h" #include #include "ui_QmitkBasicImageProcessingViewControls.h" #include "QmitkStepperAdapter.h" #include #include /*! \brief This module allows to use some basic image processing filters for preprocessing, image enhancement and testing purposes Several basic ITK image processing filters, like denoising, morphological and edge detection are encapsulated in this module and can be selected via a list and an intuitive parameter input. The selected filter will be applied on the image, and a new image showing the output is displayed as result. Also, some image arithmetic operations are available. Images can be 3D or 4D. In the 4D case, the filters work on the 3D image selected via the time slider. The result is also a 3D image. \sa QmitkFunctionality, QObject \class QmitkBasicImageProcessing \author Tobias Schwarz \version 1.0 (3M3) \date 2009-05-10 \ingroup Bundles */ class BASICIMAGEPROCESSING_EXPORT QmitkBasicImageProcessing : public QmitkFunctionality { Q_OBJECT public: /*! \brief default constructor */ QmitkBasicImageProcessing(); QmitkBasicImageProcessing(const QmitkBasicImageProcessing& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } /*! \brief default destructor */ virtual ~QmitkBasicImageProcessing(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); virtual void Activated(); /*! \brief Invoked when the DataManager selection changed */ virtual void OnSelectionChanged(std::vector nodes); protected slots: /* * When an action is selected in the "one image ops" list box */ void SelectAction(int action); /* * When an action is selected in the "two image ops" list box */ void SelectAction2(int operation); /* * The "Execute" button in the "one image ops" box was triggered */ void StartButtonClicked(); /* * The "Execute" button in the "two image ops" box was triggered */ void StartButton2Clicked(); /* * Switch between the one and the two image operations GUI */ void ChangeGUI(); private: /* * After a one image operation, reset the "one image ops" panel */ void ResetOneImageOpPanel(); /* * Helper method to reset the parameter set panel */ void ResetParameterPanel(); /* * After a two image operation, reset the "two image ops" panel */ void ResetTwoImageOpPanel(); /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkBasicImageProcessingViewControls *m_Controls; //mitk::DataNode* m_SelectedImageNode; mitk::DataStorageSelection::Pointer m_SelectedImageNode; QmitkStepperAdapter* m_TimeStepperAdapter; berry::ISelectionListener::Pointer m_SelectionListener; enum ActionType { NOACTIONSELECTED, CATEGORY_DENOISING, GAUSSIAN, MEDIAN, TOTALVARIATION, CATEGORY_MORPHOLOGICAL, DILATION, EROSION, OPENING, CLOSING, CATEGORY_EDGE_DETECTION, GRADIENT, LAPLACIAN, SOBEL, CATEGORY_MISC, THRESHOLD, INVERSION, DOWNSAMPLING, } m_SelectedAction; enum OperationType{ TWOIMAGESNOACTIONSELECTED, CATEGORY_ARITHMETIC, ADD, SUBTRACT, MULTIPLY, DIVIDE, CATEGORY_BOOLEAN, AND, OR, XOR } m_SelectedOperation; }; #endif // !defined(QmitkBasicImageProcessing_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp index e261421d69..e517f2549c 100755 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp @@ -1,357 +1,356 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFunctionality.h" #include "internal/QmitkFunctionalityUtil.h" // other includes #include // mitk Includes #include #include // berry Includes #include #include #include // Qmitk Includes #include // Qt Includes #include #include #include #include QmitkFunctionality::QmitkFunctionality() : m_Parent(0) , m_Active(false) , m_Visible(false) , m_SelectionProvider(0) , m_HandlesMultipleDataStorages(false) , m_InDataStorageChanged(false) { m_PreferencesService = berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); } void QmitkFunctionality::SetHandleMultipleDataStorages(bool multiple) { m_HandlesMultipleDataStorages = multiple; } bool QmitkFunctionality::HandlesMultipleDataStorages() const { return m_HandlesMultipleDataStorages; } mitk::DataStorage::Pointer QmitkFunctionality::GetDataStorage() const { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); if (service.IsNotNull()) { if (m_HandlesMultipleDataStorages) return service->GetActiveDataStorage()->GetDataStorage(); else return service->GetDefaultDataStorage()->GetDataStorage(); } return 0; } mitk::DataStorage::Pointer QmitkFunctionality::GetDefaultDataStorage() const { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); return service->GetDefaultDataStorage()->GetDataStorage(); } void QmitkFunctionality::CreatePartControl(void* parent) { // scrollArea QScrollArea* scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); QVBoxLayout* parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkFunctionality::AfterCreateQtPartControl() { // REGISTER DATASTORAGE LISTENER this->GetDefaultDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeAddedProxy ) ); this->GetDefaultDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeChangedProxy ) ); this->GetDefaultDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) prefs->OnChanged.AddListener(berry::MessageDelegate1(this, &QmitkFunctionality::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS m_BlueBerrySelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter(this , &QmitkFunctionality::BlueBerrySelectionChanged)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_BlueBerrySelectionListener); // REGISTER A SELECTION PROVIDER QmitkFunctionalitySelectionProvider::Pointer _SelectionProvider = QmitkFunctionalitySelectionProvider::New(this); m_SelectionProvider = _SelectionProvider.GetPointer(); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(m_SelectionProvider)); // EMULATE INITIAL SELECTION EVENTS // by default a a multi widget is always available this->StdMultiWidgetAvailable(*this->GetActiveStdMultiWidget()); // send datamanager selection this->OnSelectionChanged(this->GetDataManagerSelection()); // send preferences changed event this->OnPreferencesChanged(this->GetPreferences().Cast().GetPointer()); } void QmitkFunctionality::ClosePart() { } void QmitkFunctionality::ClosePartProxy() { this->GetDefaultDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeAddedProxy ) ); this->GetDefaultDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeRemovedProxy) ); this->GetDefaultDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeChangedProxy ) ); berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) { prefs->OnChanged.RemoveListener(berry::MessageDelegate1(this, &QmitkFunctionality::OnPreferencesChanged)); // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) // prefs->Flush(); } // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(NULL)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(m_BlueBerrySelectionListener); } this->ClosePart(); } QmitkFunctionality::~QmitkFunctionality() { this->Register(); this->ClosePartProxy(); this->UnRegister(false); } void QmitkFunctionality::OnPreferencesChanged( const berry::IBerryPreferences* ) { } void QmitkFunctionality::BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection) { if(sourcepart.IsNull() || sourcepart->GetSite()->GetId() != "org.mitk.views.datamanager") return; mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); this->OnSelectionChanged(this->DataNodeSelectionToVector(_DataNodeSelection)); } bool QmitkFunctionality::IsVisible() const { return m_Visible; } void QmitkFunctionality::SetFocus() { } void QmitkFunctionality::Activated() { } void QmitkFunctionality::Deactivated() { } void QmitkFunctionality::StdMultiWidgetAvailable( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { } void QmitkFunctionality::StdMultiWidgetNotAvailable() { } void QmitkFunctionality::DataStorageChanged() { } QmitkStdMultiWidget* QmitkFunctionality::GetActiveStdMultiWidget( bool reCreateWidget ) { QmitkStdMultiWidget* activeStdMultiWidget = 0; berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->GetActiveEditor(); if (editor.Cast().IsNotNull()) { activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } else if (reCreateWidget) { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput( service->GetActiveDataStorage() ); // open a new multi-widget editor, but do not give it the focus berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false); activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } return activeStdMultiWidget; } void QmitkFunctionality::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkFunctionality::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkFunctionality::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { } void QmitkFunctionality::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkFunctionality::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkFunctionality::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkFunctionality::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkFunctionality::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } berry::IPreferences::Pointer QmitkFunctionality::GetPreferences() const { berry::IPreferencesService::Pointer prefService = m_PreferencesService.Lock(); // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const std::string id = "/" + (const_cast(this))->GetViewSite()->GetId(); return prefService.IsNotNull() ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(0); } void QmitkFunctionality::Visible() { } void QmitkFunctionality::Hidden() { } bool QmitkFunctionality::IsExclusiveFunctionality() const { return true; } void QmitkFunctionality::SetVisible( bool visible ) { m_Visible = visible; } void QmitkFunctionality::SetActivated( bool activated ) { m_Active = activated; } bool QmitkFunctionality::IsActivated() const { return m_Active; } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h index 97e072497b..7ccd7fa325 100755 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h @@ -1,397 +1,396 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKFUNCTIONALITY_H_ #define QMITKFUNCTIONALITY_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif //# blueberry stuff #include #include #include #include //# mitk stuff #include #include "mitkDataNodeSelection.h" #include #include //# forward declarations namespace mitk { class DataNode; } namespace berry { struct IBerryPreferences; } class QmitkFunctionalitySelectionProvider; /// /// \ingroup org_mitk_gui_qt_common_legacy /// /// \class QmitkFunctionality /// /// \brief The base class of all MITK related blueberry views (~ in the old version of MITK, this was called "Functionality") /// /// QmitkFunctionality provides several convenience methods that eases the introduction of a new view: /// ///
    ///
  1. Access to the DataStorage (~ the shared data repository) ///
  2. Access to the StdMultiWidget (the 2x2 RenderWindow arrangement) ///
  3. Access to and update notification for the functionality/view preferences ///
  4. Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService ///
  5. Methods to send DataNode selections through the SelectionService ///
  6. Some events for unproblematic inter-View communication (e.g. when to add/remove interactors) ///
  7. Some minor important convenience methods (like changing the mouse cursor/exception handling) ///
/// /// Please use the Activated/Deactivated method to add/remove interactors, disabling multiwidget crosshair or anything which may /// "affect" other functionalities. For further reading please have a look at QmitkFunctionality::IsExclusiveFunctionality(). /// class MITK_QT_COMMON_LEGACY QmitkFunctionality : public berry::QtViewPart { //# public virtual methods which can be overwritten public: /// /// Creates smartpointer typedefs /// berryObjectMacro(QmitkFunctionality) /// /// Nothing to do in the standard ctor. Initiliaze your GUI in CreateQtPartControl(QWidget*) /// \see berry::QtViewPart::CreateQtPartControl(QWidget*) /// QmitkFunctionality(); /// /// Disconnects all standard event listeners /// virtual ~QmitkFunctionality(); /// /// Called, when the WorkbenchPart gets closed /// by the user directly or by closing the whole /// app (e.g. for removing event listeners) /// virtual void ClosePart(); /// /// Called when the selection in the workbench changed /// virtual void OnSelectionChanged(std::vector /*nodes*/); /// /// Called when the preferences object of this view changed. /// \see GetPreferences() /// virtual void OnPreferencesChanged(const berry::IBerryPreferences*); /// /// Make this view manage multiple DataStorage. If set to true GetDataStorage() /// will return the currently active DataStorage (and not the default one). /// \see GetDataStorage() /// void SetHandleMultipleDataStorages(bool multiple); /// /// \return true if this view handles multiple DataStorages, false otherwise /// bool HandlesMultipleDataStorages() const; /// /// Called when a StdMultiWidget is available. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when a StdMultiWidget is available. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetClosed(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available anymore. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetNotAvailable(); /// /// Only called when IsExclusiveFunctionality() returns true. /// \see IsExclusiveFunctionality() /// virtual void Activated(); /// /// \return true if this view is currently activated, false otherwise /// bool IsActivated() const; /// /// Only called when IsExclusiveFunctionality() returns true. /// \see IsExclusiveFunctionality() /// virtual void Deactivated(); /// /// Some functionalities need to add special interactors, removes the crosshair from the stdmultiwidget, etc. /// In this case the functionality has to tidy up when changing to another functionality /// which also wants to change the "default configuration". In the old Qt3-based /// version of MITK, two functionalities could never be opened at the same time so that the /// methods Activated() and Deactivated() were the right place for the functionalitites to /// add/remove their interactors, etc. This is still true for the new MITK Workbench, /// but as there can be several functionalities visible at the same time, the behaviour concerning /// when Activated() and Deactivated() are called has changed: /// /// 1. Activated() and Deactivated() are only called if IsExclusiveFunctionality() returns true /// /// 2. If only one standalone functionality is or becomes visible, Activated() will be called on that functionality /// /// 3. If two or more standalone functionalities are visible, /// Activated() will be called on the functionality that receives focus, Deactivated() will be called /// on the one that looses focus, gets hidden or closed /// /// /// As a consequence of 1. if you overwrite IsExclusiveFunctionality() and let it return false, you /// signalize the MITK Workbench that this functionality does nothing to the "default configuration" /// and can easily be visible while other functionalities are also visible. /// /// By default the method returns true. /// /// \return true if this functionality is meant to work as a standalone view, false otherwise /// virtual bool IsExclusiveFunctionality() const; /// /// Informs other parts of the workbench that node is selected via the blueberry selection service. /// void FireNodeSelected(mitk::DataNode* node); /// /// Informs other parts of the workbench that the nodes are selected via the blueberry selection service. /// void FireNodesSelected(std::vector nodes); /// /// Called when this functionality becomes visible ( no matter what IsExclusiveFunctionality() returns ) /// virtual void Visible(); /// /// \return true if this view is currently visible, false otherwise /// bool IsVisible() const; /// /// Called when this functionality is hidden ( no matter what IsExclusiveFunctionality() returns ) /// virtual void Hidden(); //# protected virtual methods which can be overwritten protected: /// /// Called when a DataStorage Add event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeAdded(const mitk::DataNode* node); /// /// Called when a DataStorage Changed event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeChanged(const mitk::DataNode* /*node*/); /// /// Called when a DataStorage Remove event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeRemoved(const mitk::DataNode* node); /// /// Called when a DataStorage add *or* remove *or* change event was thrown. May be reimplemented /// by deriving classes. /// virtual void DataStorageChanged(); /// /// \return the selection of the currently active part of the workbench or an empty vector /// if nothing is selected /// std::vector GetCurrentSelection() const; /// /// Returns the current selection made in the datamanager bundle or an empty vector /// if nothing`s selected or if the bundle does not exist /// std::vector GetDataManagerSelection() const; /// /// Returns the Preferences object for this Functionality. /// Important: When refering to this preferences, e.g. in a PreferencePage: The ID /// for this preferences object is "/", e.g. "/org.mitk.views.datamanager" /// berry::IPreferences::Pointer GetPreferences() const; /// /// Returns the default or the currently active DataStorage if m_HandlesMultipleDataStorages /// is set to true /// \see SetHandleMultipleDataStorages(bool) /// \see HandlesMultipleDataStorages() /// mitk::DataStorage::Pointer GetDataStorage() const; /// /// \return always returns the default DataStorage /// mitk::DataStorage::Pointer GetDefaultDataStorage() const; /// /// Returns the default and active StdMultiWidget. /// \param reCreateWidget a boolean flag to en-/disable the attept to re-create the StdWidget /// If there is not StdMultiWidget yet a new one is /// created in this method when called with default parameter! /// QmitkStdMultiWidget* GetActiveStdMultiWidget( bool reCreateWidget = true); /// /// Outputs an error message to the console and displays a message box containing /// the exception description. /// \param e the exception which should be handled /// \param showDialog controls, whether additionally a message box should be /// displayed to inform the user that something went wrong /// void HandleException( std::exception& e, QWidget* parent = NULL, bool showDialog = true ) const; /// /// Calls HandleException ( std::exception&, QWidget*, bool ) internally /// \see HandleException ( std::exception&, QWidget*, bool ) /// void HandleException( const char* str, QWidget* parent = NULL, bool showDialog = true ) const; /// /// Convenient method to set and reset a wait cursor ("hourglass") /// void WaitCursorOn(); /// /// Convenient method to restore the standard cursor /// void WaitCursorOff(); /// /// Convenient method to set and reset a busy cursor /// void BusyCursorOn(); /// /// Convenient method to restore the standard cursor /// void BusyCursorOff(); /// /// Convenient method to restore the standard cursor /// void RestoreOverrideCursor(); //# other public methods which should not be overwritten public: /// /// Creates a scroll area for this view and calls CreateQtPartControl then /// void CreatePartControl(void* parent); /// /// Called when this view receives the focus. Same as Activated() /// \see Activated() /// void SetFocus(); /// /// Called when a DataStorage Add Event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeAdded afterwards. /// \see m_InDataStorageChanged /// void NodeAddedProxy(const mitk::DataNode* node); /// /// Called when a DataStorage remove event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeRemoved afterwards. /// \see m_InDataStorageChanged /// void NodeRemovedProxy(const mitk::DataNode* node); /// /// Called when a DataStorage changed event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeChanged afterwards. /// \see m_InDataStorageChanged /// void NodeChangedProxy(const mitk::DataNode* node); /// /// Toggles the visible flag m_Visible /// void SetVisible(bool visible); /// /// Toggles the activated flag m_Activated /// void SetActivated(bool activated); /// /// Called, when the WorkbenchPart gets closed for removing event listeners /// Internally this method calls ClosePart after it removed the listeners registered /// by QmitkFunctionality. By having this proxy method the user does not have to /// call QmitkFunctionality::ClosePart() when overwriting ClosePart() /// void ClosePartProxy(); //# other protected methods which should not be overwritten (or which are deprecated) protected: /// /// Called immediately after CreateQtPartControl(). /// Here standard event listeners for a QmitkFunctionality are registered /// void AfterCreateQtPartControl(); /// /// code to activate the last visible functionality /// void ActivateLastVisibleFunctionality(); /// /// reactions to selection events from data manager (and potential other senders) /// void BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection); /// /// Converts a mitk::DataNodeSelection to a std::vector (possibly empty /// std::vector DataNodeSelectionToVector(mitk::DataNodeSelection::ConstPointer currentSelection) const; //# protected fields protected: /// /// helper stuff to observe BlueBerry selections /// friend struct berry::SelectionChangedAdapter; /// /// Saves the parent of this view (this is the scrollarea created in CreatePartControl(void*) /// \see CreatePartControl(void*) /// QWidget* m_Parent; /// /// Saves if this view is the currently active one. /// bool m_Active; /// /// Saves if this view is visible /// bool m_Visible; //# private fields: private: /// /// Holds the current selection (selection made by this Functionality !!!) /// QmitkFunctionalitySelectionProvider* m_SelectionProvider; /// /// object to observe BlueBerry selections /// berry::ISelectionListener::Pointer m_BlueBerrySelectionListener; /// /// Saves if this view handles multiple datastorages /// bool m_HandlesMultipleDataStorages; /// /// Saves if this class is currently working on DataStorage changes. /// This is a protector variable to avoid recursive calls on event listener functions. bool m_InDataStorageChanged; /// /// saves all visible functionalities /// std::set m_VisibleFunctionalities; /// /// The Preferences Service to retrieve and store preferences. /// berry::IPreferencesService::WeakPtr m_PreferencesService; }; #endif /*QMITKFUNCTIONALITY_H_*/ diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality2.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality2.cpp index 20d2b22647..166627cb56 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality2.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality2.cpp @@ -1,143 +1,142 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFunctionality.h" #include "internal/QmitkFunctionalityUtil.h" #include #include #include std::vector QmitkFunctionality::GetCurrentSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection()); // buffer for the data manager selection mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return this->DataNodeSelectionToVector(currentSelection); } std::vector QmitkFunctionality::GetDataManagerSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); // buffer for the data manager selection mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return this->DataNodeSelectionToVector(currentSelection); } void QmitkFunctionality::OnSelectionChanged(std::vector /*nodes*/) { } std::vector QmitkFunctionality::DataNodeSelectionToVector(mitk::DataNodeSelection::ConstPointer currentSelection) const { std::vector selectedNodes; if(currentSelection.IsNull()) return selectedNodes; mitk::DataNodeObject* _DataNodeObject = 0; mitk::DataNode* _DataNode = 0; for(mitk::DataNodeSelection::iterator it = currentSelection->Begin(); it != currentSelection->End(); ++it) { _DataNodeObject = dynamic_cast((*it).GetPointer()); if(_DataNodeObject) { _DataNode = _DataNodeObject->GetDataNode(); if(_DataNode) selectedNodes.push_back(_DataNode); } } return selectedNodes; } void QmitkFunctionality::NodeAddedProxy( const mitk::DataNode* node ) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; this->NodeAdded(node); this->DataStorageChanged(); m_InDataStorageChanged = false; } } void QmitkFunctionality::NodeAdded( const mitk::DataNode* /*node*/ ) { } void QmitkFunctionality::NodeRemovedProxy( const mitk::DataNode* node ) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; this->NodeRemoved(node); this->DataStorageChanged(); m_InDataStorageChanged = false; } } void QmitkFunctionality::NodeRemoved( const mitk::DataNode* /*node*/ ) { } void QmitkFunctionality::NodeChanged( const mitk::DataNode* /*node*/ ) { } void QmitkFunctionality::NodeChangedProxy( const mitk::DataNode* node ) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; this->NodeChanged(node); this->DataStorageChanged(); m_InDataStorageChanged = false; } } void QmitkFunctionality::FireNodeSelected( mitk::DataNode* node ) { std::vector nodes; nodes.push_back(node); this->FireNodesSelected(nodes); } void QmitkFunctionality::FireNodesSelected( std::vector nodes ) { if( !m_SelectionProvider ) return; std::vector nodesSmartPointers; for (std::vector::iterator it = nodes.begin() ; it != nodes.end(); it++) { nodesSmartPointers.push_back( *it ); } m_SelectionProvider->FireNodesSelected(nodesSmartPointers); } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp index 691f0904bb..191471fe00 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp @@ -1,223 +1,222 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFunctionalityCoordinator.h" #include "QmitkFunctionality.h" #include #include #include #include QmitkFunctionalityCoordinator::QmitkFunctionalityCoordinator() : m_StandaloneFuntionality(0) { } void QmitkFunctionalityCoordinator::Start() { berry::PlatformUI::GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this)); std::vector wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); for (std::vector::iterator i = wnds.begin(); i != wnds.end(); ++i) { (*i)->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); } } void QmitkFunctionalityCoordinator::Stop() { if (!berry::PlatformUI::IsWorkbenchRunning()) return; berry::PlatformUI::GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this)); std::vector wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); for (std::vector::iterator i = wnds.begin(); i != wnds.end(); ++i) { (*i)->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this)); } } QmitkFunctionalityCoordinator::~QmitkFunctionalityCoordinator() { } berry::IPartListener::Events::Types QmitkFunctionalityCoordinator::GetPartEventTypes() const { return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED; } void QmitkFunctionalityCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef ) { // change the active standalone functionality this->ActivateStandaloneFunctionality(partRef.GetPointer()); } void QmitkFunctionalityCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer /*partRef*/ ) { // nothing to do here: see PartActivated() } void QmitkFunctionalityCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef ) { // check for multiwidget and inform views that it is available now if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { for (std::set::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetAvailable(*(partRef ->GetPart(false).Cast()->GetStdMultiWidget())); } } else { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality.IsNotNull()) { m_Functionalities.insert(_QmitkFunctionality.GetPointer()); // save as opened functionality } } } void QmitkFunctionalityCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) { // check for multiwidget and inform views that it not available any more if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); for (std::set::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetClosed(*(stdMultiWidgetEditor->GetStdMultiWidget())); (*it)->StdMultiWidgetNotAvailable(); // deprecated call, provided for consistence } } else { // check for functionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality.IsNotNull()) { // deactivate on close ( the standalone functionality may still be activated ) this->DeactivateStandaloneFunctionality(partRef.GetPointer(), 0); // and set pointer to 0 if(m_StandaloneFuntionality == partRef.GetPointer()) m_StandaloneFuntionality = 0; m_Functionalities.erase(_QmitkFunctionality.GetPointer()); // remove as opened functionality // call PartClosed on the QmitkFunctionality _QmitkFunctionality->ClosePartProxy(); //m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // remove if necessary (should be done before in PartHidden() } } } void QmitkFunctionalityCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality != 0) { _QmitkFunctionality->SetVisible(false); _QmitkFunctionality->Hidden(); // tracking of Visible Standalone Functionalities m_VisibleStandaloneFunctionalities.erase(partRef.GetPointer()); // activate Functionality if just one Standalone Functionality is visible if( m_VisibleStandaloneFunctionalities.size() == 1 ) this->ActivateStandaloneFunctionality( *m_VisibleStandaloneFunctionalities.begin() ); } } void QmitkFunctionalityCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality.IsNotNull()) { _QmitkFunctionality->SetVisible(true); _QmitkFunctionality->Visible(); // tracking of Visible Standalone Functionalities if( _QmitkFunctionality->IsExclusiveFunctionality() ) { m_VisibleStandaloneFunctionalities.insert(partRef.GetPointer()); // activate Functionality if just one Standalone Functionality is visible if( m_VisibleStandaloneFunctionalities.size() == 1 ) this->ActivateStandaloneFunctionality( *m_VisibleStandaloneFunctionalities.begin() ); } } } void QmitkFunctionalityCoordinator::ActivateStandaloneFunctionality( berry::IWorkbenchPartReference* partRef ) { QmitkFunctionality* functionality = dynamic_cast(partRef->GetPart(false).GetPointer()); if( functionality && !functionality->IsActivated() && functionality->IsExclusiveFunctionality() ) { MITK_INFO << "**** Activating legacy standalone functionality"; // deactivate old one if necessary this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality, partRef); m_StandaloneFuntionality = partRef; MITK_INFO << "setting active flag"; // call activated on this functionality functionality->SetActivated(true); functionality->Activated(); } else if (dynamic_cast(partRef->GetPart(false).GetPointer()) && m_StandaloneFuntionality != partRef) { this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality, partRef); m_StandaloneFuntionality = partRef; } } void QmitkFunctionalityCoordinator::DeactivateStandaloneFunctionality(berry::IWorkbenchPartReference* partRef, berry::IWorkbenchPartReference* newRef) { if (partRef == 0) return; QmitkFunctionality* functionality = dynamic_cast(partRef->GetPart(false).GetPointer()); if(functionality && functionality->IsActivated()) { functionality->SetActivated(false); functionality->Deactivated(); } else if (mitk::IZombieViewPart* zombie = dynamic_cast(partRef->GetPart(false).GetPointer())) { zombie->ActivatedZombieView(berry::IWorkbenchPartReference::Pointer(newRef)); } } void QmitkFunctionalityCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer /*window*/ ) { } void QmitkFunctionalityCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window ) { window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h index 528e7180ec..a3e4862209 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h @@ -1,124 +1,123 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-01-16 19:57:43 +0100 (Sa, 16 Jan 2010) $ -Version: $Revision: 21070 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkFunctionalityCoordinator_h #define QmitkFunctionalityCoordinator_h #include #include #include #include #include class QmitkFunctionality; /// /// \ingroup org_mitk_gui_qt_common_legacy /// /// A class which coordinates active QmitkFunctionalities, e.g. calling activated and hidden on them. /// class MITK_QT_COMMON_LEGACY QmitkFunctionalityCoordinator : virtual public berry::IPartListener, virtual public berry::IWindowListener { public: berryObjectMacro(QmitkFunctionalityCoordinator); berryNewMacro(QmitkFunctionalityCoordinator); QmitkFunctionalityCoordinator(); virtual ~QmitkFunctionalityCoordinator(); /// /// Add listener /// void Start(); /// /// Remove listener /// void Stop(); //#IPartListener methods (these methods internally call Activated() or other similar methods) /// /// \see IPartListener::GetPartEventTypes() /// berry::IPartListener::Events::Types GetPartEventTypes() const; /// /// \see IPartListener::PartActivated() /// virtual void PartActivated (berry::IWorkbenchPartReference::Pointer partRef); /// /// \see IPartListener::PartDeactivated() /// virtual void PartDeactivated(berry::IWorkbenchPartReference::Pointer /*partRef*/); /// /// \see IPartListener::PartOpened() /// virtual void PartOpened(berry::IWorkbenchPartReference::Pointer partRef); /// /// \see IPartListener::PartClosed() /// virtual void PartClosed (berry::IWorkbenchPartReference::Pointer partRef); /// /// \see IPartListener::PartHidden() /// virtual void PartHidden (berry::IWorkbenchPartReference::Pointer partRef); /// /// \see IPartListener::PartVisible() /// virtual void PartVisible (berry::IWorkbenchPartReference::Pointer partRef); /** * Notifies this listener that the given window has been closed. */ virtual void WindowClosed(berry::IWorkbenchWindow::Pointer window); /** * Notifies this listener that the given window has been opened. */ virtual void WindowOpened(berry::IWorkbenchWindow::Pointer /*window*/); protected: /// /// Activates the standalone functionality /// void ActivateStandaloneFunctionality(berry::IWorkbenchPartReference *partRef); /// /// Deactivates the standalone functionality /// void DeactivateStandaloneFunctionality(berry::IWorkbenchPartReference *functionality, berry::IWorkbenchPartReference *newRef); /// /// Saves the workbench window /// berry::IWorkbenchWindow::WeakPtr m_Window; /// /// Saves the last part that added interactors /// berry::IWorkbenchPartReference* m_StandaloneFuntionality; /// /// Saves all opened QmitkFclassunctionalities /// std::set m_Functionalities; /// /// Saves all visible QmitkFunctionalities /// std::set m_VisibleStandaloneFunctionalities; }; #endif // QmitkFunctionalityCoordinator_h diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp index 5f2a25d2a0..81ac1b1f3d 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkCommonLegacyActivator.h" #include #include #include void QmitkCommonLegacyActivator::start(ctkPluginContext* context) { Q_UNUSED(context) if(berry::PlatformUI::IsWorkbenchRunning()) { m_FunctionalityCoordinator = QmitkFunctionalityCoordinator::Pointer(new QmitkFunctionalityCoordinator); m_FunctionalityCoordinator->Start(); } else { MITK_ERROR << "BlueBerry Workbench not running!"; } } void QmitkCommonLegacyActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_FunctionalityCoordinator->Stop(); m_FunctionalityCoordinator = 0; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_common_legacy, QmitkCommonLegacyActivator) diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h index c841521baa..13eed01eec 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h @@ -1,49 +1,48 @@ -/*========================================================================= +/*=================================================================== - Program: MITK Platform - Language: C++ - Date: $Date$ - Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKCOMMONLEGACYACTIVATOR_H_ #define QMITKCOMMONLEGACYACTIVATOR_H_ #include #include "QmitkFunctionalityCoordinator.h" /** * \ingroup org_mitk_gui_qt_common_legacy_internal */ class QmitkCommonLegacyActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: /** * Sets default StateMachine to EventMapper. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: QmitkFunctionalityCoordinator::Pointer m_FunctionalityCoordinator; }; #endif /* QMITKCOMMONLEGACYACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp index c68c518b0a..7dbf17ea06 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp @@ -1,63 +1,62 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFunctionalityUtil.h" #include "../QmitkFunctionality.h" QmitkFunctionalitySelectionProvider::QmitkFunctionalitySelectionProvider( QmitkFunctionality* _Functionality ) : m_Functionality(_Functionality) { } QmitkFunctionalitySelectionProvider::~QmitkFunctionalitySelectionProvider() { m_Functionality = 0; } void QmitkFunctionalitySelectionProvider::AddSelectionChangedListener( berry::ISelectionChangedListener::Pointer listener ) { m_SelectionEvents.AddListener(listener); } berry::ISelection::ConstPointer QmitkFunctionalitySelectionProvider::GetSelection() const { return m_CurrentSelection; } void QmitkFunctionalitySelectionProvider::RemoveSelectionChangedListener( berry::ISelectionChangedListener::Pointer listener ) { m_SelectionEvents.RemoveListener(listener); } void QmitkFunctionalitySelectionProvider::SetSelection( berry::ISelection::Pointer selection ) { m_CurrentSelection = selection.Cast(); } void QmitkFunctionalitySelectionProvider::FireNodesSelected( std::vector nodes ) { mitk::DataNodeSelection::Pointer sel(new mitk::DataNodeSelection(nodes)); m_CurrentSelection = sel; berry::SelectionChangedEvent::Pointer event(new berry::SelectionChangedEvent(berry::ISelectionProvider::Pointer(this) , m_CurrentSelection)); m_SelectionEvents.selectionChanged(event); } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h index 1f2bdcc48e..b4b9545199 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h @@ -1,92 +1,91 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKFUNCTIONALITYUTIL_H #define QMITKFUNCTIONALITYUTIL_H #include class QmitkFunctionality; #include #include /// /// Internal class for selection providing /// class QmitkFunctionalitySelectionProvider: public berry::ISelectionProvider { public: /// /// Creates smartpointer typedefs /// berryObjectMacro(QmitkFunctionalitySelectionProvider) /// /// Create a selection provider for the given _Functionality /// berryNewMacro1Param(QmitkFunctionalitySelectionProvider, QmitkFunctionality*) //# ISelectionProvider methods /// /// \see ISelectionProvider::AddSelectionChangedListener() /// virtual void AddSelectionChangedListener(berry::ISelectionChangedListener::Pointer listener); /// /// \see ISelectionProvider::GetSelection() /// virtual berry::ISelection::ConstPointer GetSelection() const; /// /// \see ISelectionProvider::RemoveSelectionChangedListener() /// virtual void RemoveSelectionChangedListener(berry::ISelectionChangedListener::Pointer listener); /// /// \see ISelectionProvider::SetSelection() /// virtual void SetSelection(berry::ISelection::Pointer selection); /// /// Sends the nodes as selected to the workbench /// void FireNodesSelected( std::vector nodes ); protected: /// /// nothing to do here /// QmitkFunctionalitySelectionProvider(QmitkFunctionality* _Functionality); /// /// nothing to do here /// virtual ~QmitkFunctionalitySelectionProvider(); /// /// the functionality parent /// QmitkFunctionality* m_Functionality; /// /// Holds the current selection (selection made by m_Functionality !!!) /// mitk::DataNodeSelection::Pointer m_CurrentSelection; /// /// The selection events other parts can listen too /// berry::ISelectionChangedListener::Events m_SelectionEvents; }; #endif // QMITKFUNCTIONALITYUTIL_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp index 202dddc085..fff46ace90 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.cpp @@ -1,147 +1,146 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkAbstractRenderEditor.h" #include "internal/QmitkCommonActivator.h" #include #include #include #include #include class QmitkAbstractRenderEditorPrivate { public: QmitkAbstractRenderEditorPrivate() : m_RenderingManagerInterface(mitk::MakeRenderingManagerInterface(mitk::RenderingManager::GetInstance())) , m_PrefServiceTracker(QmitkCommonActivator::GetContext()) { m_PrefServiceTracker.open(); } ~QmitkAbstractRenderEditorPrivate() { delete m_RenderingManagerInterface; } mitk::IRenderingManager* m_RenderingManagerInterface; ctkServiceTracker m_PrefServiceTracker; berry::IBerryPreferences::Pointer m_Prefs; }; QmitkAbstractRenderEditor::QmitkAbstractRenderEditor() : d(new QmitkAbstractRenderEditorPrivate) { } QmitkAbstractRenderEditor::~QmitkAbstractRenderEditor() { if (d->m_Prefs.IsNotNull()) { d->m_Prefs->OnChanged.RemoveListener(berry::MessageDelegate1 (this, &QmitkAbstractRenderEditor::OnPreferencesChanged ) ); } } void QmitkAbstractRenderEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { if (input.Cast().IsNull()) throw berry::PartInitException("Invalid Input: Must be mitk::DataStorageEditorInput"); this->SetSite(site); this->SetInput(input); d->m_Prefs = this->GetPreferences().Cast(); if (d->m_Prefs.IsNotNull()) { d->m_Prefs->OnChanged.AddListener(berry::MessageDelegate1 (this, &QmitkAbstractRenderEditor::OnPreferencesChanged ) ); } } mitk::IDataStorageReference::Pointer QmitkAbstractRenderEditor::GetDataStorageReference() const { mitk::DataStorageEditorInput::Pointer input = this->GetEditorInput().Cast(); if (input.IsNotNull()) { return input->GetDataStorageReference(); } return mitk::IDataStorageReference::Pointer(0); } mitk::DataStorage::Pointer QmitkAbstractRenderEditor::GetDataStorage() const { mitk::IDataStorageReference::Pointer ref = this->GetDataStorageReference(); if (ref.IsNotNull()) return ref->GetDataStorage(); return mitk::DataStorage::Pointer(0); } berry::IPreferences::Pointer QmitkAbstractRenderEditor::GetPreferences() const { berry::IPreferencesService* prefService = d->m_PrefServiceTracker.getService(); if (prefService != 0) { return prefService->GetSystemPreferences()->Node(this->GetSite()->GetId()); } return berry::IPreferences::Pointer(0); } mitk::IRenderingManager* QmitkAbstractRenderEditor::GetRenderingManager() const { // we use the global rendering manager here. This should maybe replaced // by a local one, managing only the render windows specific for the editor return d->m_RenderingManagerInterface; } void QmitkAbstractRenderEditor::RequestUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->RequestUpdateAll(requestType); } void QmitkAbstractRenderEditor::ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType) { if (GetRenderingManager()) GetRenderingManager()->ForceImmediateUpdateAll(requestType); } mitk::SliceNavigationController* QmitkAbstractRenderEditor::GetTimeNavigationController() const { if (GetRenderingManager()) return GetRenderingManager()->GetTimeNavigationController(); return 0; } void QmitkAbstractRenderEditor::OnPreferencesChanged(const berry::IBerryPreferences *) {} void QmitkAbstractRenderEditor::DoSave() {} void QmitkAbstractRenderEditor::DoSaveAs() {} bool QmitkAbstractRenderEditor::IsDirty() const { return false; } bool QmitkAbstractRenderEditor::IsSaveAsAllowed() const { return false; } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h index 4af4a520ca..74a1168caa 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h @@ -1,158 +1,157 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKABSTRACTRENDEREDITOR_H #define QMITKABSTRACTRENDEREDITOR_H #include #include #include "mitkIRenderWindowPart.h" #include #include #include class QmitkAbstractRenderEditorPrivate; /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK render window BlueBerry Editors. * * QmitkAbstractRenderEditor provides several convenience methods that ease the introduction of * a new editor for rendering a MITK DataStorage: * *
    *
  1. Access to the DataStorage (~ the shared data repository) *
  2. Access to and update notification for the editor's preferences *
  3. Default implementation of some mitk::IRenderWindowPart methods *
* * When inheriting from QmitkAbstractRenderEditor, you must implement the following methods: *
    *
  • void CreateQtPartControl(QWidget* parent) *
  • void SetFocus() *
* * You may reimplement the following private virtual methods to be notified about certain changes: *
    *
  • void OnPreferencesChanged(const berry::IBerryPreferences*) *
* * \see IRenderWindowPart * \see ILinkedRenderWindowPart */ class MITK_QT_COMMON QmitkAbstractRenderEditor : public berry::QtEditorPart, public virtual mitk::IRenderWindowPart { Q_OBJECT Q_INTERFACES(mitk::IRenderWindowPart) public: QmitkAbstractRenderEditor(); ~QmitkAbstractRenderEditor(); protected: /** * Initializes this editor by checking for a valid mitk::DataStorageEditorInput as input. * * \see berry::IEditorPart::Init */ void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input); /** * Get a reference to the DataStorage set by the editor input. */ virtual mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Get the DataStorage set by the editor input. */ virtual mitk::DataStorage::Pointer GetDataStorage() const; /** * Get the preferences for this editor. */ virtual berry::IPreferences::Pointer GetPreferences() const; /** * Get the RenderingManager used by this editor. This default implementation uses the * global MITK RenderingManager provided by mitk::RenderingManager::GetInstance(). * * \see mitk::IRenderWindowPart::GetRenderingManager */ mitk::IRenderingManager* GetRenderingManager() const; /** * Request an update of this editor's render windows. * This implementation calls mitk::IRenderingManager::RequestUpdate on the rendering * manager interface returned by GetRenderingManager(); * * \param requestType The type of render windows for which an update is requested. * * \see mitk::IRenderWindowPart::RequestUpdate */ void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Force an immediate update of this editor's render windows. * This implementation calls mitk::IRenderingManager::ForceImmediateUpdate() on the rendering * manager interface returned by GetRenderingManager(); * * \param requestType The type of render windows for which an immedate update is forced. * * \see mitk::IRenderWindowPart::ForceImmediateUpdate */ void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Get the time navigation controller for this editor. * This implementation returns the SliceNavigationController returned by the mitk::IRenderingManager::GetTimeNavigationController() * method of the interface implementation returned by GetRenderingManager(). * * \see mitk::IRenderingManager::GetTimeNavigationController */ mitk::SliceNavigationController* GetTimeNavigationController() const; /** \see berry::IEditorPart::DoSave */ void DoSave(); /** \see berry::IEditorPart::DoSaveAs */ void DoSaveAs(); /** \see berry::IEditorPart::IsDirty */ bool IsDirty() const; /** \see berry::IEditorPart::IsSaveAsAllowed */ bool IsSaveAsAllowed() const; private: virtual void OnPreferencesChanged(const berry::IBerryPreferences*); private: QScopedPointer d; }; #endif // QMITKABSTRACTRENDEREDITOR_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp index c230739aae..f6f72c9d89 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp @@ -1,559 +1,558 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkAbstractView.h" #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkCommonActivator.h" #include "internal/QmitkDataNodeItemModel.h" // mitk Includes #include #include #include #include #include #include // berry Includes #include #include #include // CTK Includes #include // Qt Includes #include #include #include #include #include class QmitkAbstractViewPrivate { public: QmitkAbstractViewPrivate(QmitkAbstractView* qq) : q(qq) , m_PrefServiceTracker(QmitkCommonActivator::GetContext()) , m_DataStorageServiceTracker(QmitkCommonActivator::GetContext()) , m_Parent(0) , m_DataNodeItemModel(new QmitkDataNodeItemModel) , m_DataNodeSelectionModel(new QItemSelectionModel(m_DataNodeItemModel)) , m_InDataStorageChanged(false) { m_PrefServiceTracker.open(); m_DataStorageServiceTracker.open(); } ~QmitkAbstractViewPrivate() { delete m_DataNodeSelectionModel; delete m_DataNodeItemModel; m_PrefServiceTracker.close(); m_DataStorageServiceTracker.close(); } /** * Called when a DataStorage Add Event was thrown. Sets * m_InDataStorageChanged to true and calls NodeAdded afterwards. * \see m_InDataStorageChanged */ void NodeAddedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeAdded(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage remove event was thrown. Sets * m_InDataStorageChanged to true and calls NodeRemoved afterwards. * \see m_InDataStorageChanged */ void NodeRemovedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeRemoved(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage changed event was thrown. Sets * m_InDataStorageChanged to true and calls NodeChanged afterwards. * \see m_InDataStorageChanged */ void NodeChangedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeChanged(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * reactions to selection events from views */ void BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection) { if(sourcepart.IsNull() || sourcepart.GetPointer() == static_cast(q)) return; mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); q->OnSelectionChanged(sourcepart, this->DataNodeSelectionToQList(_DataNodeSelection)); } /** * Converts a mitk::DataNodeSelection to a QList (possibly empty) */ QList DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const; QmitkAbstractView* const q; ctkServiceTracker m_PrefServiceTracker; ctkServiceTracker m_DataStorageServiceTracker; /** * Saves the parent of this view (this is the scrollarea created in CreatePartControl(void*) * \see CreatePartControl(void*) */ QWidget* m_Parent; /** * Holds the current selection (selection made by this View !!!) */ QmitkDataNodeSelectionProvider::Pointer m_SelectionProvider; /** * Holds a helper model for firing selection events. */ QmitkDataNodeItemModel* m_DataNodeItemModel; /** * The selection model for the QmitkDataNodeItemModel; */ QItemSelectionModel* m_DataNodeSelectionModel; /** * object to observe BlueBerry selections */ berry::ISelectionListener::Pointer m_BlueBerrySelectionListener; /** * Saves if this class is currently working on DataStorage changes. * This is a protector variable to avoid recursive calls on event listener functions. */ bool m_InDataStorageChanged; }; QmitkAbstractView::QmitkAbstractView() : d(new QmitkAbstractViewPrivate(this)) { } void QmitkAbstractView::CreatePartControl(void* parent) { // scrollArea QScrollArea* scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent d->m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(d->m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(d->m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); QVBoxLayout* parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkAbstractView::AfterCreateQtPartControl() { this->SetSelectionProvider(); // REGISTER DATASTORAGE LISTENER this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) prefs->OnChanged.AddListener( berry::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS d->m_BlueBerrySelectionListener = berry::ISelectionListener::Pointer( new berry::SelectionChangedAdapter(d.data(), &QmitkAbstractViewPrivate::BlueBerrySelectionChanged)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(d->m_BlueBerrySelectionListener); // EMULATE INITIAL SELECTION EVENTS // send the current selection berry::IWorkbenchPart::Pointer activePart = this->GetSite()->GetPage()->GetActivePart(); if (activePart.IsNotNull()) { this->OnSelectionChanged(activePart, this->GetCurrentSelection()); } // send preferences changed event this->OnPreferencesChanged(this->GetPreferences().Cast().GetPointer()); } QmitkAbstractView::~QmitkAbstractView() { this->Register(); this->GetDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy) ); this->GetDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) { prefs->OnChanged.RemoveListener( berry::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) // prefs->Flush(); } // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(NULL)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(d->m_BlueBerrySelectionListener); } this->UnRegister(false); } void QmitkAbstractView::SetSelectionProvider() { // REGISTER A SELECTION PROVIDER d->m_SelectionProvider = QmitkDataNodeSelectionProvider::Pointer(new QmitkDataNodeSelectionProvider); d->m_SelectionProvider->SetItemSelectionModel(GetDataNodeSelectionModel()); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(d->m_SelectionProvider)); } QItemSelectionModel *QmitkAbstractView::GetDataNodeSelectionModel() const { return d->m_DataNodeSelectionModel; } void QmitkAbstractView::OnPreferencesChanged( const berry::IBerryPreferences* ) { } void QmitkAbstractView::DataStorageModified() { } void QmitkAbstractView::DataStorageChanged(mitk::IDataStorageReference::Pointer /*dsRef*/) { } mitk::IRenderWindowPart* QmitkAbstractView::GetRenderWindowPart( IRenderWindowPartStrategies strategies ) const { berry::IWorkbenchPage::Pointer page = this->GetSite()->GetPage(); // Return the active editor if it implements mitk::IRenderWindowPart mitk::IRenderWindowPart* renderPart = dynamic_cast(page->GetActiveEditor().GetPointer()); if (renderPart) return renderPart; // No suitable active editor found, check visible editors std::list editors = page->GetEditorReferences(); for (std::list::iterator i = editors.begin(); i != editors.end(); ++i) { berry::IWorkbenchPart::Pointer part = (*i)->GetPart(false); if (page->IsPartVisible(part)) { renderPart = dynamic_cast(part.GetPointer()); if (renderPart) return renderPart; } } // No suitable visible editor found, check visible views std::vector views = page->GetViewReferences(); for(std::vector::iterator i = views.begin(); i != views.end(); ++i) { berry::IWorkbenchPart::Pointer part = (*i)->GetPart(false); if (page->IsPartVisible(part)) { renderPart = dynamic_cast(part.GetPointer()); if (renderPart) return renderPart; } } // No strategies given if (strategies == NONE) return 0; mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(GetDataStorageReference())); bool activate = false; if(strategies & ACTIVATE) { activate = true; } berry::IEditorPart::Pointer editorPart; if(strategies & OPEN) { // This will create a default editor for the given input. If an editor // with that input is already open, the editor is brought to the front. editorPart = mitk::WorkbenchUtil::OpenEditor(page, input, activate); } else if (activate || (strategies & BRING_TO_FRONT)) { // check if a suitable editor is already opened editorPart = page->FindEditor(input); if (activate) { page->Activate(editorPart); } else { page->BringToTop(editorPart); } } return dynamic_cast(editorPart.GetPointer()); } void QmitkAbstractView::RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType) { mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if (renderPart == 0) return; if (mitk::IRenderingManager* renderingManager = renderPart->GetRenderingManager()) { renderingManager->RequestUpdateAll(requestType); } else { renderPart->RequestUpdate(requestType); } } void QmitkAbstractView::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkAbstractView::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkAbstractView::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkAbstractView::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkAbstractView::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } berry::IPreferences::Pointer QmitkAbstractView::GetPreferences() const { berry::IPreferencesService* prefService = d->m_PrefServiceTracker.getService(); // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const std::string id = "/" + (const_cast(this))->GetViewSite()->GetId(); return prefService ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(0); } mitk::DataStorage::Pointer QmitkAbstractView::GetDataStorage() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != 0) { return dsService->GetDataStorage()->GetDataStorage(); } return 0; } mitk::IDataStorageReference::Pointer QmitkAbstractView::GetDataStorageReference() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != 0) { return dsService->GetDataStorage(); } return mitk::IDataStorageReference::Pointer(0); } QList QmitkAbstractView::GetCurrentSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection()); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } QList QmitkAbstractView::GetDataManagerSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } void QmitkAbstractView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& /*nodes*/) { } QList QmitkAbstractViewPrivate::DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const { QList selectedNodes; if(currentSelection.IsNull()) return selectedNodes; mitk::DataNodeObject::Pointer _DataNodeObject; mitk::DataNode::Pointer _DataNode; for(mitk::DataNodeSelection::iterator it = currentSelection->Begin(); it != currentSelection->End(); ++it) { _DataNodeObject = it->Cast(); if(_DataNodeObject.IsNotNull()) { _DataNode = _DataNodeObject->GetDataNode(); if(_DataNode.IsNotNull()) selectedNodes << _DataNode; } } return selectedNodes; } void QmitkAbstractView::NodeAdded( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeRemoved( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeChanged( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::FireNodeSelected( mitk::DataNode::Pointer node ) { QList nodes; nodes << node; this->FireNodesSelected(nodes); } void QmitkAbstractView::FireNodesSelected( const QList& nodes ) { if (nodes.empty()) { d->m_DataNodeSelectionModel->clearSelection(); d->m_DataNodeItemModel->clear(); return; } // The helper data node model is just used for sending selection events. // We add the to be selected nodes and set the selection range to everything. d->m_DataNodeItemModel->clear(); foreach(mitk::DataNode::Pointer node, nodes) { d->m_DataNodeItemModel->AddDataNode(node); } d->m_DataNodeSelectionModel->select(QItemSelection(d->m_DataNodeItemModel->index(0,0), d->m_DataNodeItemModel->index(nodes.size(), 0)), QItemSelectionModel::ClearAndSelect); } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h index b8e1d3c7ca..9c084146d3 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h @@ -1,341 +1,340 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKABSTRACTVIEW_H_ #define QMITKABSTRACTVIEW_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif //# blueberry stuff #include #include #include #include //# mitk stuff #include #include "mitkDataNodeSelection.h" #include "mitkIRenderWindowPart.h" #include #include #include class QItemSelectionModel; namespace mitk { class DataNode; } namespace berry { struct IBerryPreferences; } class QmitkAbstractViewPrivate; class QmitkAbstractViewSelectionProvider; /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK related BlueBerry Views. * * QmitkAbstractView provides several convenience methods that ease the introduction of a new view: * *
    *
  1. Access to the DataStorage (~ the shared data repository) *
  2. Access to the active IRenderWindowPart *
  3. Access to and update notification for the view's preferences *
  4. Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService *
  5. Access to and update notification for DataNode events (added/removed/modified) *
  6. Methods to send DataNode selections through the SelectionService *
  7. Some minor important convenience methods (like changing the mouse cursor/exception handling) *
* * Usually all MITK Views inherit from QmitkAbstractView to achieve a consistent Workbench behavior. * * When inheriting from QmitkAbstractView, you must implement the following methods: *
    *
  • void CreateQtPartControl(QWidget* parent) *
  • void SetFocus() *
* * You may reimplement the following private virtual methods to customize your View's behavior: *
    *
  • void SetSelectionProvider() *
  • QItemSelectionModel* GetDataNodeSelectionModel() const *
* * You may reimplement the following private virtual methods to be notified about certain changes: *
    *
  • void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) *
  • void OnPreferencesChanged(const berry::IBerryPreferences*) *
  • void NodeAdded(const mitk::DataNode* node) *
  • void NodeChanged(const mitk::DataNode* node) *
  • void NodeRemoved(const mitk::DataNode* node) *
  • void DataStorageModified() *
  • void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef) *
* * \see mitk::ILifecycleAwarePart * \see mitk::IZombieViewPart * \see mitk::IRenderWindowPartListener */ class MITK_QT_COMMON QmitkAbstractView : public berry::QtViewPart { public: /** * Describes the strategies to be used for getting a mitk::IRenderWindowPart * instance. */ enum IRenderWindowPartStrategy { /** Do nothing. */ NONE = 0x00000000, /** Bring the most recently activated mitk::IRenderWindowPart instance to the front. */ BRING_TO_FRONT = 0x00000001, /** Activate a mitk::IRenderWindowPart part (implies bringing it to the front). */ ACTIVATE = 0x00000002, /** Create a mitk::IRenderWindowPart if none is alredy opened. */ OPEN = 0x00000004 }; Q_DECLARE_FLAGS(IRenderWindowPartStrategies, IRenderWindowPartStrategy) /** * Creates smartpointer typedefs */ berryObjectMacro(QmitkAbstractView) /** * Nothing to do in the standard ctor. Initiliaze your GUI in CreateQtPartControl(QWidget*) * \see berry::QtViewPart::CreateQtPartControl(QWidget*) */ QmitkAbstractView(); /** * Disconnects all standard event listeners */ virtual ~QmitkAbstractView(); protected: /** * Informs other parts of the workbench that node is selected via the blueberry selection service. */ void FireNodeSelected(mitk::DataNode::Pointer node); /** * Informs other parts of the workbench that the nodes are selected via the blueberry selection service. */ virtual void FireNodesSelected(const QList& nodes); /** * \return the selection of the currently active part of the workbench or an empty list * if nothing is selected */ QList GetCurrentSelection() const; /** * Returns the current selection made in the datamanager bundle or an empty list * if nothing`s selected or if the data manager view does not exist */ QList GetDataManagerSelection() const; /** * Returns the Preferences object for this View. * Important: When refering to this preferences, e.g. in a PreferencePage: The ID * for this preferences object is "/", e.g. "/org.mitk.views.datamanager" */ berry::IPreferences::Pointer GetPreferences() const; /** * Returns a reference to the currently active DataStorage. */ mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Returns the currently active DataStorage. */ mitk::DataStorage::Pointer GetDataStorage() const; /** * Returns the currently active mitk::IRenderWindowPart. * * \param strategies Strategies for returning a mitk::IRenderWindowPart instance if there * is currently no active one. * \return The active mitk::IRenderWindowPart. */ mitk::IRenderWindowPart* GetRenderWindowPart(IRenderWindowPartStrategies strategies = NONE) const; /** * Request an update of all render windows of the currently active IRenderWindowPart. * * \param requestType Specifies the type of render windows for which an update * will be requested. */ void RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Outputs an error message to the console and displays a message box containing * the exception description. * \param e the exception which should be handled * \param showDialog controls, whether additionally a message box should be * displayed to inform the user that something went wrong */ void HandleException( std::exception& e, QWidget* parent = NULL, bool showDialog = true ) const; /** * Calls HandleException ( std::exception&, QWidget*, bool ) internally * \see HandleException ( std::exception&, QWidget*, bool ) */ void HandleException( const char* str, QWidget* parent = NULL, bool showDialog = true ) const; /** * Convenient method to set and reset a wait cursor ("hourglass") */ void WaitCursorOn(); /** * Convenient method to restore the standard cursor */ void WaitCursorOff(); /** * Convenient method to set and reset a busy cursor */ void BusyCursorOn(); /** * Convenient method to restore the standard cursor */ void BusyCursorOff(); /** * Convenient method to restore the standard cursor */ void RestoreOverrideCursor(); private: /** * Reimplement this method to set a custom selection provider. This method is * called once after CreateQtPartControl(). * * The default implementation registers a QmitkDataNodeSelectionProvider with * a QItemSelectionModel returned by GetDataNodeSelectionModel(). */ virtual void SetSelectionProvider(); /** * Reimplement this method to supply a custom Qt selection model. The custom * model will be used with the default selection provider QmitkDataNodeSelectionProvider * to inform the MITK Workbench about selection changes. * * If you reimplement this method, the methods FireNodeSelected() and FireNodesSelected() * will have no effect. Use your custom selection model to notify the MITK Workbench * about selection changes. * * The Qt item model used with the custom selection model must return mitk::DataNode::Pointer * objects for model indexes when the role is QmitkDataNodeRole. */ virtual QItemSelectionModel* GetDataNodeSelectionModel() const; /** * Called when the selection in the workbench changed. * May be reimplemented by deriving classes. * * \param part The source part responsible for the selection change. * \param nodes A list of selected nodes. */ virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes); /** * Called when the preferences object of this view changed. * May be reimplemented by deriving classes. * * \see GetPreferences() */ virtual void OnPreferencesChanged(const berry::IBerryPreferences*); /** * Called when a DataStorage Add event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeAdded(const mitk::DataNode* node); /** * Called when a DataStorage Changed event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeChanged(const mitk::DataNode* node); /** * Called when a DataStorage Remove event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeRemoved(const mitk::DataNode* node); /** * Called when a DataStorage add *or* remove *or* change event from the currently active * data storage is thrown. * * May be reimplemented by deriving classes. */ virtual void DataStorageModified(); /** * Called when the currently active DataStorage changed. * May be reimplemented by deriving classes. * * \param dsRef A reference to the new active DataStorage. */ virtual void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef); /** * Creates a scroll area for this view and calls CreateQtPartControl then */ void CreatePartControl(void* parent); /** * Called immediately after CreateQtPartControl(). * Here standard event listeners for a QmitkAbstractView are registered */ void AfterCreateQtPartControl(); private: friend class QmitkAbstractViewPrivate; friend class QmitkViewCoordinator; Q_DISABLE_COPY(QmitkAbstractView) const QScopedPointer d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QmitkAbstractView::IRenderWindowPartStrategies) #endif /*QMITKABSTRACTVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.cpp index f248179fd1..d8caaf21c6 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.cpp @@ -1,52 +1,51 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkDataNodeSelection.h" QmitkDataNodeSelectionProvider::QmitkDataNodeSelectionProvider() : berry::QtSelectionProvider() { } berry::ISelection::ConstPointer QmitkDataNodeSelectionProvider::GetSelection() const { return this->GetDataNodeSelection(); } mitk::DataNodeSelection::ConstPointer QmitkDataNodeSelectionProvider::GetDataNodeSelection() const { if (qSelectionModel) { QmitkDataNodeSelection::ConstPointer sel(new QmitkDataNodeSelection( qSelectionModel->selection())); return sel; } return QmitkDataNodeSelection::ConstPointer(new QmitkDataNodeSelection()); } void QmitkDataNodeSelectionProvider::FireSelectionChanged( const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { berry::ISelection::ConstPointer sel(this->GetDataNodeSelection()); berry::SelectionChangedEvent::Pointer event(new berry::SelectionChangedEvent( berry::ISelectionProvider::Pointer(this), sel)); selectionEvents.selectionChanged(event); } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.h b/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.h index 5bfb8d8396..a92e8806cc 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkDataNodeSelectionProvider.h @@ -1,58 +1,57 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDATATREENODESELECTIONPROVIDER_H_ #define QMITKDATATREENODESELECTIONPROVIDER_H_ #include #include #include /** * \ingroup org_mitk_gui_qt_common * * \brief A BlueBerry selection provider for mitk::DataNode selections. * * This class works together with a Qt item selection model which holds the actual * selection. The underlying Qt model must support the data role \e QmitkDataNodeRole * and return a mitk::DataNode::Pointer object for each QModelIndex in the selection. * * You can set a Qt item selection model using QtSelectionProvider::SetItemSelectionModel(). */ class MITK_QT_COMMON QmitkDataNodeSelectionProvider : public berry::QtSelectionProvider { public: berryObjectMacro(QmitkDataNodeSelectionProvider) QmitkDataNodeSelectionProvider(); /** * This method will always return a mitk::DataNodeSelection object. */ berry::ISelection::ConstPointer GetSelection() const; protected: mitk::DataNodeSelection::ConstPointer GetDataNodeSelection() const; virtual void FireSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); }; #endif /* QMITKDATATREENODESELECTIONPROVIDER_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp index 50594495c3..0d32a7c736 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp @@ -1,57 +1,56 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include "mitkWorkbenchUtil.h" #include QmitkDnDFrameWidget::QmitkDnDFrameWidget(QWidget *parent) : QWidget(parent) { setAcceptDrops(true); } void QmitkDnDFrameWidget::dragEnterEvent( QDragEnterEvent *event ) { // accept drags event->acceptProposedAction(); } void QmitkDnDFrameWidget::dropEvent( QDropEvent * event ) { //open dragged files QList fileNames = event->mimeData()->urls(); if (fileNames.empty()) return; QStringList fileNames2; //TODO Qt 4.7 API //fileNames2.reserve(fileNames.size()); foreach(QUrl url, fileNames) { fileNames2.push_back(url.toLocalFile()); } mitk::WorkbenchUtil::LoadFiles(fileNames2, berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); event->accept(); } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.h b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.h index dfde32d3a5..1fab5f961e 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.h @@ -1,59 +1,58 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ -Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDndFrameWidget_h #define QmitkDndFrameWidget_h #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include //drag&drop class QDragEnterEvent; class QDropEvent; class QMouseEvent; /** * \ingroup org_mitk_gui_qt_common * * \brief Enables loading data into a MITK application via Drag'n Drop. * * You can use this class inside your MITK View as a container for your widgets * if you want the user to be able to load data by dropping files onto your view. */ class MITK_QT_COMMON QmitkDnDFrameWidget : public QWidget { Q_OBJECT public: QmitkDnDFrameWidget(QWidget *parent); private: void dragEnterEvent( QDragEnterEvent *event ); void dropEvent( QDropEvent * event ); }; #endif diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp index 7296377b44..bb342290e2 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp @@ -1,57 +1,56 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkCommonActivator.h" #include #include ctkPluginContext* QmitkCommonActivator::m_Context = 0; ctkPluginContext* QmitkCommonActivator::GetContext() { return m_Context; } void QmitkCommonActivator::start(ctkPluginContext* context) { this->m_Context = context; if(berry::PlatformUI::IsWorkbenchRunning()) { m_ViewCoordinator = QmitkViewCoordinator::Pointer(new QmitkViewCoordinator); m_ViewCoordinator->Start(); } else { MITK_ERROR << "BlueBerry Workbench not running!"; } } void QmitkCommonActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_ViewCoordinator->Stop(); m_ViewCoordinator = 0; this->m_Context = 0; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_common, QmitkCommonActivator) diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h index f9c99d1cb6..4d2c29bbab 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h @@ -1,58 +1,57 @@ -/*========================================================================= +/*=================================================================== - Program: MITK Platform - Language: C++ - Date: $Date$ - Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKCOMMONACTIVATOR_H_ #define QMITKCOMMONACTIVATOR_H_ #include #include "QmitkViewCoordinator.h" /** * \ingroup org_mitk_gui_qt_common_internal * * \brief The plug-in activator for the StateMachine * * When the plug-in is started by the framework, it initializes StateMachine * specific things. */ class QmitkCommonActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: static ctkPluginContext* GetContext(); /** * Sets default StateMachine to EventMapper. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: static ctkPluginContext* m_Context; QmitkViewCoordinator::Pointer m_ViewCoordinator; }; #endif /* QMITKCOMMONACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.cpp index ae4be4ddd8..ecb23344a4 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.cpp @@ -1,46 +1,45 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDataNodeItemModel.h" #include #include QmitkDataNodeItemModel::QmitkDataNodeItemModel(QObject *parent) : QStandardItemModel(parent) { } void QmitkDataNodeItemModel::AddDataNode(mitk::DataNode::Pointer node) { QList nodes; nodes << node; this->AddDataNodes(nodes); } void QmitkDataNodeItemModel::AddDataNodes(const QList &nodes) { QList items; foreach(mitk::DataNode::Pointer node, nodes) { QStandardItem* item = new QStandardItem(); item->setData(QVariant::fromValue(node), QmitkDataNodeRole); items << item; } this->appendRow(items); } diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.h index a5afd7e7d3..3c62f0345f 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeItemModel.h @@ -1,37 +1,36 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDATANODEITEMMODEL_H #define QMITKDATANODEITEMMODEL_H #include #include class QmitkDataNodeItemModel : public QStandardItemModel { public: QmitkDataNodeItemModel(QObject* parent = 0); void AddDataNode(mitk::DataNode::Pointer node); void AddDataNodes(const QList& nodes); }; #endif // QMITKDATANODEITEMMODEL_H diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.cpp index f347409666..3dff17c80c 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.cpp @@ -1,82 +1,81 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDataNodeSelection.h" #include #include #include QmitkDataNodeSelection::QmitkDataNodeSelection() { } QmitkDataNodeSelection::QmitkDataNodeSelection( const QItemSelection& sel) : mitk::DataNodeSelection(), berry::QtItemSelection(sel) { QModelIndexList indexes = sel.indexes(); for (QModelIndexList::const_iterator index = indexes.constBegin(); index != indexes.constEnd(); ++index) { QVariant data = index->data(QmitkDataNodeRole); mitk::DataNode::Pointer node = data.value (); if (node.IsNotNull()) { berry::Object::Pointer obj(new mitk::DataNodeObject(node)); mitk::DataNodeSelection::m_Selection->push_back(obj); } } } berry::Object::Pointer QmitkDataNodeSelection::GetFirstElement() const { return mitk::DataNodeSelection::GetFirstElement(); } QmitkDataNodeSelection::iterator QmitkDataNodeSelection::Begin() const { return mitk::DataNodeSelection::Begin(); } QmitkDataNodeSelection::iterator QmitkDataNodeSelection::End() const { return mitk::DataNodeSelection::End(); } int QmitkDataNodeSelection::Size() const { return mitk::DataNodeSelection::Size(); } QmitkDataNodeSelection::ContainerType::Pointer QmitkDataNodeSelection::ToVector() const { return mitk::DataNodeSelection::ToVector(); } bool QmitkDataNodeSelection::IsEmpty() const { return mitk::DataNodeSelection::IsEmpty(); } bool QmitkDataNodeSelection::operator==(const berry::Object* obj) const { return mitk::DataNodeSelection::operator==(obj); } diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.h index 5212663b31..ea2f63e6df 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkDataNodeSelection.h @@ -1,49 +1,48 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include #include class QmitkDataNodeSelection: public mitk::DataNodeSelection, public berry::QtItemSelection { public: berryObjectMacro(QmitkDataNodeSelection); QmitkDataNodeSelection(); QmitkDataNodeSelection(const QItemSelection& sel); virtual berry::Object::Pointer GetFirstElement() const; virtual iterator Begin() const; virtual iterator End() const; virtual int Size() const; virtual ContainerType::Pointer ToVector() const; /** * @see berry::ISelection::IsEmpty() */ bool IsEmpty() const; bool operator==(const berry::Object* obj) const; }; diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp index 7c12210282..0fb0f79fab 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp @@ -1,206 +1,205 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkViewCoordinator.h" #include "QmitkAbstractView.h" #include #include #include #include #include QmitkViewCoordinator::QmitkViewCoordinator() : m_ActiveZombieView(0) , m_ActiveRenderWindowPart(0) , m_VisibleRenderWindowPart(0) { } QmitkViewCoordinator::~QmitkViewCoordinator() { } void QmitkViewCoordinator::Start() { berry::PlatformUI::GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this)); std::vector wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); for (std::vector::iterator i = wnds.begin(); i != wnds.end(); ++i) { (*i)->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); } } void QmitkViewCoordinator::Stop() { if (!berry::PlatformUI::IsWorkbenchRunning()) return; berry::PlatformUI::GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this)); std::vector wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); for (std::vector::iterator i = wnds.begin(); i != wnds.end(); ++i) { (*i)->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this)); } } berry::IPartListener::Events::Types QmitkViewCoordinator::GetPartEventTypes() const { return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED; } void QmitkViewCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef ) { //MITK_INFO << "*** PartActivated (" << partRef->GetPart(false)->GetPartName() << ")"; berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer(); // Check for a render window part and inform IRenderWindowPartListener views // that it was activated if ( mitk::IRenderWindowPart* renderPart = dynamic_cast(part) ) { if (m_VisibleRenderWindowPart != renderPart) { RenderWindowPartActivated(renderPart); m_ActiveRenderWindowPart = renderPart; m_VisibleRenderWindowPart = renderPart; } } // Check if the activated part wants to be notified if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast(part)) { lifecycleAwarePart->Activated(); } // Check if a zombie view has been activated. if (mitk::IZombieViewPart* zombieView = dynamic_cast(part)) { if (m_ActiveZombieView && (m_ActiveZombieView != zombieView)) { // Another zombie view has been activated. Tell the old one about it. m_ActiveZombieView->ActivatedZombieView(partRef); m_ActiveZombieView = zombieView; } } } void QmitkViewCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer partRef ) { //MITK_INFO << "*** PartDeactivated (" << partRef->GetPart(false)->GetPartName() << ")"; berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer(); if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast(part)) { lifecycleAwarePart->Deactivated(); } } void QmitkViewCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef ) { //MITK_INFO << "*** PartOpened (" << partRef->GetPart(false)->GetPartName() << ")"; berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer(); if (mitk::IRenderWindowPartListener* renderWindowListener = dynamic_cast(part)) { m_RenderWindowListeners.insert(renderWindowListener); } } void QmitkViewCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) { //MITK_INFO << "*** PartClosed (" << partRef->GetPart(false)->GetPartName() << ")"; berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer(); if (mitk::IRenderWindowPartListener* renderWindowListener = dynamic_cast(part)) { m_RenderWindowListeners.remove(renderWindowListener); } } void QmitkViewCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) { //MITK_INFO << "*** PartHidden (" << partRef->GetPart(false)->GetPartName() << ")"; berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer(); // Check for a render window part and if it is the currently active on. // Inform IRenderWindowPartListener views that it has been hidden. if ( mitk::IRenderWindowPart* renderPart = dynamic_cast(part) ) { if (!m_ActiveRenderWindowPart && m_VisibleRenderWindowPart == renderPart) { RenderWindowPartDeactivated(renderPart); m_VisibleRenderWindowPart = 0; } } if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast(part)) { lifecycleAwarePart->Hidden(); } } void QmitkViewCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) { //MITK_INFO << "*** PartVisible (" << partRef->GetPart(false)->GetPartName() << ")"; berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer(); // Check for a render window part and inform IRenderWindowPartListener views // that it was activated if ( mitk::IRenderWindowPart* renderPart = dynamic_cast(part) ) { if (!m_ActiveRenderWindowPart) { RenderWindowPartActivated(renderPart); m_VisibleRenderWindowPart = renderPart; } } if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast(part)) { lifecycleAwarePart->Visible(); } } void QmitkViewCoordinator::RenderWindowPartActivated(mitk::IRenderWindowPart* renderPart) { foreach (mitk::IRenderWindowPartListener* l, m_RenderWindowListeners) { l->RenderWindowPartActivated(renderPart); } } void QmitkViewCoordinator::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderPart) { foreach (mitk::IRenderWindowPartListener* l, m_RenderWindowListeners) { l->RenderWindowPartDeactivated(renderPart); } } void QmitkViewCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer /*window*/ ) { } void QmitkViewCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window ) { window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); } diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h index f06416fdbc..b1a9465d93 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h @@ -1,125 +1,124 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-01-16 19:57:43 +0100 (Sa, 16 Jan 2010) $ -Version: $Revision: 21070 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkViewCoordinator_h #define QmitkViewCoordinator_h #include #include #include #include #include namespace mitk { struct IRenderWindowPart; struct IRenderWindowPartListener; struct IZombieViewPart; } class QmitkAbstractView; /** * A class which coordinates active QmitkAbstractView s, e.g. calling activated and hidden on them. */ class QmitkViewCoordinator : public berry::IPartListener, public berry::IWindowListener { public: berryObjectMacro(QmitkViewCoordinator) /** * Add listener */ QmitkViewCoordinator(); /** * Remove listener */ virtual ~QmitkViewCoordinator(); void Start(); void Stop(); //#IPartListener methods (these methods internally call Activated() or other similar methods) /** * \see IPartListener::GetPartEventTypes() */ berry::IPartListener::Events::Types GetPartEventTypes() const; /** * \see IPartListener::PartActivated() */ virtual void PartActivated (berry::IWorkbenchPartReference::Pointer partRef); /** * \see IPartListener::PartDeactivated() */ virtual void PartDeactivated(berry::IWorkbenchPartReference::Pointer /*partRef*/); /** * \see IPartListener::PartOpened() */ virtual void PartOpened(berry::IWorkbenchPartReference::Pointer partRef); /** * \see IPartListener::PartClosed() */ virtual void PartClosed (berry::IWorkbenchPartReference::Pointer partRef); /** * \see IPartListener::PartHidden() */ virtual void PartHidden (berry::IWorkbenchPartReference::Pointer partRef); /** * \see IPartListener::PartVisible() */ virtual void PartVisible (berry::IWorkbenchPartReference::Pointer partRef); /** * Notifies this listener that the given window has been closed. */ virtual void WindowClosed(berry::IWorkbenchWindow::Pointer window); /** * Notifies this listener that the given window has been opened. */ virtual void WindowOpened(berry::IWorkbenchWindow::Pointer /*window*/); private: void RenderWindowPartActivated(mitk::IRenderWindowPart* renderPart); void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderPart); private: mitk::IZombieViewPart* m_ActiveZombieView; mitk::IRenderWindowPart* m_ActiveRenderWindowPart; mitk::IRenderWindowPart* m_VisibleRenderWindowPart; QSet m_RenderWindowListeners; }; #endif // QmitkViewCoordinator_h diff --git a/Plugins/org.mitk.gui.qt.common/testing/manifest.cpp b/Plugins/org.mitk.gui.qt.common/testing/manifest.cpp index 672b4322d8..c46f19985d 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/manifest.cpp +++ b/Plugins/org.mitk.gui.qt.common/testing/manifest.cpp @@ -1,31 +1,30 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include "src/QmitkQtCommonTestSuite.h" #include "src/api/QmitkMockFunctionality.h" POCO_BEGIN_NAMED_MANIFEST(CppUnitTest, CppUnit::Test) POCO_EXPORT_CLASS(QmitkQtCommonTestSuite) POCO_END_MANIFEST POCO_BEGIN_NAMED_MANIFEST(berryIViewPart, berry::IViewPart) POCO_EXPORT_CLASS(QmitkMockFunctionality) POCO_END_MANIFEST diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp index 8e0ebf1085..4e8f46a608 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp +++ b/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp @@ -1,34 +1,33 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkQtCommonTestSuite.h" #include "api/QmitkUiApiTestSuite.h" #include QmitkQtCommonTestSuite::QmitkQtCommonTestSuite() : CppUnit::TestSuite("QmitkQtCommonTestSuite") { addTest(new QmitkUiApiTestSuite()); } QmitkQtCommonTestSuite::QmitkQtCommonTestSuite(const QmitkQtCommonTestSuite& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h b/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h index a52864b998..02b4415167 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h +++ b/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h @@ -1,38 +1,37 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKQTCOMMONTESTSUITE_H_ #define QMITKQTCOMMONTESTSUITE_H_ #include #include Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") class QmitkQtCommonTestSuite : public QObject, public CppUnit::TestSuite { Q_OBJECT Q_INTERFACES(CppUnit::Test) public: QmitkQtCommonTestSuite(); QmitkQtCommonTestSuite(const QmitkQtCommonTestSuite& other); }; #endif /* QMITKQTCOMMONTESTSUITE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp index c0923d0c2e..57e9269d47 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp +++ b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp @@ -1,109 +1,108 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkFunctionalityTest.h" #include #include #include "QmitkMockFunctionality.h" QmitkFunctionalityTest::QmitkFunctionalityTest(const std::string& testName) : berry::UITestCase(testName) { } CppUnit::Test* QmitkFunctionalityTest::Suite() { CppUnit::TestSuite* suite = new CppUnit::TestSuite("QmitkFunctionalityTest"); CppUnit_addTest(suite, QmitkFunctionalityTest, TestOpenAndClose); return suite; } void QmitkFunctionalityTest::DoSetUp() { UITestCase::DoSetUp(); fWindow = OpenTestWindow(); fPage = fWindow->GetActivePage(); } void QmitkFunctionalityTest::DoTearDown() { fPage = 0; fWindow = 0; UITestCase::DoTearDown(); } void QmitkFunctionalityTest::TestOpenAndClose() { this->IgnoreLeakingObjects(); berry::CallHistory::Pointer history; std::vector callOrder; { // Open a functionality. QmitkMockFunctionality::Pointer part = fPage->ShowView(QmitkMockFunctionality::ID).Cast (); history = part->GetCallHistory(); //callOrder.push_back("SetInitializationData"); //callOrder.push_back("Init"); callOrder.push_back("CreateQtPartControl"); callOrder.push_back("SetFocus"); assert(history->VerifyOrder(callOrder)); // Close the part. fPage->HideView(part.Cast()); } //callOrder.push_back("WidgetDisposed"); callOrder.push_back("FunctionalityDestructor"); assert(history->VerifyOrder(callOrder)); } void QmitkFunctionalityTest::TestOpenAndWindowClose() { this->IgnoreLeakingObjects(); berry::CallHistory::Pointer history; std::vector callOrder; { // Open a new window berry::IWorkbenchWindow::Pointer newWindow = OpenTestWindow(); // Open a part. QmitkMockFunctionality::Pointer part = newWindow->GetActivePage()->ShowView(QmitkMockFunctionality::ID).Cast ();; history = part->GetCallHistory(); //callOrder.push_back("SetInitializationData"); //callOrder.push_back("Init"); callOrder.push_back("CreateQtPartControl"); callOrder.push_back("SetFocus"); assert(history->VerifyOrder(callOrder)); // Close the window. newWindow->Close(); } //callOrder.push_back("WidgetDisposed"); callOrder.push_back("FunctionalityDestructor"); assert(history->VerifyOrder(callOrder)); } diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h index 0944b23c96..3640d7994a 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h +++ b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h @@ -1,57 +1,56 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKFUNCTIONALITYTEST_H_ #define QMITKFUNCTIONALITYTEST_H_ #include #include #include #include /** * Test cases for the QmitkFunctionality API. */ class QmitkFunctionalityTest : public berry::UITestCase { public: friend class CppUnit::TestCaller; QmitkFunctionalityTest(const std::string& testName); static CppUnit::Test* Suite(); void TestOpenAndClose(); void TestOpenAndWindowClose(); protected: berry::IWorkbenchWindow::Pointer fWindow; berry::IWorkbenchPage::Pointer fPage; void DoSetUp(); void DoTearDown(); }; #endif /* QMITKFUNCTIONALITYTEST_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp index 27b9f271ad..d5b9eb59db 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp +++ b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp @@ -1,53 +1,52 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkMockFunctionality.h" const std::string QmitkMockFunctionality::ID = "org.mitk.gui.qt.common.tests.api.MockFunctionality"; QmitkMockFunctionality::QmitkMockFunctionality() : callTrace(new berry::CallHistory()) { } QmitkMockFunctionality::QmitkMockFunctionality(const QmitkMockFunctionality& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkMockFunctionality::~QmitkMockFunctionality() { callTrace->Add("FunctionalityDestructor"); } berry::CallHistory::Pointer QmitkMockFunctionality::GetCallHistory() const { return callTrace; } void QmitkMockFunctionality::CreateQtPartControl(QWidget* parent) { callTrace->Add("CreateQtPartControl"); } void QmitkMockFunctionality::SetFocus() { QmitkFunctionality::SetFocus(); callTrace->Add("SetFocus"); } diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h index e7e9856744..64c1c8983e 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h +++ b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h @@ -1,54 +1,53 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKMOCKFUNCTIONALITY_H_ #define QMITKMOCKFUNCTIONALITY_H_ #include #include class QmitkMockFunctionality : public QmitkFunctionality { Q_OBJECT public: berryObjectMacro(QmitkMockFunctionality) static const std::string ID; // = "org.mitk.gui.qt.common.tests.api.MockFunctionality"; QmitkMockFunctionality(); QmitkMockFunctionality(const QmitkMockFunctionality& other); ~QmitkMockFunctionality(); berry::CallHistory::Pointer GetCallHistory() const; void SetFocus(); protected: void CreateQtPartControl(QWidget* parent); private: berry::CallHistory::Pointer callTrace; }; #endif /* QMITKMOCKFUNCTIONALITY_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp index 4aac2b6767..0434403da4 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp +++ b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp @@ -1,27 +1,26 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkUiApiTestSuite.h" #include "QmitkFunctionalityTest.h" QmitkUiApiTestSuite::QmitkUiApiTestSuite() : CppUnit::TestSuite("QmitkUiApiTestSuite") { addTest(QmitkFunctionalityTest::Suite()); } diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h index 6b0c02a418..0b964c880d 100644 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h +++ b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h @@ -1,32 +1,31 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKUIAPITESTSUITE_H_ #define QMITKUIAPITESTSUITE_H_ #include class QmitkUiApiTestSuite : public CppUnit::TestSuite { public: QmitkUiApiTestSuite(); }; #endif /* QMITKUIAPITESTSUITE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp index 15a8d5f053..a5591c05aa 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp @@ -1,30 +1,29 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkActionBarAdvisor.h" QmitkActionBarAdvisor::QmitkActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer) : berry::ActionBarAdvisor(configurer) { } void QmitkActionBarAdvisor::FillMenuBar(void* ) { } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h index 8112027368..ba09a495c1 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h @@ -1,35 +1,34 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKACTIONBARADVISOR_H_ #define QMITKACTIONBARADVISOR_H_ #include class QmitkActionBarAdvisor : public berry::ActionBarAdvisor { public: QmitkActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer); protected: void FillMenuBar(void* menuBar); }; #endif /*QMITKACTIONBARADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp index a86f050cb4..095d863a4a 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp @@ -1,43 +1,42 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkCoreApplication.h" #include #include "QmitkWorkbenchAdvisor.h" QmitkCoreApplication::QmitkCoreApplication() { } int QmitkCoreApplication::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); int code = berry::PlatformUI::CreateAndRunWorkbench(display, new QmitkWorkbenchAdvisor()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void QmitkCoreApplication::Stop() { } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h index 5cb6e53c28..bd44b440e5 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h @@ -1,39 +1,38 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKCOREAPPLICATION_H_ #define QMITKCOREAPPLICATION_H_ #include #include class QmitkCoreApplication : public QObject, public berry::IApplication { Q_OBJECT Q_INTERFACES(berry::IApplication) public: QmitkCoreApplication(); int Start(); void Stop(); }; #endif /*QMITKCOREAPPLICATION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp index abee56e998..5f5d684058 100755 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp @@ -1,28 +1,27 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDefaultPerspective.h" QmitkDefaultPerspective::QmitkDefaultPerspective() { } void QmitkDefaultPerspective::CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/) { } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h index 58614a2815..cce77f45f8 100755 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h @@ -1,40 +1,39 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDEFAULTPERSPECTIVE_H_ #define QMITKDEFAULTPERSPECTIVE_H_ #include #include struct QmitkDefaultPerspective : public QObject, public berry::IPerspectiveFactory { QmitkDefaultPerspective(); void CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/); private: Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) }; #endif /* QMITKDEFAULTPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp index 5d948f5164..80ab599b7f 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp @@ -1,46 +1,45 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkWorkbenchAdvisor.h" #include #include "QmitkWorkbenchWindowAdvisor.h" const std::string QmitkWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.coreapp.defaultperspective"; void QmitkWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { return new QmitkWorkbenchWindowAdvisor(configurer); } std::string QmitkWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h index f271de0a2b..d7e3fe297d 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h @@ -1,46 +1,45 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKWORKBENCHADVISOR_H_ #define QMITKWORKBENCHADVISOR_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include class QmitkWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const std::string DEFAULT_PERSPECTIVE_ID; // = org.mitk.coreapp.defaultperspective void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); std::string GetInitialWindowPerspectiveId(); }; #endif /*QMITKWORKBENCHADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp index 690c6463ea..f87b2f36b0 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp @@ -1,121 +1,120 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkWorkbenchWindowAdvisor.h" #include "QmitkActionBarAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include QmitkWorkbenchWindowAdvisor::QmitkWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer) , dropTargetListener(new QmitkDefaultDropTargetListener) { } berry::ActionBarAdvisor::Pointer QmitkWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkActionBarAdvisor(configurer)); return actionBarAdvisor; } void QmitkWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast(window->GetShell()->GetControl()); QMenuBar* menuBar = mainWindow->menuBar(); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->addAction(new QmitkFileOpenAction(window)); fileMenu->addSeparator(); fileMenu->addAction(new QmitkFileExitAction(window)); berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const std::vector& viewDescriptors = viewRegistry->GetViews(); QMenu* viewMenu = menuBar->addMenu("Show &View"); // sort elements (converting vector to map...) std::vector::const_iterator iter; std::map VDMap; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; std::pair p((*iter)->GetLabel(), (*iter)); VDMap.insert(p); } QToolBar* qToolbar = new QToolBar; std::map::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); //m_ViewActions.push_back(viewAction); viewMenu->addAction(viewAction); qToolbar->addAction(viewAction); } mainWindow->addToolBar(qToolbar); QStatusBar* qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); QmitkProgressBar *progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); mainWindow->setStatusBar(qStatusBar); QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } void QmitkWorkbenchWindowAdvisor::PreWindowOpen() { this->GetWindowConfigurer()->AddEditorAreaTransfer(QStringList("text/uri-list")); this->GetWindowConfigurer()->ConfigureEditorAreaDropListener(dropTargetListener); } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h index 7d002a4891..1f794a5959 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h @@ -1,42 +1,41 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKWORKBENCHWINDOWADVISOR_H_ #define QMITKWORKBENCHWINDOWADVISOR_H_ #include class QmitkWorkbenchWindowAdvisor : public berry::WorkbenchWindowAdvisor { public: QmitkWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer); berry::ActionBarAdvisor::Pointer CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer); void PostWindowCreate(); void PreWindowOpen(); private: berry::IDropTargetListener::Pointer dropTargetListener; }; #endif /*QMITKWORKBENCHWINDOWADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp index 5563b1f0ca..511460299e 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp @@ -1,43 +1,42 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "org_mitk_gui_qt_coreapplication_Activator.h" #include "QmitkCoreApplication.h" #include "QmitkDefaultPerspective.h" #include namespace mitk { void org_mitk_gui_qt_coreapplication_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkCoreApplication, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDefaultPerspective, context) } void org_mitk_gui_qt_coreapplication_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_coreapplication, mitk::org_mitk_gui_qt_coreapplication_Activator) diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h index ea6a03db24..7c2d9580f7 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h @@ -1,43 +1,42 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include namespace mitk { class org_mitk_gui_qt_coreapplication_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // org_mitk_gui_common_Activator typedef org_mitk_gui_qt_coreapplication_Activator PluginActivator; } #endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp index 81a9b97237..ec2f56d5ba 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.cpp @@ -1,160 +1,159 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-07-07 16:57:15 +0200 (Di, 07 Jul 2009) $ - Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDataManagerHotkeysPrefPage.h" #include #include "berryIPreferencesService.h" #include "berryPlatform.h" #include #include #include #include #include #include #include using namespace berry; QmitkDataManagerHotkeysPrefPage::QmitkDataManagerHotkeysPrefPage() : m_MainControl(0) { } void QmitkDataManagerHotkeysPrefPage::Init(berry::IWorkbench::Pointer ) { } void QmitkDataManagerHotkeysPrefPage::CreateQtControl(QWidget* parent) { IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); berry::IPreferences::Pointer _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["Save selected nodes"] = new QmitkHotkeyLineEdit("Ctrl+, S"); m_HotkeyEditors["Load"] = new QmitkHotkeyLineEdit("Ctrl+, L"); m_HotkeyEditors["Show Node Information"] = new QmitkHotkeyLineEdit("Ctrl+, I"); m_MainControl = new QWidget(parent); QGridLayout* layout = new QGridLayout; int i = 0; for (std::map::iterator 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); this->Update(); } QWidget* QmitkDataManagerHotkeysPrefPage::GetQtControl() const { return m_MainControl; } bool QmitkDataManagerHotkeysPrefPage::PerformOk() { IPreferences::Pointer _DataManagerHotkeysPreferencesNode = m_DataManagerHotkeysPreferencesNode.Lock(); if(_DataManagerHotkeysPreferencesNode.IsNotNull()) { bool duplicate = false; QString keyString; QString errString; for (std::map::iterator 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::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()) { duplicate = true; break; } } if(duplicate == true) errString = QString("Duplicate hot key for \"%1\" and \"%2\"").arg(it->first).arg(it2->first); } if(!errString.isEmpty()) { QMessageBox::critical(QApplication::activeWindow(), "Error", errString); return false; } } //# no errors -> save all values and flush to file for (std::map::iterator it = m_HotkeyEditors.begin() ; it != m_HotkeyEditors.end(); ++it) _DataManagerHotkeysPreferencesNode->Put(it->first.toStdString() , it->second->GetKeySequenceAsString().toStdString()); _DataManagerHotkeysPreferencesNode->Flush(); return true; } return false; } void QmitkDataManagerHotkeysPrefPage::PerformCancel() { } void QmitkDataManagerHotkeysPrefPage::Update() { IPreferences::Pointer _DataManagerHotkeysPreferencesNode = m_DataManagerHotkeysPreferencesNode.Lock(); if(_DataManagerHotkeysPreferencesNode.IsNotNull()) { for (std::map::iterator it = m_HotkeyEditors.begin() ; it != m_HotkeyEditors.end(); ++it) { it->second->setText(QString::fromStdString(_DataManagerHotkeysPreferencesNode->Get(it->first.toStdString() , it->second->text().toStdString()))); } } } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h index dbc27406fa..da26520205 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerHotkeysPrefPage.h @@ -1,73 +1,72 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ - Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDATAMANAGERHOTKEYSPREFPAGE_H_ #define QMITKDATAMANAGERHOTKEYSPREFPAGE_H_ #include "berryIQtPreferencePage.h" #include #include #include 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); void CreateQtControl(QWidget* parent); QWidget* GetQtControl() const; /// /// \see IPreferencePage::PerformOk() /// virtual bool PerformOk(); /// /// \see IPreferencePage::PerformCancel() /// virtual void PerformCancel(); /// /// \see IPreferencePage::Update() /// virtual void Update(); protected: /// /// The node from which the properties are taken (will be catched from the preferences service in ctor) /// berry::IPreferences::WeakPtr m_DataManagerHotkeysPreferencesNode; /// /// Maps a label to hotkey lineedit, e.g. "Toggle Visibility of selected nodes" => QmitkHotkeyLineEdit /// std::map 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 061b2aa57e..a5aa4d4f03 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.cpp @@ -1,98 +1,97 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-07-07 16:57:15 +0200 (Di, 07 Jul 2009) $ - Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDataManagerPreferencePage.h" #include "QmitkDataManagerView.h" #include #include #include #include #include #include QmitkDataManagerPreferencePage::QmitkDataManagerPreferencePage() : m_MainControl(0) { } void QmitkDataManagerPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkDataManagerPreferencePage::CreateQtControl(QWidget* parent) { berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); m_DataManagerPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDataManagerView::VIEW_ID); m_MainControl = new QWidget(parent); m_EnableSingleEditing = new QCheckBox; m_PlaceNewNodesOnTop = new QCheckBox; m_ShowHelperObjects = new QCheckBox; m_ShowNodesContainingNoData = new QCheckBox; m_UseSurfaceDecimation = new QCheckBox; QFormLayout *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("&Use surface decimation:", m_UseSurfaceDecimation); m_MainControl->setLayout(formLayout); this->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("Use surface decimation" , m_UseSurfaceDecimation->isChecked()); return true; } void QmitkDataManagerPreferencePage::PerformCancel() { } 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_UseSurfaceDecimation->setChecked(m_DataManagerPreferencesNode->GetBool("Use surface decimation", true)); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h index 03d0679d6f..a2e94d1c5e 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h @@ -1,68 +1,67 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ - Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDATAMANAGERPREFERENCEPAGE_H_ #define QMITKDATAMANAGERPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include #include class QWidget; class QCheckBox; struct MITK_QT_DATAMANAGER QmitkDataManagerPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkDataManagerPreferencePage(); void Init(berry::IWorkbench::Pointer workbench); void CreateQtControl(QWidget* widget); QWidget* GetQtControl() const; /// /// \see IPreferencePage::PerformOk() /// virtual bool PerformOk(); /// /// \see IPreferencePage::PerformCancel() /// virtual void PerformCancel(); /// /// \see IPreferencePage::Update() /// virtual void Update(); protected: QWidget* m_MainControl; QCheckBox* m_EnableSingleEditing; QCheckBox* m_PlaceNewNodesOnTop; QCheckBox* m_ShowHelperObjects; QCheckBox* m_ShowNodesContainingNoData; QCheckBox* m_UseSurfaceDecimation; berry::IPreferences::Pointer m_DataManagerPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp index b034b9e5cd..020039eeb4 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp @@ -1,936 +1,935 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDataManagerView.h" #include //# Own Includes //## mitk #include "mitkDataStorageEditorInput.h" #include "mitkIDataStorageReference.h" #include "mitkNodePredicateDataType.h" #include "mitkCoreObjectFactory.h" #include "mitkPACSPlugin.h" #include "mitkDataNodeFactory.h" #include "mitkColorProperty.h" #include "mitkCommon.h" #include "mitkDelegateManager.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkEnumerationProperty.h" #include "mitkProperties.h" #include #include #include #include //## Qmitk #include #include #include #include #include #include #include "src/internal/QmitkNodeTableViewKeyFilter.h" #include "src/internal/QmitkInfoDialog.h" //## Berry #include #include #include #include #include #include //# Toolkit Includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkDataNodeObject.h" #include "mitkIContextMenuAction.h" #include "berryIExtensionPointService.h" const std::string QmitkDataManagerView::VIEW_ID = "org.mitk.views.datamanager"; QmitkDataManagerView::QmitkDataManagerView() { } QmitkDataManagerView::~QmitkDataManagerView() { //Remove all registered actions from each descriptor for (std::vector< std::pair< QmitkNodeDescriptor*, QAction* > >::iterator it = m_DescriptorActionList.begin();it != m_DescriptorActionList.end(); it++) { // first== the NodeDescriptor; second== the registered QAction (it->first)->RemoveAction(it->second); } } void QmitkDataManagerView::CreateQtPartControl(QWidget* parent) { m_CurrentRowCount = 0; m_Parent = parent; //# Preferences berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node(VIEW_ID)) .Cast(); assert( prefs ); prefs->OnChanged.AddListener( berry::MessageDelegate1( this , &QmitkDataManagerView::OnPreferencesChanged ) ); //# GUI m_NodeTreeModel = new QmitkDataStorageTreeModel(this->GetDataStorage()); m_NodeTreeModel->setParent( parent ); m_NodeTreeModel->SetPlaceNewNodesOnTop( prefs->GetBool("Place new nodes on top", true) ); m_NodeTreeModel->SetShowHelperObjects( prefs->GetBool("Show helper objects", false) ); m_NodeTreeModel->SetShowNodesContainingNoData( prefs->GetBool("Show nodes containing no data", false) ); m_SurfaceDecimation = prefs->GetBool("Use surface decimation", false); //# Tree View (experimental) m_NodeTreeView = new QTreeView; m_NodeTreeView->setSelectionMode( QAbstractItemView::ExtendedSelection ); m_NodeTreeView->setSelectionBehavior( QAbstractItemView::SelectRows ); m_NodeTreeView->setAlternatingRowColors(true); m_NodeTreeView->setDragEnabled(true); m_NodeTreeView->setDropIndicatorShown(true); m_NodeTreeView->setAcceptDrops(true); m_NodeTreeView->setContextMenuPolicy(Qt::CustomContextMenu); m_NodeTreeView->setModel(m_NodeTreeModel); m_NodeTreeView->installEventFilter(new QmitkNodeTableViewKeyFilter(this)); QObject::connect( m_NodeTreeView, SIGNAL(customContextMenuRequested(const QPoint&)) , this, SLOT(NodeTableViewContextMenuRequested(const QPoint&)) ); QObject::connect( m_NodeTreeModel, SIGNAL(rowsInserted (const QModelIndex&, int, int)) , this, SLOT(NodeTreeViewRowsInserted ( const QModelIndex&, int, int )) ); QObject::connect( m_NodeTreeModel, SIGNAL(rowsRemoved (const QModelIndex&, int, int)) , this, SLOT(NodeTreeViewRowsRemoved( const QModelIndex&, int, int )) ); QObject::connect( m_NodeTreeView->selectionModel() , SIGNAL( selectionChanged ( const QItemSelection &, const QItemSelection & ) ) , this , SLOT( NodeSelectionChanged ( const QItemSelection &, const QItemSelection & ) ) ); //# m_NodeMenu m_NodeMenu = new QMenu(m_NodeTreeView); // # Actions berry::IEditorRegistry* editorRegistry = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); std::list editors = editorRegistry->GetEditors("*.mitk"); if (editors.size() > 1) { m_ShowInMapper = new QSignalMapper(this); foreach(berry::IEditorDescriptor::Pointer descriptor, editors) { QAction* action = new QAction(QString::fromStdString(descriptor->GetLabel()), this); m_ShowInActions << action; m_ShowInMapper->connect(action, SIGNAL(triggered()), m_ShowInMapper, SLOT(map())); m_ShowInMapper->setMapping(action, QString::fromStdString(descriptor->GetId())); } connect(m_ShowInMapper, SIGNAL(mapped(QString)), this, SLOT(ShowIn(QString))); } QmitkNodeDescriptor* unknownDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetUnknownDataNodeDescriptor(); QmitkNodeDescriptor* imageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image"); QmitkNodeDescriptor* surfaceDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Surface"); QAction* globalReinitAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"), "Global Reinit", this); QObject::connect( globalReinitAction, SIGNAL( triggered(bool) ) , this, SLOT( GlobalReinit(bool) ) ); unknownDataNodeDescriptor->AddAction(globalReinitAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor, globalReinitAction)); QAction* saveAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Save_48.png"), "Save...", this); QObject::connect( saveAction, SIGNAL( triggered(bool) ) , this, SLOT( SaveSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(saveAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,saveAction)); QAction* removeAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Remove_48.png"), "Remove", this); QObject::connect( removeAction, SIGNAL( triggered(bool) ) , this, SLOT( RemoveSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(removeAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,removeAction)); QAction* reinitAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"), "Reinit", this); QObject::connect( reinitAction, SIGNAL( triggered(bool) ) , this, SLOT( ReinitSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(reinitAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,reinitAction)); // find contextMenuAction extension points and add them to the node descriptor berry::IExtensionPointService::Pointer extensionPointService = berry::Platform::GetExtensionPointService(); berry::IConfigurationElement::vector cmActions( extensionPointService->GetConfigurationElementsFor("org.mitk.gui.qt.datamanager.contextMenuActions") ); berry::IConfigurationElement::vector::iterator cmActionsIt; std::string cmNodeDescriptorName; std::string cmLabel; std::string cmIcon; std::string cmClass; QmitkNodeDescriptor* tmpDescriptor; QAction* contextMenuAction; QVariant cmActionDataIt; m_ConfElements.clear(); int i=1; for (cmActionsIt = cmActions.begin() ; cmActionsIt != cmActions.end() ; ++cmActionsIt) { cmIcon.erase(); if((*cmActionsIt)->GetAttribute("nodeDescriptorName", cmNodeDescriptorName) && (*cmActionsIt)->GetAttribute("label", cmLabel) && (*cmActionsIt)->GetAttribute("class", cmClass)) { (*cmActionsIt)->GetAttribute("icon", cmIcon); // create context menu entry here tmpDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(QString::fromStdString(cmNodeDescriptorName)); if(!tmpDescriptor) { MITK_WARN << "cannot add action \"" << cmLabel << "\" because descriptor " << cmNodeDescriptorName << " does not exist"; continue; } contextMenuAction = new QAction( QString::fromStdString(cmLabel), parent); tmpDescriptor->AddAction(contextMenuAction); m_DescriptorActionList.push_back(std::pair(tmpDescriptor,contextMenuAction)); m_ConfElements[contextMenuAction] = *cmActionsIt; cmActionDataIt.setValue(i); contextMenuAction->setData( cmActionDataIt ); connect( contextMenuAction, SIGNAL( triggered(bool) ) , this, SLOT( ContextMenuActionTriggered(bool) ) ); ++i; } } m_OpacitySlider = new QSlider; m_OpacitySlider->setMinimum(0); m_OpacitySlider->setMaximum(100); m_OpacitySlider->setOrientation(Qt::Horizontal); QObject::connect( m_OpacitySlider, SIGNAL( valueChanged(int) ) , this, SLOT( OpacityChanged(int) ) ); QLabel* _OpacityLabel = new QLabel("Opacity: "); QHBoxLayout* _OpacityWidgetLayout = new QHBoxLayout; _OpacityWidgetLayout->setContentsMargins(4,4,4,4); _OpacityWidgetLayout->addWidget(_OpacityLabel); _OpacityWidgetLayout->addWidget(m_OpacitySlider); QWidget* _OpacityWidget = new QWidget; _OpacityWidget->setLayout(_OpacityWidgetLayout); QWidgetAction* opacityAction = new QWidgetAction(this); opacityAction ->setDefaultWidget(_OpacityWidget); QObject::connect( opacityAction , SIGNAL( changed() ) , this, SLOT( OpacityActionChanged() ) ); unknownDataNodeDescriptor->AddAction(opacityAction , false); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,opacityAction)); m_ColorButton = new QPushButton; m_ColorButton->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); //m_ColorButton->setText("Change color"); QObject::connect( m_ColorButton, SIGNAL( clicked() ) , this, SLOT( ColorChanged() ) ); QLabel* _ColorLabel = new QLabel("Color: "); _ColorLabel->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); QHBoxLayout* _ColorWidgetLayout = new QHBoxLayout; _ColorWidgetLayout->setContentsMargins(4,4,4,4); _ColorWidgetLayout->addWidget(_ColorLabel); _ColorWidgetLayout->addWidget(m_ColorButton); QWidget* _ColorWidget = new QWidget; _ColorWidget->setLayout(_ColorWidgetLayout); QWidgetAction* colorAction = new QWidgetAction(this); colorAction->setDefaultWidget(_ColorWidget); QObject::connect( colorAction, SIGNAL( changed() ) , this, SLOT( ColorActionChanged() ) ); unknownDataNodeDescriptor->AddAction(colorAction, false); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,colorAction)); m_TextureInterpolation = new QAction("Texture Interpolation", this); m_TextureInterpolation->setCheckable ( true ); QObject::connect( m_TextureInterpolation, SIGNAL( changed() ) , this, SLOT( TextureInterpolationChanged() ) ); QObject::connect( m_TextureInterpolation, SIGNAL( toggled(bool) ) , this, SLOT( TextureInterpolationToggled(bool) ) ); imageDataNodeDescriptor->AddAction(m_TextureInterpolation, false); m_DescriptorActionList.push_back(std::pair(imageDataNodeDescriptor,m_TextureInterpolation)); m_SurfaceRepresentation = new QAction("Surface Representation", this); m_SurfaceRepresentation->setMenu(new QMenu); QObject::connect( m_SurfaceRepresentation->menu(), SIGNAL( aboutToShow() ) , this, SLOT( SurfaceRepresentationMenuAboutToShow() ) ); surfaceDataNodeDescriptor->AddAction(m_SurfaceRepresentation, false); m_DescriptorActionList.push_back(std::pair(surfaceDataNodeDescriptor, m_SurfaceRepresentation)); QAction* showOnlySelectedNodes = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/ShowSelectedNode_48.png") , "Show only selected nodes", this); QObject::connect( showOnlySelectedNodes, SIGNAL( triggered(bool) ) , this, SLOT( ShowOnlySelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(showOnlySelectedNodes); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor, showOnlySelectedNodes)); QAction* toggleSelectedVisibility = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/InvertShowSelectedNode_48.png") , "Toggle visibility", this); QObject::connect( toggleSelectedVisibility, SIGNAL( triggered(bool) ) , this, SLOT( ToggleVisibilityOfSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(toggleSelectedVisibility); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,toggleSelectedVisibility)); QAction* actionShowInfoDialog = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/ShowDataInfo_48.png") , "Details...", this); QObject::connect( actionShowInfoDialog, SIGNAL( triggered(bool) ) , this, SLOT( ShowInfoDialogForSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(actionShowInfoDialog); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,actionShowInfoDialog)); QAction* otsuFilterAction = new QAction("Apply Otsu Filter", this); QObject::connect( otsuFilterAction, SIGNAL( triggered(bool) ) , this, SLOT( OtsuFilter(bool) ) ); // Otsu filter does not work properly, remove it temporarily // imageDataNodeDescriptor->AddAction(otsuFilterAction); // m_DescriptorActionList.push_back(std::pair(imageDataNodeDescriptor,otsuFilterAction)); QGridLayout* _DndFrameWidgetLayout = new QGridLayout; _DndFrameWidgetLayout->addWidget(m_NodeTreeView, 0, 0); _DndFrameWidgetLayout->setContentsMargins(0,0,0,0); m_DndFrameWidget = new QmitkDnDFrameWidget(m_Parent); m_DndFrameWidget->setLayout(_DndFrameWidgetLayout); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DndFrameWidget); layout->setContentsMargins(0,0,0,0); m_Parent->setLayout(layout); } void QmitkDataManagerView::SetFocus() { } void QmitkDataManagerView::ContextMenuActionTriggered( bool ) { QAction* action = qobject_cast ( sender() ); std::map::iterator it = m_ConfElements.find( action ); if( it == m_ConfElements.end() ) { MITK_WARN << "associated conf element for action " << action->text().toStdString() << " not found"; return; } berry::IConfigurationElement::Pointer confElem = it->second; mitk::IContextMenuAction* contextMenuAction = confElem->CreateExecutableExtension("class"); std::string className; std::string smoothed; confElem->GetAttribute("class", className); confElem->GetAttribute("smoothed", smoothed); if(className == "QmitkThresholdAction") { contextMenuAction->SetDataStorage(this->GetDataStorage()); } else if(className == "QmitkCreatePolygonModelAction") { contextMenuAction->SetDataStorage(this->GetDataStorage()); if(smoothed == "false") { contextMenuAction->SetSmoothed(false); } else { contextMenuAction->SetSmoothed(true); } contextMenuAction->SetDecimated(m_SurfaceDecimation); } else if(className == "QmitkStatisticsAction") { contextMenuAction->SetFunctionality(this); } contextMenuAction->Run( this->GetCurrentSelection() ); // run the action } void QmitkDataManagerView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { if( m_NodeTreeModel->GetPlaceNewNodesOnTopFlag() != prefs->GetBool("Place new nodes on top", true) ) m_NodeTreeModel->SetPlaceNewNodesOnTop( !m_NodeTreeModel->GetPlaceNewNodesOnTopFlag() ); if( m_NodeTreeModel->GetShowHelperObjectsFlag()!= prefs->GetBool("Show helper objects", false) ) m_NodeTreeModel->SetShowHelperObjects( !m_NodeTreeModel->GetShowHelperObjectsFlag() ); if( m_NodeTreeModel->GetShowNodesContainingNoDataFlag()!= prefs->GetBool("Show nodes containing no data", false) ) m_NodeTreeModel->SetShowNodesContainingNoData( !m_NodeTreeModel->GetShowNodesContainingNoDataFlag() ); m_NodeTreeView->expandAll(); m_SurfaceDecimation = prefs->GetBool("Use surface decimation", false); this->GlobalReinit(); } void QmitkDataManagerView::NodeTableViewContextMenuRequested( const QPoint & pos ) { QModelIndex selected = m_NodeTreeView->indexAt ( pos ); mitk::DataNode::Pointer node = m_NodeTreeModel->GetNode(selected); QList selectedNodes = this->GetCurrentSelection(); if(!selectedNodes.isEmpty()) { m_NodeMenu->clear(); QList actions; if(selectedNodes.size() == 1 ) { actions = QmitkNodeDescriptorManager::GetInstance()->GetActions(node); for(QList::iterator it = actions.begin(); it != actions.end(); ++it) { (*it)->setData(QVariant::fromValue(node.GetPointer())); } } else actions = QmitkNodeDescriptorManager::GetInstance()->GetActions(selectedNodes); if (!m_ShowInActions.isEmpty()) { QMenu* showInMenu = m_NodeMenu->addMenu("Show In"); showInMenu->addActions(m_ShowInActions); } m_NodeMenu->addActions(actions); m_NodeMenu->popup(QCursor::pos()); } } void QmitkDataManagerView::OpacityChanged(int value) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(node) { float opacity = static_cast(value)/100.0f; node->SetFloatProperty("opacity", opacity); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkDataManagerView::OpacityActionChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(node) { float opacity = 0.0; if(node->GetFloatProperty("opacity", opacity)) { m_OpacitySlider->setValue(static_cast(opacity*100)); } } } void QmitkDataManagerView::ColorChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(node) { QColor color = QColorDialog::getColor(); m_ColorButton->setAutoFillBackground(true); node->SetProperty("color",mitk::ColorProperty::New(color.red()/255.0,color.green()/255.0,color.blue()/255.0)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkDataManagerView::ColorActionChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(node) { mitk::Color color; mitk::ColorProperty::Pointer colorProp; node->GetProperty(colorProp,"color"); if(colorProp.IsNull()) return; color = colorProp->GetValue(); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255)); styleSheet.append(")"); m_ColorButton->setStyleSheet(styleSheet); } } void QmitkDataManagerView::TextureInterpolationChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(node) { bool textureInterpolation = false; node->GetBoolProperty("texture interpolation", textureInterpolation); m_TextureInterpolation->setChecked(textureInterpolation); } } void QmitkDataManagerView::TextureInterpolationToggled( bool checked ) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(node) { node->SetBoolProperty("texture interpolation", checked); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkDataManagerView::SurfaceRepresentationMenuAboutToShow() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(!node) return; mitk::EnumerationProperty* representationProp = dynamic_cast (node->GetProperty("material.representation")); if(!representationProp) return; // clear menu m_SurfaceRepresentation->menu()->clear(); QAction* tmp; // create menu entries for(mitk::EnumerationProperty::EnumConstIterator it=representationProp->Begin(); it!=representationProp->End() ; it++) { tmp = m_SurfaceRepresentation->menu()->addAction(QString::fromStdString(it->second)); tmp->setCheckable(true); if(it->second == representationProp->GetValueAsString()) { tmp->setChecked(true); } QObject::connect( tmp, SIGNAL( triggered(bool) ) , this, SLOT( SurfaceRepresentationActionToggled(bool) ) ); } } void QmitkDataManagerView::SurfaceRepresentationActionToggled( bool /*checked*/ ) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_NodeTreeView->selectionModel()->currentIndex()); if(!node) return; mitk::EnumerationProperty* representationProp = dynamic_cast (node->GetProperty("material.representation")); if(!representationProp) return; QAction* senderAction = qobject_cast ( QObject::sender() ); if(!senderAction) return; std::string activatedItem = senderAction->text().toStdString(); if ( activatedItem != representationProp->GetValueAsString() ) { if ( representationProp->IsValidEnumerationValue( activatedItem ) ) { representationProp->SetValue( activatedItem ); representationProp->InvokeEvent( itk::ModifiedEvent() ); representationProp->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkDataManagerView::SaveSelectedNodes( bool ) { QModelIndexList indexesOfSelectedRows = m_NodeTreeView->selectionModel()->selectedRows(); mitk::DataNode* node = 0; unsigned int indexesOfSelectedRowsSize = indexesOfSelectedRows.size(); for (unsigned int i = 0; iGetNode(indexesOfSelectedRows.at(i)); // if node is not defined or if the node contains geometry data do not remove it if ( node != 0 ) { mitk::BaseData::Pointer data = node->GetData(); if (data.IsNotNull()) { QString error; try { CommonFunctionality::SaveBaseData( data.GetPointer(), node->GetName().c_str() ); } catch(std::exception& e) { error = e.what(); } catch(...) { error = "Unknown error occured"; } if( !error.isEmpty() ) QMessageBox::critical( m_Parent, "Error saving...", error ); } } } } void QmitkDataManagerView::ReinitSelectedNodes( bool ) { mitk::IRenderWindowPart* renderWindow = this->OpenRenderWindowPart(); QList selectedNodes = this->GetCurrentSelection(); foreach(mitk::DataNode::Pointer node, selectedNodes) { mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { renderWindow->GetRenderingManager()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); renderWindow->GetRenderingManager()->RequestUpdateAll(); } } } void QmitkDataManagerView::RemoveSelectedNodes( bool ) { QModelIndexList indexesOfSelectedRows = m_NodeTreeView->selectionModel()->selectedRows(); if(indexesOfSelectedRows.size() < 1) { return; } std::vector selectedNodes; mitk::DataNode* node = 0; QString question = tr("Do you really want to remove "); for (QModelIndexList::iterator it = indexesOfSelectedRows.begin() ; it != indexesOfSelectedRows.end(); it++) { node = m_NodeTreeModel->GetNode(*it); // if node is not defined or if the node contains geometry data do not remove it if ( node != 0 /*& strcmp(node->GetData()->GetNameOfClass(), "Geometry2DData") != 0*/ ) { selectedNodes.push_back(node); question.append(QString::fromStdString(node->GetName())); question.append(", "); } } // remove the last two characters = ", " question = question.remove(question.size()-2, 2); question.append(" from data storage?"); QMessageBox::StandardButton answerButton = QMessageBox::question( m_Parent , tr("DataManager") , question , QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(answerButton == QMessageBox::Yes) { for (std::vector::iterator it = selectedNodes.begin() ; it != selectedNodes.end(); it++) { node = *it; this->GetDataStorage()->Remove(node); this->GlobalReinit(false); } } } void QmitkDataManagerView::MakeAllNodesInvisible( bool ) { QList nodes = m_NodeTreeModel->GetNodeSet(); foreach(mitk::DataNode::Pointer node, nodes) { node->SetVisibility(false); } //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ShowOnlySelectedNodes( bool ) { QList selectedNodes = this->GetCurrentSelection(); QList allNodes = m_NodeTreeModel->GetNodeSet(); foreach(mitk::DataNode::Pointer node, allNodes) { node->SetVisibility(selectedNodes.contains(node)); } //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ToggleVisibilityOfSelectedNodes( bool ) { QList selectedNodes = this->GetCurrentSelection(); bool isVisible = false; foreach(mitk::DataNode::Pointer node, selectedNodes) { isVisible = false; node->GetBoolProperty("visible", isVisible); node->SetVisibility(!isVisible); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ShowInfoDialogForSelectedNodes( bool ) { QList selectedNodes = this->GetCurrentSelection(); QmitkInfoDialog _QmitkInfoDialog(selectedNodes, this->m_Parent); _QmitkInfoDialog.exec(); } void QmitkDataManagerView::Load( bool ) { QStringList fileNames = QFileDialog::getOpenFileNames(NULL, "Load data", "", mitk::CoreObjectFactory::GetInstance()->GetFileExtensions()); for ( QStringList::Iterator it = fileNames.begin(); it != fileNames.end(); ++it ) { FileOpen((*it).toAscii(), 0); } } void QmitkDataManagerView::FileOpen( const char * fileName, mitk::DataNode* parentNode ) { mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); try { factory->SetFileName( fileName ); QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); factory->Update(); for ( unsigned int i = 0 ; i < factory->GetNumberOfOutputs( ); ++i ) { mitk::DataNode::Pointer node = factory->GetOutput( i ); if ( ( node.IsNotNull() ) && ( node->GetData() != NULL ) ) { this->GetDataStorage()->Add(node, parentNode); mitk::BaseData::Pointer basedata = node->GetData(); mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } catch ( itk::ExceptionObject & ex ) { itkGenericOutputMacro( << "Exception during file open: " << ex ); } QApplication::restoreOverrideCursor(); } QItemSelectionModel *QmitkDataManagerView::GetDataNodeSelectionModel() const { return m_NodeTreeView->selectionModel(); } void QmitkDataManagerView::GlobalReinit( bool ) { mitk::IRenderWindowPart* renderWindow = this->OpenRenderWindowPart(); // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry renderWindow->GetRenderingManager()->InitializeViews(bounds); } void QmitkDataManagerView::OnSelectionChanged( berry::IWorkbenchPart::Pointer part , const QList& selection ) { if(part.GetPointer() == this) return; QItemSelection newSelection; m_NodeTreeView->selectionModel()->reset(); foreach(mitk::DataNode::Pointer node, selection) { QModelIndex treeIndex = m_NodeTreeModel->GetIndex(node); if(treeIndex.isValid()) newSelection.select(treeIndex, treeIndex); } m_NodeTreeView->selectionModel()->select(newSelection, QItemSelectionModel::SelectCurrent); } void QmitkDataManagerView::OtsuFilter( bool ) { QList selectedNodes = this->GetCurrentSelection(); mitk::Image::Pointer mitkImage = 0; foreach(mitk::DataNode::Pointer node, selectedNodes) { mitkImage = dynamic_cast( node->GetData() ); if(mitkImage.IsNull()) continue; try { // get selected mitk image const unsigned short dim = 3; typedef short InputPixelType; typedef unsigned char OutputPixelType; typedef itk::Image< InputPixelType, dim > InputImageType; typedef itk::Image< OutputPixelType, dim > OutputImageType; typedef itk::OtsuThresholdImageFilter< InputImageType, OutputImageType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetOutsideValue( 1 ); filter->SetInsideValue( 0 ); InputImageType::Pointer itkImage; mitk::CastToItkImage(mitkImage, itkImage); filter->SetInput( itkImage ); filter->Update(); mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); std::string nameOfResultImage = node->GetName(); nameOfResultImage.append("Otsu"); resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); resultNode->SetProperty("binary", mitk::BoolProperty::New(true) ); resultNode->SetData( mitk::ImportItkImage ( filter->GetOutput() ) ); this->GetDataStorage()->Add(resultNode, node); } catch( std::exception& err ) { MITK_ERROR(this->GetClassName()) << err.what(); } } } void QmitkDataManagerView::NodeTreeViewRowsRemoved ( const QModelIndex & /*parent*/, int /*start*/, int /*end*/ ) { m_CurrentRowCount = m_NodeTreeModel->rowCount(); } void QmitkDataManagerView::NodeTreeViewRowsInserted( const QModelIndex & parent, int, int ) { m_NodeTreeView->setExpanded(parent, true); // a new row was inserted if( m_CurrentRowCount == 0 && m_NodeTreeModel->rowCount() == 1 ) { this->OpenRenderWindowPart(); m_CurrentRowCount = m_NodeTreeModel->rowCount(); /* std::vector nodes = m_NodeTreeModel->GetNodeSet(); if(nodes.size() == 1) { QModelIndex treeIndex = m_NodeTreeModel->GetIndex(nodes.front()); m_NodeTreeView->selectionModel()->setCurrentIndex( treeIndex, QItemSelectionModel::ClearAndSelect ); } */ } } void QmitkDataManagerView::NodeSelectionChanged( const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/ ) { QList nodes = m_NodeTreeModel->GetNodeSet(); foreach(mitk::DataNode::Pointer node, nodes) { if ( node.IsNotNull() ) node->SetBoolProperty("selected", false); } nodes.clear(); nodes = this->GetCurrentSelection(); foreach(mitk::DataNode::Pointer node, nodes) { if ( node.IsNotNull() ) node->SetBoolProperty("selected", true); } //changing the selection does NOT require any rendering processes! //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ShowIn(const QString &editorId) { berry::IWorkbenchPage::Pointer page = this->GetSite()->GetPage(); berry::IEditorInput::Pointer input(new mitk::DataStorageEditorInput(this->GetDataStorageReference())); page->OpenEditor(input, editorId.toStdString(), false, berry::IWorkbenchPage::MATCH_ID); } mitk::IRenderWindowPart* QmitkDataManagerView::OpenRenderWindowPart() { return this->GetRenderWindowPart(QmitkAbstractView::ACTIVATE | QmitkAbstractView::OPEN); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h index 18c1e05074..8fd46bba80 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.h @@ -1,253 +1,252 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDATAMANAGERVIEW_H_ #define QMITKDATAMANAGERVIEW_H_ // BlueBerry includes #include /// Qmitk #include #include /// Qt #include #include // Forward declarations class QMenu; class QAction; class QComboBox; class QWidgetAction; class QSlider; class QModelIndex; class QTreeView; class QPushButton; class QToolBar; class QMenu; class QSignalMapper; class QmitkDnDFrameWidget; class QmitkDataStorageTreeModel; /// /// \ingroup org_mitk_gui_qt_datamanager_internal /// /// \brief A View class that can show all data tree nodes of a certain DataStorage /// /// \TODO: complete PACS support, in save dialog show regular filename /// class MITK_QT_DATAMANAGER QmitkDataManagerView : public QmitkAbstractView { Q_OBJECT public: static const std::string VIEW_ID; // = "org.mitk.extapp.defaultperspective" /// /// \brief Standard ctor. /// QmitkDataManagerView(); /// /// \brief Standard dtor. /// virtual ~QmitkDataManagerView(); public slots: /// /// Invoked when the opacity slider changed /// void OpacityChanged(int value); /// /// Invoked when the opacity action changed /// In this function the the opacity slider is set to the selected nodes opacity value /// void OpacityActionChanged(); /// /// Invoked when the color button is pressed /// void ColorChanged(); /// /// Invoked when the color action changed /// void ColorActionChanged(); /// /// Invoked when the color button is pressed /// void TextureInterpolationChanged(); /// /// Invoked when the color action changed /// void TextureInterpolationToggled ( bool checked ); /// /// SurfaceRepresentationActionToggled /// void SurfaceRepresentationMenuAboutToShow (); ///public /// SurfaceRepresentationActionToggled /// void SurfaceRepresentationActionToggled ( bool checked ); /// /// \brief Shows a node context menu. /// void NodeTableViewContextMenuRequested( const QPoint & index ); /// /// \brief Invoked when an element should be saved. /// void SaveSelectedNodes( bool checked = false ); /// /// \brief Invoked when an element should be removed. /// void RemoveSelectedNodes( bool checked = false ); /// /// \brief Invoked when an element should be reinitiliased. /// void ReinitSelectedNodes( bool checked = false ); /// /// \brief Invoked when the visibility of the selected nodes should be toggled. /// void MakeAllNodesInvisible ( bool checked = false ); /// /// \brief Makes all selected nodes visible, all other nodes invisible. /// void ShowOnlySelectedNodes ( bool checked = false ); /// /// \brief Invoked when the visibility of the selected nodes should be toggled. /// void ToggleVisibilityOfSelectedNodes ( bool checked = false ); /// /// \brief Invoked when infos of the selected nodes should be shown in a dialog. /// void ShowInfoDialogForSelectedNodes ( bool checked = false ); /// /// \brief Shows a load dialog. /// void Load ( bool checked = false ); /// /// \brief Reinits everything. /// void GlobalReinit ( bool checked = false ); /// /// Invoked when the preferences were changed /// void OnPreferencesChanged(const berry::IBerryPreferences*); /// /// \brief will be toggled when a extension point context menu action is toggled /// this is a proxy method which will load the corresponding extension class /// and run IContextMenuAction /// void ContextMenuActionTriggered( bool ); /// /// Invoked when the MITK workbench selection changed /// void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList& selection); /// Invoked when the median action is invoked void OtsuFilter( bool checked = false ); /// When rows are inserted auto expand them void NodeTreeViewRowsInserted ( const QModelIndex & parent, int start, int end ); /// will setup m_CurrentRowCount void NodeTreeViewRowsRemoved ( const QModelIndex & parent, int start, int end ); /// Whenever the selection changes set the "selected" property respectively void NodeSelectionChanged( const QItemSelection & selected, const QItemSelection & deselected ); /// Opens the editor with the given id using the current data storage void ShowIn(const QString& editorId); protected: /// /// \brief Create the view here. /// virtual void CreateQtPartControl(QWidget* parent); void SetFocus(); /// /// \brief Shows a file open dialog. /// void FileOpen( const char * fileName, mitk::DataNode* parentNode ); protected: QWidget* m_Parent; QmitkDnDFrameWidget* m_DndFrameWidget; /// /// \brief A plain widget as the base pane. /// QmitkDataStorageTreeModel* m_NodeTreeModel; /// /// Holds the preferences for the datamanager. /// berry::IBerryPreferences::Pointer m_DataManagerPreferencesNode; /// /// saves the configuration elements for the context menu actions from extension points /// std::map m_ConfElements; /// /// \brief The Table view to show the selected nodes. /// QTreeView* m_NodeTreeView; /// /// \brief The context menu that shows up when right clicking on a node. /// QMenu* m_NodeMenu; /// /// \brief flag indicating whether a surface created from a selected decimation is decimated with vtkQuadricDecimation or not /// bool m_SurfaceDecimation; ///# A list of ALL actions for the Context Menu std::vector< std::pair< QmitkNodeDescriptor*, QAction* > > m_DescriptorActionList; /// A Slider widget to change the opacity of a node QSlider* m_OpacitySlider; /// button to change the color of a node QPushButton* m_ColorButton; /// TextureInterpolation action QAction* m_TextureInterpolation; /// SurfaceRepresentation action QAction* m_SurfaceRepresentation; /// Maps "Show in" actions to editor ids QSignalMapper* m_ShowInMapper; /// A list of "Show in" actions QList m_ShowInActions; /// saves the current amount of rows shown in the datamanager size_t m_CurrentRowCount; private: QItemSelectionModel* GetDataNodeSelectionModel() const; /// Reopen multi widget editor if it has been closed mitk::IRenderWindowPart *OpenRenderWindowPart(); }; #endif /*QMITKDATAMANAGERVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp index 4f85714357..53150ada52 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp @@ -1,40 +1,39 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "berrySingleNodeSelection.h" #include "mitkDataNode.h" namespace berry { void SingleNodeSelection::SetNode( mitk::DataNode* _SelectedNode ) { m_Node = _SelectedNode; } mitk::DataNode* SingleNodeSelection::GetNode() const { return m_Node; } bool SingleNodeSelection::IsEmpty() const { return ( m_Node == 0 ); } } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h b/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h index 5d78a10d6a..59e74c6451 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h @@ -1,67 +1,66 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKSINGLENODESELECTION_H_ #define QMITKSINGLENODESELECTION_H_ // Own includes #include "berryISelection.h" /// Qmitk #include //# forward declarations namespace mitk { class DataNode; } namespace berry { /// /// \struct SingleNodeSelection /// \brief Represents a selection object that encapsulates the selection of a single node. /// struct MITK_QT_DATAMANAGER SingleNodeSelection: public berry::ISelection { /// /// \brief Make typdefs for pointer types. /// berryObjectMacro(SingleNodeSelection); /// /// \brief Node setter. /// void SetNode(mitk::DataNode* _SelectedNode); /// /// \brief Node getter. /// mitk::DataNode* GetNode() const; /// /// \brief Checks if node is 0. /// virtual bool IsEmpty() const; protected: /// /// \brief Holds the node that is currently selected. /// mitk::DataNode* m_Node; }; } #endif // QMITKSINGLENODESELECTION_H_ \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp index 0b2faf456f..219bd49c94 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp @@ -1,45 +1,44 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDelKeyFilter.h" #include #include QmitkDelKeyFilter::QmitkDelKeyFilter( QObject* _DataManagerView ) : QObject(_DataManagerView) { } bool QmitkDelKeyFilter::eventFilter( QObject *obj, QEvent *event ) { if (event->type() == QEvent::KeyPress) { QmitkDataManagerView* _DataManagerView = qobject_cast(this->parent()); QKeyEvent *keyEvent = static_cast(event); if(keyEvent->key() == Qt::Key_Delete && _DataManagerView) { // trigger deletion of selected node(s) _DataManagerView->ActionRemoveTriggered(false); // return true: this means the delete key event is not send to the table return true; } } // standard event processing return QObject::eventFilter(obj, event); } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h index d4b8da8686..faa9b65fd7 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h @@ -1,36 +1,35 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDELKEYFILTER_H_ #define QMITKDELKEYFILTER_H_ #include /// /// A small class which "eats" all Del-Key-pressed events on the node table. /// When the Del Key is pressed selected nodes should be removed. /// class QmitkDelKeyFilter : public QObject { Q_OBJECT public: QmitkDelKeyFilter(QObject* _DataManagerView = 0); protected: bool eventFilter(QObject *obj, QEvent *event); }; #endif // QMITKDELKEYFILTER_H_ \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.cpp index 4d461f7eba..ecdc14cd2a 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.cpp @@ -1,127 +1,126 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkInfoDialog.h" #include "QmitkDataStorageComboBox.h" #include #include #include #include #include #include #include QmitkInfoDialog::QmitkInfoDialog( const QList &_Nodes, QWidget * parent /*= 0*/, Qt::WindowFlags f /*= 0 */ ) : QDialog(parent, f) { // DIM QGridLayout* parentLayout = new QGridLayout; QmitkDataStorageComboBox* _QmitkDataStorageComboBox = new QmitkDataStorageComboBox(this, true); m_KeyWord = new QLineEdit; m_KeyWord->installEventFilter(this); m_SearchButton = new QPushButton("Search (F3)", this); m_SearchButton->installEventFilter(this); m_TextBrowser = new QTextBrowser(this); QPushButton* _CancelButton = new QPushButton("Cancel", this); // SET this->setMinimumSize(512, 512); this->setLayout(parentLayout); this->setSizeGripEnabled(true); this->setModal(true); parentLayout->addWidget(_QmitkDataStorageComboBox, 0, 0, 1, 2); parentLayout->addWidget(m_KeyWord, 1, 0); parentLayout->addWidget(m_SearchButton, 1, 1); parentLayout->addWidget(m_TextBrowser, 2, 0, 1, 2); parentLayout->addWidget(_CancelButton, 3, 0, 1, 2); QObject::connect( _QmitkDataStorageComboBox, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ) , this, SLOT( OnSelectionChanged( const mitk::DataNode* ) ) ); foreach(mitk::DataNode::Pointer node, _Nodes) { _QmitkDataStorageComboBox->AddNode(node); } QObject::connect( m_KeyWord, SIGNAL( textChanged ( const QString & ) ) , this, SLOT( KeyWordTextChanged(const QString &) ) ); QObject::connect( m_SearchButton, SIGNAL( clicked ( bool ) ) , this, SLOT( OnSearchButtonClicked( bool ) ) ); QObject::connect( _CancelButton, SIGNAL( clicked ( bool ) ) , this, SLOT( OnCancelButtonClicked( bool ) ) ); _CancelButton->setDefault(true); } void QmitkInfoDialog::OnSelectionChanged( const mitk::DataNode* node ) { std::ostringstream s; itk::Indent i(2); mitk::BaseData* _BaseData = node->GetData(); if(_BaseData) _BaseData->Print(s, i); m_TextBrowser->setPlainText(QString::fromStdString(s.str())); } void QmitkInfoDialog::OnSearchButtonClicked( bool /*checked*/ /*= false */ ) { QString keyWord = m_KeyWord->text(); QString text = m_TextBrowser->toPlainText(); if(keyWord.isEmpty() || text.isEmpty()) return; m_TextBrowser->find(keyWord); m_SearchButton->setText("Search Next(F3)"); } void QmitkInfoDialog::OnCancelButtonClicked( bool /*checked*/ /*= false */ ) { this->done(0); } bool QmitkInfoDialog::eventFilter( QObject *obj, QEvent *event ) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); if(keyEvent->key() == Qt::Key_F3 || keyEvent->key() == Qt::Key_Return) { // trigger deletion of selected node(s) this->OnSearchButtonClicked(true); // return true: this means the delete key event is not send to the table return true; } } // standard event processing return QObject::eventFilter(obj, event); } void QmitkInfoDialog::KeyWordTextChanged(const QString & /*text*/) { QTextCursor textCursor = m_TextBrowser->textCursor(); textCursor.setPosition(0); m_TextBrowser->setTextCursor(textCursor); m_SearchButton->setText("Search (F3)"); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.h b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.h index d8da23143d..a835b9a61f 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkInfoDialog.h @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKINFODIALOG_H_ #define QMITKINFODIALOG_H_ #include #include class QTextBrowser; class QLineEdit; /// /// A small class which "eats" all Del-Key-pressed events on the node table. /// When the Del Key is pressed selected nodes should be removed. /// class QmitkInfoDialog : public QDialog { Q_OBJECT public: QmitkInfoDialog(const QList& _Nodes, QWidget * parent = 0, Qt::WindowFlags f = 0 ); public slots: void OnSelectionChanged(const mitk::DataNode*); void OnSearchButtonClicked ( bool checked = false ); void OnCancelButtonClicked ( bool checked = false ); void KeyWordTextChanged(const QString & text); protected: bool eventFilter(QObject *obj, QEvent *event); protected: QLineEdit* m_KeyWord; QPushButton* m_SearchButton; QTextBrowser* m_TextBrowser; }; #endif // QMITKINFODIALOG_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 9303b9a5f6..9544caf235 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp @@ -1,104 +1,103 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkNodeTableViewKeyFilter.h" #include #include #include "../QmitkDataManagerView.h" QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter( QObject* _DataManagerView ) : QObject(_DataManagerView) { m_PreferencesService = berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); } bool QmitkNodeTableViewKeyFilter::eventFilter( QObject *obj, QEvent *event ) { QmitkDataManagerView* _DataManagerView = qobject_cast(this->parent()); if (event->type() == QEvent::KeyPress && _DataManagerView) { berry::IPreferencesService::Pointer prefService = m_PreferencesService.Lock(); berry::IPreferences::Pointer nodeTableKeyPrefs = prefService->GetSystemPreferences()->Node("/DataManager/Hotkeys"); QKeySequence _MakeAllInvisible = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Make all nodes invisible", "Ctrl+, V"))); QKeySequence _ToggleVisibility = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Toggle visibility of selected nodes", "V"))); QKeySequence _DeleteSelectedNodes = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Delete selected nodes", "Del"))); QKeySequence _Reinit = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Reinit selected nodes", "R"))); QKeySequence _GlobalReinit = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Global Reinit", "Ctrl+, R"))); QKeySequence _Save = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Save selected nodes", "Ctrl+, S"))); QKeySequence _Load = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Load", "Ctrl+, L"))); QKeySequence _ShowInfo = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Show Node Information", "Ctrl+, I"))); QKeyEvent *keyEvent = static_cast(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()); if(_KeySequence == _MakeAllInvisible) { // trigger deletion of selected node(s) _DataManagerView->MakeAllNodesInvisible(true); // return true: this means the delete key event is not send to the table return true; } else if(_KeySequence == _DeleteSelectedNodes) { // trigger deletion of selected node(s) _DataManagerView->RemoveSelectedNodes(true); // return true: this means the delete key event is not send to the table return true; } else if(_KeySequence == _ToggleVisibility) { // trigger deletion of selected node(s) _DataManagerView->ToggleVisibilityOfSelectedNodes(true); // return true: this means the delete key event is not send to the table return true; } else if(_KeySequence == _Reinit) { _DataManagerView->ReinitSelectedNodes(true); return true; } else if(_KeySequence == _GlobalReinit) { _DataManagerView->GlobalReinit(true); return true; } else if(_KeySequence == _Save) { _DataManagerView->SaveSelectedNodes(true); return true; } else if(_KeySequence == _Load) { _DataManagerView->Load(true); return true; } else if(_KeySequence == _ShowInfo) { _DataManagerView->ShowInfoDialogForSelectedNodes(true); 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 0adc0608e9..99c9d252dc 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.h @@ -1,43 +1,42 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKNODETABLEVIEWKEYFILTER_H_ #define QMITKNODETABLEVIEWKEYFILTER_H_ #include "berryIPreferencesService.h" #include /// /// A small class which "eats" all Del-Key-pressed events on the node table. /// When the Del Key is pressed selected nodes should be removed. /// class QmitkNodeTableViewKeyFilter : public QObject { Q_OBJECT public: QmitkNodeTableViewKeyFilter(QObject* _DataManagerView = 0); protected: bool eventFilter(QObject *obj, QEvent *event); /// /// The Preferences Service to retrieve and store preferences. /// berry::IPreferencesService::WeakPtr m_PreferencesService; }; #endif // QMITKNODETABLEVIEWKEYFILTER_H_ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.cpp index 6b48081a14..ef4855638e 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.cpp @@ -1,59 +1,58 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include #include #include "QmitkPropertyListView.h" #include #include #include #include const std::string QmitkPropertyListView::VIEW_ID = "org.mitk.views.propertylistview"; QmitkPropertyListView::QmitkPropertyListView() { } QmitkPropertyListView::~QmitkPropertyListView() { } void QmitkPropertyListView::CreateQtPartControl( QWidget* parent ) { m_NodePropertiesTableEditor = new QmitkPropertiesTableEditor; QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(m_NodePropertiesTableEditor); parent->setLayout(layout); } void QmitkPropertyListView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList &nodes) { if (nodes.empty() || (nodes.front().IsNull())) return; m_NodePropertiesTableEditor->SetPropertyList(nodes.front()->GetPropertyList()); } void QmitkPropertyListView::SetFocus() { m_NodePropertiesTableEditor->setFocus(); } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.h b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.h index c7a5c75a95..e44218e79c 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkPropertyListView.h @@ -1,77 +1,76 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkPropertyListView_h_ #define QmitkPropertyListView_h_ // Own includes #include #include #include class QmitkPropertiesTableEditor; /// /// A view to show /// class QmitkPropertyListView : public QmitkAbstractView { Q_OBJECT public: berryObjectMacro(QmitkPropertyListView) /// /// The unique ID of this view /// static const std::string VIEW_ID; /// /// \brief Standard ctor. /// QmitkPropertyListView(); /// /// \brief Standard dtor. /// virtual ~QmitkPropertyListView(); /// /// \brief Create the view here. /// void CreateQtPartControl(QWidget* parent); /// /// Invoked when the DataManager selection changed /// virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList& nodes); protected: void SetFocus(); private: /// /// \brief The properties table editor. /// QmitkPropertiesTableEditor* m_NodePropertiesTableEditor; friend struct berry::SelectionChangedAdapter; }; #endif /*QmitkPropertyListView_H_*/ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.cpp index 80fc4bce09..953d47f085 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.cpp @@ -1,160 +1,165 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkIVIMWidget.h" #include "mitkHistogramGenerator.h" #include #include #include //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#include QmitkIVIMWidget::QmitkIVIMWidget( QWidget * parent ) : QmitkPlotWidget(parent) { // this->SetAxisTitle( QwtPlot::xBottom, "Grayvalue" ); // this->SetAxisTitle( QwtPlot::yLeft, "Probability" ); // this->Replot(); m_Plot->setCanvasLineWidth(0); m_Plot->setMargin(0); QwtLog10ScaleEngine* logScale = new QwtLog10ScaleEngine(); m_Plot->setAxisScaleEngine(0, logScale); m_Plot->setAxisScale( 0, 0.15, 1.0 ); } QmitkIVIMWidget::~QmitkIVIMWidget() { } void QmitkIVIMWidget::DrawGauss() { } void QmitkIVIMWidget::ClearItemModel() { } std::vector QmitkIVIMWidget::vec(vnl_vector vector) { std::vector retval(vector.size()); for(unsigned int i=0; iClear(); QString s("f=%1, D=%2, D*=%3"); s = s.arg(snap.currentF,4); s = s.arg(snap.currentD,4); s = s.arg(snap.currentDStar,4); int curveId = this->InsertCurve( s.toAscii() ); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); curveId = this->InsertCurve( "ignored measurement points" ); this->SetCurveData( curveId, vec(snap.bvalues), vec(snap.allmeas) ); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); QwtSymbol whiteSymbol(QwtSymbol::Diamond, QColor(Qt::white), QColor(Qt::black), QSize(10,10)); this->SetCurveSymbol(curveId, &whiteSymbol); if(snap.currentDStar != 0) { curveId = this->InsertCurve( "additional points second fit" ); this->SetCurveData( curveId, vec(snap.bvals2), vec(snap.meas2) ); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); QwtSymbol blackSymbol(QwtSymbol::Diamond, QColor(Qt::black), QColor(Qt::black), QSize(10,10)); this->SetCurveSymbol(curveId, &blackSymbol); } curveId = this->InsertCurve( "points first fit" ); this->SetCurveData( curveId, vec(snap.bvals1), vec(snap.meas1) ); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); QwtSymbol redSymbol(QwtSymbol::Diamond, QColor(Qt::red), QColor(Qt::red), QSize(10,10)); this->SetCurveSymbol(curveId, &redSymbol); QPen pen; pen.setColor( QColor(Qt::red) ); pen.setWidth(2); double maxb = snap.bvalues.max_value(); vnl_vector xvals(2); vnl_vector yvals(2); xvals[0] = 0; xvals[1] = maxb; yvals[0] = 1-snap.currentFunceiled; yvals[1] = yvals[0]*exp(-maxb * snap.currentD); curveId = this->InsertCurve( "contribution of D to the signal" ); this->SetCurveData( curveId, vec(xvals), vec(yvals) ); this->SetCurvePen( curveId, pen ); if(snap.currentDStar != 0) { pen.setColor(Qt::black); int nsampling = 50; xvals.set_size(nsampling); yvals.set_size(nsampling); double f = 1-snap.currentFunceiled; for(int i=0; iInsertCurve( "resulting fit of the model" ); this->SetCurveData( curveId, vec(xvals), vec(yvals) ); this->SetCurvePen( curveId, pen ); } // QMargins margins; // margins.setBottom(0); // margins.setLeft(0); // margins.setRight(0); // margins.setTop(0); QwtLegend* legend = new QwtLegend(); // legend->setContentsMargins(margins); m_Plot->insertLegend(legend, QwtPlot::BottomLegend); this->Replot(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.h index aa8ad3c104..38adb241b7 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkIVIMWidget.h @@ -1,73 +1,72 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-15 18:09:46 +0200 (Fr, 15 Mai 2009) $ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkIVIMWidget_H_ #define QmitkIVIMWidget_H_ #include "QmitkPlotWidget.h" #include "QmitkHistogram.h" #include "QmitkExtExports.h" #include "mitkImage.h" #include "mitkPlanarFigure.h" #include #include #include #include #include #include #include #include "itkDiffusionIntravoxelIncoherentMotionReconstructionImageFilter.h" /** * \brief Widget for displaying image histograms based on the vtkQtChart * framework */ class QmitkIVIMWidget : public QmitkPlotWidget { public: typedef itk::DiffusionIntravoxelIncoherentMotionReconstructionImageFilter IVIMFilterType; typedef mitk::Image::HistogramType HistogramType; typedef mitk::Image::HistogramType::ConstIterator HistogramConstIteratorType; void SetParameters( IVIMFilterType::IVIMSnapshot snap ); QmitkIVIMWidget( QWidget * /*parent = 0 */); virtual ~QmitkIVIMWidget(); void DrawGauss(); void ClearItemModel(); std::vector< std::vector* > m_Vals; private: std::vector vec(vnl_vector vector); }; #endif /* QmitkIVIMWidget_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.cpp index faf92ede4a..53efae8fd4 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.cpp @@ -1,64 +1,69 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkODFDetailsWidget.h" #include QmitkODFDetailsWidget::QmitkODFDetailsWidget( QWidget * parent ) : QmitkPlotWidget(parent) { m_Plot->setCanvasLineWidth(0); m_Plot->setMargin(0); QwtLinearScaleEngine* scale = new QwtLinearScaleEngine(); m_Plot->setAxisScaleEngine(0, scale); m_Plot->setAxisScale ( 0, -0.5, 0.5 ); } QmitkODFDetailsWidget::~QmitkODFDetailsWidget() { } void QmitkODFDetailsWidget::SetParameters( itk::OrientationDistributionFunction odf ) { this->Clear(); std::vector xVals; std::vector yVals; float max = itk::NumericTraits::NonpositiveMin(); float min = itk::NumericTraits::max(); for (int i=0; imax) max = odf[i]; if (odf[i]0) m_Plot->setAxisScale ( 0, 0, max ); else m_Plot->setAxisScale ( 0, min, max ); int curveId = this->InsertCurve( "ODF Values" ); this->SetCurveData( curveId, xVals, yVals ); this->SetCurvePen( curveId, QPen(Qt::blue, 0.5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin) ); QwtLegend* legend = new QwtLegend(); //m_Plot->insertLegend(legend, QwtPlot::BottomLegend); this->Replot(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.h index ac30c7acc8..ebf2faada1 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFDetailsWidget.h @@ -1,47 +1,46 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-15 18:09:46 +0200 (Fr, 15 Mai 2009) $ -Version: $Revision: 1.12 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkODFDetailsWidget_H_ #define QmitkODFDetailsWidget_H_ #include "QmitkPlotWidget.h" #include #include /** * \brief Widget for displaying image histograms based on the vtkQtChart * framework */ class DIFFUSIONIMAGING_EXPORT QmitkODFDetailsWidget : public QmitkPlotWidget { Q_OBJECT public: void SetParameters( itk::OrientationDistributionFunction odf ); QmitkODFDetailsWidget( QWidget * /*parent = 0 */); virtual ~QmitkODFDetailsWidget(); std::vector m_Vals; private: }; #endif /* QmitkODFDetailsWidget_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp index 2fff514fea..06c55d3d1e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp @@ -1,124 +1,123 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkODFRenderWidget.h" #include #include #include #include #include QmitkODFRenderWidget::QmitkODFRenderWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f) { //create Layouts QmitkODFRenderWidgetLayout = new QHBoxLayout( this ); //Set Layout to widget this->setLayout(QmitkODFRenderWidgetLayout); //Create RenderWindow m_RenderWindow = new QmitkRenderWindow(this, "odf render widget"); m_RenderWindow->setMaximumSize(300,300); m_RenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); //m_RenderWindow->SetLayoutIndex( 3 ); QmitkODFRenderWidgetLayout->addWidget( m_RenderWindow ); } QmitkODFRenderWidget::~QmitkODFRenderWidget() { } void QmitkODFRenderWidget::GenerateODF( itk::OrientationDistributionFunction odf ) { try { m_Surface = mitk::Surface::New(); m_ds = mitk::StandaloneDataStorage::New(); m_Node = mitk::DataNode::New(); vtkPolyData* m_TemplateOdf = itk::OrientationDistributionFunction::GetBaseMesh(); vtkPolyData *polyData = vtkPolyData::New(); vtkPoints *points = vtkPoints::New(); vtkFloatArray *scalars = vtkFloatArray::New(); for (int i=0; iGetPoints()->GetPoint(i,p); double val = odf[i]; p[0] *= val; p[1] *= val; p[2] *= val; points->InsertPoint(i,p); scalars->InsertTuple1(i, 1-val); } polyData->SetPoints(points); vtkCellArray* polys = m_TemplateOdf->GetPolys(); polyData->SetPolys(polys); polyData->GetPointData()->SetScalars(scalars); polys->Delete(); scalars->Delete(); points->Delete(); m_Surface->SetVtkPolyData(polyData); m_Node->SetData(m_Surface); mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); vtkLookupTable* vtkLut = mitkLut->GetVtkLookupTable(); vtkLut->SetTableRange(0, 1); vtkLut->Build(); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); m_Node->SetProperty( "LookupTable", mitkLutProp ); m_Node->SetProperty("scalar visibility", mitk::BoolProperty::New(true)); m_Node->SetProperty("color mode", mitk::BoolProperty::New(true)); m_Node->SetProperty("material.specularCoefficient", mitk::FloatProperty::New(0.5)); m_ds->Add(m_Node); m_RenderWindow->GetRenderer()->SetDataStorage( m_ds ); // adjust camera to current plane rotation mitk::Geometry2D::ConstPointer worldGeometry = mitk::GlobalInteraction::GetInstance()->GetFocus()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast( worldGeometry.GetPointer() ); mitk::Vector3D normal = worldPlaneGeometry->GetNormal(); mitk::Vector3D up = worldPlaneGeometry->GetAxisVector(1); normal.Normalize(); up.Normalize(); vtkSmartPointer cam = vtkSmartPointer::New(); const double camPos[3] = {normal[0],normal[1],normal[2]}; const double camUp[3] = {up[0],up[1],up[2]}; cam->SetPosition(camPos); cam->SetViewUp(camUp); cam->SetParallelProjection(1); m_RenderWindow->GetRenderer()->GetVtkRenderer()->SetActiveCamera(cam); m_RenderWindow->update(); } catch (...) { } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.h index 311a4ac184..f64dd5daa9 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.h @@ -1,62 +1,61 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkODFRenderWidget_H_ #define QmitkODFRenderWidget_H_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class DIFFUSIONIMAGING_EXPORT QmitkODFRenderWidget : public QWidget { Q_OBJECT public: QmitkODFRenderWidget( QWidget* parent = 0, Qt::WindowFlags f = 0 ); virtual ~QmitkODFRenderWidget(); void GenerateODF( itk::OrientationDistributionFunction odf ); protected: QHBoxLayout* QmitkODFRenderWidgetLayout; QmitkRenderWindow* m_RenderWindow; mitk::Surface::Pointer m_Surface; mitk::StandaloneDataStorage::Pointer m_ds; mitk::DataNode::Pointer m_Node; }; #endif /*QmitkODFRenderWidget_H_*/ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.cpp index ee1fc5c8ac..1481996b15 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.cpp @@ -1,156 +1,161 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPartialVolumeAnalysisWidget.h" #include "mitkHistogramGenerator.h" #include "mitkPartialVolumeAnalysisClusteringCalculator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#include QmitkPartialVolumeAnalysisWidget::QmitkPartialVolumeAnalysisWidget( QWidget * parent ) : QmitkPlotWidget(parent) { // this->SetAxisTitle( QwtPlot::xBottom, "Grayvalue" ); // this->SetAxisTitle( QwtPlot::yLeft, "Probability" ); // this->Replot(); m_Plot->setCanvasLineWidth(0); m_Plot->setMargin(0); } QmitkPartialVolumeAnalysisWidget::~QmitkPartialVolumeAnalysisWidget() { } void QmitkPartialVolumeAnalysisWidget::DrawGauss() { } void QmitkPartialVolumeAnalysisWidget::ClearItemModel() { } void QmitkPartialVolumeAnalysisWidget::SetParameters( ParamsType *params, ResultsType *results, HistType *hist ) { this->Clear(); if(params != 0 && results != 0) { hist->Print(); params->Print(); results->Print(); for(unsigned int i=0; iGetXVals()); m_Vals.push_back(hist->GetHVals()); std::vector *xVals = hist->GetXVals(); std::vector *yVals = hist->GetHVals(); std::vector *fiberVals = new std::vector(results->GetFiberVals()); std::vector *nonFiberVals = new std::vector(results->GetNonFiberVals()); std::vector *mixedVals = new std::vector(results->GetMixedVals()); std::vector *combiVals = new std::vector(results->GetCombiVals()); double fiberFA = 0.0; double weights = 0.0; std::cout << "x, y, fiber, nonFiber, mixed, combi" << std::endl; for(int i=0; isize(); ++i) { fiberFA += xVals->at(i) * fiberVals->at(i); weights += fiberVals->at(i); std::cout << xVals->at(i) << " " << yVals->at(i) << " " << fiberVals->at(i) << " " << nonFiberVals->at(i) << " " << mixedVals->at(i) << " " << combiVals->at(i) << std::endl; } fiberFA = fiberFA / weights; QPen pen( Qt::SolidLine ); pen.setWidth(2); pen.setColor(Qt::black); int curveId = this->InsertCurve( "histogram" ); this->SetCurveData( curveId, (*m_Vals[0]), (*m_Vals[1]) ); this->SetCurvePen( curveId, pen ); // this->SetCurveTitle( curveId, "Image Histogram" ); curveId = this->InsertCurve( "fiber" ); this->SetCurveData(curveId, (*hist->GetXVals()), (*fiberVals)); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); this->SetCurveBrush(curveId, QBrush(QColor::fromRgbF(1,0,0,.5), Qt::SolidPattern)); m_Vals.push_back(fiberVals); curveId = this->InsertCurve( "nonfiber" ); this->SetCurveData( curveId, (*hist->GetXVals()), (*nonFiberVals) ); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); this->SetCurveBrush(curveId, QBrush(QColor::fromRgbF(0,1,0,.5), Qt::SolidPattern)); m_Vals.push_back(nonFiberVals); curveId = this->InsertCurve( "mixed" ); this->SetCurveData( curveId, (*hist->GetXVals()), (*mixedVals) ); this->SetCurvePen( curveId, QPen( Qt::NoPen ) ); this->SetCurveBrush(curveId, QBrush(QColor::fromRgbF(.7,.7,.7,.5), Qt::SolidPattern)); m_Vals.push_back(mixedVals); pen.setColor(Qt::blue); curveId = this->InsertCurve( "combi" ); this->SetCurveData( curveId, (*hist->GetXVals()), (*combiVals) ); this->SetCurvePen( curveId, pen ); m_Vals.push_back(combiVals); } this->Replot(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.h index 51bbc1eece..da99fdbb70 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkPartialVolumeAnalysisWidget.h @@ -1,74 +1,73 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-15 18:09:46 +0200 (Fr, 15 Mai 2009) $ -Version: $Revision: 1.12 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkPartialVolumeAnalysisWidget_H_ #define QmitkPartialVolumeAnalysisWidget_H_ #include "QmitkPlotWidget.h" #include #include "QmitkHistogram.h" #include "QmitkExtExports.h" #include "mitkImage.h" #include "mitkPlanarFigure.h" #include "mitkPartialVolumeAnalysisClusteringCalculator.h" #include #include #include #include #include #include #include /** * \brief Widget for displaying image histograms based on the vtkQtChart * framework */ class DIFFUSIONIMAGING_EXPORT QmitkPartialVolumeAnalysisWidget : public QmitkPlotWidget { Q_OBJECT public: typedef mitk::Image::HistogramType HistogramType; typedef mitk::Image::HistogramType::ConstIterator HistogramConstIteratorType; typedef mitk::PartialVolumeAnalysisClusteringCalculator ClusteringType; typedef ClusteringType::ParamsType ParamsType; typedef ClusteringType::ClusterResultType ResultsType; typedef ClusteringType::HistType HistType; /** \brief Set histogram to be displayed directly. */ void SetParameters( ParamsType *params, ResultsType *results, HistType *hist ); QmitkPartialVolumeAnalysisWidget( QWidget * /*parent = 0 */); virtual ~QmitkPartialVolumeAnalysisWidget(); void DrawGauss(); void ClearItemModel(); std::vector< std::vector* > m_Vals; }; #endif /* QmitkPartialVolumeAnalysisWidget_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp index 40298ee687..8dfa1d8adb 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp @@ -1,125 +1,130 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkResidualAnalysisWidget.h" #include #include #include #include #include #include #include #include #include #include QmitkResidualAnalysisWidget::QmitkResidualAnalysisWidget( QWidget * parent ) : QmitkPlotWidget(parent) { m_PlotPicker = new QwtPlotPicker(m_Plot->canvas()); m_PlotPicker->setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection | QwtPicker::DragSelection); m_PlotPicker->setTrackerMode(QwtPicker::ActiveOnly); } QmitkResidualAnalysisWidget::~QmitkResidualAnalysisWidget() { delete m_PlotPicker; } void QmitkResidualAnalysisWidget::DrawMeans() { this->Clear(); this->SetPlotTitle("mean residual per volume"); QPen pen( Qt::SolidLine ); pen.setWidth(1); // Create values for x-axis std::vector xAxis; for(int i=0; iInsertCurve( "Mean" ); this->SetCurveData( curveId, xAxis, m_Means ); this->SetCurvePen( curveId, pen ); this->SetCurveStyle( curveId, QwtPlotCurve::Dots); pen.setColor(Qt::blue); curveId = this->InsertCurve( "Q1" ); this->SetCurveData( curveId, xAxis, m_Q1 ); this->SetCurvePen( curveId, pen ); this->SetCurveStyle( curveId, QwtPlotCurve::Dots); pen.setColor(Qt::red); curveId = this->InsertCurve( "Q3" ); this->SetCurveData( curveId, xAxis, m_Q3 ); this->SetCurvePen( curveId, pen ); this->SetCurveStyle( curveId, QwtPlotCurve::Dots); this->m_Plot->setAxisTitle(0, "Residual"); this->m_Plot->setAxisTitle(3, "DWI Volume"); QwtLegend *legend = new QwtLegend; this->SetLegend(legend, QwtPlot::RightLegend, 0.5); this->Replot(); } void QmitkResidualAnalysisWidget::DrawPercentagesOfOutliers() { this->Clear(); this->SetPlotTitle("Percentage of outliers"); QPen pen( Qt::SolidLine ); pen.setWidth(1); // Create values for x-axis std::vector xAxis; for(int i=0; iInsertCurve( "Outliers" ); this->SetCurveData( curveId, xAxis, m_PercentagesOfOutliers ); this->SetCurvePen( curveId, pen ); //this->SetCurveStyle( curveId, QwtPlotCurve::Fitted); this->m_Plot->setAxisTitle(0, "Percentage of outliers"); this->m_Plot->setAxisTitle(3, "DWI Volume"); QwtLegend *legend = new QwtLegend; this->SetLegend(legend, QwtPlot::RightLegend, 0.5); this->Replot(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.h index 29669ca28f..afd646b664 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.h @@ -1,98 +1,97 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-15 18:09:46 +0200 (Fr, 15 Mai 2009) $ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkResidualAnalysisWidget_H_ #define QmitkResidualAnalysisWidget_H_ #include "QmitkPlotWidget.h" #include //#include "QmitkHistogram.h" #include "QmitkExtExports.h" #include "mitkImage.h" #include "mitkPlanarFigure.h" #include "itkVectorImage.h" //#include #include #include /** * \brief Widget for displaying boxplots * framework */ class DIFFUSIONIMAGING_EXPORT QmitkResidualAnalysisWidget : public QmitkPlotWidget { Q_OBJECT public: QmitkResidualAnalysisWidget( QWidget * parent); virtual ~QmitkResidualAnalysisWidget(); QwtPlot* GetPlot() { return m_Plot; } QwtPlotPicker* m_PlotPicker; void SetMeans(std::vector< double > means) { m_Means = means; } void SetQ1(std::vector< double > q1) { m_Q1 = q1; } void SetQ3(std::vector< double > q3) { m_Q3 = q3; } void SetPercentagesOfOutliers(std::vector< double > perc) { m_PercentagesOfOutliers = perc; } void DrawMeans(); void DrawPercentagesOfOutliers(); protected: std::vector< double > m_Means; std::vector< double > m_Q1; std::vector< double > m_Q3; std::vector< double > m_PercentagesOfOutliers; }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.cpp index 48a770e22e..596a9a4724 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.cpp @@ -1,165 +1,170 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkResidualViewWidget.h" #include #include QmitkResidualViewWidget::QmitkResidualViewWidget( QWidget * parent ) : QGraphicsView(parent) { } QmitkResidualViewWidget::QmitkResidualViewWidget(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent) { } void QmitkResidualViewWidget::mousePressEvent(QMouseEvent* event) { // Panning m_LastPanPoint = event->pos(); setCursor(Qt::ClosedHandCursor); QGraphicsItem *item = this->itemAt(event->pos()); if(item == m_ResidualPixmapItem) { QPointF sceneCoord(mapToScene(event->pos())); QPointF imageCoord(item->mapFromParent(sceneCoord)); int volume = (int)imageCoord.y(); int slice = (int)imageCoord.x(); emit pointSelected(slice, volume); } } void QmitkResidualViewWidget::mouseReleaseEvent(QMouseEvent* event) { setCursor(Qt::OpenHandCursor); m_LastPanPoint = QPoint(); } void QmitkResidualViewWidget::mouseMoveEvent(QMouseEvent *event) { if(!m_LastPanPoint.isNull()) { QPointF delta = mapToScene(m_LastPanPoint) - mapToScene(event->pos()); m_LastPanPoint = event->pos(); SetCenter(m_CurrentCenterPoint + delta); } } void QmitkResidualViewWidget::wheelEvent(QWheelEvent *event) { // Position of the mouse in scene coordinates QPointF before(mapToScene(event->pos())); QPointF screenCenter = m_CurrentCenterPoint; double factor = 1.15; if(event->delta() > 0) { scale(factor, factor); } else { scale(1.0 / factor, 1.0 / factor); } //Get the position after scaling, in scene coords QPointF after(mapToScene(event->pos())); //Get the offset of how the screen moved QPointF offset = before - after; //Adjust to the new center for correct zooming QPointF newCenter = screenCenter + offset; SetCenter(newCenter); } /** * Sets the current centerpoint. Also updates the scene's center point. * Unlike centerOn, which has no way of getting the floating point center * back, SetCenter() stores the center point. It also handles the special * sidebar case. This function will claim the centerPoint to sceneRec ie. * the centerPoint must be within the sceneRec. */ void QmitkResidualViewWidget::SetCenter(const QPointF& center) { QRectF visibleArea = mapToScene(rect()).boundingRect(); QRectF sceneBounds = sceneRect(); double boundX = visibleArea.width() / 2.0 ; double boundY = visibleArea.height() / 2.0; double boundWidth = sceneBounds.width() -2.0 * boundX; double boundHeight = sceneBounds.height() - 2.0 * boundY; //The max boundary that the centerPoint can be to QRectF bounds(boundX, boundY, boundWidth, boundHeight); if(bounds.contains(center)) { m_CurrentCenterPoint = center; } else { //We need to clamp or use the center of the screen if(visibleArea.contains(sceneBounds)) { //Use the center of scene ie. we can see the whole scene m_CurrentCenterPoint = sceneBounds.center(); } else{ m_CurrentCenterPoint = center; //We need to clamp the center. The centerPoint is too large if(center.x() > bounds.x() + bounds.width()) { m_CurrentCenterPoint.setX(bounds.x() + bounds.width()); } else if(center.x() < bounds.x()) { m_CurrentCenterPoint.setX(bounds.x()); } if(center.y() > bounds.y() + bounds.height()) { m_CurrentCenterPoint.setY(bounds.y() + bounds.height()); } else if(center.y() < bounds.y()) { m_CurrentCenterPoint.setY(bounds.y()); } } } // Update the scrollbars centerOn(m_CurrentCenterPoint); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.h index d5034a7293..290a614253 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualViewWidget.h @@ -1,84 +1,83 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-15 18:09:46 +0200 (Fr, 15 Mai 2009) $ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkResidualViewWidget_H_ #define QmitkResidualViewWidget_H_ //#include #include #include #include #include #include #include "QmitkExtExports.h" /** * \brief Widget for displaying the residual between an original dwi image and the dwi estimated from a tensor image * */ class DIFFUSIONIMAGING_EXPORT QmitkResidualViewWidget : public QGraphicsView { Q_OBJECT public: QmitkResidualViewWidget(QWidget *parent = 0); QmitkResidualViewWidget(QGraphicsScene *scene, QWidget *parent = 0); // ~QmitkResidualViewWidget(); void SetResidualPixmapItem(QGraphicsPixmapItem* item) { m_ResidualPixmapItem = item; } signals: void pointSelected(int slice, int volume); protected: void wheelEvent(QWheelEvent *event); void mouseMoveEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); QPointF m_CurrentCenterPoint; QGraphicsPixmapItem* m_ResidualPixmapItem; QPoint m_LastPanPoint; void SetCenter(const QPointF& centerPoint); }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.cpp index 64509314c9..bf105b937d 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.cpp @@ -1,438 +1,443 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkTbssRoiAnalysisWidget.h" #include #include #include #include #include #include #include #include #include #include #include QmitkTbssRoiAnalysisWidget::QmitkTbssRoiAnalysisWidget( QWidget * parent ) : QmitkPlotWidget(parent) { m_PlotPicker = new QwtPlotPicker(m_Plot->canvas()); m_PlotPicker->setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection | QwtPicker::DragSelection); m_PlotPicker->setTrackerMode(QwtPicker::ActiveOnly); } std::vector< std::vector > QmitkTbssRoiAnalysisWidget::CalculateGroupProfiles(std::string preprocessed) { MITK_INFO << "make profiles!"; std::vector< std::vector > profiles; //No results were preprocessed, so they must be calculated now. if(preprocessed == "") { // Iterate through the 4th dim (corresponding to subjects) // and create a profile for every subject int size = m_Projections->GetVectorLength(); for(int s=0; s profile; RoiType::iterator it; it = m_Roi.begin(); while(it != m_Roi.end()) { itk::Index<3> ix = *it; profile.push_back(m_Projections->GetPixel(ix).GetElement(s)); it++; } int pSize = profile.size(); profiles.push_back(profile); } } else{ // Use preprocessed results std::ifstream file(preprocessed.c_str()); if(file.is_open()) { std::string line; while(getline(file,line)) { std::vector tokens; Tokenize(line, tokens); std::vector::iterator it; it = tokens.begin(); std::vector< double > profile; while(it != tokens.end()) { std::string s = *it; profile.push_back (atof( s.c_str() ) ); ++it; } profiles.push_back(profile); } } } // Calculate the averages // Here a check could be build in to check whether all profiles have // the same length, but this should normally be the case if the input // data were corrected with the TBSS Module. std::vector< std::vector > groupProfiles; std::vector< std::pair >::iterator it; it = m_Groups.begin(); int c = 0; //the current profile number int nprof = profiles.size(); while(it != m_Groups.end() && profiles.size() > 0) { std::pair p = *it; int size = p.second; //initialize a vector of the right length with zeroes std::vector averageProfile; for(int i=0; iClear(); m_Vals.clear(); std::vector v1; std::vector > groupProfiles = CalculateGroupProfiles(preprocessed); std::vector xAxis; for(int i=0; iSetPlotTitle( title.c_str() ); QPen pen( Qt::SolidLine ); pen.setWidth(2); std::vector< std::pair >::iterator it; it = m_Groups.begin(); int c = 0; //the current profile number QColor colors[4] = {Qt::green, Qt::blue, Qt::yellow, Qt::red}; while(it != m_Groups.end() && groupProfiles.size() > 0) { std::pair< std::string, int > group = *it; pen.setColor(colors[c]); int curveId = this->InsertCurve( group.first.c_str() ); this->SetCurveData( curveId, xAxis, groupProfiles.at(c) ); this->SetCurvePen( curveId, pen ); c++; it++; } QwtLegend *legend = new QwtLegend; this->SetLegend(legend, QwtPlot::RightLegend, 0.5); std::cout << m_Measure << std::endl; this->m_Plot->setAxisTitle(0, m_Measure.c_str()); this->m_Plot->setAxisTitle(3, "Position"); this->Replot(); } void QmitkTbssRoiAnalysisWidget::PlotFiberBundles(TractContainerType tracts, mitk::Image *img) { this->Clear(); std::vector::iterator it = tracts.begin(); // Match points on tracts. Take the smallest tract and match all others on this one int min = std::numeric_limits::max(); TractType smallestTract; while(it != tracts.end()) { TractType tract = *it; if(tract.size() correspondingIndices; TractType correspondingPoints; for(int i=0; i::max(); int correspondingIndex = 0; PointType correspondingPoint; // Search for the point on the second tract with the smallest distance // to p and memorize it for(int j=0; j > profiles; it = tracts.begin(); while(it != tracts.end()) { std::cout << "Tract\n"; TractType tract = *it; TractType::iterator tractIt = tract.begin(); std::vector profile; while(tractIt != tract.end()) { PointType p = *tractIt; std::cout << p[0] << ' ' << p[1] << ' ' << p[2] << '\n'; // Get value from image profile.push_back( (double)img->GetPixelValueByWorldCoordinate(p) ); ++tractIt; } profiles.push_back(profile); std::cout << std::endl; ++it; } std::string title = "Fiber bundle plot"; this->SetPlotTitle( title.c_str() ); QPen pen( Qt::SolidLine ); pen.setWidth(2); std::vector< std::vector >::iterator profit = profiles.begin(); int id=0; while(profit != profiles.end()) { std::vector profile = *profit; std::vector xAxis; for(int i=0; iInsertCurve( QString::number(id).toStdString().c_str() ); this->SetCurveData( curveId, xAxis, profile ); ++profit; id++; } this->Replot(); } void QmitkTbssRoiAnalysisWidget::Boxplots() { this->Clear(); } void QmitkTbssRoiAnalysisWidget::drawBar(int x) { m_Plot->detachItems(QwtPlotItem::Rtti_PlotMarker, true); QwtPlotMarker *mX = new QwtPlotMarker(); //mX->setLabel(QString::fromLatin1("selected point")); mX->setLabelAlignment(Qt::AlignLeft | Qt::AlignBottom); mX->setLabelOrientation(Qt::Vertical); mX->setLineStyle(QwtPlotMarker::VLine); mX->setLinePen(QPen(Qt::black, 0, Qt::SolidLine)); mX->setXValue(x); mX->attach(m_Plot); this->Replot(); } QmitkTbssRoiAnalysisWidget::~QmitkTbssRoiAnalysisWidget() { delete m_PlotPicker; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.h index 96ee4d3320..90b062a10b 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkTbssRoiAnalysisWidget.h @@ -1,158 +1,157 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-15 18:09:46 +0200 (Fr, 15 Mai 2009) $ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkTbssRoiAnalysisWidget_H_ #define QmitkTbssRoiAnalysisWidget_H_ #include "QmitkPlotWidget.h" #include //#include "QmitkHistogram.h" #include "QmitkExtExports.h" #include "mitkImage.h" #include "mitkPlanarFigure.h" #include "itkVectorImage.h" //#include //#include #include #include #include #include #include typedef itk::VectorImage VectorImageType; typedef std::vector< itk::Index<3> > RoiType; typedef itk::Point PointType; typedef std::vector< PointType> TractType; typedef std::vector< TractType > TractContainerType; /** * \brief Widget for displaying boxplots * framework */ class DIFFUSIONIMAGING_EXPORT QmitkTbssRoiAnalysisWidget : public QmitkPlotWidget { Q_OBJECT public: QmitkTbssRoiAnalysisWidget( QWidget * parent); virtual ~QmitkTbssRoiAnalysisWidget(); void SetGroups(std::vector< std::pair > groups) { m_Groups = groups; } void DrawProfiles(std::string preprocessed); void PlotFiberBundles(TractContainerType tracts, mitk::Image* img); void Boxplots(); void SetProjections(VectorImageType::Pointer projections) { m_Projections = projections; } void SetRoi(RoiType roi) { m_Roi = roi; } void SetStructure(std::string structure) { m_Structure = structure; } void SetMeasure(std::string measure) { m_Measure = measure; } QwtPlot* GetPlot() { return m_Plot; } QwtPlotPicker* m_PlotPicker; void drawBar(int x); std::vector > GetVals() { return m_Vals; } protected: std::vector< std::vector > m_Vals; std::vector< std::vector > CalculateGroupProfiles(std::string preprocessed); void Tokenize(const std::string& str, std::vector& tokens, const std::string& delimiters = " ") { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } std::vector< std::pair > m_Groups; VectorImageType::Pointer m_Projections; RoiType m_Roi; std::string m_Structure; std::string m_Measure; }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.cpp index bf4b45eab5..36c7ca2d3a 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.cpp @@ -1,678 +1,677 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // ####### Blueberry includes ####### #include #include // ####### Qmitk includes ####### #include "QmitkBrainNetworkAnalysisView.h" #include "QmitkStdMultiWidget.h" // ####### Qt includes ####### #include // ####### ITK includes ####### #include // ####### MITK includes ####### #include #include "mitkConnectomicsSyntheticNetworkGenerator.h" #include "mitkConnectomicsSimulatedAnnealingManager.h" #include "mitkConnectomicsSimulatedAnnealingPermutationModularity.h" #include "mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h" // Includes for image casting between ITK and MITK #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkImageAccessByItk.h" const std::string QmitkBrainNetworkAnalysisView::VIEW_ID = "org.mitk.views.brainnetworkanalysis"; QmitkBrainNetworkAnalysisView::QmitkBrainNetworkAnalysisView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_ConnectomicsNetworkCreator( mitk::ConnectomicsNetworkCreator::New() ) , m_demomode( false ) , m_currentIndex( 0 ) { } QmitkBrainNetworkAnalysisView::~QmitkBrainNetworkAnalysisView() { } void QmitkBrainNetworkAnalysisView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkBrainNetworkAnalysisViewControls; m_Controls->setupUi( parent ); QObject::connect( m_Controls->convertToRGBAImagePushButton, SIGNAL(clicked()), this, SLOT(OnConvertToRGBAImagePushButtonClicked()) ); QObject::connect( m_Controls->networkifyPushButton, SIGNAL(clicked()), this, SLOT(OnNetworkifyPushButtonClicked()) ); QObject::connect( m_Controls->syntheticNetworkCreationPushButton, SIGNAL(clicked()), this, SLOT(OnSyntheticNetworkCreationPushButtonClicked()) ); QObject::connect( (QObject*)( m_Controls->syntheticNetworkComboBox ), SIGNAL(currentIndexChanged (int)), this, SLOT(OnSyntheticNetworkComboBoxCurrentIndexChanged(int)) ); QObject::connect( (QObject*)( m_Controls->modularizePushButton ), SIGNAL(clicked()), this, SLOT(OnModularizePushButtonClicked()) ); } // GUI is different for developer and demo mode m_demomode = false; if( m_demomode ) { this->m_Controls->convertToRGBAImagePushButton->hide(); this->m_Controls->networkifyPushButton->show(); this->m_Controls->networkifyPushButton->setText( "Create Network" ); this->m_Controls->modularizePushButton->hide(); this->m_Controls->syntheticNetworkOptionsGroupBox->show(); //--------------------------- fill comboBox--------------------------- this->m_Controls->syntheticNetworkComboBox->insertItem(0,"Regular lattice"); this->m_Controls->syntheticNetworkComboBox->insertItem(1,"Heterogenic sphere"); this->m_Controls->syntheticNetworkComboBox->insertItem(2,"Random network"); } else { this->m_Controls->convertToRGBAImagePushButton->show(); this->m_Controls->networkifyPushButton->show(); this->m_Controls->networkifyPushButton->setText( "Networkify" ); this->m_Controls->modularizePushButton->show(); this->m_Controls->syntheticNetworkOptionsGroupBox->show(); //--------------------------- fill comboBox--------------------------- this->m_Controls->syntheticNetworkComboBox->insertItem(0,"Regular lattice"); this->m_Controls->syntheticNetworkComboBox->insertItem(1,"Heterogenic sphere"); this->m_Controls->syntheticNetworkComboBox->insertItem(2,"Random network"); this->m_Controls->syntheticNetworkComboBox->insertItem(3,"Scale free network"); this->m_Controls->syntheticNetworkComboBox->insertItem(4,"Small world network"); } this->WipeDisplay(); } void QmitkBrainNetworkAnalysisView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkBrainNetworkAnalysisView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkBrainNetworkAnalysisView::WipeDisplay() { m_Controls->lblWarning->setVisible( true ); m_Controls->inputImageOneNameLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->inputImageOneNameLabel->setVisible( false ); m_Controls->inputImageOneLabel->setVisible( false ); m_Controls->inputImageTwoNameLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->inputImageTwoNameLabel->setVisible( false ); m_Controls->inputImageTwoLabel->setVisible( false ); m_Controls->numberOfVerticesLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->numberOfEdgesLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->numberOfSelfLoopsLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->averageDegreeLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->connectionDensityLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->efficiencyLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->globalClusteringLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->betweennessNetworkHistogramCanvas->SetHistogram( NULL ); m_Controls->degreeNetworkHistogramCanvas->SetHistogram( NULL ); m_Controls->shortestPathNetworkHistogramCanvas->SetHistogram( NULL ); m_Controls->betweennessNetworkHistogramCanvas->update(); m_Controls->degreeNetworkHistogramCanvas->update(); m_Controls->shortestPathNetworkHistogramCanvas->update(); m_Controls->betweennessNetworkHistogramCanvas->Clear(); m_Controls->degreeNetworkHistogramCanvas->Clear(); m_Controls->shortestPathNetworkHistogramCanvas->Clear(); m_Controls->betweennessNetworkHistogramCanvas->Replot(); m_Controls->degreeNetworkHistogramCanvas->Replot(); m_Controls->shortestPathNetworkHistogramCanvas->Replot(); } void QmitkBrainNetworkAnalysisView::OnSelectionChanged( std::vector nodes ) { this->WipeDisplay(); // Valid options are either // 1 image (parcellation) // // 1 image (parcellation) // 1 fiber bundle // // 1 network if( nodes.size() > 2 ) { return; } bool alreadyFiberBundleSelected( false ), alreadyImageSelected( false ), currentFormatUnknown( true ); // iterate all selected objects, adjust warning visibility for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; currentFormatUnknown = true; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { currentFormatUnknown = false; if( alreadyImageSelected ) { this->WipeDisplay(); return; } alreadyImageSelected = true; m_Controls->lblWarning->setVisible( false ); m_Controls->inputImageOneNameLabel->setText(node->GetName().c_str()); m_Controls->inputImageOneNameLabel->setVisible( true ); m_Controls->inputImageOneLabel->setVisible( true ); } if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { currentFormatUnknown = false; // a fiber bundle has to be in conjunction with a parcellation if( nodes.size() != 2 || alreadyFiberBundleSelected ) { this->WipeDisplay(); return; } alreadyFiberBundleSelected = true; m_Controls->lblWarning->setVisible( false ); m_Controls->inputImageTwoNameLabel->setText(node->GetName().c_str()); m_Controls->inputImageTwoNameLabel->setVisible( true ); m_Controls->inputImageTwoLabel->setVisible( true ); } { // network section mitk::ConnectomicsNetwork* network = dynamic_cast( node->GetData() ); if( node.IsNotNull() && network ) { currentFormatUnknown = false; if( nodes.size() != 1 ) { // only valid option is a single network this->WipeDisplay(); return; } m_Controls->lblWarning->setVisible( false ); m_Controls->inputImageOneNameLabel->setText(node->GetName().c_str()); m_Controls->inputImageOneNameLabel->setVisible( true ); m_Controls->inputImageOneLabel->setVisible( true ); int noVertices = network->GetNumberOfVertices(); int noEdges = network->GetNumberOfEdges(); int noSelfLoops = network->GetNumberOfSelfLoops(); double averageDegree = network->GetAverageDegree(); double connectionDensity = network->GetConnectionDensity(); double globalClustering = network->GetGlobalClusteringCoefficient(); m_Controls->numberOfVerticesLabel->setText( QString::number( noVertices ) ); m_Controls->numberOfEdgesLabel->setText( QString::number( noEdges ) ); m_Controls->numberOfSelfLoopsLabel->setText( QString::number( noSelfLoops ) ); m_Controls->averageDegreeLabel->setText( QString::number( averageDegree ) ); m_Controls->connectionDensityLabel->setText( QString::number( connectionDensity ) ); m_Controls->globalClusteringLabel->setText( QString::number( globalClustering ) ); mitk::ConnectomicsNetwork::Pointer connectomicsNetwork( network ); mitk::ConnectomicsHistogramsContainer *histogramContainer = histogramCache[ connectomicsNetwork ]; if(histogramContainer) { m_Controls->betweennessNetworkHistogramCanvas->SetHistogram( histogramContainer->GetBetweennessHistogram() ); m_Controls->degreeNetworkHistogramCanvas->SetHistogram( histogramContainer->GetDegreeHistogram() ); m_Controls->shortestPathNetworkHistogramCanvas->SetHistogram( histogramContainer->GetShortestPathHistogram() ); m_Controls->betweennessNetworkHistogramCanvas->DrawProfiles(); m_Controls->degreeNetworkHistogramCanvas->DrawProfiles(); m_Controls->shortestPathNetworkHistogramCanvas->DrawProfiles(); double efficiency = histogramContainer->GetShortestPathHistogram()->GetEfficiency(); m_Controls->efficiencyLabel->setText( QString::number( efficiency ) ); } } } // end network section if ( currentFormatUnknown ) { this->WipeDisplay(); return; } } // end for loop } void QmitkBrainNetworkAnalysisView::OnSyntheticNetworkComboBoxCurrentIndexChanged(int currentIndex) { m_currentIndex = currentIndex; switch (m_currentIndex) { case 0: this->m_Controls->parameterOneLabel->setText( "Nodes per side" ); this->m_Controls->parameterTwoLabel->setText( "Internode distance" ); this->m_Controls->parameterOneSpinBox->setEnabled( true ); this->m_Controls->parameterOneSpinBox->setValue( 5 ); this->m_Controls->parameterTwoDoubleSpinBox->setEnabled( true ); this->m_Controls->parameterTwoDoubleSpinBox->setMaximum( 999.999 ); this->m_Controls->parameterTwoDoubleSpinBox->setValue( 10.0 ); break; case 1: this->m_Controls->parameterOneLabel->setText( "Number of nodes" ); this->m_Controls->parameterTwoLabel->setText( "Radius" ); this->m_Controls->parameterOneSpinBox->setEnabled( true ); this->m_Controls->parameterOneSpinBox->setValue( 1000 ); this->m_Controls->parameterTwoDoubleSpinBox->setEnabled( true ); this->m_Controls->parameterTwoDoubleSpinBox->setMaximum( 999.999 ); this->m_Controls->parameterTwoDoubleSpinBox->setValue( 50.0 ); break; case 2: this->m_Controls->parameterOneLabel->setText( "Number of nodes" ); this->m_Controls->parameterTwoLabel->setText( "Edge percentage" ); this->m_Controls->parameterOneSpinBox->setEnabled( true ); this->m_Controls->parameterOneSpinBox->setValue( 100 ); this->m_Controls->parameterTwoDoubleSpinBox->setEnabled( true ); this->m_Controls->parameterTwoDoubleSpinBox->setMaximum( 1.0 ); this->m_Controls->parameterTwoDoubleSpinBox->setValue( 0.5 ); break; case 3: //GenerateSyntheticScaleFreeNetwork( network, 1000 ); break; case 4: //GenerateSyntheticSmallWorldNetwork( network, 1000 ); break; default: this->m_Controls->parameterOneLabel->setText( "Parameter 1" ); this->m_Controls->parameterTwoLabel->setText( "Paramater 2" ); this->m_Controls->parameterOneSpinBox->setEnabled( false ); this->m_Controls->parameterOneSpinBox->setValue( 0 ); this->m_Controls->parameterTwoDoubleSpinBox->setEnabled( false ); this->m_Controls->parameterTwoDoubleSpinBox->setValue( 0.0 ); } } void QmitkBrainNetworkAnalysisView::OnSyntheticNetworkCreationPushButtonClicked() { // warn if trying to create a very big network // big network is a network with > 5000 nodes (estimate) // this might fill up the memory to the point it freezes int numberOfNodes( 0 ); switch (m_currentIndex) { case 0: numberOfNodes = this->m_Controls->parameterOneSpinBox->value() * this->m_Controls->parameterOneSpinBox->value() * this->m_Controls->parameterOneSpinBox->value(); break; case 1: numberOfNodes = this->m_Controls->parameterOneSpinBox->value(); break; case 2: numberOfNodes = this->m_Controls->parameterOneSpinBox->value(); break; case 3: // not implemented yet break; case 4: // not implemented yet break; default: break; } if( numberOfNodes > 5000 ) { QMessageBox msgBox; msgBox.setText("Trying to generate very large network."); msgBox.setIcon( QMessageBox::Warning ); msgBox.setInformativeText("You are trying to generate a network with more than 5000 nodes, this is very resource intensive and might lead to program instability. Proceed with network generation?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: // continue break; case QMessageBox::No: // stop return; break; default: // should never be reached break; } } // proceed mitk::ConnectomicsSyntheticNetworkGenerator::Pointer generator = mitk::ConnectomicsSyntheticNetworkGenerator::New(); mitk::DataNode::Pointer networkNode = mitk::DataNode::New(); int parameterOne = this->m_Controls->parameterOneSpinBox->value(); double parameterTwo = this->m_Controls->parameterTwoDoubleSpinBox->value(); ////add network to datastorage networkNode->SetData( generator->CreateSyntheticNetwork( m_currentIndex, parameterOne, parameterTwo ) ); networkNode->SetName( mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_DEFAULT_CNF_NAME ); if( generator->WasGenerationSuccessfull() ) { this->GetDefaultDataStorage()->Add( networkNode ); } else { MITK_WARN << "Problem occured during synthetic network generation."; } return; } void QmitkBrainNetworkAnalysisView::OnConvertToRGBAImagePushButtonClicked() { std::vector nodes = this->GetDataManagerSelection(); if (nodes.empty()) return; mitk::DataNode* node = nodes.front(); if (!node) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_CONNECTOMICS_CREATION, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_SELECTION_WARNING); return; } // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item (the image) mitk::BaseData* data = node->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image* image = dynamic_cast( data ); if (image) { std::stringstream message; std::string name; message << mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_PERFORMING_IMAGE_PROCESSING_FOR_IMAGE; if (node->GetName(name)) { // a property called "name" was found for this DataNode message << "'" << name << "'"; } message << "."; MITK_INFO << message.str(); // Convert to RGBA AccessByItk( image, TurnIntoRGBA ); this->GetDefaultDataStorage()->GetNamedNode( mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_DEFAULT_RGBA_NAME )->GetData()->SetGeometry( node->GetData()->GetGeometry() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } template < typename TPixel, unsigned int VImageDimension > void QmitkBrainNetworkAnalysisView::TurnIntoRGBA( itk::Image* inputImage) { typedef itk::RGBAPixel< unsigned char > RGBAPixelType; typedef itk::Image< TPixel, VImageDimension > TemplateImageType; typedef itk::Image< RGBAPixelType, VImageDimension > RGBAImageType; itk::ImageRegionIterator it_inputImage(inputImage, inputImage->GetLargestPossibleRegion()); TPixel minimumValue, maximumValue; it_inputImage.GoToBegin(); maximumValue = minimumValue = it_inputImage.Value(); for(it_inputImage.GoToBegin(); !it_inputImage.IsAtEnd(); ++it_inputImage) { if ( it_inputImage.Value() < minimumValue ) { minimumValue = it_inputImage.Value(); } else { if ( it_inputImage.Value() > maximumValue ) { maximumValue = it_inputImage.Value(); } } } int range = int ( maximumValue - minimumValue ); //needs to be castable to int int offset = int ( minimumValue ); if ( range < 0 ) //error { return; } std::vector< unsigned int > histogram; histogram.resize( range + 1, 0 ); for(it_inputImage.GoToBegin(); !it_inputImage.IsAtEnd(); ++it_inputImage) { histogram[ int ( it_inputImage.Value() ) - offset ] += 1; } int gapCounter = 0; //this variable will be used to count the empty labels //stores how much has to be subtracted from the image to remove gaps std::vector< TPixel > subtractionStorage; subtractionStorage.resize( range + 1, 0 ); for( int index = 0; index <= range; index++ ) { if( histogram[ index ] == 0 ) { gapCounter++; //if the label is empty, increase gapCounter } else { subtractionStorage[ index ] = TPixel ( gapCounter ); } } //remove gaps from label image for(it_inputImage.GoToBegin(); !it_inputImage.IsAtEnd(); ++it_inputImage) { it_inputImage.Value() = it_inputImage.Value() - subtractionStorage[ int ( it_inputImage.Value() ) ]; } // create colour vector std::vector< RGBAPixelType > lookupTable; { RGBAPixelType backgroundColour; for( int elementIndex = 0; elementIndex < 4; ++elementIndex ) { backgroundColour.SetElement( elementIndex, 0 ); } lookupTable.push_back( backgroundColour ); for(int colourNumber = 0; colourNumber < range ; ++colourNumber) { RGBAPixelType colour; for( int elementIndex = 0; elementIndex < 3; ++elementIndex ) { colour.SetElement( elementIndex, rand() % 256 ); } colour.SetAlpha( 255 ); lookupTable.push_back( colour ); } } // create RGBA image typename RGBAImageType::Pointer rgbaImage = RGBAImageType::New(); rgbaImage->SetRegions(inputImage->GetLargestPossibleRegion().GetSize()); rgbaImage->SetSpacing(inputImage->GetSpacing()); rgbaImage->SetOrigin(inputImage->GetOrigin()); rgbaImage->Allocate(); //fill with appropriate colours itk::ImageRegionIterator it_rgbaImage(rgbaImage, rgbaImage->GetLargestPossibleRegion()); for(it_inputImage.GoToBegin(), it_rgbaImage.GoToBegin(); !it_inputImage.IsAtEnd(); ++it_inputImage, ++it_rgbaImage) { it_rgbaImage.Value() = lookupTable[ int ( it_inputImage.Value() ) ]; } mitk::Image::Pointer mitkRGBAImage = mitk::ImportItkImage( rgbaImage ); mitk::DataNode::Pointer rgbaImageNode = mitk::DataNode::New(); rgbaImageNode->SetData(mitkRGBAImage); rgbaImageNode->SetProperty(mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_NAME, mitk::StringProperty::New(mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_DEFAULT_RGBA_NAME)); rgbaImageNode->SetBoolProperty( mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_VOLUMERENDERING, true); this->GetDefaultDataStorage()->Add( rgbaImageNode ); } void QmitkBrainNetworkAnalysisView::OnNetworkifyPushButtonClicked() { std::vector nodes = this->GetDataManagerSelection(); if ( nodes.empty() ) { QMessageBox::information( NULL, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_CONNECTOMICS_CREATION, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_SELECTION_WARNING); return; } if (! ( nodes.size() == 2 ) ) { QMessageBox::information( NULL, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_CONNECTOMICS_CREATION, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_SELECTION_WARNING); return; } mitk::DataNode* firstNode = nodes.front(); mitk::DataNode* secondNode = nodes.at(1); if (!firstNode) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_CONNECTOMICS_CREATION, mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_SELECTION_WARNING); return; } // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item (the image) mitk::BaseData* firstData = firstNode->GetData(); mitk::BaseData* secondData = secondNode->GetData(); if (firstData && secondData) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image* image = dynamic_cast( firstData ); mitk::FiberBundleX* fiberBundle = dynamic_cast( secondData ); // check whether order was switched if (! (image && fiberBundle) ) { image = dynamic_cast( secondData ); fiberBundle = dynamic_cast( firstData ); } if (image && fiberBundle) { m_ConnectomicsNetworkCreator->SetSegmentation( image ); m_ConnectomicsNetworkCreator->SetFiberBundle( fiberBundle ); m_ConnectomicsNetworkCreator->CreateNetworkFromFibersAndSegmentation(); mitk::DataNode::Pointer networkNode = mitk::DataNode::New(); ////add network to datastorage networkNode->SetData( m_ConnectomicsNetworkCreator->GetNetwork() ); networkNode->SetName( mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_DEFAULT_CNF_NAME ); this->GetDefaultDataStorage()->Add( networkNode ); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkBrainNetworkAnalysisView::OnModularizePushButtonClicked() { std::vector nodes = this->GetDataManagerSelection(); if ( nodes.empty() ) { QMessageBox::information( NULL, "Modularization calculation", "Please select exactly one network."); return; } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { return; } { mitk::ConnectomicsNetwork* network = dynamic_cast( node->GetData() ); if( node.IsNotNull() && network ) { typedef mitk::ConnectomicsSimulatedAnnealingPermutationModularity::ToModuleMapType MappingType; int depthOfModuleRecursive( 2 ); double startTemperature( 2.0 ); double stepSize( 4.0 ); mitk::ConnectomicsNetwork::Pointer connectomicsNetwork( network ); mitk::ConnectomicsSimulatedAnnealingManager::Pointer manager = mitk::ConnectomicsSimulatedAnnealingManager::New(); mitk::ConnectomicsSimulatedAnnealingPermutationModularity::Pointer permutation = mitk::ConnectomicsSimulatedAnnealingPermutationModularity::New(); mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::Pointer costFunction = mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::New(); permutation->SetCostFunction( costFunction.GetPointer() ); permutation->SetNetwork( connectomicsNetwork ); permutation->SetDepth( depthOfModuleRecursive ); permutation->SetStepSize( stepSize ); manager->SetPermutation( permutation.GetPointer() ); manager->RunSimulatedAnnealing( startTemperature, stepSize ); MappingType mapping = permutation->GetMapping(); MappingType::iterator iter = mapping.begin(); MappingType::iterator end = mapping.end(); int loop( 0 ); while( iter != end ) { MBI_DEBUG << "Vertex " << iter->first << " belongs to module " << iter->second ; MBI_INFO << "Vertex " << iter->first << " belongs to module " << iter->second ; iter++; } MBI_DEBUG << "Overall number of modules is " << permutation->getNumberOfModules( &mapping ) ; MBI_DEBUG << "Cost is " << costFunction->Evaluate( network, &mapping ) ; MBI_INFO << "Overall number of modules is " << permutation->getNumberOfModules( &mapping ) ; MBI_INFO << "Cost is " << costFunction->Evaluate( network, &mapping ) ; return; } } } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.h index 36592fa804..ef6158c2bc 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkBrainNetworkAnalysisView.h @@ -1,116 +1,115 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkBrainNetworkAnalysisView_h #define QmitkBrainNetworkAnalysisView_h #include #include #include "ui_QmitkBrainNetworkAnalysisViewControls.h" #include "mitkConnectomicsNetworkCreator.h" #include "mitkConnectomicsNetworkMapper3D.h" #include "mitkConnectomicsHistogramCache.h" // ####### ITK includes ####### #include /*! \brief QmitkBrainNetworkAnalysisView This bundle provides GUI for the brain network analysis algorithms. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkBrainNetworkAnalysisView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkBrainNetworkAnalysisView(); virtual ~QmitkBrainNetworkAnalysisView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /// \brief Called when the user clicks the GUI button void OnConvertToRGBAImagePushButtonClicked(); /// \brief Align two images by copying the geometry void OnNetworkifyPushButtonClicked(); /// \brief Create synthetic networks void OnSyntheticNetworkCreationPushButtonClicked(); /// \brief Adjust parameters depending on synthetic network type void OnSyntheticNetworkComboBoxCurrentIndexChanged(int currentIndex); /// \brief Create modularization of network void OnModularizePushButtonClicked(); protected: // ####### Functions ####### /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); /// \brief Converts an image into a RGBA image template < typename TPixel, unsigned int VImageDimension > void TurnIntoRGBA( itk::Image* inputImage); /// \brief Wipe display and empty statistics void WipeDisplay(); // ####### Variables ####### Ui::QmitkBrainNetworkAnalysisViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; mitk::ConnectomicsNetworkCreator::Pointer m_ConnectomicsNetworkCreator; mitk::ConnectomicsNetworkMapper3D::Pointer m_NetworkMapper; /// Cache for histograms mitk::ConnectomicsHistogramCache histogramCache; // Demo/Developer mode toggle bool m_demomode; // The selected synthetic network type int m_currentIndex; }; #endif // _QMITKBRAINNETWORKANALYSISVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp index 5aaab3a638..ebc822274e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp @@ -1,99 +1,98 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkNetworkHistogramCanvas.h" #include #include #include #include #include #include #include QmitkNetworkHistogramCanvas::QmitkNetworkHistogramCanvas(QWidget * parent, Qt::WindowFlags f) : QmitkPlotWidget(parent) { setEnabled(false); setFocusPolicy(Qt::ClickFocus); } QmitkNetworkHistogramCanvas::~QmitkNetworkHistogramCanvas() { } void QmitkNetworkHistogramCanvas::DrawProfiles( ) { this->Clear(); if( !(m_Histogram) || !( m_Histogram->IsValid() )) { return; } std::vector histogramVector = m_Histogram->GetHistogramVector(); // create a data vector which contains the points to be drawn // to create nice bars, the curve takes four points for each bar std::vector< std::pair< double, double > > dataPointsVector; std::pair< double, double > leftBottom, leftTop, rightTop, rightBottom; // how wide the bar is, the gap to the next one will be 1 - barWidth double barWidth( 0.95 ); const int range = histogramVector.size(); for(int i=0; i < range ; ++i) { leftBottom.first = ((double) i) ; leftBottom.second = 0.0; leftTop.first = ((double) i) ; leftTop.second = histogramVector.at( i ); rightTop.first = ((double) i) + barWidth ; rightTop.second = histogramVector.at( i ); rightBottom.first = ((double) i) + barWidth ; rightBottom.second = 0.0; dataPointsVector.push_back( leftBottom ); dataPointsVector.push_back( leftTop ); dataPointsVector.push_back( rightTop ); dataPointsVector.push_back( rightBottom ); } this->SetPlotTitle( (m_Histogram->GetSubject()).c_str() ); QPen pen( Qt::NoPen ); QBrush brush( Qt::SolidPattern ); brush.setColor( Qt::blue ); int curveId = this->InsertCurve( (m_Histogram->GetSubject()).c_str() ); this->SetCurveData( curveId, dataPointsVector ); this->SetCurvePen( curveId, pen ); this->SetCurveBrush( curveId, brush ); // Axis 0 is the y axis, axis to the x axis this->m_Plot->setAxisTitle(0, "n"); //this->m_Plot->setAxisTitle(2, ""); this->Replot(); } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.h index 37a84e83ff..73a310d7e1 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.h @@ -1,75 +1,74 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkNetworkHistogramCanvas_H_INCLUDED #define QmitkNetworkHistogramCanvas_H_INCLUDED #include #include #include "QmitkPlotWidget.h" #include #include #include #include #include //##Documentation //## @brief A widget for displaying the data in a ConnectomicsHistogramBase class QmitkNetworkHistogramCanvas : public QmitkPlotWidget { Q_OBJECT public: QmitkNetworkHistogramCanvas( QWidget * parent=0, Qt::WindowFlags f = 0 ); ~QmitkNetworkHistogramCanvas(); /** @brief Returns the histogram the canvas is using */ mitk::ConnectomicsHistogramBase* GetHistogram() { return m_Histogram; } /** @brief Set the histogram the canvas is to use */ void SetHistogram(mitk::ConnectomicsHistogramBase *histogram) { m_Histogram = histogram; } /** @brief Draw the histogram */ void DrawProfiles(); /** @brief Return the plot */ QwtPlot* GetPlot() { return m_Plot; } protected: /** @brief The histogram to be plotted */ mitk::ConnectomicsHistogramBase *m_Histogram; }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp index cb742dd831..b33fe57deb 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp @@ -1,1775 +1,1773 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkControlVisualizationPropertiesView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" #include "mitkTbssImage.h" #include "mitkPlanarFigure.h" #include "mitkFiberBundleX.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFiberBundleInteractor.h" #include "mitkPlanarFigureInteractor.h" #include #include #include #include "mitkGlobalInteraction.h" #include "mitkGeometry2D.h" #include "mitkSegTool2D.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" #include #include "qwidgetaction.h" #include "qcolordialog.h" const std::string QmitkControlVisualizationPropertiesView::VIEW_ID = "org.mitk.views.controlvisualizationpropertiesview"; using namespace berry; struct CvpSelListener : ISelectionListener { berryObjectMacro(CvpSelListener); CvpSelListener(QmitkControlVisualizationPropertiesView* view) { m_View = view; } void ApplySettings(mitk::DataNode::Pointer node) { bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("ShowMaxNumber", val); m_View->m_Controls->m_ShowMaxNumber->setValue(val); m_View->m_Controls->m_NormalizationDropdown->setCurrentIndex(dynamic_cast(node->GetProperty("Normalization"))->GetValueAsId()); float fval; node->GetFloatProperty("Scaling",fval); m_View->m_Controls->m_ScalingFactor->setValue(fval); m_View->m_Controls->m_AdditionalScaling->setCurrentIndex(dynamic_cast(node->GetProperty("ScaleBy"))->GetValueAsId()); node->GetFloatProperty("IndexParam1",fval); m_View->m_Controls->m_IndexParam1->setValue(fval); node->GetFloatProperty("IndexParam2",fval); m_View->m_Controls->m_IndexParam2->setValue(fval); } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); m_View->m_Controls->m_VisibleOdfsON_T->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_S->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_C->setVisible(false); m_View->m_Controls->m_TextureIntON->setVisible(false); m_View->m_Controls->m_ImageControlsFrame->setVisible(false); m_View->m_Controls->m_PlanarFigureControlsFrame->setVisible(false); m_View->m_Controls->m_BundleControlsFrame->setVisible(false); m_View->m_SelectedNode = 0; if(m_View->m_CurrentSelection.IsNull()) return; if(m_View->m_CurrentSelection->Size() == 1) { mitk::DataNodeObject::Pointer nodeObj = m_View->m_CurrentSelection->Begin()->Cast(); if(nodeObj.IsNotNull()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV mitk::BaseData* nodeData = node->GetData(); if(nodeData != NULL ) { if(dynamic_cast(nodeData) != 0) { m_View->m_Controls->m_PlanarFigureControlsFrame->setVisible(true); m_View->m_SelectedNode = node; float val; node->GetFloatProperty("planarfigure.line.width", val); m_View->m_Controls->m_PFWidth->setValue((int)(val*10.0)); QString label = "Width %1"; label = label.arg(val); m_View->m_Controls->label_pfwidth->setText(label); float color[3]; node->GetColor( color, NULL, "planarfigure.default.line.color"); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_View->m_Controls->m_PFColor->setAutoFillBackground(true); m_View->m_Controls->m_PFColor->setStyleSheet(styleSheet); node->GetColor( color, NULL, "color"); styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_View->PlanarFigureFocus(); } if(dynamic_cast(nodeData) != 0) { m_View->m_Controls->m_BundleControlsFrame->setVisible(true); m_View->m_SelectedNode = node; if(m_View->m_CurrentPickingNode != 0 && node.GetPointer() != m_View->m_CurrentPickingNode) { m_View->m_Controls->m_Crosshair->setEnabled(false); } else { m_View->m_Controls->m_Crosshair->setEnabled(true); } float val; node->GetFloatProperty("TubeRadius", val); m_View->m_Controls->m_TubeRadius->setValue((int)(val * 100.0)); QString label = "Radius %1"; label = label.arg(val); m_View->m_Controls->label_tuberadius->setText(label); int width; node->GetIntProperty("LineWidth", width); m_View->m_Controls->m_LineWidth->setValue(width); label = "Width %1"; label = label.arg(width); m_View->m_Controls->label_linewidth->setText(label); float range; node->GetFloatProperty("Fiber2DSliceThickness",range); label = "Range %1"; label = label.arg(range*0.1); m_View->m_Controls->label_range->setText(label); } } // check node data != NULL } } if(m_View->m_CurrentSelection->Size() > 0 && m_View->m_SelectedNode == 0) { m_View->m_Controls->m_ImageControlsFrame->setVisible(true); bool foundDiffusionImage = false; bool foundQBIVolume = false; bool foundTensorVolume = false; bool foundImage = false; bool foundMultipleOdfImages = false; bool foundRGBAImage = false; bool foundTbssImage = false; // do something with the selected items if(m_View->m_CurrentSelection) { // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); mitk::BaseData* nodeData = node->GetData(); if(nodeData != NULL ) { // only look at interesting types if(QString("DiffusionImage").compare(nodeData->GetNameOfClass())==0) { foundDiffusionImage = true; bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("DisplayChannel", val); m_View->m_Controls->m_DisplayIndex->setValue(val); QString label = "Channel %1"; label = label.arg(val); m_View->m_Controls->label_channel->setText(label); int maxVal = (dynamic_cast* >(nodeData))->GetVectorImage()->GetVectorLength(); m_View->m_Controls->m_DisplayIndex->setMaximum(maxVal-1); } if(QString("TbssImage").compare(nodeData->GetNameOfClass())==0) { foundTbssImage = true; bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("DisplayChannel", val); m_View->m_Controls->m_DisplayIndex->setValue(val); QString label = "Channel %1"; label = label.arg(val); m_View->m_Controls->label_channel->setText(label); int maxVal = (dynamic_cast(nodeData))->GetImage()->GetVectorLength(); m_View->m_Controls->m_DisplayIndex->setMaximum(maxVal-1); } else if(QString("QBallImage").compare(nodeData->GetNameOfClass())==0) { foundMultipleOdfImages = foundQBIVolume || foundTensorVolume; foundQBIVolume = true; ApplySettings(node); } else if(QString("TensorImage").compare(nodeData->GetNameOfClass())==0) { foundMultipleOdfImages = foundQBIVolume || foundTensorVolume; foundTensorVolume = true; ApplySettings(node); } else if(QString("Image").compare(nodeData->GetNameOfClass())==0) { foundImage = true; mitk::Image::Pointer img = dynamic_cast(nodeData); if(img.IsNotNull() && img->GetPixelType().GetPixelTypeId() == typeid(itk::RGBAPixel) ) { foundRGBAImage = true; } bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } } } // END CHECK node != NULL } } } m_View->m_FoundSingleOdfImage = (foundQBIVolume || foundTensorVolume) && !foundMultipleOdfImages; m_View->m_Controls->m_NumberGlyphsFrame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_NormalizationDropdown->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->label->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_ScalingFactor->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_AdditionalScaling->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_NormalizationScalingFrame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->OpacMinFrame->setVisible(foundRGBAImage || m_View->m_FoundSingleOdfImage); // changed for SPIE paper, Principle curvature scaling //m_View->m_Controls->params_frame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->params_frame->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_T->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_VisibleOdfsON_S->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_VisibleOdfsON_C->setVisible(m_View->m_FoundSingleOdfImage); bool foundAnyImage = foundDiffusionImage || foundQBIVolume || foundTensorVolume || foundImage || foundTbssImage; m_View->m_Controls->m_Reinit->setVisible(foundAnyImage); m_View->m_Controls->m_TextureIntON->setVisible(foundAnyImage); m_View->m_Controls->m_TSMenu->setVisible(foundAnyImage); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkControlVisualizationPropertiesView* m_View; }; QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_NodeUsedForOdfVisualization(NULL), m_IconTexOFF(new QIcon(":/QmitkDiffusionImaging/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkDiffusionImaging/texIntONIcon.png")), m_IconGlyOFF_T(new QIcon(":/QmitkDiffusionImaging/glyphsoff_T.png")), m_IconGlyON_T(new QIcon(":/QmitkDiffusionImaging/glyphson_T.png")), m_IconGlyOFF_C(new QIcon(":/QmitkDiffusionImaging/glyphsoff_C.png")), m_IconGlyON_C(new QIcon(":/QmitkDiffusionImaging/glyphson_C.png")), m_IconGlyOFF_S(new QIcon(":/QmitkDiffusionImaging/glyphsoff_S.png")), m_IconGlyON_S(new QIcon(":/QmitkDiffusionImaging/glyphson_S.png")), m_CurrentSelection(0), m_CurrentPickingNode(0), m_GlyIsOn_S(false), m_GlyIsOn_C(false), m_GlyIsOn_T(false), m_FiberBundleObserverTag(0), m_Color(NULL) { currentThickSlicesMode = 1; m_MyMenu = NULL; } QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView(const QmitkControlVisualizationPropertiesView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkControlVisualizationPropertiesView::~QmitkControlVisualizationPropertiesView() { if(m_SlicesRotationObserverTag1 ) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if( coordinator) coordinator->RemoveObserver(m_SlicesRotationObserverTag1); } if( m_SlicesRotationObserverTag2) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if( coordinator ) coordinator->RemoveObserver(m_SlicesRotationObserverTag1); } this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); } void QmitkControlVisualizationPropertiesView::OnThickSlicesModeSelected( QAction* action ) { currentThickSlicesMode = action->data().toInt(); switch(currentThickSlicesMode) { default: case 1: this->m_Controls->m_TSMenu->setText("MIP"); break; case 2: this->m_Controls->m_TSMenu->setText("SUM"); break; case 3: this->m_Controls->m_TSMenu->setText("WEIGH"); break; } mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::OnTSNumChanged(int num) { if(num==0) { mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); } else { mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); } m_TSLabel->setText(QString::number(num*2+1)); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_2DWINDOWS); } void QmitkControlVisualizationPropertiesView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkControlVisualizationPropertiesViewControls; m_Controls->setupUi(parent); this->CreateConnections(); // hide warning (ODFs in rotated planes) m_Controls->m_lblRotatedPlanesWarning->hide(); m_MyMenu = new QMenu(parent); connect( m_MyMenu, SIGNAL( aboutToShow() ), this, SLOT(OnMenuAboutToShow()) ); // button for changing rotation mode m_Controls->m_TSMenu->setMenu( m_MyMenu ); //m_CrosshairModeButton->setIcon( QIcon( iconCrosshairMode_xpm ) ); m_Controls->params_frame->setVisible(false); QIcon icon5(":/QmitkDiffusionImaging/Refresh_48.png"); m_Controls->m_Reinit->setIcon(icon5); m_Controls->m_Focus->setIcon(icon5); QIcon iconColor(":/QmitkDiffusionImaging/color24.gif"); m_Controls->m_PFColor->setIcon(iconColor); m_Controls->m_Color->setIcon(iconColor); QIcon iconReset(":/QmitkDiffusionImaging/reset.png"); m_Controls->m_ResetColoring->setIcon(iconReset); m_Controls->m_PFColor->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QIcon iconCrosshair(":/QmitkDiffusionImaging/crosshair.png"); m_Controls->m_Crosshair->setIcon(iconCrosshair); // was is los QIcon iconPaint(":/QmitkDiffusionImaging/paint2.png"); m_Controls->m_TDI->setIcon(iconPaint); QIcon iconFiberFade(":/QmitkDiffusionImaging/MapperEfx2D.png"); m_Controls->m_FiberFading2D->setIcon(iconFiberFade); m_Controls->m_TextureIntON->setCheckable(true); #ifndef DIFFUSION_IMAGING_EXTENDED int size = m_Controls->m_AdditionalScaling->count(); for(int t=0; tm_AdditionalScaling->itemText(t).toStdString() == "Scale by ASR") { m_Controls->m_AdditionalScaling->removeItem(t); } } #endif m_Controls->m_OpacitySlider->setRange(0.0,1.0); m_Controls->m_OpacitySlider->setLowerValue(0.0); m_Controls->m_OpacitySlider->setUpperValue(0.0); m_Controls->m_ScalingFrame->setVisible(false); m_Controls->m_NormalizationFrame->setVisible(false); m_Controls->frame_tube->setVisible(false); m_Controls->frame_wire->setVisible(false); } m_IsInitialized = false; m_SelListener = berry::ISelectionListener::Pointer(new CvpSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); m_IsInitialized = true; } void QmitkControlVisualizationPropertiesView::OnMenuAboutToShow () { // THICK SLICE SUPPORT QMenu *myMenu = m_MyMenu; myMenu->clear(); QActionGroup* thickSlicesActionGroup = new QActionGroup(myMenu); thickSlicesActionGroup->setExclusive(true); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); int currentTSMode = 0; { mitk::ResliceMethodProperty::Pointer m = dynamic_cast(renderer->GetCurrentWorldGeometry2DNode()->GetProperty( "reslice.thickslices" )); if( m.IsNotNull() ) currentTSMode = m->GetValueAsId(); } const int maxTS = 30; int currentNum = 0; { mitk::IntProperty::Pointer m = dynamic_cast(renderer->GetCurrentWorldGeometry2DNode()->GetProperty( "reslice.thickslices.num" )); if( m.IsNotNull() ) { currentNum = m->GetValue(); if(currentNum < 0) currentNum = 0; if(currentNum > maxTS) currentNum = maxTS; } } if(currentTSMode==0) currentNum=0; QSlider *m_TSSlider = new QSlider(myMenu); m_TSSlider->setMinimum(0); m_TSSlider->setMaximum(maxTS-1); m_TSSlider->setValue(currentNum); m_TSSlider->setOrientation(Qt::Horizontal); connect( m_TSSlider, SIGNAL( valueChanged(int) ), this, SLOT( OnTSNumChanged(int) ) ); QHBoxLayout* _TSLayout = new QHBoxLayout; _TSLayout->setContentsMargins(4,4,4,4); _TSLayout->addWidget(m_TSSlider); _TSLayout->addWidget(m_TSLabel=new QLabel(QString::number(currentNum*2+1),myMenu)); QWidget* _TSWidget = new QWidget; _TSWidget->setLayout(_TSLayout); QActionGroup* thickSliceModeActionGroup = new QActionGroup(myMenu); thickSliceModeActionGroup->setExclusive(true); QWidgetAction *m_TSSliderAction = new QWidgetAction(myMenu); m_TSSliderAction->setDefaultWidget(_TSWidget); myMenu->addAction(m_TSSliderAction); QAction* mipThickSlicesAction = new QAction(myMenu); mipThickSlicesAction->setActionGroup(thickSliceModeActionGroup); mipThickSlicesAction->setText("MIP (max. intensity proj.)"); mipThickSlicesAction->setCheckable(true); mipThickSlicesAction->setChecked(currentThickSlicesMode==1); mipThickSlicesAction->setData(1); myMenu->addAction( mipThickSlicesAction ); QAction* sumThickSlicesAction = new QAction(myMenu); sumThickSlicesAction->setActionGroup(thickSliceModeActionGroup); sumThickSlicesAction->setText("SUM (sum intensity proj.)"); sumThickSlicesAction->setCheckable(true); sumThickSlicesAction->setChecked(currentThickSlicesMode==2); sumThickSlicesAction->setData(2); myMenu->addAction( sumThickSlicesAction ); QAction* weightedThickSlicesAction = new QAction(myMenu); weightedThickSlicesAction->setActionGroup(thickSliceModeActionGroup); weightedThickSlicesAction->setText("WEIGHTED (gaussian proj.)"); weightedThickSlicesAction->setCheckable(true); weightedThickSlicesAction->setChecked(currentThickSlicesMode==3); weightedThickSlicesAction->setData(3); myMenu->addAction( weightedThickSlicesAction ); connect( thickSliceModeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(OnThickSlicesModeSelected(QAction*)) ); } void QmitkControlVisualizationPropertiesView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; if (m_MultiWidget) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SliceRotation ); m_SlicesRotationObserverTag1 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } coordinator = m_MultiWidget->GetSlicesSwiveller(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SliceRotation ); m_SlicesRotationObserverTag2 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } } } void QmitkControlVisualizationPropertiesView::SliceRotation(const itk::EventObject&) { // test if plane rotated if( m_GlyIsOn_T || m_GlyIsOn_C || m_GlyIsOn_S ) { if( this->IsPlaneRotated() ) { // show label m_Controls->m_lblRotatedPlanesWarning->show(); } else { //hide label m_Controls->m_lblRotatedPlanesWarning->hide(); } } } void QmitkControlVisualizationPropertiesView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkControlVisualizationPropertiesView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_DisplayIndex), SIGNAL(valueChanged(int)), this, SLOT(DisplayIndexChanged(int)) ); connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); connect( (QObject*)(m_Controls->m_Reinit), SIGNAL(clicked()), this, SLOT(Reinit()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_T), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_T()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_S), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_S()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_C), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_C()) ); connect( (QObject*)(m_Controls->m_ShowMaxNumber), SIGNAL(editingFinished()), this, SLOT(ShowMaxNumberChanged()) ); connect( (QObject*)(m_Controls->m_NormalizationDropdown), SIGNAL(currentIndexChanged(int)), this, SLOT(NormalizationDropdownChanged(int)) ); connect( (QObject*)(m_Controls->m_ScalingFactor), SIGNAL(valueChanged(double)), this, SLOT(ScalingFactorChanged(double)) ); connect( (QObject*)(m_Controls->m_AdditionalScaling), SIGNAL(currentIndexChanged(int)), this, SLOT(AdditionalScaling(int)) ); connect( (QObject*)(m_Controls->m_IndexParam1), SIGNAL(valueChanged(double)), this, SLOT(IndexParam1Changed(double)) ); connect( (QObject*)(m_Controls->m_IndexParam2), SIGNAL(valueChanged(double)), this, SLOT(IndexParam2Changed(double)) ); connect( (QObject*)(m_Controls->m_ScalingCheckbox), SIGNAL(clicked()), this, SLOT(ScalingCheckbox()) ); connect( (QObject*)(m_Controls->m_OpacitySlider), SIGNAL(spanChanged(double,double)), this, SLOT(OpacityChanged(double,double)) ); connect((QObject*) m_Controls->m_Wire, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationWire())); connect((QObject*) m_Controls->m_Tube, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationTube())); connect((QObject*) m_Controls->m_Color, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationColor())); connect((QObject*) m_Controls->m_ResetColoring, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationResetColoring())); connect((QObject*) m_Controls->m_Focus, SIGNAL(clicked()), (QObject*) this, SLOT(PlanarFigureFocus())); connect((QObject*) m_Controls->m_FiberFading2D, SIGNAL(clicked()), (QObject*) this, SLOT( Fiber2DfadingEFX() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(sliderReleased()), (QObject*) this, SLOT( FiberSlicingThickness2D() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(valueChanged(int)), (QObject*) this, SLOT( FiberSlicingUpdateLabel(int) )); connect((QObject*) m_Controls->m_Crosshair, SIGNAL(clicked()), (QObject*) this, SLOT(SetInteractor())); connect((QObject*) m_Controls->m_PFWidth, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(PFWidth(int))); connect((QObject*) m_Controls->m_PFColor, SIGNAL(clicked()), (QObject*) this, SLOT(PFColor())); connect((QObject*) m_Controls->m_TDI, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateTdi())); connect((QObject*) m_Controls->m_LineWidth, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(LineWidthChanged(int))); connect((QObject*) m_Controls->m_TubeRadius, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(TubeRadiusChanged(int))); connect((QObject*) m_Controls->m_Welcome, SIGNAL(clicked()), (QObject*) this, SLOT(Welcome())); } } void QmitkControlVisualizationPropertiesView::Activated() { berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); QmitkFunctionality::Activated(); } void QmitkControlVisualizationPropertiesView::Deactivated() { QmitkFunctionality::Deactivated(); } int QmitkControlVisualizationPropertiesView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkControlVisualizationPropertiesView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return m_FoundSingleOdfImage ? 120 : 80; } else { return preferredResult; } } // set diffusion image channel to b0 volume void QmitkControlVisualizationPropertiesView::NodeAdded(const mitk::DataNode *node) { mitk::DataNode* notConst = const_cast(node); if (dynamic_cast*>(notConst->GetData())) { mitk::DiffusionImage::Pointer dimg = dynamic_cast*>(notConst->GetData()); // if there is no b0 image in the dataset, the GetB0Indices() returns a vector of size 0 // and hence we cannot set the Property directly to .front() int displayChannelPropertyValue = 0; if( dimg->GetB0Indices().size() > 0) displayChannelPropertyValue = dimg->GetB0Indices().front(); notConst->SetIntProperty("DisplayChannel", displayChannelPropertyValue ); } } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkControlVisualizationPropertiesView::OnSelectionChanged( std::vector nodes ) { if ( !this->IsVisible() ) { // do nothing if nobody wants to see me :-( return; } // deactivate channel slider if no diffusion weighted image or tbss image is selected m_Controls->m_DisplayIndex->setVisible(false); m_Controls->label_channel->setVisible(false); for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; if (node.IsNotNull() && (dynamic_cast(nodeData) || dynamic_cast*>(nodeData))) { m_Controls->m_DisplayIndex->setVisible(true); m_Controls->label_channel->setVisible(true); } else if (node.IsNotNull() && dynamic_cast(node->GetData())) { if (m_Color.IsNotNull()) m_Color->RemoveObserver(m_FiberBundleObserverTag); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SetFiberBundleCustomColor ); m_Color = dynamic_cast(node->GetProperty("color", NULL)); if (m_Color.IsNotNull()) m_FiberBundleObserverTag = m_Color->AddObserver( itk::ModifiedEvent(), command ); } } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; if( node.IsNotNull() && (dynamic_cast(nodeData) || dynamic_cast(nodeData)) ) { if(m_NodeUsedForOdfVisualization.IsNotNull()) { m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", false); } m_NodeUsedForOdfVisualization = node; m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); m_Controls->m_TSMenu->setVisible(false); // deactivate mip etc. for tensor and q-ball images break; } else m_Controls->m_TSMenu->setVisible(true); } } mitk::DataStorage::SetOfObjects::Pointer QmitkControlVisualizationPropertiesView::ActiveSet(std::string classname) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV const mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; if(QString(classname.c_str()).compare(nodeData->GetNameOfClass())==0) { set->InsertElement(at++, node); } } } return set; } return 0; } void QmitkControlVisualizationPropertiesView::SetBoolProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, bool value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetBoolProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetIntProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, int value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetFloatProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, float value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetFloatProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetLevelWindowProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::LevelWindow value) { if(set.IsNotNull()) { mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(value); mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), prop); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetEnumProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::EnumerationProperty::Pointer value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::DisplayIndexChanged(int dispIndex) { QString label = "Channel %1"; label = label.arg(dispIndex); m_Controls->label_channel->setText(label); std::vector sets; sets.push_back("DiffusionImage"); sets.push_back("TbssImage"); std::vector::iterator it = sets.begin(); while(it != sets.end()) { std::string s = *it; mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet(s); if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty("DisplayChannel", dispIndex); ++itemiter; } //m_MultiWidget->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } it++; } } void QmitkControlVisualizationPropertiesView::Reinit() { if (m_CurrentSelection) { mitk::DataNodeObject::Pointer nodeObj = m_CurrentSelection->Begin()->Cast(); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkControlVisualizationPropertiesView::TextIntON() { if(m_TexIsOn) { m_Controls->m_TextureIntON->setIcon(*m_IconTexOFF); } else { m_Controls->m_TextureIntON->setIcon(*m_IconTexON); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("DiffusionImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("TensorImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("QBallImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("Image"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); m_TexIsOn = !m_TexIsOn; if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_S() { m_GlyIsOn_S = m_Controls->m_VisibleOdfsON_S->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); VisibleOdfsON(0); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_T() { m_GlyIsOn_T = m_Controls->m_VisibleOdfsON_T->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); VisibleOdfsON(1); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_C() { m_GlyIsOn_C = m_Controls->m_VisibleOdfsON_C->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); VisibleOdfsON(2); } bool QmitkControlVisualizationPropertiesView::IsPlaneRotated() { // for all 2D renderwindows of m_MultiWidget check alignment mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast( m_MultiWidget->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D() ); if (displayPlane.IsNull()) return false; mitk::Image* currentImage = dynamic_cast( m_NodeUsedForOdfVisualization->GetData() ); if( currentImage == NULL ) { MITK_ERROR << " Casting problems. Returning false"; return false; } int affectedDimension(-1); int affectedSlice(-1); return !(mitk::SegTool2D::DetermineAffectedImageSlice( currentImage, displayPlane, affectedDimension, affectedSlice )); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON(int view) { if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ShowMaxNumberChanged() { int maxNr = m_Controls->m_ShowMaxNumber->value(); if ( maxNr < 1 ) { m_Controls->m_ShowMaxNumber->setValue( 1 ); maxNr = 1; } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetIntProp(set,"ShowMaxNumber", maxNr); set = ActiveSet("TensorImage"); SetIntProp(set,"ShowMaxNumber", maxNr); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::NormalizationDropdownChanged(int normDropdown) { typedef mitk::OdfNormalizationMethodProperty PropType; PropType::Pointer normMeth = PropType::New(); switch(normDropdown) { case 0: normMeth->SetNormalizationToMinMax(); break; case 1: normMeth->SetNormalizationToMax(); break; case 2: normMeth->SetNormalizationToNone(); break; case 3: normMeth->SetNormalizationToGlobalMax(); break; default: normMeth->SetNormalizationToMinMax(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); // if(m_MultiWidget) // m_MultiWidget->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::ScalingFactorChanged(double scalingFactor) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"Scaling", scalingFactor); set = ActiveSet("TensorImage"); SetFloatProp(set,"Scaling", scalingFactor); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::AdditionalScaling(int additionalScaling) { typedef mitk::OdfScaleByProperty PropType; PropType::Pointer scaleBy = PropType::New(); switch(additionalScaling) { case 0: scaleBy->SetScaleByNothing(); break; case 1: scaleBy->SetScaleByGFA(); //m_Controls->params_frame->setVisible(true); break; #ifdef DIFFUSION_IMAGING_EXTENDED case 2: scaleBy->SetScaleByPrincipalCurvature(); // commented in for SPIE paper, Principle curvature scaling //m_Controls->params_frame->setVisible(true); break; #endif default: scaleBy->SetScaleByNothing(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::IndexParam1Changed(double param1) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam1", param1); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam1", param1); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::IndexParam2Changed(double param2) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam2", param2); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam2", param2); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::OpacityChanged(double l, double u) { mitk::LevelWindow olw; olw.SetRangeMinMax(l*255, u*255); mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("TensorImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("Image"); SetLevelWindowProp(set,"opaclevelwindow", olw); m_Controls->m_OpacityMinFaLabel->setText(QString::number(l,'f',2) + " : " + QString::number(u,'f',2)); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ScalingCheckbox() { m_Controls->m_ScalingFrame->setVisible( m_Controls->m_ScalingCheckbox->isChecked()); if(!m_Controls->m_ScalingCheckbox->isChecked()) { m_Controls->m_AdditionalScaling->setCurrentIndex(0); m_Controls->m_ScalingFactor->setValue(1.0); } } void QmitkControlVisualizationPropertiesView::Fiber2DfadingEFX() { if (m_SelectedNode) { bool currentMode; m_SelectedNode->GetBoolProperty("Fiber2DfadeEFX", currentMode); m_SelectedNode->SetProperty("Fiber2DfadeEFX", mitk::BoolProperty::New(!currentMode)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingThickness2D() { if (m_SelectedNode) { float fibThickness = m_Controls->m_FiberThicknessSlider->value() * 0.1; m_SelectedNode->SetProperty("Fiber2DSliceThickness", mitk::FloatProperty::New(fibThickness)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingUpdateLabel(int value) { QString label = "Range %1"; label = label.arg(value * 0.1); m_Controls->label_range->setText(label); } void QmitkControlVisualizationPropertiesView::BundleRepresentationWire() { if(m_SelectedNode) { int width = m_Controls->m_LineWidth->value(); m_SelectedNode->SetProperty("LineWidth",mitk::IntProperty::New(width)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(15)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(18)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(1)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(2)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(3)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(4)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationTube() { if(m_SelectedNode) { float radius = m_Controls->m_TubeRadius->value() / 100.0; m_SelectedNode->SetProperty("TubeRadius",mitk::FloatProperty::New(radius)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(17)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(13)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(16)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::SetFiberBundleCustomColor(const itk::EventObject& /*e*/) { float color[3]; m_SelectedNode->GetColor(color); m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(color[0], color[1], color[2])); mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_CUSTOM); m_SelectedNode->Modified(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkControlVisualizationPropertiesView::BundleRepresentationColor() { if(m_SelectedNode) { QColor color = QColorDialog::getColor(); if (!color.isValid()) return; m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_CUSTOM); m_SelectedNode->Modified(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationResetColoring() { if(m_SelectedNode) { MITK_INFO << "reset colorcoding to oBased"; m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb(255,255,255)"; m_Controls->m_Color->setStyleSheet(styleSheet); // m_SelectedNode->SetProperty("color",NULL); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(1.0, 1.0, 1.0)); mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_ORIENTATION_BASED); fib->DoColorCodingOrientationBased(); m_SelectedNode->Modified(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::PlanarFigureFocus() { if(m_SelectedNode) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (m_SelectedNode->GetData()); if (_PlanarFigure) { QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); if (m_SelectedNode->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); mitk::VnlVector normal = _PlaneGeometry->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry1 = RenderWindow1->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane1 = dynamic_cast( worldGeometry1.GetPointer() ); mitk::VnlVector normal1 = _Plane1->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry2 = RenderWindow2->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane2 = dynamic_cast( worldGeometry2.GetPointer() ); mitk::VnlVector normal2 = _Plane2->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry3 = RenderWindow3->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane3 = dynamic_cast( worldGeometry3.GetPointer() ); mitk::VnlVector normal3 = _Plane3->GetNormalVnl(); normal[0] = fabs(normal[0]); normal[1] = fabs(normal[1]); normal[2] = fabs(normal[2]); normal1[0] = fabs(normal1[0]); normal1[1] = fabs(normal1[1]); normal1[2] = fabs(normal1[2]); normal2[0] = fabs(normal2[0]); normal2[1] = fabs(normal2[1]); normal2[2] = fabs(normal2[2]); normal3[0] = fabs(normal3[0]); normal3[1] = fabs(normal3[1]); normal3[2] = fabs(normal3[2]); double ang1 = angle(normal, normal1); double ang2 = angle(normal, normal2); double ang3 = angle(normal, normal3); if(ang1 < ang2 && ang1 < ang3) { selectedRenderWindow = RenderWindow1; } else { if(ang2 < ang3) { selectedRenderWindow = RenderWindow2; } else { selectedRenderWindow = RenderWindow3; } } // make node visible if (selectedRenderWindow) { mitk::Point3D centerP = _PlaneGeometry->GetOrigin(); selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); selectedRenderWindow->GetSliceNavigationController()->SelectSliceByPoint( centerP); } } // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(m_SelectedNode->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", m_SelectedNode); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); m_SelectedNode->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); } } void QmitkControlVisualizationPropertiesView::SetInteractor() { typedef std::vector Container; Container _NodeSet = this->GetDataManagerSelection(); mitk::DataNode* node = 0; mitk::FiberBundleX* bundle = 0; mitk::FiberBundleInteractor::Pointer bundleInteractor = 0; // finally add all nodes to the model for(Container::const_iterator it=_NodeSet.begin(); it!=_NodeSet.end() ; it++) { node = const_cast(*it); bundle = dynamic_cast(node->GetData()); if(bundle) { bundleInteractor = dynamic_cast(node->GetInteractor()); if(bundleInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(bundleInteractor); if(!m_Controls->m_Crosshair->isChecked()) { m_Controls->m_Crosshair->setChecked(false); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::ArrowCursor); m_CurrentPickingNode = 0; } else { m_Controls->m_Crosshair->setChecked(true); bundleInteractor = mitk::FiberBundleInteractor::New("FiberBundleInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(bundleInteractor); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::CrossCursor); m_CurrentPickingNode = node; } } } } void QmitkControlVisualizationPropertiesView::PFWidth(int w) { double width = w/10.0; m_SelectedNode->SetProperty("planarfigure.line.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.outline.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.helperline.width", mitk::FloatProperty::New(width) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QString label = "Width %1"; label = label.arg(width); m_Controls->label_pfwidth->setText(label); } void QmitkControlVisualizationPropertiesView::PFColor() { QColor color = QColorDialog::getColor(); if (!color.isValid()) return; m_Controls->m_PFColor->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_PFColor->setStyleSheet(styleSheet); m_SelectedNode->SetProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::GenerateTdi() { if(m_SelectedNode) { mitk::FiberBundleX* bundle = dynamic_cast(m_SelectedNode->GetData()); if(!bundle) return; typedef float OutPixType; typedef itk::Image OutImageType; // run generator itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); generator->SetFiberBundle(bundle); generator->SetUpsamplingFactor(2); generator->Update(); // get result OutImageType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // to datastorage mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); QString name(m_SelectedNode->GetName().c_str()); name += "_TDI"; node->SetName(name.toStdString()); node->SetVisibility(true); GetDataStorage()->Add(node); } } void QmitkControlVisualizationPropertiesView::LineWidthChanged(int w) { QString label = "Width %1"; label = label.arg(w); m_Controls->label_linewidth->setText(label); BundleRepresentationWire(); } void QmitkControlVisualizationPropertiesView::TubeRadiusChanged(int r) { QString label = "Radius %1"; label = label.arg(r / 100.0); m_Controls->label_tuberadius->setText(label); this->BundleRepresentationTube(); } void QmitkControlVisualizationPropertiesView::Welcome() { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( GetSite()->GetWorkbenchWindow(), false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h index e1b7620944..b4ef0f6067 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h @@ -1,181 +1,179 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKControlVisualizationPropertiesView_H_INCLUDED #define _QMITKControlVisualizationPropertiesView_H_INCLUDED #include #include #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include "berryISizeProvider.h" #include "ui_QmitkControlVisualizationPropertiesViewControls.h" #include "mitkEnumerationProperty.h" /*! * \ingroup org_mitk_gui_qt_diffusionquantification_internal * * \brief QmitkControlVisualizationPropertiesView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkControlVisualizationPropertiesView : public QmitkFunctionality//, public berry::ISizeProvider { friend struct CvpSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkControlVisualizationPropertiesView(); QmitkControlVisualizationPropertiesView(const QmitkControlVisualizationPropertiesView& other); virtual ~QmitkControlVisualizationPropertiesView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); mitk::DataStorage::SetOfObjects::Pointer ActiveSet(std::string); void SetBoolProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,bool); void SetIntProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,int); void SetFloatProp(mitk::DataStorage::SetOfObjects::Pointer,std::string,float); void SetLevelWindowProp(mitk::DataStorage::SetOfObjects::Pointer,std::string,mitk::LevelWindow); void SetEnumProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,mitk::EnumerationProperty::Pointer); virtual int GetSizeFlags(bool width); virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); protected slots: void DisplayIndexChanged(int); void TextIntON(); void Reinit(); void VisibleOdfsON(int view); void VisibleOdfsON_S(); void VisibleOdfsON_T(); void VisibleOdfsON_C(); void ShowMaxNumberChanged(); void NormalizationDropdownChanged(int); void ScalingFactorChanged(double); void AdditionalScaling(int); void IndexParam1Changed(double); void IndexParam2Changed(double); void OpacityChanged(double,double); void ScalingCheckbox(); void OnThickSlicesModeSelected( QAction* action ); void OnTSNumChanged(int num); void OnMenuAboutToShow (); void BundleRepresentationWire(); void BundleRepresentationTube(); void BundleRepresentationColor(); void BundleRepresentationResetColoring(); void PlanarFigureFocus(); void Fiber2DfadingEFX(); void FiberSlicingThickness2D(); void FiberSlicingUpdateLabel(int); void SetInteractor(); void PFWidth(int); void PFColor(); void LineWidthChanged(int); void TubeRadiusChanged(int); void GenerateTdi(); void Welcome(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); virtual void NodeAdded(const mitk::DataNode *node); void SetFiberBundleCustomColor(const itk::EventObject& /*e*/); bool IsPlaneRotated(); void SliceRotation(const itk::EventObject&); Ui::QmitkControlVisualizationPropertiesViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; bool m_FoundSingleOdfImage; bool m_IsInitialized; mitk::DataNode::Pointer m_NodeUsedForOdfVisualization; QIcon* m_IconTexOFF; QIcon* m_IconTexON; QIcon* m_IconGlyOFF_T; QIcon* m_IconGlyON_T; QIcon* m_IconGlyOFF_C; QIcon* m_IconGlyON_C; QIcon* m_IconGlyOFF_S; QIcon* m_IconGlyON_S; bool m_TexIsOn; bool m_GlyIsOn_T; bool m_GlyIsOn_C; bool m_GlyIsOn_S; int currentThickSlicesMode; QLabel* m_TSLabel; QMenu* m_MyMenu; // for planarfigure and bundle handling: mitk::DataNode* m_SelectedNode; mitk::DataNode* m_CurrentPickingNode; unsigned long m_SlicesRotationObserverTag1; unsigned long m_SlicesRotationObserverTag2; unsigned long m_FiberBundleObserverTag; mitk::ColorProperty::Pointer m_Color; }; #endif // _QMITKControlVisualizationPropertiesView_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.cpp index 52114cd27b..b7e0a1f08c 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.cpp @@ -1,737 +1,742 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionDicomImportView.h" // qt includes #include // itk includes #include "itkTimeProbesCollectorBase.h" #include "itkGDCMSeriesFileNames.h" #include "itksys/SystemTools.hxx" // mitk includes #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkMemoryUtilities.h" // diffusion module includes #include "mitkDicomDiffusionImageHeaderReader.h" #include "mitkGroupDiffusionHeadersFilter.h" #include "mitkDicomDiffusionImageReader.h" #include "mitkDiffusionImage.h" #include "mitkNrrdDiffusionImageWriter.h" #include "gdcmDirectory.h" #include "gdcmScanner.h" #include "gdcmSorter.h" #include "gdcmIPPSorter.h" #include "gdcmAttribute.h" #include "gdcmVersion.h" #include const std::string QmitkDiffusionDicomImport::VIEW_ID = "org.mitk.views.diffusiondicomimport"; QmitkDiffusionDicomImport::QmitkDiffusionDicomImport(QObject* /*parent*/, const char* /*name*/) : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_OutputFolderName(""), m_OutputFolderNameSet(false) { } QmitkDiffusionDicomImport::QmitkDiffusionDicomImport(const QmitkDiffusionDicomImport& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkDiffusionDicomImport::~QmitkDiffusionDicomImport() {} void QmitkDiffusionDicomImport::CreateQtPartControl(QWidget *parent) { m_Parent = parent; if (m_Controls == NULL) { m_Controls = new Ui::QmitkDiffusionDicomImportControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_DicomLoadRecursiveCheckbox->setChecked(true); m_Controls->m_DicomLoadAverageDuplicatesCheckbox->setChecked(false); m_Controls->m_DicomLoadRecursiveCheckbox->setVisible(false); AverageClicked(); } } void QmitkDiffusionDicomImport::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_AddFoldersButton, SIGNAL(clicked()), this, SLOT(DicomLoadAddFolderNames()) ); connect( m_Controls->m_DeleteFoldersButton, SIGNAL(clicked()), this, SLOT(DicomLoadDeleteFolderNames()) ); connect( m_Controls->m_DicomLoadStartLoadButton, SIGNAL(clicked()), this, SLOT(DicomLoadStartLoad()) ); connect( m_Controls->m_DicomLoadAverageDuplicatesCheckbox, SIGNAL(clicked()), this, SLOT(AverageClicked()) ); connect( m_Controls->m_OutputSetButton, SIGNAL(clicked()), this, SLOT(OutputSet()) ); connect( m_Controls->m_OutputClearButton, SIGNAL(clicked()), this, SLOT(OutputClear()) ); connect( m_Controls->m_Remove, SIGNAL(clicked()), this, SLOT(Remove()) ); } } void QmitkDiffusionDicomImport::Remove() { int i = m_Controls->listWidget->currentRow(); m_Controls->listWidget->takeItem(i); } void QmitkDiffusionDicomImport::OutputSet() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select folders containing DWI data") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_OutputFolderName = w->selectedFiles()[0]; m_OutputFolderNameSet = true; m_Controls->m_OutputLabel->setText(m_OutputFolderName); } void QmitkDiffusionDicomImport::OutputClear() { m_OutputFolderName = ""; m_OutputFolderNameSet = false; m_Controls->m_OutputLabel->setText("... optional out-folder ..."); } void QmitkDiffusionDicomImport::AverageClicked() { m_Controls->m_Blur->setEnabled(m_Controls->m_DicomLoadAverageDuplicatesCheckbox->isChecked()); } void QmitkDiffusionDicomImport::Activated() { QmitkFunctionality::Activated(); } void QmitkDiffusionDicomImport::DicomLoadDeleteFolderNames() { m_Controls->listWidget->clear(); } void QmitkDiffusionDicomImport::DicomLoadAddFolderNames() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select folders containing DWI data") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->listWidget->addItems(w->selectedFiles()); } bool SortBySeriesUID(gdcm::DataSet const & ds1, gdcm::DataSet const & ds2 ) { gdcm::Attribute<0x0020,0x000e> at1; at1.Set( ds1 ); gdcm::Attribute<0x0020,0x000e> at2; at2.Set( ds2 ); return at1 < at2; } bool SortByAcquisitionNumber(gdcm::DataSet const & ds1, gdcm::DataSet const & ds2 ) { gdcm::Attribute<0x0020,0x0012> at1; at1.Set( ds1 ); gdcm::Attribute<0x0020,0x0012> at2; at2.Set( ds2 ); return at1 < at2; } bool SortBySeqName(gdcm::DataSet const & ds1, gdcm::DataSet const & ds2 ) { gdcm::Attribute<0x0018, 0x0024> at1; at1.Set( ds1 ); gdcm::Attribute<0x0018, 0x0024> at2; at2.Set( ds2 ); std::string str1 = at1.GetValue().Trim(); std::string str2 = at2.GetValue().Trim(); return std::lexicographical_compare(str1.begin(), str1.end(), str2.begin(), str2.end() ); } void QmitkDiffusionDicomImport::Status(QString status) { mitk::StatusBar::GetInstance()->DisplayText(status.toAscii()); MITK_INFO << status.toStdString().c_str(); } void QmitkDiffusionDicomImport::Status(std::string status) { mitk::StatusBar::GetInstance()->DisplayText(status.c_str()); MITK_INFO << status.c_str(); } void QmitkDiffusionDicomImport::Status(const char* status) { mitk::StatusBar::GetInstance()->DisplayText(status); MITK_INFO << status; } void QmitkDiffusionDicomImport::Error(QString status) { mitk::StatusBar::GetInstance()->DisplayErrorText(status.toAscii()); MITK_ERROR << status.toStdString().c_str(); } void QmitkDiffusionDicomImport::Error(std::string status) { mitk::StatusBar::GetInstance()->DisplayErrorText(status.c_str()); MITK_ERROR << status.c_str(); } void QmitkDiffusionDicomImport::Error(const char* status) { mitk::StatusBar::GetInstance()->DisplayErrorText(status); MITK_ERROR << status; } void QmitkDiffusionDicomImport::PrintMemoryUsage() { size_t processSize = mitk::MemoryUtilities::GetProcessMemoryUsage(); size_t totalSize = mitk::MemoryUtilities::GetTotalSizeOfPhysicalRam(); float percentage = ( (float) processSize / (float) totalSize ) * 100.0; MITK_INFO << "Current memory usage: " << GetMemoryDescription( processSize, percentage ); } std::string QmitkDiffusionDicomImport::FormatMemorySize( size_t size ) { double val = size; std::string descriptor("B"); if ( val >= 1000.0 ) { val /= 1024.0; descriptor = "KB"; } if ( val >= 1000.0 ) { val /= 1024.0; descriptor = "MB"; } if ( val >= 1000.0 ) { val /= 1024.0; descriptor = "GB"; } std::ostringstream str; str << std::fixed << std::setprecision(2) << val << " " << descriptor; return str.str(); } std::string QmitkDiffusionDicomImport::FormatPercentage( double val ) { std::ostringstream str; str << std::fixed << std::setprecision(2) << val << " " << "%"; return str.str(); } std::string QmitkDiffusionDicomImport::GetMemoryDescription( size_t processSize, float percentage ) { std::ostringstream str; str << FormatMemorySize(processSize) << " (" << FormatPercentage( percentage ) <<")" ; return str.str(); } void QmitkDiffusionDicomImport::DicomLoadStartLoad() { itk::TimeProbesCollectorBase clock; bool imageSuccessfullySaved = true; try { const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); if ( locale.compare(currLocale)!=0 ) { try { MITK_INFO << " ** Changing locale from " << setlocale(LC_ALL, NULL) << " to '" << locale << "'"; setlocale(LC_ALL, locale.c_str()); } catch(...) { MITK_INFO << "Could not set locale " << locale; } } int nrFolders = m_Controls->listWidget->count(); if(!nrFolders) { Error(QString("No input folders were selected. ABORTING.")); return; } Status(QString("GDCM %1 used for DICOM parsing and sorting!").arg(gdcm::Version::GetVersion())); PrintMemoryUsage(); QString status; mitk::DataNode::Pointer node; mitk::ProgressBar::GetInstance()->AddStepsToDo(2*nrFolders); std::string folder = m_Controls->m_OutputLabel->text().toStdString(); if(berry::Platform::IsWindows()) { folder.append("\\import.log"); } else { folder.append("/import.log"); } ofstream logfile; if(m_OutputFolderNameSet) logfile.open(folder.c_str()); while(m_Controls->listWidget->count()) { // RETREIVE FOLDERNAME QListWidgetItem * item = m_Controls->listWidget->takeItem(0); QString folderName = item->text(); if(m_OutputFolderNameSet) logfile << "Reading " << folderName.toStdString() << '\n'; // PARSING DIRECTORY PrintMemoryUsage(); clock.Start(folderName.toAscii()); std::vector seriesUIDs(0); std::vector > seriesFilenames(0); Status("== Initial Directory Scan =="); if(m_OutputFolderNameSet) logfile << "== Initial Directory Scan ==\n"; gdcm::Directory d; d.Load( folderName.toStdString().c_str(), true ); // recursive ! const gdcm::Directory::FilenamesType &l1 = d.GetFilenames(); const unsigned int ntotalfiles = l1.size(); Status(QString(" ... found %1 different files").arg(ntotalfiles)); if(m_OutputFolderNameSet)logfile << "...found " << ntotalfiles << " different files\n"; Status("Scanning Headers"); if(m_OutputFolderNameSet) logfile << "Scanning Headers\n"; gdcm::Scanner s; const gdcm::Tag t1(0x0020,0x000d); // Study Instance UID const gdcm::Tag t2(0x0020,0x000e); // Series Instance UID const gdcm::Tag t5(0x0028, 0x0010); // number rows const gdcm::Tag t6(0x0028, 0x0011); // number cols s.AddTag( t1 ); s.AddTag( t2 ); s.AddTag( t5 ); s.AddTag( t6 ); bool b = s.Scan( d.GetFilenames() ); if( !b ) { Error("Scanner failed"); if(m_OutputFolderNameSet )logfile << "ERROR: scanner failed\n"; continue; } // Only get the DICOM files: gdcm::Directory::FilenamesType l2 = s.GetKeys(); const int nfiles = l2.size(); if(nfiles < 1) { Error("No DICOM files found"); if(m_OutputFolderNameSet)logfile << "ERROR: No DICOM files found\n"; continue; } Status(QString(" ... successfully scanned %1 headers.").arg(nfiles)); if(m_OutputFolderNameSet) logfile << "...succesfully scanned " << nfiles << " headers\n"; Status("Sorting"); if(m_OutputFolderNameSet) logfile << "Sorting\n"; const gdcm::Scanner::ValuesType &values1 = s.GetValues(t1); int nvalues; if(m_Controls->m_DuplicateID->isChecked()) { nvalues = 1; } else { nvalues = values1.size(); } if(nvalues>1) { Error("Multiple sSeries tudies found. Please limit to 1 study per folder"); if(m_OutputFolderNameSet) logfile << "Multiple series found. Limit to one. If you are convinced this is an error use the merge duplicate study IDs option \n"; continue; } const gdcm::Scanner::ValuesType &values5 = s.GetValues(t5); const gdcm::Scanner::ValuesType &values6 = s.GetValues(t6); if(values5.size()>1 || values6.size()>1) { Error("Folder contains images of unequal dimensions that cannot be combined in one 3d volume. ABORTING."); if(m_OutputFolderNameSet) logfile << "Folder contains images of unequal dimensions that cannot be combined in one 3d volume. ABORTING\n."; continue; } const gdcm::Scanner::ValuesType &values2 = s.GetValues(t2); int nSeries; if(m_Controls->m_DuplicateID->isChecked()) { nSeries = 1; } else { nSeries = values2.size(); } gdcm::Directory::FilenamesType files; if(nSeries > 1) { gdcm::Sorter sorter; sorter.SetSortFunction( SortBySeriesUID ); sorter.StableSort( l2 ); files = sorter.GetFilenames(); } else { files = l2; } unsigned int nTotalAcquis = 0; if(nfiles % nSeries != 0) { Error("Number of files in series not equal, ABORTING"); if(m_OutputFolderNameSet) logfile << "Number of files in series not equal, Some volumes are probably incomplete. ABORTING \n"; continue; } int filesPerSeries = nfiles / nSeries; gdcm::Scanner::ValuesType::const_iterator it2 = values2.begin(); for(int i=0; i & list = ippsorter.GetFilenames(); seriesFilenames.push_back(list); seriesUIDs.push_back(identifier.c_str()); } ++it2; } if(nfiles % nTotalAcquis != 0) { Error("Number of files per acquisition differs between series, ABORTING"); if(m_OutputFolderNameSet) logfile << "Number of files per acquisition differs between series, ABORTING \n"; continue; } int slices = nfiles/nTotalAcquis; Status(QString("Series is composed of %1 different 3D volumes with %2 slices.").arg(nTotalAcquis).arg(slices)); if(m_OutputFolderNameSet) logfile << "Series is composed of " << nTotalAcquis << " different 3D volumes with " << slices << " slices\n"; // READING HEADER-INFOS PrintMemoryUsage(); Status(QString("Reading Headers %1").arg(folderName)); if(m_OutputFolderNameSet) logfile << "Reading Headers "<< folderName.toStdString() << "\n"; mitk::DicomDiffusionImageHeaderReader::Pointer headerReader; mitk::GroupDiffusionHeadersFilter::InputType inHeaders; unsigned int size2 = seriesUIDs.size(); for ( unsigned int i = 0 ; i < size2 ; ++i ) { Status(QString("Reading header image #%1/%2").arg(i+1).arg(size2)); headerReader = mitk::DicomDiffusionImageHeaderReader::New(); headerReader->SetSeriesDicomFilenames(seriesFilenames[i]); headerReader->Update(); inHeaders.push_back(headerReader->GetOutput()); //Status(std::endl; } mitk::ProgressBar::GetInstance()->Progress(); // // GROUP HEADERS // mitk::GroupDiffusionHeadersFilter::Pointer grouper // = mitk::GroupDiffusionHeadersFilter::New(); // mitk::GroupDiffusionHeadersFilter::OutputType outHeaders; // grouper->SetInput(inHeaders); // grouper->Update(); // outHeaders = grouper->GetOutput(); // READ VOLUMES PrintMemoryUsage(); if(m_OutputFolderNameSet) logfile << "Loading volumes\n"; Status(QString("Loading Volumes %1").arg(folderName)); typedef short PixelValueType; typedef mitk::DicomDiffusionImageReader< PixelValueType, 3 > VolumesReader; VolumesReader::Pointer vReader = VolumesReader::New(); VolumesReader::HeaderContainer hc = inHeaders; // hc.insert(hc.end(), outHeaders[1].begin(), outHeaders[1].end() ); // hc.insert(hc.end(), outHeaders[2].begin(), outHeaders[2].end() ); if(hc.size()>1) { vReader->SetHeaders(hc); vReader->Update(); VolumesReader::OutputImageType::Pointer vecImage; vecImage = vReader->GetOutput(); Status(QString("Volumes Loaded (%1)").arg(folderName)); // CONSTRUCT CONTAINER WITH DIRECTIONS typedef vnl_vector_fixed< double, 3 > GradientDirectionType; typedef itk::VectorContainer< unsigned int, GradientDirectionType > GradientDirectionContainerType; GradientDirectionContainerType::Pointer directions = GradientDirectionContainerType::New(); std::vector b_vals; double maxb = 0; for(unsigned int i=0; ibValue; if(maxb vect = hc[i]->DiffusionVector; vect.normalize(); vect *= sqrt(b_vals[i]/maxb); directions->push_back(vect); } // DWI TO DATATREE PrintMemoryUsage(); Status(QString("Initializing Diffusion Image")); if(m_OutputFolderNameSet) logfile << "Initializing Diffusion Image\n"; typedef mitk::DiffusionImage DiffVolumesType; DiffVolumesType::Pointer diffImage = DiffVolumesType::New(); diffImage->SetDirections(directions); diffImage->SetOriginalDirections(directions); diffImage->SetVectorImage(vecImage); diffImage->SetB_Value(maxb); diffImage->InitializeFromVectorImage(); Status(QString("Diffusion Image initialized")); if(m_OutputFolderNameSet) logfile << "Diffusion Image initialized\n"; if(m_Controls->m_DicomLoadAverageDuplicatesCheckbox->isChecked()) { PrintMemoryUsage(); Status(QString("Averaging gradient directions")); logfile << "Averaging gradient directions\n"; diffImage->AverageRedundantGradients(m_Controls->m_Blur->value()); } QString descr = QString("%1_%2_%3") .arg(((inHeaders)[0])->seriesDescription.c_str()) .arg(((inHeaders)[0])->seriesNumber) .arg(((inHeaders)[0])->patientName.c_str()); descr = descr.trimmed(); descr = descr.replace(" ", "_"); if(!m_OutputFolderNameSet) { node=mitk::DataNode::New(); node->SetData( diffImage ); GetDefaultDataStorage()->Add(node); SetDwiNodeProperties(node, descr.toStdString().c_str()); Status(QString("Image %1 added to datastorage").arg(descr)); } else { typedef mitk::NrrdDiffusionImageWriter WriterType; WriterType::Pointer writer = WriterType::New(); QString fullpath = QString("%1/%2.dwi") .arg(m_OutputFolderName) .arg(descr); writer->SetFileName(fullpath.toStdString()); writer->SetInput(diffImage); try { writer->Update(); } catch (itk::ExceptionObject &ex) { imageSuccessfullySaved = false; Error(QString("%1\n%2\n%3\n%4\n%5\n%6").arg(ex.GetNameOfClass()).arg(ex.GetFile()).arg(ex.GetLine()).arg(ex.GetLocation()).arg(ex.what()).arg(ex.GetDescription())); logfile << QString("%1\n%2\n%3\n%4\n%5\n%6").arg(ex.GetNameOfClass()).arg(ex.GetFile()).arg(ex.GetLine()).arg(ex.GetLocation()).arg(ex.what()).arg(ex.GetDescription()).toStdString() << "\n"; node=mitk::DataNode::New(); node->SetData( diffImage ); GetDefaultDataStorage()->Add(node); SetDwiNodeProperties(node, descr.toStdString().c_str()); Status(QString("Image %1 added to datastorage").arg(descr)); logfile << "Image " << descr.toStdString() << " added to datastorage\n"; continue ; } Status(QString("Image %1 written to disc (%1)").arg(fullpath.toStdString().c_str())); logfile << "Image " << fullpath.toStdString() << "\n"; } } else { Status(QString("No diffusion information found (%1)").arg(folderName)); if(m_OutputFolderNameSet) logfile << "No diffusion information found "<< folderName.toStdString(); } Status(QString("Finished processing %1 with memory:").arg(folderName)); if(m_OutputFolderNameSet) logfile << "Finished processing " << folderName.toStdString() << "\n"; PrintMemoryUsage(); clock.Stop(folderName.toAscii()); mitk::ProgressBar::GetInstance()->Progress(); int lwidget = m_Controls->listWidget->count(); std::cout << lwidget <GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); try { MITK_INFO << " ** Changing locale back from " << setlocale(LC_ALL, NULL) << " to '" << currLocale << "'"; setlocale(LC_ALL, currLocale.c_str()); } catch(...) { MITK_INFO << "Could not reset locale " << currLocale; } } catch (itk::ExceptionObject &ex) { Error(QString("%1\n%2\n%3\n%4\n%5\n%6").arg(ex.GetNameOfClass()).arg(ex.GetFile()).arg(ex.GetLine()).arg(ex.GetLocation()).arg(ex.what()).arg(ex.GetDescription())); return ; } if (!imageSuccessfullySaved) QMessageBox::warning(NULL,"WARNING","One or more files could not be saved! The according files where moved to the datastorage."); Status(QString("Finished import with memory:")); PrintMemoryUsage(); } void QmitkDiffusionDicomImport::SetDwiNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "IsDWIRawVolume", mitk::BoolProperty::New( true ) ); // set foldername as string property mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New( name ); node->SetProperty( "name", nameProp ); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.h index 87aceb3cab..0cd06aedeb 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionDicomImportView.h @@ -1,112 +1,110 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-05 11:31:02 +0200 (Di, 05 Mai 2009) $ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDiffusionDicomImportView_H__INCLUDED #define QmitkDiffusionDicomImportView_H__INCLUDED #include "QmitkFunctionality.h" #include "ui_QmitkDiffusionDicomImportViewControls.h" /*! \brief QmitkDiffusionDicomImport \sa QmitkFunctionality \ingroup Functionalities */ class QmitkDiffusionDicomImport : public QmitkFunctionality { Q_OBJECT public: static const std::string VIEW_ID; /*! \ Convenient typedefs */ typedef mitk::DataStorage::SetOfObjects ConstVector; typedef ConstVector::ConstPointer ConstVectorPointer; typedef ConstVector::ConstIterator ConstVectorIterator; /*! \brief default constructor */ QmitkDiffusionDicomImport(QObject *parent=0, const char *name=0); QmitkDiffusionDicomImport(const QmitkDiffusionDicomImport& other); /*! \brief default destructor */ virtual ~QmitkDiffusionDicomImport(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); virtual void Activated(); void SetDwiNodeProperties(mitk::DataNode::Pointer node, std::string name); protected slots: void DicomLoadAddFolderNames(); void DicomLoadDeleteFolderNames(); void DicomLoadStartLoad() ; void AverageClicked(); void OutputSet(); void OutputClear(); void Remove(); protected: void Status(QString status); void Status(std::string status); void Status(const char* status); void Error(QString status); void Error(std::string status); void Error(const char* status); void PrintMemoryUsage(); std::string FormatMemorySize( size_t size ); std::string FormatPercentage( double val ); std::string GetMemoryDescription( size_t processSize, float percentage ); /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkDiffusionDicomImportControls *m_Controls; QmitkStdMultiWidget* m_MultiWidget; QWidget *m_Parent; QString m_OutputFolderName; bool m_OutputFolderNameSet; }; #endif // !defined(QmitkDiffusionDicomImport_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.cpp index 1fa8ea91ab..175edb861d 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.cpp @@ -1,79 +1,78 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionImagingPublicPerspective.h" #include "berryIViewLayout.h" QmitkDiffusionImagingPublicPerspective::QmitkDiffusionImagingPublicPerspective() { } QmitkDiffusionImagingPublicPerspective::QmitkDiffusionImagingPublicPerspective(const QmitkDiffusionImagingPublicPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } void QmitkDiffusionImagingPublicPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mitk.leftcontrols", berry::IPageLayout::BOTTOM, 0.125f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, 0.8f, "org.mitk.leftcontrols"); layout->AddStandaloneView("org.mitk.views.perspectiveswitcher", false, berry::IPageLayout::BOTTOM, 0.99f, "org.mitk.views.imagenavigator"); // layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", // berry::IPageLayout::TOP, 0.9f, "org.mitk.views.perspectiveswitcher",false); left->AddView("org.mitk.views.diffusionpreprocessing"); left->AddView("org.mitk.views.tensorreconstruction"); left->AddView("org.mitk.views.qballreconstruction"); left->AddView("org.mitk.views.diffusionquantification"); left->AddView("org.mitk.views.diffusiondicomimport"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusionpreprocessing"); lo->SetCloseable(false); lo = layout->GetViewLayout("org.mitk.views.qballreconstruction"); lo->SetCloseable(false); lo = layout->GetViewLayout("org.mitk.views.tensorreconstruction"); lo->SetCloseable(false); lo = layout->GetViewLayout("org.mitk.views.diffusionquantification"); lo->SetCloseable(false); lo = layout->GetViewLayout("org.mitk.views.diffusiondicomimport"); lo->SetCloseable(false); //berry::IFolderLayout::Pointer right2 = // layout->CreateFolder("right2", berry::IPageLayout::BOTTOM, 0.5f, "right"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.h index 12013e5d92..3c14b8c150 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionImagingPublicPerspective.h @@ -1,37 +1,36 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDIFFUSIONIMAGINGPUBLICPERSPECTIVE_H_ #define QMITKDIFFUSIONIMAGINGPUBLICPERSPECTIVE_H_ #include class QmitkDiffusionImagingPublicPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDiffusionImagingPublicPerspective(); QmitkDiffusionImagingPublicPerspective(const QmitkDiffusionImagingPublicPerspective& other); void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QMITKDIFFUSIONIMAGINGPUBLICPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.cpp index 198577bba2..b8654b0a75 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.cpp @@ -1,573 +1,571 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionQuantificationView.h" #include "mitkDiffusionImagingConfigure.h" #include "itkTimeProbe.h" #include "itkImage.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkQBallImage.h" #include #include "mitkImageCast.h" #include "mitkStatusBar.h" #include "itkDiffusionQballGeneralizedFaImageFilter.h" #include "itkShiftScaleImageFilter.h" #include "itkTensorFractionalAnisotropyImageFilter.h" #include "itkTensorRelativeAnisotropyImageFilter.h" #include "itkTensorDerivedMeasurementsFilter.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkDiffusionQuantificationView::VIEW_ID = "org.mitk.views.diffusionquantification"; QmitkDiffusionQuantificationView::QmitkDiffusionQuantificationView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { m_QBallImages = mitk::DataStorage::SetOfObjects::New(); m_TensorImages = mitk::DataStorage::SetOfObjects::New(); } QmitkDiffusionQuantificationView::QmitkDiffusionQuantificationView(const QmitkDiffusionQuantificationView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkDiffusionQuantificationView::~QmitkDiffusionQuantificationView() { } void QmitkDiffusionQuantificationView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkDiffusionQuantificationViewControls; m_Controls->setupUi(parent); this->CreateConnections(); GFACheckboxClicked(); #ifndef DIFFUSION_IMAGING_EXTENDED m_Controls->m_StandardGFACheckbox->setVisible(false); m_Controls->frame_3->setVisible(false); m_Controls->m_CurvatureButton->setVisible(false); #endif } } void QmitkDiffusionQuantificationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkDiffusionQuantificationView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkDiffusionQuantificationView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_StandardGFACheckbox), SIGNAL(clicked()), this, SLOT(GFACheckboxClicked()) ); connect( (QObject*)(m_Controls->m_GFAButton), SIGNAL(clicked()), this, SLOT(GFA()) ); connect( (QObject*)(m_Controls->m_CurvatureButton), SIGNAL(clicked()), this, SLOT(Curvature()) ); connect( (QObject*)(m_Controls->m_FAButton), SIGNAL(clicked()), this, SLOT(FA()) ); connect( (QObject*)(m_Controls->m_RAButton), SIGNAL(clicked()), this, SLOT(RA()) ); connect( (QObject*)(m_Controls->m_ADButton), SIGNAL(clicked()), this, SLOT(AD()) ); connect( (QObject*)(m_Controls->m_RDButton), SIGNAL(clicked()), this, SLOT(RD()) ); connect( (QObject*)(m_Controls->m_MDButton), SIGNAL(clicked()), this, SLOT(MD()) ); connect( (QObject*)(m_Controls->m_ClusteringAnisotropy), SIGNAL(clicked()), this, SLOT(ClusterAnisotropy()) ); } } void QmitkDiffusionQuantificationView::OnSelectionChanged( std::vector nodes ) { if (!m_Visible) return; m_QBallImages = mitk::DataStorage::SetOfObjects::New(); m_TensorImages = mitk::DataStorage::SetOfObjects::New(); bool foundQBIVolume = false; bool foundTensorVolume = false; mitk::DataNode::Pointer selNode = NULL; int c=0; for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { foundQBIVolume = true; m_QBallImages->push_back(node); selNode = node; c++; } else if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { foundTensorVolume = true; m_TensorImages->push_back(node); selNode = node; c++; } } m_Controls->m_GFAButton->setEnabled(foundQBIVolume); m_Controls->m_CurvatureButton->setEnabled(foundQBIVolume); if (c>0) m_Controls->m_InputImageLabel->setText(selNode->GetName().c_str()); else m_Controls->m_InputImageLabel->setText("-"); m_Controls->m_FAButton->setEnabled(foundTensorVolume); m_Controls->m_RAButton->setEnabled(foundTensorVolume); m_Controls->m_ADButton->setEnabled(foundTensorVolume); m_Controls->m_RDButton->setEnabled(foundTensorVolume); m_Controls->m_MDButton->setEnabled(foundTensorVolume); m_Controls->m_ClusteringAnisotropy->setEnabled(foundTensorVolume); } void QmitkDiffusionQuantificationView::Activated() { QmitkFunctionality::Activated(); } void QmitkDiffusionQuantificationView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkDiffusionQuantificationView::GFACheckboxClicked() { m_Controls->frame_2->setVisible(m_Controls->m_StandardGFACheckbox->isChecked()); } void QmitkDiffusionQuantificationView::GFA() { if(m_Controls->m_StandardGFACheckbox->isChecked()) { QBIQuantify(13); } else { QBIQuantify(0); } } void QmitkDiffusionQuantificationView::Curvature() { QBIQuantify(12); } void QmitkDiffusionQuantificationView::FA() { TensorQuantify(0); } void QmitkDiffusionQuantificationView::RA() { TensorQuantify(1); } void QmitkDiffusionQuantificationView::AD() { TensorQuantify(2); } void QmitkDiffusionQuantificationView::RD() { TensorQuantify(3); } void QmitkDiffusionQuantificationView::ClusterAnisotropy() { TensorQuantify(4); } void QmitkDiffusionQuantificationView::MD() { TensorQuantify(5); } void QmitkDiffusionQuantificationView::QBIQuantify(int method) { QBIQuantification(m_QBallImages, method); } void QmitkDiffusionQuantificationView::TensorQuantify(int method) { TensorQuantification(m_TensorImages, method); } void QmitkDiffusionQuantificationView::QBIQuantification( mitk::DataStorage::SetOfObjects::Pointer inImages, int method) { itk::TimeProbe clock; QString status; int nrFiles = inImages->size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { typedef float TOdfPixelType; const int odfsize = QBALL_ODFSIZE; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast((*itemiter)->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); ++itemiter; float p1 = m_Controls->m_ParamKEdit->text().toFloat(); float p2 = m_Controls->m_ParamPEdit->text().toFloat(); // COMPUTE RA clock.Start(); MBI_INFO << "Computing GFA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing GFA for %s", nodename.c_str()).toAscii()); typedef OdfVectorType::ValueType RealValueType; typedef itk::Image< RealValueType, 3 > RAImageType; typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(8); double scale = 1; std::string newname; newname.append(nodename); switch(method) { case 0: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); newname.append("GFA"); break; } case 1: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILES_HIGH_LOW); newname.append("01"); break; } case 2: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILE_HIGH); newname.append("02"); break; } case 3: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MAX_ODF_VALUE); newname.append("03"); break; } case 4: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_DECONVOLUTION_COEFFS); newname.append("04"); break; } case 5: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MIN_MAX_NORMALIZED_STANDARD); newname.append("05"); break; } case 6: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_NORMALIZED_ENTROPY); newname.append("06"); break; } case 7: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_NEMATIC_ORDER_PARAMETER); newname.append("07"); break; } case 8: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILES_LOW_HIGH); newname.append("08"); break; } case 9: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILE_LOW); newname.append("09"); break; } case 10: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MIN_ODF_VALUE); newname.append("10"); break; } case 11: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_STD_BY_MAX); newname.append("11"); break; } case 12: { p1 = m_Controls->MinAngle->text().toFloat(); p2 = m_Controls->MaxAngle->text().toFloat(); gfaFilter->SetComputationMethod(GfaFilterType::GFA_PRINCIPLE_CURVATURE); QString paramString; paramString = paramString.append("PC%1-%2").arg(p1).arg(p2); newname.append(paramString.toAscii()); gfaFilter->SetParam1(p1); gfaFilter->SetParam2(p2); break; } case 13: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_GENERALIZED_GFA); QString paramString; paramString = paramString.append("GFAK%1P%2").arg(p1).arg(p2); newname.append(paramString.toAscii()); gfaFilter->SetParam1(p1); gfaFilter->SetParam2(p2); break; } default: { newname.append("0"); gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); } } gfaFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; typedef itk::Image ImgType; ImgType::Pointer img = ImgType::New(); img->SetSpacing( gfaFilter->GetOutput()->GetSpacing() ); // Set the image spacing img->SetOrigin( gfaFilter->GetOutput()->GetOrigin() ); // Set the image origin img->SetDirection( gfaFilter->GetOutput()->GetDirection() ); // Set the image direction img->SetLargestPossibleRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion()); img->SetBufferedRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion() ); img->Allocate(); itk::ImageRegionIterator ot (img, img->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionConstIterator it (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { GfaFilterType::OutputImageType::PixelType val = it.Get(); ot.Set(val * m_Controls->m_ScaleImageValuesBox->value()); ++ot; } // GFA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( img.GetPointer() ); image->SetVolume( img->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); node->SetProperty( "name", mitk::StringProperty::New(newname) ); nodes.push_back(node); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); m_MultiWidget->RequestUpdate(); } void QmitkDiffusionQuantificationView::TensorQuantification( mitk::DataStorage::SetOfObjects::Pointer inImages, int method) { itk::TimeProbe clock; QString status; int nrFiles = inImages->size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; mitk::Image* vol = static_cast((*itemiter)->GetData()); TensorImageType::Pointer itkvol = TensorImageType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); ++itemiter; // COMPUTE FA clock.Start(); MBI_INFO << "Computing FA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing FA for %s", nodename.c_str()).toAscii()); typedef itk::Image< TTensorPixelType, 3 > FAImageType; typedef itk::ShiftScaleImageFilter ShiftScaleFilterType; ShiftScaleFilterType::Pointer multi = ShiftScaleFilterType::New(); multi->SetShift(0.0); multi->SetScale(m_Controls->m_ScaleImageValuesBox->value());//itk::NumericTraits::max() typedef itk::TensorDerivedMeasurementsFilter MeasurementsType; if(method == 0) //FA { /* typedef itk::TensorFractionalAnisotropyImageFilter< TensorImageType, FAImageType > FilterType; FilterType::Pointer anisotropyFilter = FilterType::New(); anisotropyFilter->SetInput( itkvol.GetPointer() ); anisotropyFilter->Update(); multi->SetInput(anisotropyFilter->GetOutput()); nodename = QString(nodename.c_str()).append("_FA").toStdString();*/ MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itkvol.GetPointer() ); measurementsCalculator->SetMeasure(MeasurementsType::FA); measurementsCalculator->Update(); multi->SetInput(measurementsCalculator->GetOutput()); nodename = QString(nodename.c_str()).append("_FA").toStdString(); } else if(method == 1) //RA { /*typedef itk::TensorRelativeAnisotropyImageFilter< TensorImageType, FAImageType > FilterType; FilterType::Pointer anisotropyFilter = FilterType::New(); anisotropyFilter->SetInput( itkvol.GetPointer() ); anisotropyFilter->Update(); multi->SetInput(anisotropyFilter->GetOutput()); nodename = QString(nodename.c_str()).append("_RA").toStdString();*/ MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itkvol.GetPointer() ); measurementsCalculator->SetMeasure(MeasurementsType::RA); measurementsCalculator->Update(); multi->SetInput(measurementsCalculator->GetOutput()); nodename = QString(nodename.c_str()).append("_RA").toStdString(); } else if(method == 2) // AD (Axial diffusivity) { MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itkvol.GetPointer() ); measurementsCalculator->SetMeasure(MeasurementsType::AD); measurementsCalculator->Update(); multi->SetInput(measurementsCalculator->GetOutput()); nodename = QString(nodename.c_str()).append("_AD").toStdString(); } else if(method == 3) // RD (Radial diffusivity, (Lambda2+Lambda3)/2 { MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itkvol.GetPointer() ); measurementsCalculator->SetMeasure(MeasurementsType::RD); measurementsCalculator->Update(); multi->SetInput(measurementsCalculator->GetOutput()); nodename = QString(nodename.c_str()).append("_RD").toStdString(); } else if(method == 4) // 1-(Lambda2+Lambda3)/(2*Lambda1) { MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itkvol.GetPointer() ); measurementsCalculator->SetMeasure(MeasurementsType::CA); measurementsCalculator->Update(); multi->SetInput(measurementsCalculator->GetOutput()); nodename = QString(nodename.c_str()).append("_CA").toStdString(); } else if(method == 5) // MD (Mean Diffusivity, (Lambda1+Lambda2+Lambda3)/3 ) { MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itkvol.GetPointer() ); measurementsCalculator->SetMeasure(MeasurementsType::MD); measurementsCalculator->Update(); multi->SetInput(measurementsCalculator->GetOutput()); nodename = QString(nodename.c_str()).append("_MD").toStdString(); } multi->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // FA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( multi->GetOutput() ); image->SetVolume( multi->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); node->SetProperty( "name", mitk::StringProperty::New(nodename) ); nodes.push_back(node); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); m_MultiWidget->RequestUpdate(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.h index 3e8c319f7b..b23baf608e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionQuantificationView.h @@ -1,104 +1,102 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKDIFFUSIONQUANTIFICATIONVIEW_H_INCLUDED #define _QMITKDIFFUSIONQUANTIFICATIONVIEW_H_INCLUDED #include #include #include "ui_QmitkDiffusionQuantificationViewControls.h" /*! * \ingroup org_mitk_gui_qt_diffusionquantification_internal * * \brief QmitkDiffusionQuantificationView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkDiffusionQuantificationView : public QmitkFunctionality { friend struct DqSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkDiffusionQuantificationView(); QmitkDiffusionQuantificationView(const QmitkDiffusionQuantificationView& other); virtual ~QmitkDiffusionQuantificationView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: void GFACheckboxClicked(); void GFA(); void Curvature(); void FA(); void RA(); void AD(); void RD(); void ClusterAnisotropy(); void MD(); void QBIQuantify(int method); void QBIQuantification(mitk::DataStorage::SetOfObjects::Pointer inImages, int method) ; void TensorQuantify(int method); void TensorQuantification(mitk::DataStorage::SetOfObjects::Pointer inImages, int method) ; protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkDiffusionQuantificationViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; mitk::DataStorage::SetOfObjects::Pointer m_QBallImages; mitk::DataStorage::SetOfObjects::Pointer m_TensorImages; static const float m_ScaleDAIValues; }; #endif // _QMITKDIFFUSIONQUANTIFICATIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp index 254f7e51b1..cc1e3abf53 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp @@ -1,1811 +1,1810 @@ -/*========================================================================= - - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ - Version: $Revision: 21975 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ //=========FOR TESTING========== //random generation, number of points equal requested points // Blueberry application and interaction service #include #include // Qmitk #include "QmitkFiberBundleDeveloperView.h" #include // Qt #include // MITK #include #include #include //===needed when timeSlicedGeometry is null to invoke rendering mechansims ==== #include #include // VTK #include //for randomized FiberStructure #include //for fiberStructure #include //for fiberStructure #include //for geometry //ITK #include //============================================== //======== W O R K E R S ____ S T A R T ======== //============================================== /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --generate FiberIDs--*/ QmitkFiberIDWorker::QmitkFiberIDWorker(QThread* hostingThread, Package4WorkingThread itemPackage) : m_itemPackage(itemPackage), m_hostingThread(hostingThread) { } void QmitkFiberIDWorker::run() { if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); /* MEASUREMENTS AND FANCY GUI EFFECTS * accurate time measurement using ITK timeProbe*/ itk::TimeProbe clock; clock.Start(); //set GUI representation of timer to 0, is essential for correct timer incrementation m_itemPackage.st_Controls->infoTimerGenerateFiberIds->setText(QString::number(0)); m_itemPackage.st_FancyGUITimer1->start(); //do processing m_itemPackage.st_FBX->GenerateFiberIds(); /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ clock.Stop(); m_itemPackage.st_FancyGUITimer1->stop(); m_itemPackage.st_Controls->infoTimerGenerateFiberIds->setText( QString::number(clock.GetTotal()) ); delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore m_hostingThread->quit(); } /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * -- extract fibers by given PlanarFigure --*/ QmitkFiberExtractorWorker::QmitkFiberExtractorWorker(QThread* hostingThread, Package4WorkingThread itemPackage) : m_itemPackage(itemPackage), m_hostingThread(hostingThread) { } void QmitkFiberExtractorWorker::run() { if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); /* MEASUREMENTS AND FANCY GUI EFFECTS * accurate time measurement using ITK timeProbe*/ itk::TimeProbe clock; clock.Start(); //set GUI representation of timer to 0, is essential for correct timer incrementation m_itemPackage.st_Controls->infoTimerExtractFibers->setText(QString::number(0)); m_itemPackage.st_FancyGUITimer1->start(); //do processing std::vector fibIds = m_itemPackage.st_FBX->ExtractFiberIdSubset(m_itemPackage.st_PlanarFigure); //generate new fiberbundle by fiber iDs vtkSmartPointer newFBPolyData = m_itemPackage.st_FBX->GeneratePolyDataByIds(fibIds); // call function to convert fiberstructure into fiberbundleX and pass it to datastorage (m_itemPackage.st_host->*m_itemPackage.st_pntr_to_Method_PutFibersToDataStorage)(newFBPolyData); /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ clock.Stop(); m_itemPackage.st_FancyGUITimer1->stop(); m_itemPackage.st_Controls->infoTimerExtractFibers->setText( QString::number(clock.GetTotal()) ); delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore m_hostingThread->quit(); } /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --set FA values to fiberbundle--*/ QmitkFiberColoringWorker::QmitkFiberColoringWorker(QThread* hostingThread, Package4WorkingThread itemPackage) : m_itemPackage(itemPackage) , m_hostingThread(hostingThread) { } void QmitkFiberColoringWorker::run() { if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); /* MEASUREMENTS AND FANCY GUI EFFECTS * accurate time measurement using ITK timeProbe*/ itk::TimeProbe clock; clock.Start(); //set GUI representation of timer to 0, is essential for correct timer incrementation m_itemPackage.st_Controls->infoTimerColorCoding->setText(QString::number(0)); m_itemPackage.st_FancyGUITimer1->start(); //do processing if(m_itemPackage.st_Controls->radioButton_ColorOrient->isChecked()) { m_itemPackage.st_FBX->DoColorCodingOrientationBased(); } else if(m_itemPackage.st_Controls->radioButton_ColorFA->isChecked()) { m_itemPackage.st_FBX->DoColorCodingFaBased(); } else if(m_itemPackage.st_Controls->radioButton_OpacityFA->isChecked()) { // m_itemPackage.st_FBX->SetColorCoding(""); m_itemPackage.st_PassedDataNode->SetOpacity(0.999); m_itemPackage.st_FBX->DoUseFaFiberOpacity(); } else if(m_itemPackage.st_Controls->radioButton_ColorCustom->isChecked()){ m_itemPackage.st_FBX->SetColorCoding(mitk::FiberBundleX::COLORCODING_CUSTOM); } /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ clock.Stop(); m_itemPackage.st_FancyGUITimer1->stop(); m_itemPackage.st_Controls->infoTimerColorCoding->setText( QString::number(clock.GetTotal()) ); delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore m_hostingThread->quit(); } QmitkFiberFeederFAWorker::QmitkFiberFeederFAWorker(QThread* hostingThread, Package4WorkingThread itemPackage) : m_itemPackage(itemPackage), m_hostingThread(hostingThread) { } void QmitkFiberFeederFAWorker::run() { if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); /* MEASUREMENTS AND FANCY GUI EFFECTS * accurate time measurement using ITK timeProbe */ itk::TimeProbe clock; clock.Start(); //set GUI representation of timer to 0, is essential for correct timer incrementation m_itemPackage.st_Controls->infoTimerSetFA->setText(QString::number(0)); m_itemPackage.st_FancyGUITimer1->start(); //do processing mitk::Image::Pointer FAImg = dynamic_cast(m_itemPackage.st_PassedDataNode->GetData()); if(FAImg.IsNotNull()) m_itemPackage.st_FBX->SetFAMap(FAImg); /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ clock.Stop(); m_itemPackage.st_FancyGUITimer1->stop(); m_itemPackage.st_Controls->infoTimerSetFA->setText( QString::number(clock.GetTotal()) ); disconnect(m_itemPackage.st_FancyGUITimer1); delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore m_hostingThread->quit(); } /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --generate random fibers--*/ QmitkFiberGenerateRandomWorker::QmitkFiberGenerateRandomWorker(QThread* hostingThread, Package4WorkingThread itemPackage) : m_itemPackage(itemPackage), m_hostingThread(hostingThread) { } void QmitkFiberGenerateRandomWorker::run() { if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); /* MEASUREMENTS AND FANCY GUI EFFECTS */ //MAKE SURE by yourself THAT NOTHING ELSE THAN A NUMBER IS SET IN THAT LABEL m_itemPackage.st_Controls->infoTimerGenerateFiberBundle->setText(QString::number(0)); m_itemPackage.st_FancyGUITimer1->start(); //do processing, generateRandomFibers int numOfFibers = m_itemPackage.st_Controls->boxFiberNumbers->value(); int distrRadius = m_itemPackage.st_Controls->boxDistributionRadius->value(); int numOfPoints = numOfFibers * distrRadius; std::vector< std::vector > fiberStorage; for (int i=0; i a; fiberStorage.push_back( a ); } /* Generate Point Cloud */ vtkSmartPointer randomPoints = vtkSmartPointer::New(); randomPoints->SetCenter(0.0, 0.0, 0.0); randomPoints->SetNumberOfPoints(numOfPoints); randomPoints->SetRadius(distrRadius); randomPoints->Update(); vtkPoints* pnts = randomPoints->GetOutput()->GetPoints(); /* ASSIGN EACH POINT TO A RANDOM FIBER */ srand((unsigned)time(0)); // init randomizer for (int i=0; iGetNumberOfPoints(); ++i) { //generate random number between 0 and numOfFibers-1 int random_integer; random_integer = (rand()%numOfFibers); //add current point to random fiber fiberStorage.at(random_integer).push_back(i); // MITK_INFO << "point" << i << " |" << pnts->GetPoint(random_integer)[0] << "|" << pnts->GetPoint(random_integer)[1]<< "|" << pnts->GetPoint(random_integer)[2] << "| into fiber" << random_integer; } // initialize accurate time measurement itk::TimeProbe clock; clock.Start(); /* GENERATE VTK POLYLINES OUT OF FIBERSTORAGE */ vtkSmartPointer linesCell = vtkSmartPointer::New(); // Host vtkPolyLines linesCell->Allocate(pnts->GetNumberOfPoints()*2); //allocate for each cellindex also space for the pointId, e.g. [idx | pntID] for (long i=0; i singleFiber = fiberStorage.at(i); vtkSmartPointer fiber = vtkSmartPointer::New(); fiber->GetPointIds()->SetNumberOfIds((int)singleFiber.size()); for (long si=0; siGetPointIds()->SetId( si, singleFiber.at(si) ); } linesCell->InsertNextCell(fiber); } /* checkpoint for cellarray allocation */ if ( (linesCell->GetSize()/pnts->GetNumberOfPoints()) != 2 ) //e.g. size: 12, number of points:6 .... each cell hosts point ids (6 ids) + cell index for each idPoint. 6 * 2 = 12 { MITK_INFO << "RANDOM FIBER ALLOCATION CAN NOT BE TRUSTED ANYMORE! Correct leak or remove command: linesCell->Allocate(pnts->GetNumberOfPoints()*2) but be aware of possible loss in performance."; } /* HOSTING POLYDATA FOR RANDOM FIBERSTRUCTURE */ vtkSmartPointer PDRandom = vtkPolyData::New(); //could also be a standard pointer instead of smartpointer cuz ther is no need to delete because data is managed in datastorage. PDRandom->SetPoints(pnts); PDRandom->SetLines(linesCell); // accurate timer measurement stop clock.Stop(); //MITK_INFO << "=====Assambling random Fibers to Polydata======\nMean: " << clock.GetMean() << " Total: " << clock.GetTotal() << std::endl; // call function to convert fiberstructure into fiberbundleX and pass it to datastorage (m_itemPackage.st_host->*m_itemPackage.st_pntr_to_Method_PutFibersToDataStorage)(PDRandom); /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ m_itemPackage.st_FancyGUITimer1->stop(); m_itemPackage.st_Controls->infoTimerGenerateFiberBundle->setText( QString::number(clock.GetTotal()) ); delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore m_hostingThread->quit(); } /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --update GUI elements of thread monitor-- * implementation not thread safe, not needed so far because * there exists only 1 thread for fiberprocessing * for threadsafety, you need to implement checking mechanisms in methods "::threadFor...." */ QmitkFiberThreadMonitorWorker::QmitkFiberThreadMonitorWorker( QThread* hostingThread, Package4WorkingThread itemPackage ) : m_itemPackage(itemPackage) , m_hostingThread(hostingThread) , m_pixelstepper(10) //for next rendering call, move object 10px , m_steppingDistance(220) //use only a multiple value of pixelstepper, x-axis border for fancy stuff { //set timers m_thtimer_initMonitor = new QTimer; m_thtimer_initMonitor->setInterval(10); m_thtimer_initMonitorSetFinalPosition = new QTimer; m_thtimer_initMonitorSetFinalPosition->setInterval(10); m_thtimer_initMonitorSetMasks = new QTimer; m_thtimer_initMonitorSetFinalPosition->setInterval(10); m_thtimer_threadStarted = new QTimer; m_thtimer_threadStarted->setInterval(50); m_thtimer_threadFinished = new QTimer; m_thtimer_threadFinished->setInterval(50); m_thtimer_threadTerminated = new QTimer; m_thtimer_threadTerminated->setInterval(50); connect (m_thtimer_initMonitor, SIGNAL( timeout()), this, SLOT( fancyMonitorInitialization() ) ); connect ( m_thtimer_initMonitorSetFinalPosition, SIGNAL( timeout() ), this, SLOT( fancyMonitorInitializationFinalPos() ) ); connect ( m_thtimer_initMonitorSetMasks, SIGNAL( timeout() ), this, SLOT( fancyMonitorInitializationMask() ) ); connect (m_thtimer_threadStarted, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadStarted() ) ); connect (m_thtimer_threadFinished, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadFinished() ) ); connect (m_thtimer_threadTerminated, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadTerminated() ) ); //first, the current text shall turn transparent m_decreaseOpacity_threadStarted = true; m_decreaseOpacity_threadFinished = true; m_decreaseOpacity_threadTerminated = true; } void QmitkFiberThreadMonitorWorker::run() { } void QmitkFiberThreadMonitorWorker::initializeMonitor() { //fancy configuration of animation start mitk::Point2D pntOpen; pntOpen[0] = 118; pntOpen[1] = 10; mitk::Point2D headPos; headPos[0] = 19; headPos[1] = 10; mitk::Point2D statusPos; statusPos[0] = 105; statusPos[1] = 23; mitk::Point2D startedPos; startedPos[0] = 68; startedPos[1] = 10; mitk::Point2D finishedPos; finishedPos[0] = 143; finishedPos[1] = 10; mitk::Point2D terminatedPos; terminatedPos[0] = 240; terminatedPos[1] = 10; m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntOpen); m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); m_itemPackage.st_FBX_Monitor->setHeadingPosition(headPos); m_itemPackage.st_FBX_Monitor->setMaskPosition(headPos); m_itemPackage.st_FBX_Monitor->setStatusPosition(statusPos); m_itemPackage.st_FBX_Monitor->setStartedPosition(startedPos); m_itemPackage.st_FBX_Monitor->setFinishedPosition(finishedPos); m_itemPackage.st_FBX_Monitor->setTerminatedPosition(terminatedPos); m_thtimer_initMonitor->start(); } void QmitkFiberThreadMonitorWorker::setThreadStatus(QString status) { m_itemPackage.st_FBX_Monitor->setStatus(status); m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } /* Methods to set status of running threads * Following three methods are usually called - before a thread starts and - a thread is finished or terminated */ void QmitkFiberThreadMonitorWorker::threadForFiberProcessingStarted() { if(!m_thtimer_threadStarted->isActive()) { m_thtimer_threadStarted->start(); } else { //fast change without fancy stuff, needed to keep threaddebugger info up to date int counter = m_itemPackage.st_FBX_Monitor->getStarted(); m_itemPackage.st_FBX_Monitor->setStarted(++counter); } } void QmitkFiberThreadMonitorWorker::threadForFiberProcessingFinished() { if(!m_thtimer_threadFinished->isActive()) { m_thtimer_threadFinished->start(); } else { //fast change without fancy stuff int counter = m_itemPackage.st_FBX_Monitor->getFinished(); m_itemPackage.st_FBX_Monitor->setFinished(++counter); } } void QmitkFiberThreadMonitorWorker::threadForFiberProcessingTerminated() { if(!m_thtimer_threadTerminated->isActive()) { m_thtimer_threadTerminated->start(); } else { //fast change without fancy stuff int counter = m_itemPackage.st_FBX_Monitor->getTerminated(); m_itemPackage.st_FBX_Monitor->setTerminated(++counter); } } /* Helper methods for fancy fading efx for thread monitor */ void QmitkFiberThreadMonitorWorker::fancyTextFading_threadStarted() { if (m_decreaseOpacity_threadStarted) { int startedOpacity = m_itemPackage.st_FBX_Monitor->getStartedOpacity(); m_itemPackage.st_FBX_Monitor->setStartedOpacity( --startedOpacity ); if (startedOpacity == 0) { int counter = m_itemPackage.st_FBX_Monitor->getStarted(); m_itemPackage.st_FBX_Monitor->setStarted(++counter); m_decreaseOpacity_threadStarted = false; } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } else { int startedOpacity = m_itemPackage.st_FBX_Monitor->getStartedOpacity(); m_itemPackage.st_FBX_Monitor->setStartedOpacity( ++startedOpacity ); if (startedOpacity >= 10) { m_thtimer_threadStarted->stop(); m_decreaseOpacity_threadStarted = true; //set back to true, cuz next iteration shall decrease opacity as well } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } } void QmitkFiberThreadMonitorWorker::fancyTextFading_threadFinished() { if (m_decreaseOpacity_threadFinished) { int finishedOpacity = m_itemPackage.st_FBX_Monitor->getFinishedOpacity(); m_itemPackage.st_FBX_Monitor->setFinishedOpacity( --finishedOpacity ); if (finishedOpacity == 0) { int counter = m_itemPackage.st_FBX_Monitor->getFinished(); m_itemPackage.st_FBX_Monitor->setFinished(++counter); m_decreaseOpacity_threadFinished = false; } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } else { int finishedOpacity = m_itemPackage.st_FBX_Monitor->getFinishedOpacity(); m_itemPackage.st_FBX_Monitor->setFinishedOpacity( ++finishedOpacity ); if (finishedOpacity >= 10) { m_thtimer_threadFinished->stop(); m_decreaseOpacity_threadFinished = true; //set back to true, cuz next iteration shall decrease opacity as well } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } } void QmitkFiberThreadMonitorWorker::fancyTextFading_threadTerminated() { if (m_decreaseOpacity_threadTerminated) { int terminatedOpacity = m_itemPackage.st_FBX_Monitor->getTerminatedOpacity(); m_itemPackage.st_FBX_Monitor->setTerminatedOpacity( --terminatedOpacity ); if (terminatedOpacity == 0) { int counter = m_itemPackage.st_FBX_Monitor->getTerminated(); m_itemPackage.st_FBX_Monitor->setTerminated(++counter); m_decreaseOpacity_threadTerminated = false; } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } else { int terminatedOpacity = m_itemPackage.st_FBX_Monitor->getTerminatedOpacity(); m_itemPackage.st_FBX_Monitor->setTerminatedOpacity( ++terminatedOpacity ); if (terminatedOpacity >= 10) { m_thtimer_threadTerminated->stop(); m_decreaseOpacity_threadTerminated = true; //set back to true, cuz next iteration shall decrease opacity as well } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } } void QmitkFiberThreadMonitorWorker::fancyMonitorInitialization() { mitk::Point2D pntClose = m_itemPackage.st_FBX_Monitor->getBracketClosePosition(); //possible bottleneck, set pntClose to member mitk::Point2D pntOpen = m_itemPackage.st_FBX_Monitor->getBracketOpenPosition(); //possible bottleneck, set pntClose to member pntClose[0] += m_pixelstepper; pntOpen[0] -= m_pixelstepper; //MITK_INFO << pntClose[0] << " " << pntOpen[0]; m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntClose); m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); int opacity = m_itemPackage.st_FBX_Monitor->getHeadingOpacity() + 1; if (opacity > 10) opacity = 10; m_itemPackage.st_FBX_Monitor->setHeadingOpacity(opacity); if (pntClose[0] >= m_steppingDistance) { if (m_itemPackage.st_FBX_Monitor->getHeadingOpacity() != 10 ) { m_itemPackage.st_FBX_Monitor->setHeadingOpacity(10); m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } m_thtimer_initMonitor->stop(); //position them to obt y=25 m_thtimer_initMonitorSetFinalPosition->start(); } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } void QmitkFiberThreadMonitorWorker::fancyMonitorInitializationFinalPos() { //get y pos of mitk::Point2D pntClose = m_itemPackage.st_FBX_Monitor->getBracketClosePosition(); mitk::Point2D pntOpen = m_itemPackage.st_FBX_Monitor->getBracketOpenPosition(); mitk::Point2D pntHead = m_itemPackage.st_FBX_Monitor->getHeadingPosition(); pntClose[1] += 5; pntOpen[1] += 5; pntHead[1] += 5; m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntClose); m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); m_itemPackage.st_FBX_Monitor->setHeadingPosition(pntHead); if (pntClose[1] >= 35) { //35 = y position m_thtimer_initMonitorSetFinalPosition->stop(); //now init mask of labels m_thtimer_initMonitorSetMasks->start(); } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } void QmitkFiberThreadMonitorWorker::fancyMonitorInitializationMask() { //increase opacity int opacity = m_itemPackage.st_FBX_Monitor->getMaskOpacity(); opacity++; m_itemPackage.st_FBX_Monitor->setMaskOpacity(opacity); m_itemPackage.st_FBX_Monitor->setStartedOpacity(opacity); m_itemPackage.st_FBX_Monitor->setFinishedOpacity(opacity); m_itemPackage.st_FBX_Monitor->setTerminatedOpacity(opacity); m_itemPackage.st_FBX_Monitor->setStatusOpacity(opacity); if (opacity >=10) { m_thtimer_initMonitorSetMasks->stop(); } m_itemPackage.st_ThreadMonitorDataNode->Modified(); m_itemPackage.st_MultiWidget->RequestUpdate(); } //============================================== //======== W O R K E R S ________ E N D ======== //============================================== //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### // HERE STARTS THE ACTUAL FIBERBUNDLE DEVELOPER VIEW IMPLEMENTATION //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### //========#########################===============###########################=====================######################### const std::string QmitkFiberBundleDeveloperView::VIEW_ID = "org.mitk.views.fiberbundledeveloper"; const std::string id_DataManager = "org.mitk.views.datamanager"; using namespace berry; QmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_FiberIDGenerator( NULL) , m_GeneratorFibersRandom( NULL ) , m_FiberFeederFASlave( NULL ) , m_FiberColoringSlave(NULL) , m_FiberExtractor(NULL) , m_fiberMonitorIsOn( false ) , m_CircleCounter( 0 ) , m_suppressSignal(false) { m_hostThread = new QThread; m_threadInProgress = false; } // Destructor QmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView() { //m_FiberBundleX->Delete(); using weakPointer, therefore no delete necessary delete m_hostThread; } void QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done in QtDesigner, etc. if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls; m_Controls->setupUi( parent ); /*=========INITIALIZE BUTTON CONFIGURATION ================*/ m_Controls->radioButton_directionX->setEnabled(false); m_Controls->radioButton_directionY->setEnabled(false); m_Controls->radioButton_directionZ->setEnabled(false); m_Controls->buttonGenerateFiberIds->setEnabled(false); m_Controls->buttonGenerateFibers->setEnabled(true); m_Controls->buttonColorFibers->setEnabled(false); m_Controls->ddAvailableColorcodings->setEnabled(false); m_Controls->buttonExtractFibers->setEnabled(false); m_Controls->button_FAMap->setEnabled(true); m_Controls->buttonSMFibers->setEnabled(false);//not yet implemented m_Controls->buttonVtkDecimatePro->setEnabled(false);//not yet implemented m_Controls->buttonVtkSmoothPD->setEnabled(false);//not yet implemented m_Controls->buttonGenerateTubes->setEnabled(false);//not yet implemented connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) ); connect( m_Controls->buttonGenerateFiberIds, SIGNAL(clicked()), this, SLOT(DoGenerateFiberIDs()) ); connect( m_Controls->button_FAMapExecute, SIGNAL(clicked()), this, SLOT(DoSetFAValues()) ); connect( m_Controls->button_FAMap, SIGNAL(clicked()), this, SLOT(DoSetFAMap()) ); connect( m_Controls->buttonExtractFibers, SIGNAL(clicked()), this, SLOT(DoExtractFibers()) ); connect( m_Controls->radioButton_directionRandom, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); connect( m_Controls->radioButton_directionX, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); connect( m_Controls->radioButton_directionY, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); connect( m_Controls->radioButton_directionZ, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); connect( m_Controls->toolBox, SIGNAL(currentChanged ( int ) ), this, SLOT(SelectionChangedToolBox(int)) ); connect( m_Controls->m_CircleButton, SIGNAL( clicked() ), this, SLOT( ActionDrawEllipseTriggered() ) ); connect( m_Controls->buttonColorFibers, SIGNAL(clicked()), this, SLOT(DoColorFibers()) ); // connect( m_Controls->ddAvailableColorcodings, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCurrentColorCoding(int) )); connect( m_Controls->ddAvailableColorcodings, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCurrentColorCoding(int) )); connect( m_Controls->checkBoxMonitorFiberThreads, SIGNAL(stateChanged(int)), this, SLOT(DoMonitorFiberThreads(int)) ); } // Checkpoint for fiber ORIENTATION if ( m_DirectionRadios.empty() ) { m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom); m_DirectionRadios.insert(1, m_Controls->radioButton_directionX); m_DirectionRadios.insert(2, m_Controls->radioButton_directionY); m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ); } // set GUI elements of FiberGenerator to according configuration DoUpdateGenerateFibersWidget(); } /* THIS METHOD UPDATES ALL GUI ELEMENTS OF QGroupBox DEPENDING ON CURRENTLY SELECTED * RADIO BUTTONS */ void QmitkFiberBundleDeveloperView::DoUpdateGenerateFibersWidget() { //get selected radioButton QString fibDirection; //stores the object_name of selected radiobutton QVector::const_iterator i; for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) { QRadioButton* rdbtn = *i; if (rdbtn->isChecked()) fibDirection = rdbtn->objectName(); } if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { // disable radiobuttons if (m_Controls->boxFiberMinLength->isEnabled()) m_Controls->boxFiberMinLength->setEnabled(false); if (m_Controls->labelFiberMinLength->isEnabled()) m_Controls->labelFiberMinLength->setEnabled(false); if (m_Controls->boxFiberMaxLength->isEnabled()) m_Controls->boxFiberMaxLength->setEnabled(false); if (m_Controls->labelFiberMaxLength->isEnabled()) m_Controls->labelFiberMaxLength->setEnabled(false); //enable radiobuttons if (!m_Controls->labelFibersTotal->isEnabled()) m_Controls->labelFibersTotal->setEnabled(true); if (!m_Controls->boxFiberNumbers->isEnabled()) m_Controls->boxFiberNumbers->setEnabled(true); if (!m_Controls->labelDistrRadius->isEnabled()) m_Controls->labelDistrRadius->setEnabled(true); if (!m_Controls->boxDistributionRadius->isEnabled()) m_Controls->boxDistributionRadius->setEnabled(true); } else { // disable radiobuttons if (m_Controls->labelDistrRadius->isEnabled()) m_Controls->labelDistrRadius->setEnabled(false); if (m_Controls->boxDistributionRadius->isEnabled()) m_Controls->boxDistributionRadius->setEnabled(false); //enable radiobuttons if (!m_Controls->labelFibersTotal->isEnabled()) m_Controls->labelFibersTotal->setEnabled(true); if (!m_Controls->boxFiberNumbers->isEnabled()) m_Controls->boxFiberNumbers->setEnabled(true); if (!m_Controls->boxFiberMinLength->isEnabled()) m_Controls->boxFiberMinLength->setEnabled(true); if (!m_Controls->labelFiberMinLength->isEnabled()) m_Controls->labelFiberMinLength->setEnabled(true); if (!m_Controls->boxFiberMaxLength->isEnabled()) m_Controls->boxFiberMaxLength->setEnabled(true); if (!m_Controls->labelFiberMaxLength->isEnabled()) m_Controls->labelFiberMaxLength->setEnabled(true); } } void QmitkFiberBundleDeveloperView::DoGenerateFibers() { // GET SELECTED FIBER DIRECTION QString fibDirection; //stores the object_name of selected radiobutton QVector::const_iterator i; for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) { QRadioButton* rdbtn = *i; if (rdbtn->isChecked()) fibDirection = rdbtn->objectName(); } // vtkPolyData* output; // FiberPD stores the generated PolyData... going to be generated in thread if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { // build polydata with random lines and fibers // output = GenerateVtkFibersRandom(); } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_X ) { // build polydata with XDirection fibers //output = GenerateVtkFibersDirectionX(); } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Y ) { // build polydata with YDirection fibers // output = GenerateVtkFibersDirectionY(); } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Z ) { // build polydata with ZDirection fibers // output = GenerateVtkFibersDirectionZ(); } } void QmitkFiberBundleDeveloperView::DoExtractFibers() { /* ===== TIMER CONFIGURATIONS for visual effect ====== * start and stop is called in Thread */ QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough localTimer->setInterval( 10 ); connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateExtractFibersTimer()) ); struct Package4WorkingThread ItemPackageForExtractor; ItemPackageForExtractor.st_FBX = m_FiberBundleX; ItemPackageForExtractor.st_Controls = m_Controls; ItemPackageForExtractor.st_FancyGUITimer1 = localTimer; ItemPackageForExtractor.st_host = this; //needed to access method "PutFibersToDataStorage()" ItemPackageForExtractor.st_pntr_to_Method_PutFibersToDataStorage = &QmitkFiberBundleDeveloperView::PutFibersToDataStorage; //actual functor calling method putFibersToDataStorage ItemPackageForExtractor.st_PlanarFigure = m_PlanarFigure; //set element for thread monitoring if (m_fiberMonitorIsOn) ItemPackageForExtractor.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; if (m_threadInProgress) return; //maybe popup window saying, working thread still in progress...pls wait m_FiberExtractor = new QmitkFiberExtractorWorker(m_hostThread, ItemPackageForExtractor); m_FiberExtractor->moveToThread(m_hostThread); //connections connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_FiberExtraction() )); connect(m_hostThread, SIGNAL(started()), m_FiberExtractor, SLOT( run() )); connect(m_hostThread, SIGNAL(finished()), this, SLOT( AfterThread_FiberExtraction() )); connect(m_hostThread, SIGNAL(terminated()), this, SLOT( AfterThread_FiberExtraction() )); m_hostThread->start(QThread::HighestPriority) ; } void QmitkFiberBundleDeveloperView::UpdateExtractFibersTimer() { // Make sure that thread has set according info-label to number! here we do not check if value is numeric! shall be done in beforeThreadstarted() QString crntValue = m_Controls->infoTimerExtractFibers->text(); int tmpVal = crntValue.toInt(); m_Controls->infoTimerExtractFibers->setText(QString::number(++tmpVal)); m_Controls->infoTimerExtractFibers->update(); } void QmitkFiberBundleDeveloperView::BeforeThread_FiberExtraction() { m_threadInProgress = true; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); //m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); } } void QmitkFiberBundleDeveloperView::AfterThread_FiberExtraction() { m_threadInProgress = false; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); } // disconnect(m_hostThread, 0, 0, 0); m_hostThread->disconnect(); // m_FiberExtractor->disconnect(); delete m_FiberExtractor; m_FiberBundleNode->Modified(); m_MultiWidget->RequestUpdate(); } void QmitkFiberBundleDeveloperView::PutFibersToDataStorage( vtkSmartPointer threadOutput) { MITK_INFO << "lines: " << threadOutput->GetNumberOfLines() << "pnts: " << threadOutput->GetNumberOfPoints(); //qthread mutex lock mitk::FiberBundleX::Pointer FB = mitk::FiberBundleX::New(threadOutput); mitk::DataNode::Pointer FBNode; FBNode = mitk::DataNode::New(); FBNode->SetName("FiberBundleX"); FBNode->SetData(FB); FBNode->SetVisibility(true); FBNode->SetOpacity(1.0); GetDataStorage()->Add(FBNode); FBNode->Modified(); const mitk::PlaneGeometry * tsgeo = m_MultiWidget->GetTimeNavigationController()->GetCurrentPlaneGeometry(); if (tsgeo == NULL) { /* GetDataStorage()->Modified etc. have no effect, therefore proceed as followed below */ // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = GetDataStorage()->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } else { GetDataStorage()->Modified(); m_MultiWidget->RequestUpdate(); //necessary?? } //qthread mutex unlock } void QmitkFiberBundleDeveloperView::PutFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name) { mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); std::vector selectedNodes = GetDataManagerSelection(); for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } newNode->SetSelected(true); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,0.0,0.0)); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true)); newNode->AddProperty( "selected", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawoutline", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(false) ); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(3.0) ); newNode->AddProperty( "planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.outline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.helperline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(0.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.marker.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.marker.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.line.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.outline.opacity", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.helperline.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.marker.opacity",mitk::FloatProperty::New(2.0)); // figure drawn on the topmost layer / image this->GetDataStorage()->Add(newNode); } /* * Generate polydata of random fibers */ void QmitkFiberBundleDeveloperView::GenerateVtkFibersRandom() { /* ===== TIMER CONFIGURATIONS for visual effect ====== * start and stop is called in Thread */ QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough localTimer->setInterval( 10 ); connect( localTimer, SIGNAL(timeout()), this, SLOT(UpdateGenerateRandomFibersTimer()) ); struct Package4WorkingThread ItemPackageForRandomGenerator; ItemPackageForRandomGenerator.st_FBX = m_FiberBundleX; ItemPackageForRandomGenerator.st_Controls = m_Controls; ItemPackageForRandomGenerator.st_FancyGUITimer1 = localTimer; ItemPackageForRandomGenerator.st_host = this; //needed to access method "PutFibersToDataStorage()" ItemPackageForRandomGenerator.st_pntr_to_Method_PutFibersToDataStorage = &QmitkFiberBundleDeveloperView::PutFibersToDataStorage; //actual functor calling method putFibersToDataStorage //set element for thread monitoring if (m_fiberMonitorIsOn) ItemPackageForRandomGenerator.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; if (m_threadInProgress) return; //maybe popup window saying, working thread still in progress...pls wait m_GeneratorFibersRandom = new QmitkFiberGenerateRandomWorker(m_hostThread, ItemPackageForRandomGenerator); m_GeneratorFibersRandom->moveToThread(m_hostThread); connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_GenerateFibersRandom()) ); connect(m_hostThread, SIGNAL(started()), m_GeneratorFibersRandom, SLOT(run()) ); connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_GenerateFibersRandom()) ); connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_GenerateFibersRandom()) ); m_hostThread->start(QThread::LowestPriority); } void QmitkFiberBundleDeveloperView::UpdateColorFibersTimer() { // Make sure that thread has set according info-label to number! here we do not check if value is numeric! QString crntValue = m_Controls->infoTimerColorCoding->text(); int tmpVal = crntValue.toInt(); m_Controls->infoTimerColorCoding->setText(QString::number(++tmpVal)); m_Controls->infoTimerColorCoding->update(); } void QmitkFiberBundleDeveloperView::UpdateGenerateRandomFibersTimer() { // Make sure that thread has set according info-label to number! here we do not check if value is numeric! QString crntValue = m_Controls->infoTimerGenerateFiberBundle->text(); int tmpVal = crntValue.toInt(); m_Controls->infoTimerGenerateFiberBundle->setText(QString::number(++tmpVal)); m_Controls->infoTimerGenerateFiberBundle->update(); } void QmitkFiberBundleDeveloperView::UpdateSetFAValuesTimer() { // Make sure that thread has set according info-label to number! here we do not check if value is numeric! QString crntValue = m_Controls->infoTimerSetFA->text(); int tmpVal = crntValue.toInt(); m_Controls->infoTimerSetFA->setText(QString::number(++tmpVal)); m_Controls->infoTimerSetFA->update(); } void QmitkFiberBundleDeveloperView::BeforeThread_GenerateFibersRandom() { m_threadInProgress = true; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); //m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); } } void QmitkFiberBundleDeveloperView::AfterThread_GenerateFibersRandom() { m_threadInProgress = false; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); } // disconnect(m_hostThread, 0, 0, 0); m_hostThread->disconnect(); delete m_GeneratorFibersRandom; } vtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionX() { int numOfFibers = m_Controls->boxFiberNumbers->value(); vtkSmartPointer linesCell = vtkSmartPointer::New(); vtkSmartPointer points = vtkSmartPointer::New(); //insert Origin point, this point has index 0 in point array double originX = 0.0; double originY = 0.0; double originZ = 0.0; //after each iteration the origin of the new fiber increases //here you set which direction is affected. double increaseX = 0.0; double increaseY = 1.0; double increaseZ = 0.0; //walk along X axis //length of fibers increases in each iteration for (int i=0; i newFiber = vtkSmartPointer::New(); newFiber->GetPointIds()->SetNumberOfIds(i+2); //create starting point and add it to pointset points->InsertNextPoint(originX + (double)i * increaseX , originY + (double)i * increaseY, originZ + (double)i * increaseZ); //add starting point to fiber newFiber->GetPointIds()->SetId(0,points->GetNumberOfPoints()-1); //insert remaining points for fiber for (int pj=0; pj<=i ; ++pj) { //generate next point on X axis points->InsertNextPoint( originX + (double)pj+1 , originY + (double)i * increaseY, originZ + (double)i * increaseZ ); newFiber->GetPointIds()->SetId(pj+1,points->GetNumberOfPoints()-1); } linesCell->InsertNextCell(newFiber); } vtkSmartPointer PDX = vtkSmartPointer::New(); PDX->SetPoints(points); PDX->SetLines(linesCell); return PDX; } vtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionY() { vtkSmartPointer PDY = vtkSmartPointer::New(); //todo return PDY; } vtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionZ() { vtkSmartPointer PDZ = vtkSmartPointer::New(); //todo return PDZ; } void QmitkFiberBundleDeveloperView::DoSetFAValues() { QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough localTimer->setInterval( 10 ); connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateSetFAValuesTimer() ) ); // pack items which are needed by thread processing struct Package4WorkingThread ItemPackageToSetFAMap; ItemPackageToSetFAMap.st_FBX = m_FiberBundleX; ItemPackageToSetFAMap.st_FancyGUITimer1 = localTimer; ItemPackageToSetFAMap.st_PassedDataNode = m_FANode; ItemPackageToSetFAMap.st_Controls = m_Controls; if (m_fiberMonitorIsOn) ItemPackageToSetFAMap.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; if (m_threadInProgress) return; //maybe popup window saying, working thread still in progress...pls wait m_FiberFeederFASlave = new QmitkFiberFeederFAWorker(m_hostThread, ItemPackageToSetFAMap); m_FiberFeederFASlave->moveToThread(m_hostThread); connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_FiberSetFA()) ); connect(m_hostThread, SIGNAL(started()), m_FiberFeederFASlave, SLOT(run()) ); connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_FiberSetFA())); connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_FiberSetFA())); m_hostThread->start(QThread::LowestPriority); } void QmitkFiberBundleDeveloperView::DoSetFAMap() { std::vector nodes = GetDataManagerSelection(); if (nodes.empty()) { m_Controls->lineEdit_FAMap->setText("N/A"); return; } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNotNull() && dynamic_cast(node->GetData())) { // this node is what we want m_FANode = node; m_Controls->lineEdit_FAMap->setText(node->GetName().c_str()); return; } } } void QmitkFiberBundleDeveloperView::BeforeThread_FiberSetFA() { m_threadInProgress = true; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); } } void QmitkFiberBundleDeveloperView::AfterThread_FiberSetFA() { m_threadInProgress = false; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); } disconnect(m_hostThread, 0, 0, 0); m_hostThread->disconnect(); //update renderer m_FiberBundleNode->Modified(); m_MultiWidget->ForceImmediateUpdate(); //update QComboBox(dropDown menu) in view of available ColorCodings this->DoGatherColorCodings(); delete m_FiberFeederFASlave; } void QmitkFiberBundleDeveloperView::DoColorFibers() { // MITK_INFO << "call fibercoloring in fiberBundleX"; QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough localTimer->setInterval( 10 ); connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateColorFibersTimer() ) ); // pack items which are needed by thread processing struct Package4WorkingThread ItemPackageForFiberColoring; ItemPackageForFiberColoring.st_FBX = m_FiberBundleX; ItemPackageForFiberColoring.st_PassedDataNode = m_FiberBundleNode; ItemPackageForFiberColoring.st_FancyGUITimer1 = localTimer; ItemPackageForFiberColoring.st_Controls = m_Controls; //needed to catch up some selections and set options in GUI if (m_fiberMonitorIsOn) ItemPackageForFiberColoring.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; if (m_threadInProgress) return; //maybe popup window saying, working thread still in progress...pls wait m_FiberColoringSlave = new QmitkFiberColoringWorker(m_hostThread, ItemPackageForFiberColoring); m_FiberColoringSlave->moveToThread(m_hostThread); connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_FiberColorCoding()) ); connect(m_hostThread, SIGNAL(started()), m_FiberColoringSlave, SLOT(run()) ); connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_FiberColorCoding())); connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_FiberColorCoding())); m_hostThread->start(QThread::LowestPriority); } void QmitkFiberBundleDeveloperView::BeforeThread_FiberColorCoding() { m_threadInProgress = true; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); } } void QmitkFiberBundleDeveloperView::AfterThread_FiberColorCoding() { m_threadInProgress = false; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); } disconnect(m_hostThread, 0, 0, 0); m_hostThread->disconnect(); //update renderer m_FiberBundleNode->Modified(); m_MultiWidget->ForceImmediateUpdate(); //update QComboBox(dropDown menu) in view of available ColorCodings this->DoGatherColorCodings(); delete m_FiberColoringSlave; } void QmitkFiberBundleDeveloperView::DoGatherColorCodings() { QStringList fbxColorCodings = m_FiberBundleX->GetAvailableColorCodings(); //update dropDown Menu //remove all items from menu m_suppressSignal = true; int ddItems = m_Controls->ddAvailableColorcodings->count(); for(int i=ddItems-1; i>=0; i--) { //note, after each item remove, index in QComboBox is updated. sending signal: index changed m_Controls->ddAvailableColorcodings->removeItem(i); } //fill new data into menu m_Controls->ddAvailableColorcodings->addItems(fbxColorCodings); m_Controls->ddAvailableColorcodings->addItem(m_FiberBundleX->COLORCODING_CUSTOM); //highlight current colorcoding QString cc = m_FiberBundleX->GetCurrentColorCoding(); MITK_INFO << cc.toStdString().c_str() << " is at idx: " << m_Controls->ddAvailableColorcodings->findText(cc); m_Controls->ddAvailableColorcodings->setCurrentIndex( m_Controls->ddAvailableColorcodings->findText(cc) ); m_Controls->ddAvailableColorcodings->update(); m_suppressSignal = false; } void QmitkFiberBundleDeveloperView::SetCurrentColorCoding(int idx) { if(!m_suppressSignal){ QString selectedColorCoding = m_Controls->ddAvailableColorcodings->itemText(idx); m_FiberBundleX->SetColorCoding(selectedColorCoding.toStdString().c_str() ); //QString to char // update rendering m_FiberBundleNode->Modified(); m_MultiWidget->ForceImmediateUpdate(); } } /* === OutSourcedMethod: THIS METHOD GENERATES ESSENTIAL GEOMETRY PARAMETERS FOR THE MITK FRAMEWORK === * WITHOUT, the rendering mechanism will ignore objects without valid Geometry * for each object, MITK requires: ORIGIN, SPACING, TRANSFORM MATRIX, BOUNDING-BOX */ mitk::Geometry3D::Pointer QmitkFiberBundleDeveloperView::GenerateStandardGeometryForMITK() { mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); // generate origin mitk::Point3D origin; origin[0] = 0; origin[1] = 0; origin[2] = 0; geometry->SetOrigin(origin); // generate spacing float spacing[3] = {1,1,1}; geometry->SetSpacing(spacing); // generate identity transform-matrix vtkSmartPointer m = vtkMatrix4x4::New(); geometry->SetIndexToWorldTransformByVtkMatrix(m); // generate boundingbox // for an usable bounding-box use gui parameters to estimate the boundingbox float bounds[] = {500, 500, 500, -500, -500, -500}; // GET SELECTED FIBER DIRECTION QString fibDirection; //stores the object_name of selected radiobutton QVector::const_iterator i; for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) { QRadioButton* rdbtn = *i; if (rdbtn->isChecked()) fibDirection = rdbtn->objectName(); } if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { // use information about distribution parameter to calculate bounding box int distrRadius = m_Controls->boxDistributionRadius->value(); bounds[0] = distrRadius; bounds[1] = distrRadius; bounds[2] = distrRadius; bounds[3] = -distrRadius; bounds[4] = -distrRadius; bounds[5] = -distrRadius; } else { // so far only X,Y,Z directions are available MITK_INFO << "_______GEOMETRY ISSUE_____\n***BoundingBox for X, Y, Z fiber directions are not optimized yet!***"; int maxFibLength = m_Controls->boxFiberMaxLength->value(); bounds[0] = maxFibLength; bounds[1] = maxFibLength; bounds[2] = maxFibLength; bounds[3] = -maxFibLength; bounds[4] = -maxFibLength; bounds[5] = -maxFibLength; } geometry->SetFloatBounds(bounds); geometry->SetImageGeometry(true); //?? return geometry; } void QmitkFiberBundleDeveloperView::UpdateFiberIDTimer() { //MAKE SURE by yourself THAT NOTHING ELSE THAN A NUMBER IS SET IN THAT LABEL QString crntValue = m_Controls->infoTimerGenerateFiberIds->text(); int tmpVal = crntValue.toInt(); m_Controls->infoTimerGenerateFiberIds->setText(QString::number(++tmpVal)); m_Controls->infoTimerGenerateFiberIds->update(); } /* Initialie ID dataset in FiberBundleX */ void QmitkFiberBundleDeveloperView::DoGenerateFiberIDs() { /* ===== TIMER CONFIGURATIONS for visual effect ====== * start and stop is called in Thread */ QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough localTimer->setInterval( 10 ); connect( localTimer, SIGNAL(timeout()), this, SLOT(UpdateFiberIDTimer()) ); // pack items which are needed by thread processing struct Package4WorkingThread FiberIdPackage; FiberIdPackage.st_FBX = m_FiberBundleX; FiberIdPackage.st_FancyGUITimer1 = localTimer; FiberIdPackage.st_Controls = m_Controls; //set element for thread monitoring if (m_fiberMonitorIsOn) FiberIdPackage.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; if (m_threadInProgress) return; //maybe popup window saying, working thread still in progress...pls wait // THREAD CONFIGURATION m_FiberIDGenerator = new QmitkFiberIDWorker(m_hostThread, FiberIdPackage); m_FiberIDGenerator->moveToThread(m_hostThread); connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_IdGenerate()) ); connect(m_hostThread, SIGNAL(started()), m_FiberIDGenerator, SLOT(run())); connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_IdGenerate())); connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_IdGenerate())); m_hostThread->start(QThread::LowestPriority); // m_Controls->infoTimerGenerateFiberIds->setText(QString::number(clock.GetTotal())); } void QmitkFiberBundleDeveloperView::BeforeThread_IdGenerate() { m_threadInProgress = true; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); } } void QmitkFiberBundleDeveloperView::AfterThread_IdGenerate() { m_threadInProgress = false; if (m_fiberMonitorIsOn){ m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); } disconnect(m_hostThread, 0, 0, 0); m_hostThread->disconnect(); delete m_FiberIDGenerator; } void QmitkFiberBundleDeveloperView::ResetFiberInfoWidget() { if (m_Controls->infoAnalyseNumOfFibers->isEnabled()) { m_Controls->infoAnalyseNumOfFibers->setText("-"); m_Controls->infoAnalyseNumOfPoints->setText("-"); m_Controls->infoAnalyseNumOfFibers->setEnabled(false); } } void QmitkFiberBundleDeveloperView::FeedFiberInfoWidget() { if (!m_Controls->infoAnalyseNumOfFibers->isEnabled()) m_Controls->infoAnalyseNumOfFibers->setEnabled(true); QString numOfFibers; numOfFibers.setNum( m_FiberBundleX->GetFiberPolyData()->GetNumberOfLines() ); QString numOfPoints; numOfPoints.setNum( m_FiberBundleX->GetFiberPolyData()->GetNumberOfPoints() ); m_Controls->infoAnalyseNumOfFibers->setText( numOfFibers ); m_Controls->infoAnalyseNumOfPoints->setText( numOfPoints ); } void QmitkFiberBundleDeveloperView::SelectionChangedToolBox(int idx) { // show/reset items of selected toolbox page FiberInfo if (m_Controls->page_FiberInfo->isVisible()) { if (m_FiberBundleX != NULL) { FeedFiberInfoWidget(); } else { //if infolables are disabled: return //else set info back to - and set label and info to disabled ResetFiberInfoWidget(); } } // show/reset items of selected toolbox page FiberProcessing if (m_Controls->page_FiberProcessing->isVisible()) { if (m_FiberBundleX.IsNotNull() && m_PlanarFigure.IsNotNull() ) { //show fiber extraction button m_Controls->buttonExtractFibers->setEnabled(true); } else { m_Controls->buttonExtractFibers->setEnabled(false); } if (m_FiberBundleX.IsNotNull()) { //show button colorCoding m_Controls->buttonColorFibers->setEnabled(true); m_Controls->ddAvailableColorcodings->setEnabled(true); m_Controls->buttonGenerateFiberIds->setEnabled(true); // m_Controls->buttonSMFibers->setEnabled(true); // m_Controls->buttonVtkDecimatePro->setEnabled(true); // m_Controls->buttonVtkSmoothPD->setEnabled(true); // m_Controls->buttonGenerateTubes->setEnabled(true); } else { m_Controls->buttonColorFibers->setEnabled(false); m_Controls->ddAvailableColorcodings->setEnabled(false); m_Controls->buttonGenerateFiberIds->setEnabled(false); m_Controls->buttonSMFibers->setEnabled(false); m_Controls->buttonVtkDecimatePro->setEnabled(false); m_Controls->buttonVtkSmoothPD->setEnabled(false); m_Controls->buttonGenerateTubes->setEnabled(true); } } } void QmitkFiberBundleDeveloperView::FBXDependendGUIElementsConfigurator() { // ==== FIBER PROCESSING ELEMENTS and ALL ELEMENTS WHICH NEED A FBX DATANODE====== // m_Controls->buttonGenerateFiberIds->setEnabled(isVisible); moved to selectionChangedToolBox SelectionChangedToolBox(-1); //set gui elements with respect to active tab, widget, etc. -1 has no effect } void QmitkFiberBundleDeveloperView::DoMonitorFiberThreads(int checkStatus) { //check if in datanode exists already a node of type mitkFiberBundleXThreadMonitor //if not then put node to datastorage //if checkStatus is 1 then start qtimer using fading in starting text in datanode //if checkStatus is 0 then fade out dataNode using qtimer if (checkStatus) { m_fiberMonitorIsOn = true; // Generate Node hosting thread information mitk::FiberBundleXThreadMonitor::Pointer FBXThreadMonitor = mitk::FiberBundleXThreadMonitor::New(); FBXThreadMonitor->SetGeometry(this->GenerateStandardGeometryForMITK()); m_MonitorNode = mitk::DataNode::New(); m_MonitorNode->SetName("FBX_threadMonitor"); m_MonitorNode->SetData(FBXThreadMonitor); m_MonitorNode->SetVisibility(true); m_MonitorNode->SetOpacity(1.0); GetDataStorage()->Add(m_MonitorNode); //following code is needed for rendering text in mitk! without geometry nothing is rendered const mitk::PlaneGeometry * tsgeo = m_MultiWidget->GetTimeNavigationController()->GetCurrentPlaneGeometry(); if (tsgeo == NULL) { /* GetDataStorage()->Modified etc. have no effect, therefore proceed as followed below */ // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New( "includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = GetDataStorage()->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } else { GetDataStorage()->Modified(); m_MultiWidget->RequestUpdate(); //necessary?? } //__GEOMETRY FOR THREADMONITOR GENERATED /* ====== initialize thread for managing fiberThread information ========= */ m_monitorThread = new QThread; // the package needs datastorage, MonitorDatanode, standardmultiwidget, struct Package4WorkingThread ItemPackageForThreadMonitor; ItemPackageForThreadMonitor.st_DataStorage = GetDataStorage(); ItemPackageForThreadMonitor.st_ThreadMonitorDataNode = m_MonitorNode; ItemPackageForThreadMonitor.st_MultiWidget = m_MultiWidget; ItemPackageForThreadMonitor.st_FBX_Monitor = FBXThreadMonitor; m_fiberThreadMonitorWorker = new QmitkFiberThreadMonitorWorker(m_monitorThread, ItemPackageForThreadMonitor); m_fiberThreadMonitorWorker->moveToThread(m_monitorThread); connect ( m_monitorThread, SIGNAL( started() ), m_fiberThreadMonitorWorker, SLOT( run() ) ); m_monitorThread->start(QThread::LowestPriority); m_fiberThreadMonitorWorker->initializeMonitor();//do some init animation ;-) } else { m_fiberMonitorIsOn = false; m_monitorThread->quit(); //think about outsourcing following lines to quit / terminate slot of thread GetDataStorage()->Remove(m_MonitorNode); GetDataStorage()->Modified(); m_MultiWidget->RequestUpdate(); //necessary?? } } void QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector nodes ) { if (nodes.empty()) return; /* ==== reset everyhing related to FiberBundleX ====== * - variable m_FiberBundleX * - visualization of analysed fiberbundle */ m_FiberBundleNode = NULL; m_FiberBundleX = NULL; //reset pointer, so that member does not point to depricated locations m_PlanarFigure = NULL; ResetFiberInfoWidget(); //timer reset only when no thread is in progress if (!m_threadInProgress) { m_Controls->infoTimerGenerateFiberIds->setText("-"); //set GUI representation of timer to - m_Controls->infoTimerGenerateFiberBundle->setText( "-" ); m_Controls->infoTimerColorCoding->setText( "-" ); } //==================================================== for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; /* CHECKPOINT: FIBERBUNDLE*/ if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_FiberBundleNode = node; m_FiberBundleX = dynamic_cast(node->GetData()); if (m_FiberBundleX.IsNull()){ MITK_INFO << "========ATTENTION=========\n unable to load selected FiberBundleX to FiberBundleDeveloper-plugin \n"; m_FiberBundleNode = NULL; } // ==== FIBERBUNDLE_INFO ELEMENTS ==== if ( m_Controls->page_FiberInfo->isVisible() ) FeedFiberInfoWidget(); // enable FiberBundleX related Gui Elements, such as buttons etc. this->FBXDependendGUIElementsConfigurator(); this->DoGatherColorCodings(); } /* CHECKPOINT: PLANARFIGURE */ else if ( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_PlanarFigure = dynamic_cast(node->GetData()); MITK_INFO << "PF selected"; if (m_PlanarFigure.IsNull()) MITK_INFO << "========ATTENTION=========\n unable to load selected Planarfigure to FiberBundleDeveloper-plugin \n"; } } //update gui elements depending on given nodes FBXDependendGUIElementsConfigurator(); //every gui element which needs a FBX for processing is disabled } void QmitkFiberBundleDeveloperView::ActionDrawEllipseTriggered() { // bool checked = m_Controls->m_CircleButton->isChecked(); mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); this->PutFigureToDataStorage(figure, QString("Circle%1").arg(++m_CircleCounter)); MITK_INFO << "PlanarCircle created ..."; mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } } void QmitkFiberBundleDeveloperView::Activated() { MITK_INFO << "FB DevelopersV ACTIVATED()"; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h index 4f3492e822..f6ae58efb0 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h @@ -1,383 +1,382 @@ -/*========================================================================= - - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ - Version: $Revision: 21975 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkFiberBundleDeveloperView_h #define QmitkFiberBundleDeveloperView_h #include #include #include #include "ui_QmitkFiberBundleDeveloperViewControls.h" #include #include #include #include // Qt #include #include #include // VTK #include #include #include #include #include #include class QmitkFiberThreadMonitorWorker; //include needed for struct element class QmitkFiberBundleDeveloperView; //this include is needed for the struct element, especially for functors to QmitkFiberBundleDeveloperView /* ==== THIS STRUCT CONTAINS ALL NECESSARY VARIABLES * TO EXECUTE AND UPDATE GUI ELEMENTS DURING PROCESSING OF A THREAD * why? either you add tons of friendclasses (e.g. FiberWorker objects), or you create a package containing all items needed. Otherwise you have to set all members etc. to public! */ struct Package4WorkingThread { mitk::FiberBundleX* st_FBX; QTimer* st_FancyGUITimer1; Ui::QmitkFiberBundleDeveloperViewControls* st_Controls; //functors to outdoor methods QmitkFiberBundleDeveloperView* st_host; void (QmitkFiberBundleDeveloperView::*st_pntr_to_Method_PutFibersToDataStorage) (vtkSmartPointer); //==DO NOT TOUCH THIS SECTION=== you might extend this section, but do NOT shorten it! hai capito! //host MITK I/O elements, especially needed for thread monitoring QmitkFiberThreadMonitorWorker *st_fiberThreadMonitorWorker; mitk::FiberBundleXThreadMonitor::Pointer st_FBX_Monitor; //needed for direct access do animation/fancy methods mitk::DataNode::Pointer st_ThreadMonitorDataNode; //needed for renderer to recognize node modifications mitk::DataNode::Pointer st_PassedDataNode; //put an extra node if needed mitk::DataStorage::Pointer st_DataStorage; //well that is discussable if needed ;-) probably not QmitkStdMultiWidget* st_MultiWidget; //needed for rendering update mitk::PlanarFigure::Pointer st_PlanarFigure; //needed for fiberextraction }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== //## Documentation //## This class does the actual work for generating fiber ids. class QmitkFiberIDWorker : public QObject { Q_OBJECT public: QmitkFiberIDWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== //## Documentation //## This class does the actual work for colorcoding fibers. class QmitkFiberColoringWorker : public QObject { Q_OBJECT public: QmitkFiberColoringWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== class QmitkFiberGenerateRandomWorker : public QObject { Q_OBJECT public: QmitkFiberGenerateRandomWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== class QmitkFiberFeederFAWorker : public QObject { Q_OBJECT public: QmitkFiberFeederFAWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== class QmitkFiberExtractorWorker : public QObject { Q_OBJECT public: QmitkFiberExtractorWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== class QmitkFiberThreadMonitorWorker : public QObject { Q_OBJECT public: QmitkFiberThreadMonitorWorker( QThread*, Package4WorkingThread ); void initializeMonitor(); void threadForFiberProcessingStarted(); void threadForFiberProcessingFinished(); void threadForFiberProcessingTerminated(); void setThreadStatus(QString); public slots: void run(); void fancyMonitorInitialization(); void fancyMonitorInitializationFinalPos(); void fancyMonitorInitializationMask(); void fancyTextFading_threadStarted(); void fancyTextFading_threadFinished(); void fancyTextFading_threadTerminated(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; QTimer* m_thtimer_initMonitor; QTimer* m_thtimer_initMonitorSetFinalPosition; QTimer* m_thtimer_initMonitorSetMasks; QTimer* m_thtimer_threadStarted; QTimer* m_thtimer_threadFinished; QTimer* m_thtimer_threadTerminated; // flags for fancy fading bool m_decreaseOpacity_threadStarted; bool m_decreaseOpacity_threadFinished; bool m_decreaseOpacity_threadTerminated; // members for fancy animation int m_pixelstepper; int m_steppingDistance; }; // strings to display fiber_thread monitor const QString FBX_STATUS_IDLE = "idle"; const QString FBX_STATUS_STARTED = "starting"; const QString FBX_STATUS_RUNNING = "running"; // ========= HERE STARTS THE ACTUAL FIBERBUNDLE DEVELOPER VIEW ======= const QString FIB_RADIOBUTTON_DIRECTION_RANDOM = "radioButton_directionRandom"; const QString FIB_RADIOBUTTON_DIRECTION_X = "radioButton_directionX"; const QString FIB_RADIOBUTTON_DIRECTION_Y = "radioButton_directionY"; const QString FIB_RADIOBUTTON_DIRECTION_Z = "radioButton_directionZ"; /*! \brief QmitkFiberBundleView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkFiberBundleDeveloperView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkFiberBundleDeveloperView(); virtual ~QmitkFiberBundleDeveloperView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void Activated(); protected slots: void DoGenerateFibers(); void DoGenerateFiberIDs(); void DoExtractFibers(); void DoUpdateGenerateFibersWidget(); void SelectionChangedToolBox(int); void DoMonitorFiberThreads(int); void DoSetFAValues(); void DoSetFAMap(); void DoColorFibers(); void DoGatherColorCodings(); void SetCurrentColorCoding(int); void ActionDrawEllipseTriggered(); //SLOTS FOR THREADS void BeforeThread_IdGenerate(); void AfterThread_IdGenerate(); void BeforeThread_GenerateFibersRandom(); void AfterThread_GenerateFibersRandom(); void BeforeThread_FiberSetFA(); void AfterThread_FiberSetFA(); void BeforeThread_FiberColorCoding(); void AfterThread_FiberColorCoding(); void BeforeThread_FiberExtraction(); void AfterThread_FiberExtraction(); //SLOTS FOR TIMERS void UpdateFiberIDTimer(); void UpdateGenerateRandomFibersTimer(); void UpdateColorFibersTimer(); void UpdateExtractFibersTimer(); void UpdateSetFAValuesTimer(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkFiberBundleDeveloperViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; private: /* METHODS GENERATING FIBERSTRUCTURES */ void GenerateVtkFibersRandom(); vtkSmartPointer GenerateVtkFibersDirectionX(); vtkSmartPointer GenerateVtkFibersDirectionY(); vtkSmartPointer GenerateVtkFibersDirectionZ(); void PutFibersToDataStorage( vtkSmartPointer ); void PutFigureToDataStorage(mitk::PlanarFigure* , const QString& ); /* METHODS FOR FIBER PROCESSING OR PREPROCESSING */ /* HELPERMETHODS */ mitk::Geometry3D::Pointer GenerateStandardGeometryForMITK(); void ResetFiberInfoWidget(); void FeedFiberInfoWidget(); void FBXDependendGUIElementsConfigurator(); void SetGeneratedFBX(); //contains the selected FiberBundle, PlanarFigure mitk::DataNode::Pointer m_FiberBundleNode; mitk::WeakPointer m_FiberBundleX; mitk::PlanarFigure::Pointer m_PlanarFigure; // radiobutton groups QVector< QRadioButton* > m_DirectionRadios; QVector< QRadioButton* > m_FARadios; QVector< QRadioButton* > m_GARadios; // Thread based Workers which do some processing of fibers QmitkFiberIDWorker* m_FiberIDGenerator; QmitkFiberGenerateRandomWorker* m_GeneratorFibersRandom; QmitkFiberFeederFAWorker* m_FiberFeederFASlave; QmitkFiberColoringWorker* m_FiberColoringSlave; QmitkFiberExtractorWorker* m_FiberExtractor; QThread* m_hostThread; QThread* m_monitorThread; bool m_threadInProgress; mitk::DataNode::Pointer m_MonitorNode; QmitkFiberThreadMonitorWorker *m_fiberThreadMonitorWorker; bool m_fiberMonitorIsOn; // counters for ROI nodes int m_CircleCounter; mitk::DataNode::Pointer m_FANode; // flag to bypass signal from qcombobox "index changed(int)" bool m_suppressSignal; }; #endif // _QMITKFIBERTRACKINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp index 204f17b3ff..397b9cef81 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp @@ -1,1767 +1,1766 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ - Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkFiberProcessingView.h" #include // Qt #include // MITK #include #include #include #include #include #include #include #include #include #include #include // ITK #include #include #include #include #include #include #include #include const std::string QmitkFiberProcessingView::VIEW_ID = "org.mitk.views.fiberprocessing"; const std::string id_DataManager = "org.mitk.views.datamanager"; using namespace mitk; QmitkFiberProcessingView::QmitkFiberProcessingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_EllipseCounter(0) , m_PolygonCounter(0) , m_UpsamplingFactor(5) { } // Destructor QmitkFiberProcessingView::~QmitkFiberProcessingView() { } void QmitkFiberProcessingView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkFiberProcessingViewControls; m_Controls->setupUi( parent ); m_Controls->doExtractFibersButton->setDisabled(true); m_Controls->PFCompoANDButton->setDisabled(true); m_Controls->PFCompoORButton->setDisabled(true); m_Controls->PFCompoNOTButton->setDisabled(true); m_Controls->m_PlanarFigureButtonsFrame->setEnabled(false); m_Controls->m_RectangleButton->setVisible(false); connect( m_Controls->doExtractFibersButton, SIGNAL(clicked()), this, SLOT(DoFiberExtraction()) ); connect( m_Controls->m_CircleButton, SIGNAL( clicked() ), this, SLOT( OnDrawCircle() ) ); connect( m_Controls->m_PolygonButton, SIGNAL( clicked() ), this, SLOT( OnDrawPolygon() ) ); connect(m_Controls->PFCompoANDButton, SIGNAL(clicked()), this, SLOT(GenerateAndComposite()) ); connect(m_Controls->PFCompoORButton, SIGNAL(clicked()), this, SLOT(GenerateOrComposite()) ); connect(m_Controls->PFCompoNOTButton, SIGNAL(clicked()), this, SLOT(GenerateNotComposite()) ); connect(m_Controls->m_JoinBundles, SIGNAL(clicked()), this, SLOT(JoinBundles()) ); connect(m_Controls->m_SubstractBundles, SIGNAL(clicked()), this, SLOT(SubstractBundles()) ); connect(m_Controls->m_GenerateRoiImage, SIGNAL(clicked()), this, SLOT(GenerateRoiImage()) ); connect(m_Controls->m_Extract3dButton, SIGNAL(clicked()), this, SLOT(Extract3d())); connect( m_Controls->m_ProcessFiberBundleButton, SIGNAL(clicked()), this, SLOT(ProcessSelectedBundles()) ); connect( m_Controls->m_ResampleFibersButton, SIGNAL(clicked()), this, SLOT(ResampleSelectedBundles()) ); connect(m_Controls->m_FaColorFibersButton, SIGNAL(clicked()), this, SLOT(DoFaColorCoding())); } } void QmitkFiberProcessingView::Extract3d() { std::vector nodes = this->GetDataManagerSelection(); if (nodes.empty()) return; mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(); mitk::Surface::Pointer roi = mitk::Surface::New(); bool fibB = false; bool roiB = false; for (int i=0; i(nodes.at(i)->GetData())) { fib = dynamic_cast(nodes.at(i)->GetData()); fibB = true; } else if (dynamic_cast(nodes.at(i)->GetData())) { roi = dynamic_cast(nodes.at(i)->GetData()); roiB = true; } } if (!fibB) return; if (!roiB) return; vtkSmartPointer polyRoi = roi->GetVtkPolyData(); vtkSmartPointer polyFib = fib->GetFiberPolyData(); vtkSmartPointer selectEnclosedPoints = vtkSmartPointer::New(); selectEnclosedPoints->SetInput(polyFib); selectEnclosedPoints->SetSurface(polyRoi); selectEnclosedPoints->Update(); vtkSmartPointer newPoly = vtkSmartPointer::New(); vtkSmartPointer newCellArray = vtkSmartPointer::New(); vtkSmartPointer newPoints = vtkSmartPointer::New(); vtkSmartPointer newPolyComplement = vtkSmartPointer::New(); vtkSmartPointer newCellArrayComplement = vtkSmartPointer::New(); vtkSmartPointer newPointsComplement = vtkSmartPointer::New(); vtkSmartPointer vLines = polyFib->GetLines(); vLines->InitTraversal(); int numberOfLines = vLines->GetNumberOfCells(); // each line for (int j=0; jGetNextCell ( numPoints, points ); bool isPassing = false; // each point of this line for (int k=0; kIsInside(points[k])) { isPassing = true; // fill new polydata vtkSmartPointer container = vtkSmartPointer::New(); for (int k=0; kGetPoint(points[k]); vtkIdType pointId = newPoints->InsertNextPoint(point); container->GetPointIds()->InsertNextId(pointId); } newCellArray->InsertNextCell(container); break; } } if (!isPassing) { vtkSmartPointer container = vtkSmartPointer::New(); for (int k=0; kGetPoint(points[k]); vtkIdType pointId = newPointsComplement->InsertNextPoint(point); container->GetPointIds()->InsertNextId(pointId); } newCellArrayComplement->InsertNextCell(container); } } newPoly->SetPoints(newPoints); newPoly->SetLines(newCellArray); mitk::FiberBundleX::Pointer fb = mitk::FiberBundleX::New(newPoly); DataNode::Pointer newNode = DataNode::New(); newNode->SetData(fb); newNode->SetName("passing surface"); GetDefaultDataStorage()->Add(newNode); newPolyComplement->SetPoints(newPointsComplement); newPolyComplement->SetLines(newCellArrayComplement); mitk::FiberBundleX::Pointer fbComplement = mitk::FiberBundleX::New(newPolyComplement); DataNode::Pointer newNodeComplement = DataNode::New(); newNodeComplement->SetData(fbComplement); newNodeComplement->SetName("not passing surface"); GetDefaultDataStorage()->Add(newNodeComplement); } void QmitkFiberProcessingView::GenerateRoiImage(){ if (m_SelectedPF.empty()) return; mitk::Geometry3D::Pointer geometry; if (!m_SelectedFB.empty()) { mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedFB.front()->GetData()); geometry = fib->GetGeometry(); } else return; mitk::Vector3D spacing = geometry->GetSpacing(); spacing /= m_UpsamplingFactor; mitk::Point3D newOrigin = geometry->GetOrigin(); mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); newOrigin[0] += bounds.GetElement(0); newOrigin[1] += bounds.GetElement(2); newOrigin[2] += bounds.GetElement(4); itk::Matrix direction; itk::ImageRegion<3> imageRegion; for (int i=0; i<3; i++) for (int j=0; j<3; j++) direction[j][i] = geometry->GetMatrixColumn(i)[j]/spacing[j]; imageRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); imageRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); imageRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); m_PlanarFigureImage = itkUCharImageType::New(); m_PlanarFigureImage->SetSpacing( spacing ); // Set the image spacing m_PlanarFigureImage->SetOrigin( newOrigin ); // Set the image origin m_PlanarFigureImage->SetDirection( direction ); // Set the image direction m_PlanarFigureImage->SetRegions( imageRegion ); m_PlanarFigureImage->Allocate(); m_PlanarFigureImage->FillBuffer( 0 ); Image::Pointer tmpImage = Image::New(); tmpImage->InitializeByItk(m_PlanarFigureImage.GetPointer()); tmpImage->SetVolume(m_PlanarFigureImage->GetBufferPointer()); for (int i=0; iInitializeByItk(m_PlanarFigureImage.GetPointer()); tmpImage->SetVolume(m_PlanarFigureImage->GetBufferPointer()); node->SetData(tmpImage); node->SetName("ROI Image"); this->GetDefaultDataStorage()->Add(node); } void QmitkFiberProcessingView::CompositeExtraction(mitk::DataNode::Pointer node, mitk::Image* image) { if (dynamic_cast(node.GetPointer()->GetData()) && !dynamic_cast(node.GetPointer()->GetData())) { m_PlanarFigure = dynamic_cast(node.GetPointer()->GetData()); AccessFixedDimensionByItk_2( image, InternalReorientImagePlane, 3, m_PlanarFigure->GetGeometry(), -1); // itk::Image< unsigned char, 3 >::Pointer outimage = itk::Image< unsigned char, 3 >::New(); // outimage->SetSpacing( m_PlanarFigure->GetGeometry()->GetSpacing()/m_UpsamplingFactor ); // Set the image spacing // mitk::Point3D origin = m_PlanarFigure->GetGeometry()->GetOrigin(); // mitk::Point3D indexOrigin; // m_PlanarFigure->GetGeometry()->WorldToIndex(origin, indexOrigin); // indexOrigin[0] = indexOrigin[0] - .5 * (1.0-1.0/m_UpsamplingFactor); // indexOrigin[1] = indexOrigin[1] - .5 * (1.0-1.0/m_UpsamplingFactor); // indexOrigin[2] = indexOrigin[2] - .5 * (1.0-1.0/m_UpsamplingFactor); // mitk::Point3D newOrigin; // m_PlanarFigure->GetGeometry()->IndexToWorld(indexOrigin, newOrigin); // outimage->SetOrigin( newOrigin ); // Set the image origin // itk::Matrix matrix; // for (int i=0; i<3; i++) // for (int j=0; j<3; j++) // matrix[j][i] = m_PlanarFigure->GetGeometry()->GetMatrixColumn(i)[j]/m_PlanarFigure->GetGeometry()->GetSpacing().GetElement(i); // outimage->SetDirection( matrix ); // Set the image direction // itk::ImageRegion<3> upsampledRegion; // upsampledRegion.SetSize(0, m_PlanarFigure->GetGeometry()->GetParametricExtentInMM(0)/m_PlanarFigure->GetGeometry()->GetSpacing()[0]); // upsampledRegion.SetSize(1, m_PlanarFigure->GetGeometry()->GetParametricExtentInMM(1)/m_PlanarFigure->GetGeometry()->GetSpacing()[1]); // upsampledRegion.SetSize(2, 1); // typename itk::Image< unsigned char, 3 >::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); // for (unsigned int n = 0; n < 2; n++) // { // upsampledSize[n] = upsampledSize[n] * m_UpsamplingFactor; // } // upsampledRegion.SetSize( upsampledSize ); // outimage->SetRegions( upsampledRegion ); // outimage->Allocate(); // this->m_InternalImage = mitk::Image::New(); // this->m_InternalImage->InitializeByItk( outimage.GetPointer() ); // this->m_InternalImage->SetVolume( outimage->GetBufferPointer() ); AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateMaskFromPlanarFigure, 3, 2, node->GetName() ); } } template < typename TPixel, unsigned int VImageDimension > void QmitkFiberProcessingView::InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::Geometry3D* planegeo3D, int additionalIndex ) { MITK_INFO << "InternalReorientImagePlane() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< float, VImageDimension > FloatImageType; typedef itk::ResampleImageFilter ResamplerType; typename ResamplerType::Pointer resampler = ResamplerType::New(); mitk::PlaneGeometry* planegeo = dynamic_cast(planegeo3D); float upsamp = m_UpsamplingFactor; float gausssigma = 0.5; // Spacing typename ResamplerType::SpacingType spacing = planegeo->GetSpacing(); spacing[0] = image->GetSpacing()[0] / upsamp; spacing[1] = image->GetSpacing()[1] / upsamp; spacing[2] = image->GetSpacing()[2]; resampler->SetOutputSpacing( spacing ); // Size typename ResamplerType::SizeType size; size[0] = planegeo->GetParametricExtentInMM(0) / spacing[0]; size[1] = planegeo->GetParametricExtentInMM(1) / spacing[1]; size[2] = 1; resampler->SetSize( size ); // Origin typename mitk::Point3D orig = planegeo->GetOrigin(); typename mitk::Point3D corrorig; planegeo3D->WorldToIndex(orig,corrorig); corrorig[0] += 0.5/upsamp; corrorig[1] += 0.5/upsamp; corrorig[2] += 0; planegeo3D->IndexToWorld(corrorig,corrorig); resampler->SetOutputOrigin(corrorig ); // Direction typename ResamplerType::DirectionType direction; typename mitk::AffineTransform3D::MatrixType matrix = planegeo->GetIndexToWorldTransform()->GetMatrix(); for(int c=0; cSetOutputDirection( direction ); // Gaussian interpolation if(gausssigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = gausssigma * image->GetSpacing()[d]; } double alpha = 2.0; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typename GaussianInterpolatorType::Pointer interpolator = GaussianInterpolatorType::New(); interpolator->SetInputImage( image ); interpolator->SetParameters( sigma, alpha ); resampler->SetInterpolator( interpolator ); } else { // typedef typename itk::BSplineInterpolateImageFunction // InterpolatorType; typedef typename itk::LinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); } // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); MITK_INFO << "Resampling requested image plane ... "; resampler->Update(); MITK_INFO << " ... done"; if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( resampler->GetOutput() ); this->m_InternalImage->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } } template < typename TPixel, unsigned int VImageDimension > void QmitkFiberProcessingView::InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis, std::string nodeName ) { MITK_INFO << "InternalCalculateMaskFromPlanarFigure() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::CastImageFilter< ImageType, itkUCharImageType > CastFilterType; // Generate mask image as new image with same header as input image and // initialize with "1". itkUCharImageType::Pointer newMaskImage = itkUCharImageType::New(); newMaskImage->SetSpacing( image->GetSpacing() ); // Set the image spacing newMaskImage->SetOrigin( image->GetOrigin() ); // Set the image origin newMaskImage->SetDirection( image->GetDirection() ); // Set the image direction newMaskImage->SetRegions( image->GetLargestPossibleRegion() ); newMaskImage->Allocate(); newMaskImage->FillBuffer( 1 ); // Generate VTK polygon from (closed) PlanarFigure polyline // (The polyline points are shifted by -0.5 in z-direction to make sure // that the extrusion filter, which afterwards elevates all points by +0.5 // in z-direction, creates a 3D object which is cut by the the plane z=0) const Geometry2D *planarFigureGeometry2D = m_PlanarFigure->GetGeometry2D(); const PlanarFigure::PolyLineType planarFigurePolyline = m_PlanarFigure->GetPolyLine( 0 ); const Geometry3D *imageGeometry3D = m_InternalImage->GetGeometry( 0 ); vtkPolyData *polyline = vtkPolyData::New(); polyline->Allocate( 1, 1 ); // Determine x- and y-dimensions depending on principal axis int i0, i1; switch ( axis ) { case 0: i0 = 1; i1 = 2; break; case 1: i0 = 0; i1 = 2; break; case 2: default: i0 = 0; i1 = 1; break; } // Create VTK polydata object of polyline contour vtkPoints *points = vtkPoints::New(); PlanarFigure::PolyLineType::const_iterator it; std::vector indices; unsigned int numberOfPoints = 0; for ( it = planarFigurePolyline.begin(); it != planarFigurePolyline.end(); ++it ) { Point3D point3D; // Convert 2D point back to the local index coordinates of the selected // image Point2D point2D = it->Point; planarFigureGeometry2D->WorldToIndex(point2D, point2D); point2D[0] -= 0.5/m_UpsamplingFactor; point2D[1] -= 0.5/m_UpsamplingFactor; planarFigureGeometry2D->IndexToWorld(point2D, point2D); planarFigureGeometry2D->Map( point2D, point3D ); // Polygons (partially) outside of the image bounds can not be processed // further due to a bug in vtkPolyDataToImageStencil if ( !imageGeometry3D->IsInside( point3D ) ) { float bounds[2] = {0,0}; bounds[0] = this->m_InternalImage->GetLargestPossibleRegion().GetSize().GetElement(i0); bounds[1] = this->m_InternalImage->GetLargestPossibleRegion().GetSize().GetElement(i1); imageGeometry3D->WorldToIndex( point3D, point3D ); // if (point3D[i0]<0) // point3D[i0] = 0.5; // else if (point3D[i0]>bounds[0]) // point3D[i0] = bounds[0]-0.5; // if (point3D[i1]<0) // point3D[i1] = 0.5; // else if (point3D[i1]>bounds[1]) // point3D[i1] = bounds[1]-0.5; if (point3D[i0]<0) point3D[i0] = 0.0; else if (point3D[i0]>bounds[0]) point3D[i0] = bounds[0]-0.001; if (point3D[i1]<0) point3D[i1] = 0.0; else if (point3D[i1]>bounds[1]) point3D[i1] = bounds[1]-0.001; points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); numberOfPoints++; } else { imageGeometry3D->WorldToIndex( point3D, point3D ); // Add point to polyline array points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); numberOfPoints++; } } polyline->SetPoints( points ); points->Delete(); vtkIdType *ptIds = new vtkIdType[numberOfPoints]; for ( vtkIdType i = 0; i < numberOfPoints; ++i ) { ptIds[i] = i; } polyline->InsertNextCell( VTK_POLY_LINE, numberOfPoints, ptIds ); // Extrude the generated contour polygon vtkLinearExtrusionFilter *extrudeFilter = vtkLinearExtrusionFilter::New(); extrudeFilter->SetInput( polyline ); extrudeFilter->SetScaleFactor( 1 ); extrudeFilter->SetExtrusionTypeToNormalExtrusion(); extrudeFilter->SetVector( 0.0, 0.0, 1.0 ); // Make a stencil from the extruded polygon vtkPolyDataToImageStencil *polyDataToImageStencil = vtkPolyDataToImageStencil::New(); polyDataToImageStencil->SetInput( extrudeFilter->GetOutput() ); // Export from ITK to VTK (to use a VTK filter) typedef itk::VTKImageImport< itkUCharImageType > ImageImportType; typedef itk::VTKImageExport< itkUCharImageType > ImageExportType; typename ImageExportType::Pointer itkExporter = ImageExportType::New(); itkExporter->SetInput( newMaskImage ); vtkImageImport *vtkImporter = vtkImageImport::New(); this->ConnectPipelines( itkExporter, vtkImporter ); vtkImporter->Update(); // Apply the generated image stencil to the input image vtkImageStencil *imageStencilFilter = vtkImageStencil::New(); imageStencilFilter->SetInputConnection( vtkImporter->GetOutputPort() ); imageStencilFilter->SetStencil( polyDataToImageStencil->GetOutput() ); imageStencilFilter->ReverseStencilOff(); imageStencilFilter->SetBackgroundValue( 0 ); imageStencilFilter->Update(); // Export from VTK back to ITK vtkImageExport *vtkExporter = vtkImageExport::New(); vtkExporter->SetInputConnection( imageStencilFilter->GetOutputPort() ); vtkExporter->Update(); typename ImageImportType::Pointer itkImporter = ImageImportType::New(); this->ConnectPipelines( vtkExporter, itkImporter ); itkImporter->Update(); // calculate cropping bounding box m_InternalImageMask3D = itkImporter->GetOutput(); m_InternalImageMask3D->SetDirection(image->GetDirection()); itk::ImageRegionConstIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itk::ImageRegionIterator itimage(image, image->GetLargestPossibleRegion()); itmask = itmask.Begin(); itimage = itimage.Begin(); typename ImageType::SizeType lowersize = {{9999999999,9999999999,9999999999}}; typename ImageType::SizeType uppersize = {{0,0,0}}; while( !itmask.IsAtEnd() ) { if(itmask.Get() == 0) { itimage.Set(0); } else { typename ImageType::IndexType index = itimage.GetIndex(); typename ImageType::SizeType signedindex; signedindex[0] = index[0]; signedindex[1] = index[1]; signedindex[2] = index[2]; lowersize[0] = signedindex[0] < lowersize[0] ? signedindex[0] : lowersize[0]; lowersize[1] = signedindex[1] < lowersize[1] ? signedindex[1] : lowersize[1]; lowersize[2] = signedindex[2] < lowersize[2] ? signedindex[2] : lowersize[2]; uppersize[0] = signedindex[0] > uppersize[0] ? signedindex[0] : uppersize[0]; uppersize[1] = signedindex[1] > uppersize[1] ? signedindex[1] : uppersize[1]; uppersize[2] = signedindex[2] > uppersize[2] ? signedindex[2] : uppersize[2]; } ++itmask; ++itimage; } typename ImageType::IndexType index; index[0] = lowersize[0]; index[1] = lowersize[1]; index[2] = lowersize[2]; typename ImageType::SizeType size; size[0] = uppersize[0] - lowersize[0] + 1; size[1] = uppersize[1] - lowersize[1] + 1; size[2] = uppersize[2] - lowersize[2] + 1; itk::ImageRegion<3> cropRegion = itk::ImageRegion<3>(index, size); // crop internal mask typedef itk::RegionOfInterestImageFilter< itkUCharImageType, itkUCharImageType > ROIMaskFilterType; typename ROIMaskFilterType::Pointer roi2 = ROIMaskFilterType::New(); roi2->SetRegionOfInterest(cropRegion); roi2->SetInput(m_InternalImageMask3D); roi2->Update(); m_InternalImageMask3D = roi2->GetOutput(); Image::Pointer tmpImage = Image::New(); tmpImage->InitializeByItk(m_InternalImageMask3D.GetPointer()); tmpImage->SetVolume(m_InternalImageMask3D->GetBufferPointer()); Image::Pointer tmpImage2 = Image::New(); tmpImage2->InitializeByItk(m_PlanarFigureImage.GetPointer()); const Geometry3D *pfImageGeometry3D = tmpImage2->GetGeometry( 0 ); const Geometry3D *intImageGeometry3D = tmpImage->GetGeometry( 0 ); typedef itk::ImageRegionIteratorWithIndex IteratorType; IteratorType imageIterator (m_InternalImageMask3D, m_InternalImageMask3D->GetRequestedRegion()); imageIterator.GoToBegin(); while ( !imageIterator.IsAtEnd() ) { unsigned char val = imageIterator.Value(); if (val>0) { itk::Index<3> index = imageIterator.GetIndex(); Point3D point; point[0] = index[0]; point[1] = index[1]; point[2] = index[2]; intImageGeometry3D->IndexToWorld(point, point); pfImageGeometry3D->WorldToIndex(point, point); point[i0] += 0.5; point[i1] += 0.5; index[0] = point[0]; index[1] = point[1]; index[2] = point[2]; if (pfImageGeometry3D->IsIndexInside(index)) m_PlanarFigureImage->SetPixel(index, 1); } ++imageIterator; } // Clean up VTK objects polyline->Delete(); extrudeFilter->Delete(); polyDataToImageStencil->Delete(); vtkImporter->Delete(); imageStencilFilter->Delete(); //vtkExporter->Delete(); // TODO: crashes when outcommented; memory leak?? delete[] ptIds; } void QmitkFiberProcessingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkFiberProcessingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkFiberProcessingView::UpdateGui() { // are fiber bundles selected? if ( m_SelectedFB.empty() ) { m_Controls->m_JoinBundles->setEnabled(false); m_Controls->m_SubstractBundles->setEnabled(false); m_Controls->m_ProcessFiberBundleButton->setEnabled(false); m_Controls->doExtractFibersButton->setEnabled(false); m_Controls->m_Extract3dButton->setEnabled(false); m_Controls->m_ResampleFibersButton->setEnabled(false); m_Controls->m_PlanarFigureButtonsFrame->setEnabled(false); m_Controls->m_FaColorFibersButton->setEnabled(false); } else { m_Controls->m_PlanarFigureButtonsFrame->setEnabled(true); m_Controls->m_ProcessFiberBundleButton->setEnabled(true); m_Controls->m_ResampleFibersButton->setEnabled(true); if (m_Surfaces.size()>0) m_Controls->m_Extract3dButton->setEnabled(true); // one bundle and one planar figure needed to extract fibers if (!m_SelectedPF.empty()) m_Controls->doExtractFibersButton->setEnabled(true); // more than two bundles needed to join/subtract if (m_SelectedFB.size() > 1) { m_Controls->m_JoinBundles->setEnabled(true); m_Controls->m_SubstractBundles->setEnabled(true); } else { m_Controls->m_JoinBundles->setEnabled(false); m_Controls->m_SubstractBundles->setEnabled(false); } if (m_SelectedImage.IsNotNull()) m_Controls->m_FaColorFibersButton->setEnabled(true); } // are planar figures selected? if ( m_SelectedPF.empty() ) { m_Controls->doExtractFibersButton->setEnabled(false); m_Controls->PFCompoANDButton->setEnabled(false); m_Controls->PFCompoORButton->setEnabled(false); m_Controls->PFCompoNOTButton->setEnabled(false); m_Controls->m_GenerateRoiImage->setEnabled(false); } else { if ( !m_SelectedFB.empty() ) m_Controls->m_GenerateRoiImage->setEnabled(true); else m_Controls->m_GenerateRoiImage->setEnabled(false); if (m_SelectedPF.size() > 1) { m_Controls->PFCompoANDButton->setEnabled(true); m_Controls->PFCompoORButton->setEnabled(true); m_Controls->PFCompoNOTButton->setEnabled(false); } else { m_Controls->PFCompoANDButton->setEnabled(false); m_Controls->PFCompoORButton->setEnabled(false); m_Controls->PFCompoNOTButton->setEnabled(true); } } } void QmitkFiberProcessingView::OnSelectionChanged( std::vector nodes ) { if ( !this->IsVisible() ) return; //reset existing Vectors containing FiberBundles and PlanarFigures from a previous selection m_SelectedFB.clear(); m_SelectedPF.clear(); m_Surfaces.clear(); m_SelectedImage = NULL; for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if ( dynamic_cast(node->GetData()) ) m_SelectedFB.push_back(node); else if (dynamic_cast(node->GetData())) m_SelectedPF.push_back(node); else if (dynamic_cast(node->GetData())) m_SelectedImage = dynamic_cast(node->GetData()); else if (dynamic_cast(node->GetData())) m_Surfaces.push_back(dynamic_cast(node->GetData())); } UpdateGui(); GenerateStats(); } void QmitkFiberProcessingView::OnDrawPolygon() { // bool checked = m_Controls->m_PolygonButton->isChecked(); // if(!this->AssertDrawingIsPossible(checked)) // return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); this->AddFigureToDataStorage(figure, QString("Polygon%1").arg(++m_PolygonCounter)); MITK_INFO << "PlanarPolygon created ..."; mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } } void QmitkFiberProcessingView::OnDrawCircle() { //bool checked = m_Controls->m_CircleButton->isChecked(); //if(!this->AssertDrawingIsPossible(checked)) // return; mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); this->AddFigureToDataStorage(figure, QString("Circle%1").arg(++m_EllipseCounter)); this->GetDataStorage()->Modified(); MITK_INFO << "PlanarCircle created ..."; //call mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } } void QmitkFiberProcessingView::Activated() { MITK_INFO << "FB OPerations ACTIVATED()"; /* mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figure = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } */ } void QmitkFiberProcessingView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey, mitk::BaseProperty *property ) { // initialize figure's geometry with empty geometry mitk::PlaneGeometry::Pointer emptygeometry = mitk::PlaneGeometry::New(); figure->SetGeometry2D( emptygeometry ); //set desired data to DataNode where Planarfigure is stored mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,0.0,0.0)); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true)); newNode->AddProperty( "selected", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawoutline", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(false) ); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(3.0) ); newNode->AddProperty( "planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.outline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.helperline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(0.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.marker.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.marker.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.line.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.outline.opacity", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.helperline.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.marker.opacity",mitk::FloatProperty::New(2.0)); // figure drawn on the topmost layer / image newNode->SetColor(1.0,1.0,1.0); newNode->SetOpacity(0.8); GetDataStorage()->Add(newNode ); std::vector selectedNodes = GetDataManagerSelection(); for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } newNode->SetSelected(true); } void QmitkFiberProcessingView::DoFiberExtraction() { if ( m_SelectedFB.empty() ){ QMessageBox::information( NULL, "Warning", "No fibe bundle selected!"); MITK_WARN("QmitkFiberProcessingView") << "no fibe bundle selected"; return; } for (int i=0; i(m_SelectedFB.at(i)->GetData()); mitk::PlanarFigure::Pointer roi = dynamic_cast (m_SelectedPF.at(0)->GetData()); mitk::FiberBundleX::Pointer extFB = fib->ExtractFiberSubset(roi); if (extFB->GetNumFibers()<=0) continue; mitk::DataNode::Pointer node; node = mitk::DataNode::New(); node->SetData(extFB); QString name(m_SelectedFB.at(i)->GetName().c_str()); name += "_"; name += m_SelectedPF.at(0)->GetName().c_str(); node->SetName(name.toStdString()); GetDataStorage()->Add(node); m_SelectedFB.at(i)->SetVisibility(false); } } void QmitkFiberProcessingView::GenerateAndComposite() { mitk::PlanarFigureComposite::Pointer PFCAnd = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCAnd->SetGeometry2D(currentGeometry2D); PFCAnd->setOperationType(mitk::PFCOMPOSITION_AND_OPERATION); for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCAnd->addPlanarFigure( tmpPF ); PFCAnd->addDataNode( nodePF ); PFCAnd->setDisplayName("AND_COMPO"); } AddCompositeToDatastorage(PFCAnd, NULL); } void QmitkFiberProcessingView::GenerateOrComposite() { mitk::PlanarFigureComposite::Pointer PFCOr = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCOr->SetGeometry2D(currentGeometry2D); PFCOr->setOperationType(mitk::PFCOMPOSITION_OR_OPERATION); for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCOr->addPlanarFigure( tmpPF ); PFCOr->addDataNode( nodePF ); PFCOr->setDisplayName("OR_COMPO"); } AddCompositeToDatastorage(PFCOr, NULL); } void QmitkFiberProcessingView::GenerateNotComposite() { mitk::PlanarFigureComposite::Pointer PFCNot = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCNot->SetGeometry2D(currentGeometry2D); PFCNot->setOperationType(mitk::PFCOMPOSITION_NOT_OPERATION); for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCNot->addPlanarFigure( tmpPF ); PFCNot->addDataNode( nodePF ); PFCNot->setDisplayName("NOT_COMPO"); } AddCompositeToDatastorage(PFCNot, NULL); } /* CLEANUP NEEDED */ void QmitkFiberProcessingView::AddCompositeToDatastorage(mitk::PlanarFigureComposite::Pointer pfcomp, mitk::DataNode::Pointer parentDataNode ) { mitk::DataNode::Pointer newPFCNode; newPFCNode = mitk::DataNode::New(); newPFCNode->SetName( pfcomp->getDisplayName() ); newPFCNode->SetData(pfcomp); newPFCNode->SetVisibility(true); switch (pfcomp->getOperationType()) { case 0: { if (!parentDataNode.IsNull()) { GetDataStorage()->Add(newPFCNode, parentDataNode); } else { GetDataStorage()->Add(newPFCNode); } //iterate through its childs for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // make new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; } else { MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } MITK_INFO << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } case 1: { if (!parentDataNode.IsNull()) { MITK_INFO << "adding " << newPFCNode->GetName() << " to " << parentDataNode->GetName() ; GetDataStorage()->Add(newPFCNode, parentDataNode); } else { MITK_INFO << "adding " << newPFCNode->GetName(); GetDataStorage()->Add(newPFCNode); } for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // make new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } MITK_INFO << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } case 2: { if (!parentDataNode.IsNull()) { MITK_INFO << "adding " << newPFCNode->GetName() << " to " << parentDataNode->GetName() ; GetDataStorage()->Add(newPFCNode, parentDataNode); } else { MITK_INFO << "adding " << newPFCNode->GetName(); GetDataStorage()->Add(newPFCNode); } //iterate through its childs for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // makeRemoveBundle new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } MITK_INFO << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } default: MITK_INFO << "we have an UNDEFINED composition... ERROR" ; break; } } void QmitkFiberProcessingView::JoinBundles() { if ( m_SelectedFB.size()<2 ){ QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); MITK_WARN("QmitkFiberProcessingView") << "Select at least two fiber bundles!"; return; } std::vector::const_iterator it = m_SelectedFB.begin(); mitk::FiberBundleX::Pointer newBundle = dynamic_cast((*it)->GetData()); QString name(""); name += QString((*it)->GetName().c_str()); ++it; for (it; it!=m_SelectedFB.end(); ++it) { newBundle = newBundle->AddBundle(dynamic_cast((*it)->GetData())); name += "+"+QString((*it)->GetName().c_str()); } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } void QmitkFiberProcessingView::SubstractBundles() { if ( m_SelectedFB.size()<2 ){ QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); MITK_WARN("QmitkFiberProcessingView") << "Select at least two fiber bundles!"; return; } std::vector::const_iterator it = m_SelectedFB.begin(); mitk::FiberBundleX::Pointer newBundle = dynamic_cast((*it)->GetData()); QString name(""); name += QString((*it)->GetName().c_str()); ++it; for (it; it!=m_SelectedFB.end(); ++it) { newBundle = newBundle->SubtractBundle(dynamic_cast((*it)->GetData())); if (newBundle.IsNull()) break; name += "-"+QString((*it)->GetName().c_str()); } if (newBundle.IsNull()) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers. Did you select the fiber bundles in the correct order? X-Y is not equal to Y-X!"); return; } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } void QmitkFiberProcessingView::GenerateStats() { if ( m_SelectedFB.empty() ) return; QString stats(""); for( int i=0; i(node->GetData())) { if (i>0) stats += "\n-----------------------------\n"; stats += QString(node->GetName().c_str()) + "\n"; mitk::FiberBundleX::Pointer fib = dynamic_cast(node->GetData()); vtkSmartPointer fiberPolyData = fib->GetFiberPolyData(); vtkSmartPointer vLines = fiberPolyData->GetLines(); vLines->InitTraversal(); int numberOfLines = vLines->GetNumberOfCells(); stats += "Number of fibers: "+ QString::number(numberOfLines) + "\n"; float length = 0; std::vector lengths; for (int i=0; iGetNextCell ( numPoints, points ); float l=0; for (unsigned int j=0; j p1; itk::Point p2; fiberPolyData->GetPoint(points[j], p1.GetDataPointer()); fiberPolyData->GetPoint(points[j+1], p2.GetDataPointer()); float dist = p1.EuclideanDistanceTo(p2); length += dist; l += dist; } itk::Point p2; fiberPolyData->GetPoint(points[numPoints-1], p2.GetDataPointer()); lengths.push_back(l); } std::sort(lengths.begin(), lengths.end()); if (numberOfLines>0) length /= numberOfLines; float dev=0; int count = 0; vLines->InitTraversal(); for (int i=0; iGetNextCell ( numPoints, points ); float l=0; for (unsigned int j=0; j p1; itk::Point p2; fiberPolyData->GetPoint(points[j], p1.GetDataPointer()); fiberPolyData->GetPoint(points[j+1], p2.GetDataPointer()); float dist = p1.EuclideanDistanceTo(p2); l += dist; } dev += (length-l)*(length-l); count++; } if (numberOfLines>1) dev /= (numberOfLines-1); else dev = 0; stats += "Min. length: "+ QString::number(lengths.front(),'f',1) + " mm\n"; stats += "Max. length: "+ QString::number(lengths.back(),'f',1) + " mm\n"; stats += "Mean length: "+ QString::number(length,'f',1) + " mm\n"; stats += "Median length: "+ QString::number(lengths.at(lengths.size()/2),'f',1) + " mm\n"; stats += "Standard deviation: "+ QString::number(sqrt(dev),'f',1) + " mm\n"; } } this->m_Controls->m_StatsTextEdit->setText(stats); } void QmitkFiberProcessingView::ProcessSelectedBundles() { if ( m_SelectedFB.empty() ){ QMessageBox::information( NULL, "Warning", "No fibe bundle selected!"); MITK_WARN("QmitkFiberProcessingView") << "no fibe bundle selected"; return; } int generationMethod = m_Controls->m_GenerationBox->currentIndex(); for( int i=0; i(node->GetData())) { mitk::FiberBundleX::Pointer fib = dynamic_cast(node->GetData()); QString name(node->GetName().c_str()); DataNode::Pointer newNode = NULL; switch(generationMethod){ case 0: newNode = GenerateTractDensityImage(fib, false); name += "_TDI"; break; case 1: newNode = GenerateTractDensityImage(fib, true); name += "_envelope"; break; case 2: newNode = GenerateColorHeatmap(fib); break; case 3: newNode = GenerateFiberEndingsImage(fib); name += "_fiber_endings"; break; case 4: newNode = GenerateFiberEndingsPointSet(fib); name += "_fiber_endings"; break; } if (newNode.IsNotNull()) { newNode->SetName(name.toStdString()); GetDataStorage()->Add(newNode); } } } } // generate pointset displaying the fiber endings mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateFiberEndingsPointSet(mitk::FiberBundleX::Pointer fib) { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); vtkSmartPointer fiberPolyData = fib->GetFiberPolyData(); vtkSmartPointer vLines = fiberPolyData->GetLines(); vLines->InitTraversal(); int count = 0; int numFibers = fib->GetNumFibers(); for( int i=0; iGetNextCell ( numPoints, points ); if (numPoints>0) { double* point = fiberPolyData->GetPoint(points[0]); itk::Point itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; pointSet->InsertPoint(count, itkPoint); count++; } if (numPoints>2) { double* point = fiberPolyData->GetPoint(points[numPoints-1]); itk::Point itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; pointSet->InsertPoint(count, itkPoint); count++; } } mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( pointSet ); return node; } // generate image displaying the fiber endings mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateFiberEndingsImage(mitk::FiberBundleX::Pointer fib) { typedef unsigned char OutPixType; typedef itk::Image OutImageType; typedef itk::TractsToFiberEndingsImageFilter< OutImageType > ImageGeneratorType; ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); generator->SetFiberBundle(fib); generator->SetInvertImage(m_Controls->m_InvertCheckbox->isChecked()); generator->SetUpsamplingFactor(m_Controls->m_UpsamplingSpinBox->value()); if (m_SelectedImage.IsNotNull()) { OutImageType::Pointer itkImage = OutImageType::New(); CastToItkImage(m_SelectedImage, itkImage); generator->SetInputImage(itkImage); generator->SetUseImageGeometry(true); } generator->Update(); // get output image OutImageType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); return node; } // generate rgba heatmap from fiber bundle mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateColorHeatmap(mitk::FiberBundleX::Pointer fib) { typedef itk::RGBAPixel OutPixType; typedef itk::Image OutImageType; typedef itk::TractsToRgbaImageFilter< OutImageType > ImageGeneratorType; ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); generator->SetFiberBundle(fib); generator->SetUpsamplingFactor(m_Controls->m_UpsamplingSpinBox->value()); if (m_SelectedImage.IsNotNull()) { itk::Image::Pointer itkImage = itk::Image::New(); CastToItkImage(m_SelectedImage, itkImage); generator->SetInputImage(itkImage); generator->SetUseImageGeometry(true); } generator->Update(); // get output image typedef itk::Image OutType; OutType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); return node; } // generate tract density image from fiber bundle mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateTractDensityImage(mitk::FiberBundleX::Pointer fib, bool binary) { typedef float OutPixType; typedef itk::Image OutImageType; itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); generator->SetFiberBundle(fib); generator->SetBinaryOutput(binary); generator->SetInvertImage(m_Controls->m_InvertCheckbox->isChecked()); generator->SetUpsamplingFactor(m_Controls->m_UpsamplingSpinBox->value()); if (m_SelectedImage.IsNotNull()) { OutImageType::Pointer itkImage = OutImageType::New(); CastToItkImage(m_SelectedImage, itkImage); generator->SetInputImage(itkImage); generator->SetUseImageGeometry(true); } generator->Update(); // get output image typedef itk::Image OutType; OutType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); return node; } void QmitkFiberProcessingView::ResampleSelectedBundles() { int factor = this->m_Controls->m_ResampleFibersSpinBox->value(); for (int i=0; i(m_SelectedFB.at(i)->GetData()); fib->DoFiberSmoothing(factor); } } void QmitkFiberProcessingView::DoFaColorCoding() { if (m_SelectedImage.IsNull()) return; // mitk::PixelType pType = mitk::MakeScalarPixelType(); // if (m_SelectedImage->GetPixelType()!=pType) // { // //mitk::Image bla; bla.GetPixelType().GetNameOfClass() // MITK_INFO << m_SelectedImage->GetPixelType().GetNameOfClass(); // QMessageBox::warning(NULL, "Wrong Image Type", "FA/GFA image should be of type float"); //// return; // } for( int i=0; i(m_SelectedFB.at(i)->GetData()); fib->SetFAMap(m_SelectedImage); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_FA_BASED); fib->DoColorCodingFaBased(); } if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h index 0216663e73..c1f606e896 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h @@ -1,198 +1,197 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkFiberProcessingView_h #define QmitkFiberProcessingView_h #include #include "ui_QmitkFiberProcessingViewControls.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /*! \brief QmitkFiberProcessingView \warning View to process fiber bundles. Supplies methods to extract fibers from the bundle, join and subtract bundles, generate images from the selected bundle and much more. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkFiberProcessingView : public QmitkFunctionality { // 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: typedef itk::Image< unsigned char, 3 > itkUCharImageType; typedef itk::Image< float, 3 > itkFloatImageType; static const std::string VIEW_ID; QmitkFiberProcessingView(); virtual ~QmitkFiberProcessingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void Activated(); protected slots: void OnDrawCircle(); void OnDrawPolygon(); void DoFiberExtraction(); void GenerateAndComposite(); void GenerateOrComposite(); void GenerateNotComposite(); void JoinBundles(); void SubstractBundles(); void GenerateRoiImage(); void ProcessSelectedBundles(); void ResampleSelectedBundles(); void DoFaColorCoding(); void Extract3d(); virtual void AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey = NULL, mitk::BaseProperty *property = NULL ); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkFiberProcessingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; /** Connection from VTK to ITK */ template void ConnectPipelines(VTK_Exporter* exporter, ITK_Importer importer) { importer->SetUpdateInformationCallback(exporter->GetUpdateInformationCallback()); importer->SetPipelineModifiedCallback(exporter->GetPipelineModifiedCallback()); importer->SetWholeExtentCallback(exporter->GetWholeExtentCallback()); importer->SetSpacingCallback(exporter->GetSpacingCallback()); importer->SetOriginCallback(exporter->GetOriginCallback()); importer->SetScalarTypeCallback(exporter->GetScalarTypeCallback()); importer->SetNumberOfComponentsCallback(exporter->GetNumberOfComponentsCallback()); importer->SetPropagateUpdateExtentCallback(exporter->GetPropagateUpdateExtentCallback()); importer->SetUpdateDataCallback(exporter->GetUpdateDataCallback()); importer->SetDataExtentCallback(exporter->GetDataExtentCallback()); importer->SetBufferPointerCallback(exporter->GetBufferPointerCallback()); importer->SetCallbackUserData(exporter->GetCallbackUserData()); } template void ConnectPipelines(ITK_Exporter exporter, VTK_Importer* importer) { importer->SetUpdateInformationCallback(exporter->GetUpdateInformationCallback()); importer->SetPipelineModifiedCallback(exporter->GetPipelineModifiedCallback()); importer->SetWholeExtentCallback(exporter->GetWholeExtentCallback()); importer->SetSpacingCallback(exporter->GetSpacingCallback()); importer->SetOriginCallback(exporter->GetOriginCallback()); importer->SetScalarTypeCallback(exporter->GetScalarTypeCallback()); importer->SetNumberOfComponentsCallback(exporter->GetNumberOfComponentsCallback()); importer->SetPropagateUpdateExtentCallback(exporter->GetPropagateUpdateExtentCallback()); importer->SetUpdateDataCallback(exporter->GetUpdateDataCallback()); importer->SetDataExtentCallback(exporter->GetDataExtentCallback()); importer->SetBufferPointerCallback(exporter->GetBufferPointerCallback()); importer->SetCallbackUserData(exporter->GetCallbackUserData()); } template < typename TPixel, unsigned int VImageDimension > void InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis, std::string nodeName ); template < typename TPixel, unsigned int VImageDimension > void InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::Geometry3D* planegeo3D, int additionalIndex ); void GenerateStats(); void UpdateGui(); berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; private: int m_EllipseCounter; int m_PolygonCounter; //contains the selected FiberBundles std::vector m_SelectedFB; //contains the selected PlanarFigures std::vector m_SelectedPF; mitk::Image::Pointer m_SelectedImage; mitk::Image::Pointer m_InternalImage; mitk::PlanarFigure::Pointer m_PlanarFigure; float m_UpsamplingFactor; itkUCharImageType::Pointer m_InternalImageMask3D; itkUCharImageType::Pointer m_PlanarFigureImage; std::vector m_Surfaces; void AddCompositeToDatastorage(mitk::PlanarFigureComposite::Pointer, mitk::DataNode::Pointer); void debugPFComposition(mitk::PlanarFigureComposite::Pointer , int ); void CompositeExtraction(mitk::DataNode::Pointer node, mitk::Image* image); mitk::DataNode::Pointer GenerateTractDensityImage(mitk::FiberBundleX::Pointer fib, bool binary); mitk::DataNode::Pointer GenerateColorHeatmap(mitk::FiberBundleX::Pointer fib); mitk::DataNode::Pointer GenerateFiberEndingsImage(mitk::FiberBundleX::Pointer fib); mitk::DataNode::Pointer GenerateFiberEndingsPointSet(mitk::FiberBundleX::Pointer fib); }; #endif // _QMITKFIBERTRACKINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp index 269b2de3aa..b1b5eb8239 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp @@ -1,765 +1,770 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkGibbsTrackingView.h" #include // Qt #include #include #include // MITK #include #include #include #include #include // ITK #include #include #include // MISC #include QmitkTrackingWorker::QmitkTrackingWorker(QmitkGibbsTrackingView* view) : m_View(view) { } void QmitkTrackingWorker::run() { m_View->m_GlobalTracker = QmitkGibbsTrackingView::GibbsTrackingFilterType::New(); MITK_INFO << "Resampling mask images"; // setup resampler typedef itk::ResampleImageFilter ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); resampler->SetOutputSpacing( m_View->m_ItkQBallImage->GetSpacing() ); resampler->SetOutputOrigin( m_View->m_ItkQBallImage->GetOrigin() ); resampler->SetOutputDirection( m_View->m_ItkQBallImage->GetDirection() ); resampler->SetSize( m_View->m_ItkQBallImage->GetLargestPossibleRegion().GetSize() ); // resample mask image resampler->SetInput( m_View->m_MaskImage ); resampler->SetDefaultPixelValue(0); resampler->Update(); m_View->m_MaskImage = resampler->GetOutput(); m_View->m_GlobalTracker->SetInput0(m_View->m_ItkQBallImage.GetPointer()); m_View->m_GlobalTracker->SetMaskImage(m_View->m_MaskImage); m_View->m_GlobalTracker->SetTempStart((float)m_View->m_Controls->m_StartTempSlider->value()/100); m_View->m_GlobalTracker->SetTempEnd((float)m_View->m_Controls->m_EndTempSlider->value()/10000); m_View->m_GlobalTracker->SetNumIt(m_View->m_Iterations); m_View->m_GlobalTracker->SetParticleWeight((float)m_View->m_Controls->m_ParticleWeightSlider->value()/10000); m_View->m_GlobalTracker->SetSubtractMean(m_View->m_Controls->m_MeanSubtractionCheckbox->isChecked()); m_View->m_GlobalTracker->SetParticleWidth((float)(m_View->m_Controls->m_ParticleWidthSlider->value())/10); m_View->m_GlobalTracker->SetParticleLength((float)(m_View->m_Controls->m_ParticleLengthSlider->value())/10); m_View->m_GlobalTracker->SetInexBalance((float)m_View->m_Controls->m_InExBalanceSlider->value()/10); m_View->m_GlobalTracker->SetFiberLength(m_View->m_Controls->m_FiberLengthSlider->value()); m_View->m_GlobalTracker->SetCurvatureHardThreshold(cos((float)m_View->m_Controls->m_CurvatureThresholdSlider->value()*3.14159265/180)); m_View->m_GlobalTracker->Update(); m_View->m_TrackingThread.quit(); } const std::string QmitkGibbsTrackingView::VIEW_ID = "org.mitk.views.gibbstracking"; QmitkGibbsTrackingView::QmitkGibbsTrackingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_ThreadIsRunning(false) , m_GlobalTracker(NULL) , m_QBallImage(NULL) , m_MaskImage(NULL) , m_QBallImageNode(NULL) , m_ItkQBallImage(NULL) , m_FiberBundleNode(NULL) , m_MaskImageNode(NULL) , m_TrackingWorker(this) , m_Iterations(10000000) , m_LastStep(0) { m_TrackingWorker.moveToThread(&m_TrackingThread); connect(&m_TrackingThread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_TrackingThread, SIGNAL(started()), &m_TrackingWorker, SLOT(run())); connect(&m_TrackingThread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_TrackingThread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_TrackingTimer = new QTimer(this); } QmitkGibbsTrackingView::~QmitkGibbsTrackingView() { delete m_TrackingTimer; } // update tracking status and generate fiber bundle void QmitkGibbsTrackingView::TimerUpdate() { int currentStep = m_GlobalTracker->GetCurrentStep(); mitk::ProgressBar::GetInstance()->Progress(currentStep-m_LastStep); UpdateTrackingStatus(); GenerateFiberBundle(false); m_LastStep = currentStep; } // tell global tractography filter to stop after current step void QmitkGibbsTrackingView::StopGibbsTracking() { if (m_GlobalTracker.IsNull()) return; //mitk::ProgressBar::GetInstance()->Progress(m_GlobalTracker->GetSteps()-m_LastStep+1); m_GlobalTracker->SetAbortTracking(true); m_Controls->m_TrackingStop->setEnabled(false); m_Controls->m_TrackingStop->setText("Stopping Tractography ..."); } // update gui elements and generate fiber bundle after tracking is finished void QmitkGibbsTrackingView::AfterThread() { m_ThreadIsRunning = false; m_TrackingTimer->stop(); mitk::ProgressBar::GetInstance()->Progress(m_GlobalTracker->GetSteps()-m_LastStep+1); UpdateGUI(); UpdateTrackingStatus(); if(m_Controls->m_ParticleWeightSlider->value()==0) { m_Controls->m_ParticleWeightLabel->setText(QString::number(m_GlobalTracker->GetParticleWeight())); m_Controls->m_ParticleWeightSlider->setValue(m_GlobalTracker->GetParticleWeight()*10000); } if(m_Controls->m_ParticleWidthSlider->value()==0) { m_Controls->m_ParticleWidthLabel->setText(QString::number(m_GlobalTracker->GetParticleWidth())); m_Controls->m_ParticleWidthSlider->setValue(m_GlobalTracker->GetParticleWidth()*10); } if(m_Controls->m_ParticleLengthSlider->value()==0) { m_Controls->m_ParticleLengthLabel->setText(QString::number(m_GlobalTracker->GetParticleLength())); m_Controls->m_ParticleLengthSlider->setValue(m_GlobalTracker->GetParticleLength()*10); } GenerateFiberBundle(true); m_FiberBundleNode = NULL; } // start tracking timer and update gui elements before tracking is started void QmitkGibbsTrackingView::BeforeThread() { m_ThreadIsRunning = true; m_TrackingTime = QTime::currentTime(); m_ElapsedTime = 0; m_TrackingTimer->start(1000); m_LastStep = 0; UpdateGUI(); } // setup gui elements and signal/slot connections void QmitkGibbsTrackingView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkGibbsTrackingViewControls; m_Controls->setupUi( parent ); AdvancedSettings(); connect( m_TrackingTimer, SIGNAL(timeout()), this, SLOT(TimerUpdate()) ); connect( m_Controls->m_TrackingStop, SIGNAL(clicked()), this, SLOT(StopGibbsTracking()) ); connect( m_Controls->m_TrackingStart, SIGNAL(clicked()), this, SLOT(StartGibbsTracking()) ); connect( m_Controls->m_AdvancedSettingsCheckbox, SIGNAL(clicked()), this, SLOT(AdvancedSettings()) ); connect( m_Controls->m_SaveTrackingParameters, SIGNAL(clicked()), this, SLOT(SaveTrackingParameters()) ); connect( m_Controls->m_LoadTrackingParameters, SIGNAL(clicked()), this, SLOT(LoadTrackingParameters()) ); connect( m_Controls->m_IterationsSlider, SIGNAL(valueChanged(int)), this, SLOT(SetIterations(int)) ); connect( m_Controls->m_ParticleWidthSlider, SIGNAL(valueChanged(int)), this, SLOT(SetParticleWidth(int)) ); connect( m_Controls->m_ParticleLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(SetParticleLength(int)) ); connect( m_Controls->m_InExBalanceSlider, SIGNAL(valueChanged(int)), this, SLOT(SetInExBalance(int)) ); connect( m_Controls->m_FiberLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(SetFiberLength(int)) ); connect( m_Controls->m_ParticleWeightSlider, SIGNAL(valueChanged(int)), this, SLOT(SetParticleWeight(int)) ); connect( m_Controls->m_StartTempSlider, SIGNAL(valueChanged(int)), this, SLOT(SetStartTemp(int)) ); connect( m_Controls->m_EndTempSlider, SIGNAL(valueChanged(int)), this, SLOT(SetEndTemp(int)) ); connect( m_Controls->m_CurvatureThresholdSlider, SIGNAL(valueChanged(int)), this, SLOT(SetCurvatureThreshold(int)) ); connect( m_Controls->m_OutputFileButton, SIGNAL(clicked()), this, SLOT(SetOutputFile()) ); } } void QmitkGibbsTrackingView::SetInExBalance(int value) { m_Controls->m_InExBalanceLabel->setText(QString::number((float)value/10)); } void QmitkGibbsTrackingView::SetFiberLength(int value) { m_Controls->m_FiberLengthLabel->setText(QString::number(value)+"mm"); } void QmitkGibbsTrackingView::SetParticleWeight(int value) { if (value>0) m_Controls->m_ParticleWeightLabel->setText(QString::number((float)value/10000)); else m_Controls->m_ParticleWeightLabel->setText("auto"); } void QmitkGibbsTrackingView::SetStartTemp(int value) { m_Controls->m_StartTempLabel->setText(QString::number((float)value/100)); } void QmitkGibbsTrackingView::SetEndTemp(int value) { m_Controls->m_EndTempLabel->setText(QString::number((float)value/10000)); } void QmitkGibbsTrackingView::SetParticleWidth(int value) { if (value>0) m_Controls->m_ParticleWidthLabel->setText(QString::number((float)value/10)+" mm"); else m_Controls->m_ParticleWidthLabel->setText("auto"); } void QmitkGibbsTrackingView::SetParticleLength(int value) { if (value>0) m_Controls->m_ParticleLengthLabel->setText(QString::number((float)value/10)+" mm"); else m_Controls->m_ParticleLengthLabel->setText("auto"); } void QmitkGibbsTrackingView::SetCurvatureThreshold(int value) { m_Controls->m_CurvatureThresholdLabel->setText(QString::number(value)+"°"); } void QmitkGibbsTrackingView::SetIterations(int value) { switch(value) { case 0: m_Controls->m_IterationsLabel->setText("Iterations: 1x10^4"); m_Iterations = 10000; break; case 1: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^4"); m_Iterations = 50000; break; case 2: m_Controls->m_IterationsLabel->setText("Iterations: 1x10^5"); m_Iterations = 100000; break; case 3: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^5"); m_Iterations = 500000; break; case 4: m_Controls->m_IterationsLabel->setText("Iterations: 1x10^6"); m_Iterations = 1000000; break; case 5: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^6"); m_Iterations = 5000000; break; case 6: m_Controls->m_IterationsLabel->setText("Iterations: 1x10^7"); m_Iterations = 10000000; break; case 7: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^7"); m_Iterations = 50000000; break; case 8: m_Controls->m_IterationsLabel->setText("Iterations: 1x10^8"); m_Iterations = 100000000; break; case 9: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^8"); m_Iterations = 500000000; break; case 10: m_Controls->m_IterationsLabel->setText("Iterations: 1x10^9"); m_Iterations = 1000000000; break; } } void QmitkGibbsTrackingView::StdMultiWidgetAvailable(QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkGibbsTrackingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } // called if datamanager selection changes void QmitkGibbsTrackingView::OnSelectionChanged( std::vector nodes ) { if (m_ThreadIsRunning) return; m_QBallImageNode = NULL; m_MaskImageNode = NULL; // iterate all selected objects for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) m_QBallImageNode = node; else if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { bool isBinary = false; node->GetPropertyValue("binary", isBinary); if (isBinary) m_MaskImageNode = node; } } UpdateGUI(); } // update gui elements displaying trackings status void QmitkGibbsTrackingView::UpdateTrackingStatus() { if (m_GlobalTracker.IsNull()) return; m_ElapsedTime += m_TrackingTime.elapsed()/1000; m_TrackingTime.restart(); unsigned long hours = m_ElapsedTime/3600; unsigned long minutes = (m_ElapsedTime%3600)/60; unsigned long seconds = m_ElapsedTime%60; m_Controls->m_ProposalAcceptance->setText(QString::number(m_GlobalTracker->GetProposalAcceptance()*100)+"%"); m_Controls->m_TrackingTimeLabel->setText( QString::number(hours)+QString("h ")+QString::number(minutes)+QString("m ")+QString::number(seconds)+QString("s") ); m_Controls->m_NumConnectionsLabel->setText( QString::number(m_GlobalTracker->GetNumConnections()) ); m_Controls->m_NumParticlesLabel->setText( QString::number(m_GlobalTracker->GetNumParticles()) ); m_Controls->m_CurrentStepLabel->setText( QString::number(100*(float)m_GlobalTracker->GetCurrentStep()/m_GlobalTracker->GetSteps())+"%" ); m_Controls->m_AcceptedFibersLabel->setText( QString::number(m_GlobalTracker->GetNumAcceptedFibers()) ); } // update gui elements (enable/disable elements and set tooltips) void QmitkGibbsTrackingView::UpdateGUI() { if (m_QBallImageNode.IsNotNull()) m_Controls->m_QballImageLabel->setText(m_QBallImageNode->GetName().c_str()); else m_Controls->m_QballImageLabel->setText("-"); if (m_MaskImageNode.IsNotNull()) m_Controls->m_MaskImageLabel->setText(m_MaskImageNode->GetName().c_str()); else m_Controls->m_MaskImageLabel->setText("-"); if (!m_ThreadIsRunning && m_QBallImageNode.IsNotNull()) { m_Controls->m_TrackingStop->setEnabled(false); m_Controls->m_TrackingStart->setEnabled(true); m_Controls->m_LoadTrackingParameters->setEnabled(true); m_Controls->m_IterationsSlider->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_TrackingStop->setText("Stop Tractography"); m_Controls->m_TrackingStart->setToolTip("Start tractography. No further change of parameters possible."); m_Controls->m_TrackingStop->setToolTip(""); } else if (!m_ThreadIsRunning) { m_Controls->m_TrackingStop->setEnabled(false); m_Controls->m_TrackingStart->setEnabled(false); m_Controls->m_LoadTrackingParameters->setEnabled(true); m_Controls->m_IterationsSlider->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_TrackingStop->setText("Stop Tractography"); m_Controls->m_TrackingStart->setToolTip("No Q-Ball image selected."); m_Controls->m_TrackingStop->setToolTip(""); } else { m_Controls->m_TrackingStop->setEnabled(true); m_Controls->m_TrackingStart->setEnabled(false); m_Controls->m_LoadTrackingParameters->setEnabled(false); m_Controls->m_IterationsSlider->setEnabled(false); m_Controls->m_AdvancedFrame->setEnabled(false); m_Controls->m_AdvancedFrame->setVisible(false); m_Controls->m_AdvancedSettingsCheckbox->setChecked(false); m_Controls->m_TrackingStart->setToolTip("Tracking in progress."); m_Controls->m_TrackingStop->setToolTip("Stop tracking and display results."); } } // show/hide advanced settings frame void QmitkGibbsTrackingView::AdvancedSettings() { m_Controls->m_AdvancedFrame->setVisible(m_Controls->m_AdvancedSettingsCheckbox->isChecked()); } // set mask image data node void QmitkGibbsTrackingView::SetMask() { std::vector nodes = GetDataManagerSelection(); if (nodes.empty()) { m_MaskImageNode = NULL; m_Controls->m_MaskImageLabel->setText("-"); return; } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNotNull() && dynamic_cast(node->GetData())) { m_MaskImageNode = node; m_Controls->m_MaskImageLabel->setText(node->GetName().c_str()); return; } } } // cast image to float template void QmitkGibbsTrackingView::CastToFloat(InputImageType* image, mitk::Image::Pointer outImage) { typedef itk::CastImageFilter ItkCastFilter; typename ItkCastFilter::Pointer itkCaster = ItkCastFilter::New(); itkCaster->SetInput(image); itkCaster->Update(); outImage->InitializeByItk(itkCaster->GetOutput()); outImage->SetVolume(itkCaster->GetOutput()->GetBufferPointer()); } // check for mask and qbi and start tracking thread void QmitkGibbsTrackingView::StartGibbsTracking() { if(m_ThreadIsRunning) { MITK_WARN("QmitkGibbsTrackingView")<<"Thread already running!"; return; } if (m_QBallImageNode.IsNull()) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, "Warning", "Please load and select a qball image before starting image processing."); return; } // a node itself is not very useful, we need its data item (the image) mitk::BaseData* data = m_QBallImageNode->GetData(); if (!data) return; // test if this data item is an image or not (could also be a surface or something totally different) m_QBallImage = dynamic_cast( data ); if (m_QBallImage.IsNull()) return; // cast qbi to itk m_ItkQBallImage = ItkQBallImgType::New(); mitk::CastToItkImage(m_QBallImage, m_ItkQBallImage); // mask image found? // catch exceptions thrown by the itkAccess macros try{ if(m_MaskImageNode.IsNotNull()) { m_MaskImage = 0; if (dynamic_cast(m_MaskImageNode->GetData())) mitk::CastToItkImage(dynamic_cast(m_MaskImageNode->GetData()), m_MaskImage); } } catch(...) { QMessageBox::warning(NULL, "Warning", "Incompatible mask image chosen. Processing without masking."); //reset mask image m_MaskImage = NULL; } // if no mask image is selected generate it if( m_MaskImage.IsNull() ) { m_MaskImage = MaskImgType::New(); m_MaskImage->SetSpacing( m_ItkQBallImage->GetSpacing() ); // Set the image spacing m_MaskImage->SetOrigin( m_ItkQBallImage->GetOrigin() ); // Set the image origin m_MaskImage->SetDirection( m_ItkQBallImage->GetDirection() ); // Set the image direction m_MaskImage->SetLargestPossibleRegion( m_ItkQBallImage->GetLargestPossibleRegion()); m_MaskImage->SetBufferedRegion( m_ItkQBallImage->GetLargestPossibleRegion() ); m_MaskImage->Allocate(); itk::ImageRegionIterator it (m_MaskImage, m_MaskImage->GetLargestPossibleRegion() ); for (it = it.Begin(); !it.IsAtEnd(); ++it) { it.Set(1); } } unsigned int steps = m_Iterations/10000; if (steps<10) steps = 10; m_LastStep = 1; mitk::ProgressBar::GetInstance()->AddStepsToDo(steps); // start worker thread m_TrackingThread.start(QThread::LowestPriority); } // generate mitkFiberBundle from tracking filter output void QmitkGibbsTrackingView::GenerateFiberBundle(bool smoothFibers) { if (m_GlobalTracker.IsNull() || (!(m_Controls->m_VisualizationCheckbox->isChecked() || m_Controls->m_VisualizeOnceButton->isChecked()) && m_ThreadIsRunning)) return; if (m_Controls->m_VisualizeOnceButton->isChecked()) m_Controls->m_VisualizeOnceButton->setChecked(false); vtkSmartPointer fiberBundle = m_GlobalTracker->GetFiberBundle(); if ( fiberBundle->GetNumberOfLines()==0 ) return; m_FiberBundle = mitk::FiberBundleX::New(fiberBundle); if (smoothFibers) m_FiberBundle->DoFiberSmoothing(10); if (m_FiberBundleNode.IsNotNull()){ GetDefaultDataStorage()->Remove(m_FiberBundleNode); m_FiberBundleNode = 0; } m_FiberBundleNode = mitk::DataNode::New(); m_FiberBundleNode->SetData(m_FiberBundle); QString name(m_QBallImageNode->GetName().c_str()); name += "_FiberBundle"; m_FiberBundleNode->SetName(name.toStdString()); m_FiberBundleNode->SetVisibility(true); if (!m_OutputFileName.isEmpty()) { QString filename = m_OutputFileName; mitk::FiberBundleXWriter::Pointer writer = mitk::FiberBundleXWriter::New(); writer->SetFileName(filename.toStdString()); writer->SetInputFiberBundleX(m_FiberBundle.GetPointer()); try { writer->Update(); QMessageBox::information(NULL, "Fiber bundle saved to", filename); } catch (itk::ExceptionObject &ex) { QMessageBox::information(NULL, "Fiber bundle could not be saved", QString("%1\n%2\n%3\n%4\n%5\n%6").arg(ex.GetNameOfClass()).arg(ex.GetFile()).arg(ex.GetLine()).arg(ex.GetLocation()).arg(ex.what()).arg(ex.GetDescription())); if(m_QBallImageNode.IsNull()) GetDataStorage()->Add(m_FiberBundleNode); else GetDataStorage()->Add(m_FiberBundleNode, m_QBallImageNode); } } else { if(m_QBallImageNode.IsNull()) GetDataStorage()->Add(m_FiberBundleNode); else GetDataStorage()->Add(m_FiberBundleNode, m_QBallImageNode); } } void QmitkGibbsTrackingView::SetOutputFile() { // SELECT FOLDER DIALOG m_OutputFileName = QFileDialog::getSaveFileName(0, tr("Set file name"), QDir::currentPath()+"/FiberBundle.fib", tr("Fiber Bundle (*.fib)") ); if (m_OutputFileName.isEmpty()) m_Controls->m_OutputFileLabel->setText("N/A"); else m_Controls->m_OutputFileLabel->setText(m_OutputFileName); } // save current tracking paramters as xml file (.gtp) void QmitkGibbsTrackingView::SaveTrackingParameters() { TiXmlDocument documentXML; TiXmlDeclaration* declXML = new TiXmlDeclaration( "1.0", "", "" ); documentXML.LinkEndChild( declXML ); TiXmlElement* mainXML = new TiXmlElement("global_tracking_parameter_file"); mainXML->SetAttribute("file_version", "0.1"); documentXML.LinkEndChild(mainXML); TiXmlElement* paramXML = new TiXmlElement("parameter_set"); paramXML->SetAttribute("iterations", QString::number(m_Iterations).toStdString()); paramXML->SetAttribute("particle_length", QString::number((float)m_Controls->m_ParticleLengthSlider->value()/10).toStdString()); paramXML->SetAttribute("particle_width", QString::number((float)m_Controls->m_ParticleWidthSlider->value()/10).toStdString()); paramXML->SetAttribute("particle_weight", QString::number((float)m_Controls->m_ParticleWeightSlider->value()/10000).toStdString()); paramXML->SetAttribute("temp_start", QString::number((float)m_Controls->m_StartTempSlider->value()/100).toStdString()); paramXML->SetAttribute("temp_end", QString::number((float)m_Controls->m_EndTempSlider->value()/10000).toStdString()); paramXML->SetAttribute("inexbalance", QString::number((float)m_Controls->m_InExBalanceSlider->value()/10).toStdString()); paramXML->SetAttribute("fiber_length", QString::number(m_Controls->m_FiberLengthSlider->value()).toStdString()); paramXML->SetAttribute("curvature_threshold", QString::number(m_Controls->m_CurvatureThresholdSlider->value()).toStdString()); mainXML->LinkEndChild(paramXML); QString filename = QFileDialog::getSaveFileName( 0, tr("Save Parameters"), QDir::currentPath()+"/param.gtp", tr("Global Tracking Parameters (*.gtp)") ); if(filename.isEmpty() || filename.isNull()) return; if(!filename.endsWith(".gtp")) filename += ".gtp"; documentXML.SaveFile( filename.toStdString() ); } void QmitkGibbsTrackingView::UpdateIteraionsGUI(unsigned long iterations) { switch(iterations) { case 10000: m_Controls->m_IterationsSlider->setValue(0); m_Controls->m_IterationsLabel->setText("Iterations: 10^4"); break; case 50000: m_Controls->m_IterationsSlider->setValue(1); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^4"); break; case 100000: m_Controls->m_IterationsSlider->setValue(2); m_Controls->m_IterationsLabel->setText("Iterations: 10^5"); break; case 500000: m_Controls->m_IterationsSlider->setValue(3); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^5"); break; case 1000000: m_Controls->m_IterationsSlider->setValue(4); m_Controls->m_IterationsLabel->setText("Iterations: 10^6"); break; case 5000000: m_Controls->m_IterationsSlider->setValue(5); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^6"); break; case 10000000: m_Controls->m_IterationsSlider->setValue(6); m_Controls->m_IterationsLabel->setText("Iterations: 10^7"); break; case 50000000: m_Controls->m_IterationsSlider->setValue(7); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^7"); break; case 100000000: m_Controls->m_IterationsSlider->setValue(8); m_Controls->m_IterationsLabel->setText("Iterations: 10^8"); break; case 500000000: m_Controls->m_IterationsSlider->setValue(9); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^8"); break; case 1000000000: m_Controls->m_IterationsSlider->setValue(10); m_Controls->m_IterationsLabel->setText("Iterations: 10^9"); break; case 5000000000: m_Controls->m_IterationsSlider->setValue(11); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^9"); break; } } // load current tracking paramters from xml file (.gtp) void QmitkGibbsTrackingView::LoadTrackingParameters() { QString filename = QFileDialog::getOpenFileName(0, tr("Load Parameters"), QDir::currentPath(), tr("Global Tracking Parameters (*.gtp)") ); if(filename.isEmpty() || filename.isNull()) return; TiXmlDocument doc( filename.toStdString() ); doc.LoadFile(); TiXmlHandle hDoc(&doc); TiXmlElement* pElem; TiXmlHandle hRoot(0); pElem = hDoc.FirstChildElement().Element(); hRoot = TiXmlHandle(pElem); pElem = hRoot.FirstChildElement("parameter_set").Element(); QString iterations(pElem->Attribute("iterations")); m_Iterations = iterations.toULong(); UpdateIteraionsGUI(m_Iterations); QString particleLength(pElem->Attribute("particle_length")); float pLength = particleLength.toFloat(); QString particleWidth(pElem->Attribute("particle_width")); float pWidth = particleWidth.toFloat(); if (pLength==0) m_Controls->m_ParticleLengthLabel->setText("auto"); else m_Controls->m_ParticleLengthLabel->setText(particleLength+" mm"); if (pWidth==0) m_Controls->m_ParticleWidthLabel->setText("auto"); else m_Controls->m_ParticleWidthLabel->setText(particleWidth+" mm"); m_Controls->m_ParticleWidthSlider->setValue(pWidth*10); m_Controls->m_ParticleLengthSlider->setValue(pLength*10); QString partWeight(pElem->Attribute("particle_weight")); m_Controls->m_ParticleWeightSlider->setValue(partWeight.toFloat()*10000); m_Controls->m_ParticleWeightLabel->setText(partWeight); QString startTemp(pElem->Attribute("temp_start")); m_Controls->m_StartTempSlider->setValue(startTemp.toFloat()*100); m_Controls->m_StartTempLabel->setText(startTemp); QString endTemp(pElem->Attribute("temp_end")); m_Controls->m_EndTempSlider->setValue(endTemp.toFloat()*10000); m_Controls->m_EndTempLabel->setText(endTemp); QString inExBalance(pElem->Attribute("inexbalance")); m_Controls->m_InExBalanceSlider->setValue(inExBalance.toFloat()*10); m_Controls->m_InExBalanceLabel->setText(inExBalance); QString fiberLength(pElem->Attribute("fiber_length")); m_Controls->m_FiberLengthSlider->setValue(fiberLength.toInt()); m_Controls->m_FiberLengthLabel->setText(fiberLength+"mm"); QString curvThres(pElem->Attribute("curvature_threshold")); m_Controls->m_CurvatureThresholdSlider->setValue(curvThres.toInt()); m_Controls->m_CurvatureThresholdLabel->setText(curvThres+"°"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h index 0285ee11ec..74776790f4 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h @@ -1,165 +1,165 @@ -/*========================================================================= -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +/*=================================================================== -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -=========================================================================*/ +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkGibbsTrackingView_h #define QmitkGibbsTrackingView_h #include #include #include "ui_QmitkGibbsTrackingViewControls.h" #include #include #include #include #include #include #include class QmitkGibbsTrackingView; class QmitkTrackingWorker : public QObject { Q_OBJECT public: QmitkTrackingWorker(QmitkGibbsTrackingView* view); public slots: void run(); private: QmitkGibbsTrackingView* m_View; }; /*! \brief QmitkGibbsTrackingView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ typedef itk::Image< float, 3 > FloatImageType; namespace itk { template class GibbsTrackingFilter; } class QmitkGibbsTrackingView : public QmitkFunctionality { // 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: typedef itk::Image MaskImgType; typedef itk::Vector OdfVectorType; typedef itk::Image ItkQBallImgType; typedef itk::GibbsTrackingFilter GibbsTrackingFilterType; static const std::string VIEW_ID; QmitkGibbsTrackingView(); virtual ~QmitkGibbsTrackingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); signals: protected slots: void StartGibbsTracking(); void StopGibbsTracking(); void AfterThread(); void BeforeThread(); void TimerUpdate(); void SetMask(); void AdvancedSettings(); void SaveTrackingParameters(); void LoadTrackingParameters(); void SetIterations(int value); void SetParticleWidth(int value); void SetParticleLength(int value); void SetInExBalance(int value); void SetFiberLength(int value); void SetParticleWeight(int value); void SetStartTemp(int value); void SetEndTemp(int value); void SetCurvatureThreshold(int value); void SetOutputFile(); private: // Visualization & GUI void GenerateFiberBundle(bool smoothFibers); void UpdateGUI(); void UpdateTrackingStatus(); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); template void CastToFloat(InputImageType* image, typename mitk::Image::Pointer outImage); void UpdateIteraionsGUI(unsigned long iterations); Ui::QmitkGibbsTrackingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; // data objects mitk::FiberBundleX::Pointer m_FiberBundle; MaskImgType::Pointer m_MaskImage; mitk::QBallImage::Pointer m_QBallImage; ItkQBallImgType::Pointer m_ItkQBallImage; // data nodes mitk::DataNode::Pointer m_QBallImageNode; mitk::DataNode::Pointer m_MaskImageNode; mitk::DataNode::Pointer m_FiberBundleNode; // flags etc. bool m_ThreadIsRunning; QTimer* m_TrackingTimer; QTime m_TrackingTime; unsigned long m_ElapsedTime; unsigned long m_Iterations; int m_LastStep; QString m_OutputFileName; // global tracker and friends itk::SmartPointer m_GlobalTracker; QmitkTrackingWorker m_TrackingWorker; QThread m_TrackingThread; friend class QmitkTrackingWorker; }; #endif // _QMITKGibbsTrackingVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.cpp index 17eb182803..2301b85fbf 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.cpp @@ -1,814 +1,819 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkIVIMView.h" #include "QmitkStdMultiWidget.h" // qt #include "qmessagebox.h" #include "qclipboard.h" // mitk #include "mitkDiffusionImage.h" #include "mitkImageCast.h" // itk #include "itkScalarImageToHistogramGenerator.h" #include "itkRegionOfInterestImageFilter.h" #include "itkImageRegionConstIteratorWithIndex.h" // itk/mitk #include "itkDiffusionIntravoxelIncoherentMotionReconstructionImageFilter.h" #include "itkRegularizedIVIMReconstructionFilter.h" #include "mitkImageCast.h" const std::string QmitkIVIMView::VIEW_ID = "org.mitk.views.ivim"; QmitkIVIMView::QmitkIVIMView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_Active(false) , m_SliceObserverTag1(0), m_SliceObserverTag2(0), m_SliceObserverTag3(0) , m_DiffusionImageNode(NULL) , m_MaskImageNode(NULL) { } QmitkIVIMView::~QmitkIVIMView() { QmitkStdMultiWidget* MultiWidget = this->GetActiveStdMultiWidget(false); if(MultiWidget) { //unregister observers when view is destroyed if( MultiWidget->mitkWidget1 != NULL && m_SliceObserverTag1 != 0) { mitk::SliceNavigationController* slicer = MultiWidget->mitkWidget1->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag1 ); } if( MultiWidget->mitkWidget2 != NULL && m_SliceObserverTag2 != 0) { mitk::SliceNavigationController* slicer = MultiWidget->mitkWidget2->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag2 ); } if( MultiWidget->mitkWidget3!= NULL && m_SliceObserverTag3 != 0) { mitk::SliceNavigationController* slicer = MultiWidget->mitkWidget3->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag3 ); } } } void QmitkIVIMView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkIVIMViewControls; m_Controls->setupUi( parent ); connect( m_Controls->m_ButtonStart, SIGNAL(clicked()), this, SLOT(FittIVIMStart()) ); connect( m_Controls->m_ButtonAutoThres, SIGNAL(clicked()), this, SLOT(AutoThreshold()) ); connect( m_Controls->m_MethodCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(MethodCombo(int)) ); connect( m_Controls->m_DStarSlider, SIGNAL(valueChanged(int)), this, SLOT(DStarSlider(int)) ); connect( m_Controls->m_BThreshSlider, SIGNAL(valueChanged(int)), this, SLOT(BThreshSlider(int)) ); connect( m_Controls->m_S0ThreshSlider, SIGNAL(valueChanged(int)), this, SLOT(S0ThreshSlider(int)) ); connect( m_Controls->m_NumItSlider, SIGNAL(valueChanged(int)), this, SLOT(NumItsSlider(int)) ); connect( m_Controls->m_LambdaSlider, SIGNAL(valueChanged(int)), this, SLOT(LambdaSlider(int)) ); connect( m_Controls->m_DisplayResultsCheckbox, SIGNAL(clicked()), this, SLOT(Checkbox()) ); connect( m_Controls->m_CheckDStar, SIGNAL(clicked()), this, SLOT(Checkbox()) ); connect( m_Controls->m_CheckD, SIGNAL(clicked()), this, SLOT(Checkbox()) ); connect( m_Controls->m_Checkf, SIGNAL(clicked()), this, SLOT(Checkbox()) ); connect( m_Controls->m_ChooseMethod, SIGNAL(clicked()), this, SLOT(ChooseMethod()) ); connect( m_Controls->m_CurveClipboard, SIGNAL(clicked()), this, SLOT(ClipboardCurveButtonClicked()) ); connect( m_Controls->m_ValuesClipboard, SIGNAL(clicked()), this, SLOT(ClipboardStatisticsButtonClicked()) ); } QString dstar = QString::number(m_Controls->m_DStarSlider->value()/1000.0); m_Controls->m_DStarLabel->setText(dstar); QString bthresh = QString::number(m_Controls->m_BThreshSlider->value()*5.0); m_Controls->m_BThreshLabel->setText(bthresh); QString s0thresh = QString::number(m_Controls->m_S0ThreshSlider->value()*0.5); m_Controls->m_S0ThreshLabel->setText(s0thresh); QString numits = QString::number(m_Controls->m_NumItSlider->value()); m_Controls->m_NumItsLabel->setText(numits); QString lambda = QString::number(m_Controls->m_LambdaSlider->value()*.00001); m_Controls->m_LambdaLabel->setText(lambda); m_Controls->m_VisualizeResultsWidget->setVisible(m_Controls->m_DisplayResultsCheckbox->isChecked()); m_Controls->m_MethodCombo->setVisible(m_Controls->m_ChooseMethod->isChecked()); m_Controls->m_Warning->setVisible(false); MethodCombo(m_Controls->m_MethodCombo->currentIndex()); } void QmitkIVIMView::Checkbox() { m_Controls->m_VisualizeResultsWidget->setVisible(m_Controls->m_DisplayResultsCheckbox->isChecked()); // m_Controls->m_ADCBValues->setVisible(m_Controls->m_CheckADC->isChecked()); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::MethodCombo(int val) { switch(val) { case 0: m_Controls->m_DstarFrame->setVisible(false); m_Controls->m_NeglSiFrame->setVisible(true); m_Controls->m_NeglBframe->setVisible(false); m_Controls->m_IterationsFrame->setVisible(false); m_Controls->m_LambdaFrame->setVisible(false); break; case 1: m_Controls->m_DstarFrame->setVisible(true); m_Controls->m_NeglSiFrame->setVisible(true); m_Controls->m_NeglBframe->setVisible(false); m_Controls->m_IterationsFrame->setVisible(false); m_Controls->m_LambdaFrame->setVisible(false); break; case 2: m_Controls->m_DstarFrame->setVisible(false); m_Controls->m_NeglSiFrame->setVisible(true); m_Controls->m_NeglBframe->setVisible(true); m_Controls->m_IterationsFrame->setVisible(false); m_Controls->m_LambdaFrame->setVisible(false); break; case 3: m_Controls->m_DstarFrame->setVisible(false); m_Controls->m_NeglSiFrame->setVisible(true); m_Controls->m_NeglBframe->setVisible(true); m_Controls->m_IterationsFrame->setVisible(false); m_Controls->m_LambdaFrame->setVisible(false); break; case 4: m_Controls->m_DstarFrame->setVisible(false); m_Controls->m_NeglSiFrame->setVisible(false); m_Controls->m_NeglBframe->setVisible(false); m_Controls->m_IterationsFrame->setVisible(false); m_Controls->m_LambdaFrame->setVisible(false); break; } itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::DStarSlider (int val) { QString sval = QString::number(val/1000.0); m_Controls->m_DStarLabel->setText(sval); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::BThreshSlider (int val) { QString sval = QString::number(val*5.0); m_Controls->m_BThreshLabel->setText(sval); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::S0ThreshSlider (int val) { QString sval = QString::number(val*0.5); m_Controls->m_S0ThreshLabel->setText(sval); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::NumItsSlider (int val) { QString sval = QString::number(val); m_Controls->m_NumItsLabel->setText(sval); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::LambdaSlider (int val) { QString sval = QString::number(val*.00001); m_Controls->m_LambdaLabel->setText(sval); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget1->GetSliceNavigationController(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkIVIMView::OnSliceChanged ); m_SliceObserverTag1 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget2->GetSliceNavigationController(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkIVIMView::OnSliceChanged ); m_SliceObserverTag2 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget3->GetSliceNavigationController(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkIVIMView::OnSliceChanged ); m_SliceObserverTag3 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } } void QmitkIVIMView::StdMultiWidgetNotAvailable() { { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget1->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag1 ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget2->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag2 ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget3->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag3 ); } m_MultiWidget = NULL; } void QmitkIVIMView::OnSelectionChanged( std::vector nodes ) { bool foundOneDiffusionImage = false; m_Controls->m_DiffusionImageLabel->setText("-"); m_Controls->m_MaskImageLabel->setText("-"); m_MaskImageNode = NULL; m_DiffusionImageNode = NULL; // iterate all selected objects, adjust warning visibility for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { if( dynamic_cast*>(node->GetData()) ) { m_DiffusionImageNode = node; foundOneDiffusionImage = true; m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); } else { bool isBinary = false; node->GetPropertyValue("binary", isBinary); if (isBinary) { m_MaskImageNode = node; m_Controls->m_MaskImageLabel->setText(node->GetName().c_str()); } } } } m_Controls->m_ButtonStart->setEnabled( foundOneDiffusionImage ); m_Controls->m_ButtonAutoThres->setEnabled( foundOneDiffusionImage ); m_Controls->m_ControlsFrame->setEnabled( foundOneDiffusionImage ); m_Controls->m_BottomControlsFrame->setEnabled( foundOneDiffusionImage ); itk::StartEvent dummy; OnSliceChanged(dummy); } void QmitkIVIMView::AutoThreshold() { std::vector nodes = this->GetDataManagerSelection(); if (nodes.empty()) return; if (!nodes.front()) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, "Template", "Please load and select a diffusion image before starting image processing."); return; } typedef mitk::DiffusionImage DiffImgType; DiffImgType* dimg = dynamic_cast(nodes.front()->GetData()); if (!dimg) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, "Template", "No valid diffusion image was found."); return; } // find bzero index int index = -1; DiffImgType::GradientDirectionContainerType::Pointer directions = dimg->GetDirections(); for(DiffImgType::GradientDirectionContainerType::ConstIterator it = directions->Begin(); it != directions->End(); ++it) { index++; DiffImgType::GradientDirectionType g = it.Value(); if(g[0] == 0 && g[1] == 0 && g[2] == 0 ) break; } typedef itk::VectorImage VecImgType; VecImgType::Pointer vecimg = dimg->GetVectorImage(); int vecLength = vecimg->GetVectorLength(); index = index > vecLength-1 ? vecLength-1 : index; MITK_INFO << "Performing Histogram Analysis on Channel" << index; typedef itk::Image ImgType; ImgType::Pointer img = ImgType::New(); mitk::CastToItkImage(dimg, img); itk::ImageRegionIterator itw (img, img->GetLargestPossibleRegion() ); itw = itw.Begin(); itk::ImageRegionConstIterator itr (vecimg, vecimg->GetLargestPossibleRegion() ); itr = itr.Begin(); while(!itr.IsAtEnd()) { itw.Set(itr.Get().GetElement(index)); ++itr; ++itw; } typedef itk::Statistics::ScalarImageToHistogramGenerator< ImgType > HistogramGeneratorType; typedef HistogramGeneratorType::HistogramType HistogramType; HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New(); histogramGenerator->SetInput( img ); histogramGenerator->SetMarginalScale( 10 ); // Defines y-margin width of histogram histogramGenerator->SetNumberOfBins( 100 ); // CT range [-1024, +2048] --> bin size 4 values histogramGenerator->SetHistogramMin( dimg->GetScalarValueMin() ); histogramGenerator->SetHistogramMax( dimg->GetScalarValueMax() * .5 ); histogramGenerator->Compute(); HistogramType::ConstIterator iter = histogramGenerator->GetOutput()->Begin(); float maxFreq = 0; float maxValue = 0; while ( iter != histogramGenerator->GetOutput()->End() ) { if(iter.GetFrequency() > maxFreq) { maxFreq = iter.GetFrequency(); maxValue = iter.GetMeasurementVector()[0]; } ++iter; } maxValue *= 2; int sliderPos = maxValue * 2; m_Controls->m_S0ThreshSlider->setValue(sliderPos); S0ThreshSlider(sliderPos); } void QmitkIVIMView::FittIVIMStart() { std::vector nodes = this->GetDataManagerSelection(); if (nodes.empty()) return; if (!nodes.front()) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, "Template", "Please load and select a diffusion image before starting image processing."); return; } mitk::DiffusionImage* img = dynamic_cast*>( nodes.front()->GetData()); if (!img) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, "Template", "No valid diffusion image was found."); return; } typedef itk::VectorImage VecImgType; VecImgType::Pointer vecimg = img->GetVectorImage(); OutImgType::IndexType dummy; FittIVIM(vecimg, img->GetDirections(), img->GetB_Value(), true, dummy); OutputToDatastorage(nodes); } void QmitkIVIMView::OnSliceChanged(const itk::EventObject& /*e*/) { m_Controls->m_Warning->setVisible(false); if(!m_Controls || m_DiffusionImageNode.IsNull()) return; // if(!m_Active) // return; m_Controls->m_VisualizeResultsWidget->setVisible(false); if(!m_Controls->m_DisplayResultsCheckbox->isChecked()) return; mitk::DiffusionImage::Pointer diffusionImg = dynamic_cast*>(m_DiffusionImageNode->GetData()); mitk::Image::Pointer maskImg = NULL; if (m_MaskImageNode.IsNotNull()) maskImg = dynamic_cast(m_MaskImageNode->GetData()); IVIMFilterType::GradientDirectionContainerType::ConstIterator gdcit = diffusionImg->GetDirections()->Begin(); bool foundB0 = false; while( gdcit != diffusionImg->GetDirections()->End() ) { if(gdcit.Value().one_norm() <= 0.0) foundB0 = true; ++gdcit; } if(!foundB0) { m_Controls->m_Warning->setText(QString("No baseline (non diffusion-weighted) image found.. aborting:(")); m_Controls->m_Warning->setVisible(true); } else { m_Controls->m_Warning->setVisible(false); } if (!m_MultiWidget) return; m_Controls->m_VisualizeResultsWidget->setVisible(true); typedef itk::VectorImage VecImgType; VecImgType::Pointer vecimg = (VecImgType*)diffusionImg->GetVectorImage().GetPointer(); VecImgType::Pointer roiImage = VecImgType::New(); if(maskImg.IsNull()) { int roisize = 0; if(m_Controls->m_MethodCombo->currentIndex() == 4) roisize = 5; mitk::Point3D pos = m_MultiWidget->GetCrossPosition(); VecImgType::IndexType crosspos; diffusionImg->GetTimeSlicedGeometry()->WorldToIndex(pos, crosspos); VecImgType::IndexType index; index[0] = crosspos[0] - roisize; index[0] = index[0] < 0 ? 0 : index[0]; index[1] = crosspos[1] - roisize; index[1] = index[1] < 0 ? 0 : index[1]; index[2] = crosspos[2] - roisize; index[2] = index[2] < 0 ? 0 : index[2]; VecImgType::SizeType size; size[0] = roisize*2+1; size[1] = roisize*2+1; size[2] = roisize*2+1; VecImgType::SizeType maxSize = vecimg->GetLargestPossibleRegion().GetSize(); size[0] = index[0]+size[0] > maxSize[0] ? maxSize[0]-index[0] : size[0]; size[1] = index[1]+size[1] > maxSize[1] ? maxSize[1]-index[1] : size[1]; size[2] = index[2]+size[2] > maxSize[2] ? maxSize[2]-index[2] : size[2]; VecImgType::RegionType region; region.SetSize( size ); region.SetIndex( index ); vecimg->SetRequestedRegion( region ); VecImgType::IndexType newstart; newstart.Fill(0); VecImgType::RegionType newregion; newregion.SetSize( size ); newregion.SetIndex( newstart ); roiImage->CopyInformation( vecimg ); roiImage->SetRegions( newregion ); roiImage->SetOrigin( pos ); roiImage->Allocate(); roiImage->SetPixel(newstart, vecimg->GetPixel(index)); FittIVIM(roiImage, diffusionImg->GetDirections(), diffusionImg->GetB_Value(), false, crosspos); } else { typedef itk::Image MaskImgType; MaskImgType::Pointer maskItk; CastToItkImage( maskImg, maskItk ); mitk::Point3D pos; pos[0] = 0; pos[1] = 0; pos[2] = 0; VecImgType::IndexType index; index[0] = 0; index[1] = 0; index[2] = 0; VecImgType::SizeType size; size[0] = 1; size[1] = 1; size[2] = 1; VecImgType::RegionType region; region.SetSize( size ); region.SetIndex( index ); vecimg->SetRequestedRegion( region ); // iterators over output and input itk::ImageRegionConstIteratorWithIndex vecit(vecimg, vecimg->GetLargestPossibleRegion()); itk::VariableLengthVector avg(vecimg->GetVectorLength()); avg.Fill(0); float numPixels = 0; while ( ! vecit.IsAtEnd() ) { VecImgType::PointType point; vecimg->TransformIndexToPhysicalPoint(vecit.GetIndex(), point); MaskImgType::IndexType index; maskItk->TransformPhysicalPointToIndex(point, index); if(maskItk->GetPixel(index) != 0) { avg += vecit.Get(); numPixels += 1.0; } // update iterators ++vecit; } avg /= numPixels; m_Controls->m_Warning->setText(QString("Averaging ")+QString::number((int)numPixels)+QString(" voxels!")); m_Controls->m_Warning->setVisible(true); roiImage->CopyInformation( vecimg ); roiImage->SetRegions( region ); roiImage->SetOrigin( pos ); roiImage->Allocate(); roiImage->SetPixel(index, avg); FittIVIM(roiImage, diffusionImg->GetDirections(), diffusionImg->GetB_Value(), false, index); } vecimg->SetRegions( vecimg->GetLargestPossibleRegion() ); m_Controls->m_VisualizeResultsWidget->SetParameters(m_Snap); } void QmitkIVIMView::FittIVIM(itk::VectorImage* vecimg, DirContainerType* dirs, float bval, bool multivoxel, OutImgType::IndexType &crosspos) { IVIMFilterType::Pointer filter = IVIMFilterType::New(); filter->SetInput(vecimg); filter->SetGradientDirections(dirs); filter->SetBValue(bval); switch(m_Controls->m_MethodCombo->currentIndex()) { case 0: filter->SetMethod(IVIMFilterType::IVIM_FIT_ALL); filter->SetS0Thres(m_Controls->m_S0ThreshLabel->text().toDouble()); break; case 1: filter->SetMethod(IVIMFilterType::IVIM_DSTAR_FIX); filter->SetDStar(m_Controls->m_DStarLabel->text().toDouble()); filter->SetS0Thres(m_Controls->m_S0ThreshLabel->text().toDouble()); break; case 2: filter->SetMethod(IVIMFilterType::IVIM_D_THEN_DSTAR); filter->SetBThres(m_Controls->m_BThreshLabel->text().toDouble()); filter->SetS0Thres(m_Controls->m_S0ThreshLabel->text().toDouble()); filter->SetFitDStar(m_Controls->m_CheckDStar->isChecked()); break; case 3: filter->SetMethod(IVIMFilterType::IVIM_LINEAR_D_THEN_F); filter->SetBThres(m_Controls->m_BThreshLabel->text().toDouble()); filter->SetS0Thres(m_Controls->m_S0ThreshLabel->text().toDouble()); filter->SetFitDStar(m_Controls->m_CheckDStar->isChecked()); break; case 4: filter->SetMethod(IVIMFilterType::IVIM_REGULARIZED); filter->SetBThres(m_Controls->m_BThreshLabel->text().toDouble()); filter->SetS0Thres(m_Controls->m_S0ThreshLabel->text().toDouble()); filter->SetNumberIterations(m_Controls->m_NumItsLabel->text().toInt()); filter->SetLambda(m_Controls->m_LambdaLabel->text().toDouble()); filter->SetFitDStar(m_Controls->m_CheckDStar->isChecked()); break; } if(!multivoxel) { filter->SetFitDStar(true); } filter->SetNumberOfThreads(1); filter->SetVerbose(multivoxel); filter->SetCrossPosition(crosspos); filter->Update(); m_Snap = filter->GetSnapshot(); m_DStarMap = filter->GetOutput(2); m_DMap = filter->GetOutput(1); m_fMap = filter->GetOutput(0); } void QmitkIVIMView::OutputToDatastorage(std::vector nodes) { // Outputs to Datastorage QString basename(nodes.front()->GetName().c_str()); if(m_Controls->m_CheckDStar->isChecked()) { mitk::Image::Pointer dstarimage = mitk::Image::New(); dstarimage->InitializeByItk(m_DStarMap.GetPointer()); dstarimage->SetVolume(m_DStarMap->GetBufferPointer()); QString newname2 = basename; newname2 = newname2.append("_DStarMap%1").arg(m_Controls->m_MethodCombo->currentIndex()); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( dstarimage ); node2->SetName(newname2.toAscii()); GetDefaultDataStorage()->Add(node2); } if(m_Controls->m_CheckD->isChecked()) { mitk::Image::Pointer dimage = mitk::Image::New(); dimage->InitializeByItk(m_DMap.GetPointer()); dimage->SetVolume(m_DMap->GetBufferPointer()); QString newname1 = basename; newname1 = newname1.append("_DMap%1").arg(m_Controls->m_MethodCombo->currentIndex()); mitk::DataNode::Pointer node1=mitk::DataNode::New(); node1->SetData( dimage ); node1->SetName(newname1.toAscii()); GetDefaultDataStorage()->Add(node1); } if(m_Controls->m_Checkf->isChecked()) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(m_fMap.GetPointer()); image->SetVolume(m_fMap->GetBufferPointer()); QString newname0 = basename; newname0 = newname0.append("_fMap%1").arg(m_Controls->m_MethodCombo->currentIndex()); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); node->SetName(newname0.toAscii()); GetDefaultDataStorage()->Add(node); } m_MultiWidget->RequestUpdate(); } void QmitkIVIMView::ChooseMethod() { m_Controls->m_MethodCombo->setVisible(m_Controls->m_ChooseMethod->isChecked()); } void QmitkIVIMView::ClipboardCurveButtonClicked() { if(true) { QString clipboard("Measurement Points\n"); for ( int i=0; isetText( clipboard, QClipboard::Clipboard ); } else { QApplication::clipboard()->clear(); } } void QmitkIVIMView::ClipboardStatisticsButtonClicked() { if ( true ) { QString clipboard( "f \t D \t D* \n" ); clipboard = clipboard.append( "%L1 \t %L2 \t %L3" ) .arg( m_Snap.currentF, 0, 'f', 10 ) .arg( m_Snap.currentD, 0, 'f', 10 ) .arg( m_Snap.currentDStar, 0, 'f', 10 ) ; QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); } else { QApplication::clipboard()->clear(); } } void QmitkIVIMView::Activated() { m_Active = true; } void QmitkIVIMView::Deactivated() { m_Active = false; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.h index c06c29d8de..f8a7c4d74e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkIVIMView.h @@ -1,115 +1,115 @@ -/*========================================================================= -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +/*=================================================================== -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -=========================================================================*/ +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKIVIMVIEW_H_INCLUDED #define _QMITKIVIMVIEW_H_INCLUDED #include #include #include "ui_QmitkIVIMViewControls.h" #include "itkVectorImage.h" #include "itkImage.h" #include "mitkDiffusionImage.h" #include "itkDiffusionIntravoxelIncoherentMotionReconstructionImageFilter.h" /*! \brief QmitkIVIMView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkIVIMView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkIVIMView(); virtual ~QmitkIVIMView(); typedef mitk::DiffusionImage::GradientDirectionContainerType DirContainerType; typedef itk::DiffusionIntravoxelIncoherentMotionReconstructionImageFilter IVIMFilterType; typedef itk::Image OutImgType; virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); void OnSliceChanged(const itk::EventObject& e); void OutputToDatastorage(std::vector nodes); void FittIVIM(itk::VectorImage* vecimg, DirContainerType* dirs, float bval, bool multivoxel, OutImgType::IndexType &crosspos); void Activated(); void Deactivated(); protected slots: /// \brief Called when the user clicks the GUI button void FittIVIMStart(); void AutoThreshold(); void MethodCombo(int val); void Checkbox(); void DStarSlider(int val); void BThreshSlider(int val); void S0ThreshSlider(int val); void NumItsSlider(int val); void LambdaSlider(int val); void ChooseMethod(); void ClipboardStatisticsButtonClicked(); void ClipboardCurveButtonClicked(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkIVIMViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; int m_SliceObserverTag1; int m_SliceObserverTag2; int m_SliceObserverTag3; OutImgType::Pointer m_DStarMap; OutImgType::Pointer m_DMap; OutImgType::Pointer m_fMap; IVIMFilterType::IVIMSnapshot m_Snap; mitk::DataNode::Pointer m_DiffusionImageNode; mitk::DataNode::Pointer m_MaskImageNode; bool m_Active; }; #endif // _QMITKIVIMVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp index c13bd7be11..e3b542bccb 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp @@ -1,323 +1,328 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkODFDetailsView.h" #include #include #include #include #include #include #include #include #include #include #include const std::string QmitkODFDetailsView::VIEW_ID = "org.mitk.views.odfdetails"; QmitkODFDetailsView::QmitkODFDetailsView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_OdfNormalization(0) , m_ImageNode(NULL) { m_VtkActor = vtkActor::New(); m_VtkMapper = vtkPolyDataMapper::New(); m_Renderer = vtkRenderer::New(); m_VtkRenderWindow = vtkRenderWindow::New(); m_RenderWindowInteractor = vtkRenderWindowInteractor::New(); m_Camera = vtkCamera::New(); m_VtkRenderWindow->SetSize(300,300); } QmitkODFDetailsView::~QmitkODFDetailsView() { QmitkStdMultiWidget* MultiWidget = this->GetActiveStdMultiWidget(false); if(MultiWidget) { //unregister observers when view is destroyed if( MultiWidget->mitkWidget1 != NULL && m_SliceObserverTag1 != 0) { mitk::SliceNavigationController* slicer = MultiWidget->mitkWidget1->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag1 ); } if( MultiWidget->mitkWidget2 != NULL && m_SliceObserverTag2 != 0) { mitk::SliceNavigationController* slicer = MultiWidget->mitkWidget2->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag2 ); } if( MultiWidget->mitkWidget3!= NULL && m_SliceObserverTag3 != 0) { mitk::SliceNavigationController* slicer = MultiWidget->mitkWidget3->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag3 ); } } } void QmitkODFDetailsView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkODFDetailsViewControls; m_Controls->setupUi( parent ); m_Controls->m_OdfBox->setVisible(false); m_Controls->m_ODFRenderWidget->setVisible(false); } } void QmitkODFDetailsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget1->GetSliceNavigationController(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_SliceObserverTag1 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget2->GetSliceNavigationController(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_SliceObserverTag2 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget3->GetSliceNavigationController(); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_SliceObserverTag3 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } } void QmitkODFDetailsView::StdMultiWidgetNotAvailable() { { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget1->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag1 ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget2->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag2 ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget3->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag3 ); } m_MultiWidget = NULL; } void QmitkODFDetailsView::OnSelectionChanged( std::vector nodes ) { if (m_ImageNode.IsNotNull()) m_ImageNode->RemoveObserver( m_PropertyObserverTag ); m_ImageNode = NULL; m_Controls->m_InputImageLabel->setText("-"); // iterate selection for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && (dynamic_cast(node->GetData()) || dynamic_cast(node->GetData())) ) { m_Controls->m_InputImageLabel->setText(node->GetName().c_str()); m_ImageNode = node; } } UpdateOdf(); if (m_ImageNode.IsNotNull()) { itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_PropertyObserverTag = m_ImageNode->AddObserver( itk::ModifiedEvent(), command ); } } void QmitkODFDetailsView::UpdateOdf() { try { m_Values.clear(); m_Controls->m_OverviewBox->setVisible(true); if (m_ImageNode.IsNull() || !m_MultiWidget) { m_Controls->m_ODFRenderWidget->setVisible(false); m_Controls->m_OdfBox->setVisible(false); m_Controls->m_OverviewBox->setVisible(false); return; } // ODF Normalization Property mitk::OdfNormalizationMethodProperty* nmp = dynamic_cast(m_ImageNode->GetProperty( "Normalization" )); if(nmp) m_OdfNormalization = nmp->GetNormalization(); m_TemplateOdf = itk::OrientationDistributionFunction::GetBaseMesh(); m_OdfTransform = vtkSmartPointer::New(); m_OdfTransform->Identity(); m_OdfVals = vtkSmartPointer::New(); m_OdfSource = vtkSmartPointer::New(); itk::OrientationDistributionFunction odf; mitk::Point3D world = m_MultiWidget->GetCrossPosition(); mitk::Point3D index; mitk::Image::Pointer img = dynamic_cast(m_ImageNode->GetData()); img->GetTimeSlicedGeometry()->WorldToIndex(world, index); float sum = 0; float max = itk::NumericTraits::NonpositiveMin(); float min = itk::NumericTraits::max(); QString values; QString overviewText; // check if dynamic_cast successfull and if the crosshair position is inside of the geometry of the ODF data // otherwise possible crash for a scenario with multiple nodes if (dynamic_cast(m_ImageNode->GetData()) && ( m_ImageNode->GetData()->GetGeometry()->IsInside(world) ) ) { m_Controls->m_ODFRenderWidget->setVisible(true); m_Controls->m_OdfBox->setVisible(true); OdfVectorImgType::Pointer itkQBallImage = OdfVectorImgType::New(); mitk::CastToItkImage(dynamic_cast(m_ImageNode->GetData()), itkQBallImage); OdfVectorImgType::IndexType ind; ind[0] = (int)(index[0]+0.5); ind[1] = (int)(index[1]+0.5); ind[2] = (int)(index[2]+0.5); OdfVectorImgType::PixelType pixel = itkQBallImage->GetPixel(ind); for (int i=0; imax) max = val; if (val pd = odf.GetDirection(odf.GetPrincipleDiffusionDirection()); overviewText += "Main Diffusion:\n "+QString::number(pd[0])+"\n "+QString::number(pd[1])+"\n "+QString::number(pd[2])+"\n"; m_Controls->m_OdfValuesTextEdit->setText(values); } else if (dynamic_cast(m_ImageNode->GetData())) { m_Controls->m_ODFRenderWidget->setVisible(true); m_Controls->m_OdfBox->setVisible(false); TensorImageType::Pointer itkQBallImage = TensorImageType::New(); mitk::CastToItkImage(dynamic_cast(m_ImageNode->GetData()), itkQBallImage); TensorImageType::IndexType ind; ind[0] = (int)(index[0]+0.5); ind[1] = (int)(index[1]+0.5); ind[2] = (int)(index[2]+0.5); TensorImageType::PixelType pixel = itkQBallImage->GetPixel(ind); float tensorelems[6] = { (float)pixel[0], (float)pixel[1], (float)pixel[2], (float)pixel[3], (float)pixel[4], (float)pixel[5], }; itk::DiffusionTensor3D tensor(tensorelems); odf.InitFromTensor(tensor); /** Array of eigen-values. */ typedef itk::FixedArray EigenValuesArrayType; /** Matrix of eigen-vectors. */ typedef itk::Matrix MatrixType; typedef itk::Matrix EigenVectorsMatrixType; EigenValuesArrayType eigenValues; EigenVectorsMatrixType eigenVectors; QString pos = QString::number(ind[0])+", "+QString::number(ind[1])+", "+QString::number(ind[2]); overviewText += "Coordinates: "+pos+"\n"; overviewText += "FA: "+QString::number(tensor.GetFractionalAnisotropy())+"\n"; overviewText += "RA: "+QString::number(tensor.GetRelativeAnisotropy())+"\n"; overviewText += "Trace: "+QString::number(tensor.GetTrace())+"\n"; tensor.ComputeEigenAnalysis(eigenValues,eigenVectors); overviewText += "Eigenvalues:\n "+QString::number(eigenValues[2])+"\n "+QString::number(eigenValues[1])+"\n "+QString::number(eigenValues[0])+"\n"; overviewText += "Main Diffusion:\n "+QString::number(eigenVectors[0][0])+"\n "+QString::number(eigenVectors[1][0])+"\n "+QString::number(eigenVectors[2][0])+"\n"; overviewText += "Values:\n "+QString::number(tensorelems[0])+"\n "+QString::number(tensorelems[1])+"\n "+QString::number(tensorelems[2])+"\n "+QString::number(tensorelems[3])+"\n "+QString::number(tensorelems[4])+"\n "+QString::number(tensorelems[5])+"\n "+"\n"; } else { m_Controls->m_ODFRenderWidget->setVisible(false); m_Controls->m_OdfBox->setVisible(false); overviewText += "Please reinit image geometry.\n"; } m_Controls->m_ODFDetailsWidget->SetParameters(odf); switch(m_OdfNormalization) { case 0: odf = odf.MinMaxNormalize(); break; case 1: odf = odf.MaxNormalize(); break; case 2: odf = odf.MaxNormalize(); break; default: odf = odf.MinMaxNormalize(); } m_Controls->m_ODFRenderWidget->GenerateODF(odf); m_Controls->m_OverviewTextEdit->setText(overviewText.toStdString().c_str()); } catch(...) { QMessageBox::critical(0, "Error", "Data could not be analyzed. The image might be corrupted."); } } void QmitkODFDetailsView::OnSliceChanged(const itk::EventObject& /*e*/) { UpdateOdf(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.h index 37162c8af2..29a931e860 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.h @@ -1,115 +1,119 @@ -/*========================================================================= +/*=================================================================== -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -=========================================================================*/ +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKQmitkODFDetailsView_H_INCLUDED #define _QMITKQmitkODFDetailsView_H_INCLUDED #include #include #include "ui_QmitkODFDetailsViewControls.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include /*! \brief QmitkODFDetailsView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkODFDetailsView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkODFDetailsView(); QmitkODFDetailsView(const QmitkODFDetailsView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkODFDetailsView(); typedef float TOdfPixelType; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; typedef itk::DiffusionTensor3D< TOdfPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); void OnSliceChanged(const itk::EventObject& e); protected slots: protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); void UpdateOdf(); Ui::QmitkODFDetailsViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; int m_SliceObserverTag1; int m_SliceObserverTag2; int m_SliceObserverTag3; int m_PropertyObserverTag; vtkPolyData* m_TemplateOdf; vtkSmartPointer m_OdfTransform; vtkSmartPointer m_OdfVals; vtkSmartPointer m_OdfSource; vtkActor* m_VtkActor; vtkPolyDataMapper* m_VtkMapper; vtkRenderer* m_Renderer; vtkRenderWindow* m_VtkRenderWindow; vtkRenderWindowInteractor* m_RenderWindowInteractor; vtkCamera* m_Camera; std::vector m_Values; int m_OdfNormalization; mitk::DataNode::Pointer m_ImageNode; }; #endif // _QmitkODFDetailsView_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp index 560405779d..a1c109e4b0 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp @@ -1,2139 +1,2138 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-22 11:00:35 +0200 (Fr, 22 Mai 2009) $ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPartialVolumeAnalysisView.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkStdMultiWidget.h" #include "QmitkStdMultiWidgetEditor.h" #include "QmitkSliderNavigatorWidget.h" #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateOr.h" #include "mitkImageTimeSelector.h" #include "mitkProperties.h" #include "mitkProgressBar.h" #include "mitkImageCast.h" #include "mitkImageToItk.h" #include "mitkITKImageImport.h" #include "mitkDataNodeObject.h" #include "mitkNodePredicateData.h" #include "mitkPlanarFigureInteractor.h" #include "mitkGlobalInteraction.h" #include "mitkTensorImage.h" #include "mitkPlanarCircle.h" #include "mitkPlanarRectangle.h" #include "mitkPlanarPolygon.h" #include "mitkPartialVolumeAnalysisClusteringCalculator.h" #include "mitkDiffusionImage.h" #include #include "itkTensorDerivedMeasurementsFilter.h" #include "itkDiffusionTensor3D.h" #include "itkCartesianToPolarVectorImageFilter.h" #include "itkPolarToCartesianVectorImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkMaskImageFilter.h" #include "itkCastImageFilter.h" #include "itkImageMomentsCalculator.h" #include #include #include #include #define _USE_MATH_DEFINES #include #define PVA_PI M_PI const std::string QmitkPartialVolumeAnalysisView::VIEW_ID = "org.mitk.views.partialvolumeanalysisview"; class QmitkRequestStatisticsUpdateEvent : public QEvent { public: enum Type { StatisticsUpdateRequest = QEvent::MaxUser - 1025 }; QmitkRequestStatisticsUpdateEvent() : QEvent( (QEvent::Type) StatisticsUpdateRequest ) {}; }; typedef itk::Image ImageType; typedef itk::Image FloatImageType; typedef itk::Image, 3> VectorImageType; inline bool my_isnan(float x) { volatile float d = x; if(d!=d) return true; if(d==d) return false; return d != d; } QmitkPartialVolumeAnalysisView::QmitkPartialVolumeAnalysisView(QObject * /*parent*/, const char * /*name*/) : //QmitkFunctionality(), m_Controls( NULL ), m_TimeStepperAdapter( NULL ), m_MeasurementInfoRenderer(0), m_MeasurementInfoAnnotation(0), m_SelectedImageNodes( ), m_SelectedImage( NULL ), m_SelectedMaskNode( NULL ), m_SelectedImageMask( NULL ), m_SelectedPlanarFigureNodes(0), m_SelectedPlanarFigure( NULL ), m_IsTensorImage(false), m_FAImage(0), m_RDImage(0), m_ADImage(0), m_MDImage(0), m_CAImage(0), // m_DirectionImage(0), m_DirectionComp1Image(0), m_DirectionComp2Image(0), m_AngularErrorImage(0), m_SelectedRenderWindow(NULL), m_LastRenderWindow(NULL), m_ImageObserverTag( -1 ), m_ImageMaskObserverTag( -1 ), m_PlanarFigureObserverTag( -1 ), m_CurrentStatisticsValid( false ), m_StatisticsUpdatePending( false ), m_GaussianSigmaChangedSliding(false), m_NumberBinsSliding(false), m_UpsamplingChangedSliding(false), m_ClusteringResult(NULL), m_EllipseCounter(0), m_RectangleCounter(0), m_PolygonCounter(0), m_CurrentFigureNodeInitialized(false), m_QuantifyClass(2), m_IconTexOFF(new QIcon(":/QmitkPartialVolumeAnalysisView/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkPartialVolumeAnalysisView/texIntONIcon.png")), m_TexIsOn(true), m_Visible(false) { } QmitkPartialVolumeAnalysisView::~QmitkPartialVolumeAnalysisView() { if ( m_SelectedImage.IsNotNull() ) m_SelectedImage->RemoveObserver( m_ImageObserverTag ); if ( m_SelectedImageMask.IsNotNull() ) m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); if ( m_SelectedPlanarFigure.IsNotNull() ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_SelectedPlanarFigure->RemoveObserver( m_InitializedObserverTag ); } this->GetDataStorage()->AddNodeEvent -= mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeAddedInDataStorage ); m_SelectedPlanarFigureNodes->NodeChanged.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedPlanarFigureNodes->NodeRemoved.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); m_SelectedPlanarFigureNodes->PropertyChanged.RemoveListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); m_SelectedImageNodes->NodeChanged.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedImageNodes->NodeRemoved.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); m_SelectedImageNodes->PropertyChanged.RemoveListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); } void QmitkPartialVolumeAnalysisView::CreateQtPartControl(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new Ui::QmitkPartialVolumeAnalysisViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } SetHistogramVisibility(); m_Controls->m_TextureIntON->setIcon(*m_IconTexON); m_Controls->m_SimilarAnglesFrame->setVisible(false); m_Controls->m_SimilarAnglesLabel->setVisible(false); vtkTextProperty *textProp = vtkTextProperty::New(); textProp->SetColor(1.0, 1.0, 1.0); m_MeasurementInfoAnnotation = vtkCornerAnnotation::New(); m_MeasurementInfoAnnotation->SetMaximumFontSize(12); m_MeasurementInfoAnnotation->SetTextProperty(textProp); m_MeasurementInfoRenderer = vtkRenderer::New(); m_MeasurementInfoRenderer->AddActor(m_MeasurementInfoAnnotation); m_SelectedPlanarFigureNodes = mitk::DataStorageSelection::New(this->GetDataStorage(), false); m_SelectedPlanarFigureNodes->NodeChanged.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedPlanarFigureNodes->NodeRemoved.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); m_SelectedPlanarFigureNodes->PropertyChanged.AddListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); m_SelectedImageNodes = mitk::DataStorageSelection::New(this->GetDataStorage(), false); m_SelectedImageNodes->PropertyChanged.AddListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); m_SelectedImageNodes->NodeChanged.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedImageNodes->NodeRemoved.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeAddedInDataStorage ) ); Select(NULL,true,true); SetAdvancedVisibility(); } void QmitkPartialVolumeAnalysisView::SetHistogramVisibility() { m_Controls->m_HistogramWidget->setVisible(m_Controls->m_DisplayHistogramCheckbox->isChecked()); } void QmitkPartialVolumeAnalysisView::SetAdvancedVisibility() { m_Controls->frame_7->setVisible(m_Controls->m_AdvancedCheckbox->isChecked()); } void QmitkPartialVolumeAnalysisView::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_DisplayHistogramCheckbox, SIGNAL( clicked() ) , this, SLOT( SetHistogramVisibility() ) ); connect( m_Controls->m_AdvancedCheckbox, SIGNAL( clicked() ) , this, SLOT( SetAdvancedVisibility() ) ); connect( m_Controls->m_NumberBinsSlider, SIGNAL( sliderReleased () ), this, SLOT( NumberBinsReleasedSlider( ) ) ); connect( m_Controls->m_UpsamplingSlider, SIGNAL( sliderReleased( ) ), this, SLOT( UpsamplingReleasedSlider( ) ) ); connect( m_Controls->m_GaussianSigmaSlider, SIGNAL( sliderReleased( ) ), this, SLOT( GaussianSigmaReleasedSlider( ) ) ); connect( m_Controls->m_SimilarAnglesSlider, SIGNAL( sliderReleased( ) ), this, SLOT( SimilarAnglesReleasedSlider( ) ) ); connect( m_Controls->m_NumberBinsSlider, SIGNAL( valueChanged (int) ), this, SLOT( NumberBinsChangedSlider( int ) ) ); connect( m_Controls->m_UpsamplingSlider, SIGNAL( valueChanged( int ) ), this, SLOT( UpsamplingChangedSlider( int ) ) ); connect( m_Controls->m_GaussianSigmaSlider, SIGNAL( valueChanged( int ) ), this, SLOT( GaussianSigmaChangedSlider( int ) ) ); connect( m_Controls->m_SimilarAnglesSlider, SIGNAL( valueChanged( int ) ), this, SLOT( SimilarAnglesChangedSlider(int) ) ); connect( m_Controls->m_OpacitySlider, SIGNAL( valueChanged( int ) ), this, SLOT( OpacityChangedSlider(int) ) ); connect( (QObject*)(m_Controls->m_ButtonCopyHistogramToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(ToClipBoard())); connect( m_Controls->m_CircleButton, SIGNAL( clicked() ) , this, SLOT( ActionDrawEllipseTriggered() ) ); connect( m_Controls->m_RectangleButton, SIGNAL( clicked() ) , this, SLOT( ActionDrawRectangleTriggered() ) ); connect( m_Controls->m_PolygonButton, SIGNAL( clicked() ) , this, SLOT( ActionDrawPolygonTriggered() ) ); connect( m_Controls->m_GreenRadio, SIGNAL( clicked(bool) ) , this, SLOT( GreenRadio(bool) ) ); connect( m_Controls->m_PartialVolumeRadio, SIGNAL( clicked(bool) ) , this, SLOT( PartialVolumeRadio(bool) ) ); connect( m_Controls->m_BlueRadio, SIGNAL( clicked(bool) ) , this, SLOT( BlueRadio(bool) ) ); connect( m_Controls->m_AllRadio, SIGNAL( clicked(bool) ) , this, SLOT( AllRadio(bool) ) ); connect( m_Controls->m_EstimateCircle, SIGNAL( clicked() ) , this, SLOT( EstimateCircle() ) ); connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); connect( m_Controls->m_ExportClusteringResultsButton, SIGNAL(clicked()), this, SLOT(ExportClusteringResults())); } } void QmitkPartialVolumeAnalysisView::ExportClusteringResults() { if (m_ClusteringResult.IsNull() || m_SelectedImage.IsNull()) return; mitk::Geometry3D* geometry = m_SelectedImage->GetGeometry(); itk::Image< short, 3>::Pointer referenceImage = itk::Image< short, 3>::New(); mitk::Vector3D newSpacing = geometry->GetSpacing(); mitk::Point3D newOrigin = geometry->GetOrigin(); mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); newOrigin[0] += bounds.GetElement(0); newOrigin[1] += bounds.GetElement(2); newOrigin[2] += bounds.GetElement(4); itk::Matrix newDirection; itk::ImageRegion<3> imageRegion; for (int i=0; i<3; i++) for (int j=0; j<3; j++) newDirection[j][i] = geometry->GetMatrixColumn(i)[j]/newSpacing[j]; imageRegion.SetSize(0, geometry->GetExtent(0)); imageRegion.SetSize(1, geometry->GetExtent(1)); imageRegion.SetSize(2, geometry->GetExtent(2)); // apply new image parameters referenceImage->SetSpacing( newSpacing ); referenceImage->SetOrigin( newOrigin ); referenceImage->SetDirection( newDirection ); referenceImage->SetRegions( imageRegion ); referenceImage->Allocate(); typedef itk::Image< float, 3 > OutType; mitk::Image::Pointer mitkInImage = dynamic_cast(m_ClusteringResult->GetData()); typedef itk::Image< itk::RGBAPixel, 3 > ItkRgbaImageType; typedef mitk::ImageToItk< ItkRgbaImageType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(mitkInImage); caster->Update(); ItkRgbaImageType::Pointer itkInImage = caster->GetOutput(); typedef itk::ExtractChannelFromRgbaImageFilter< itk::Image< short, 3>, OutType > ExtractionFilterType; ExtractionFilterType::Pointer filter = ExtractionFilterType::New(); filter->SetInput(itkInImage); filter->SetChannel(ExtractionFilterType::ALPHA); filter->SetReferenceImage(referenceImage); filter->Update(); OutType::Pointer outImg = filter->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); node->SetName("Clustering Result"); GetDataStorage()->Add(node); } void QmitkPartialVolumeAnalysisView::EstimateCircle() { typedef itk::Image SegImageType; SegImageType::Pointer mask_itk = SegImageType::New(); typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(m_SelectedImageMask); caster->Update(); typedef itk::ImageMomentsCalculator< SegImageType > MomentsType; MomentsType::Pointer momentsCalc = MomentsType::New(); momentsCalc->SetImage(caster->GetOutput()); momentsCalc->Compute(); MomentsType::VectorType cog = momentsCalc->GetCenterOfGravity(); MomentsType::MatrixType axes = momentsCalc->GetPrincipalAxes(); MomentsType::VectorType moments = momentsCalc->GetPrincipalMoments(); // moments-coord conversion // third coordinate min oder max? // max-min = extent MomentsType::AffineTransformPointer trafo = momentsCalc->GetPhysicalAxesToPrincipalAxesTransform(); itk::ImageRegionIterator itimage(caster->GetOutput(), caster->GetOutput()->GetLargestPossibleRegion()); itimage = itimage.Begin(); double max = -9999999999.0; double min = 9999999999.0; while( !itimage.IsAtEnd() ) { if(itimage.Get()) { ImageType::IndexType index = itimage.GetIndex(); itk::Point point; caster->GetOutput()->TransformIndexToPhysicalPoint(index,point); itk::Point newPoint; newPoint = trafo->TransformPoint(point); if(newPoint[2]max) max = newPoint[2]; } ++itimage; } double extent = max - min; MITK_INFO << "EXTENT = " << extent; mitk::Point3D origin; mitk::Vector3D right, bottom, normal; double factor = 1000.0; mitk::FillVector3D(origin, cog[0]-factor*axes[1][0]-factor*axes[2][0], cog[1]-factor*axes[1][1]-factor*axes[2][1], cog[2]-factor*axes[1][2]-factor*axes[2][2]); // mitk::FillVector3D(normal, axis[0][0],axis[0][1],axis[0][2]); mitk::FillVector3D(bottom, 2*factor*axes[1][0], 2*factor*axes[1][1], 2*factor*axes[1][2]); mitk::FillVector3D(right, 2*factor*axes[2][0], 2*factor*axes[2][1], 2*factor*axes[2][2]); mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); planegeometry->InitializeStandardPlane(right.Get_vnl_vector(), bottom.Get_vnl_vector()); planegeometry->SetOrigin(origin); double len1 = sqrt(axes[1][0]*axes[1][0] + axes[1][1]*axes[1][1] + axes[1][2]*axes[1][2]); double len2 = sqrt(axes[2][0]*axes[2][0] + axes[2][1]*axes[2][1] + axes[2][2]*axes[2][2]); mitk::Point2D point1; point1[0] = factor*len1; point1[1] = factor*len2; mitk::Point2D point2; point2[0] = factor*len1+extent*.5; point2[1] = factor*len2; mitk::PlanarCircle::Pointer circle = mitk::PlanarCircle::New(); circle->SetGeometry2D(planegeometry); circle->PlaceFigure( point1 ); circle->SetControlPoint(0,point1); circle->SetControlPoint(1,point2); //circle->SetCurrentControlPoint( point2 ); mitk::PlanarFigure::PolyLineType polyline = circle->GetPolyLine( 0 ); MITK_INFO << "SIZE of planar figure polyline: " << polyline.size(); AddFigureToDataStorage(circle, "Circle"); } bool QmitkPartialVolumeAnalysisView::AssertDrawingIsPossible(bool checked) { if (m_SelectedImageNodes->GetNode().IsNull()) { checked = false; this->HandleException("Please select an image!", dynamic_cast(this->parent()), true); return false; } //this->GetActiveStdMultiWidget()->SetWidgetPlanesVisibility(false); return checked; } void QmitkPartialVolumeAnalysisView::ActionDrawEllipseTriggered() { bool checked = m_Controls->m_CircleButton->isChecked(); if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); this->AddFigureToDataStorage(figure, QString("Circle%1").arg(++m_EllipseCounter)); MITK_INFO << "PlanarCircle created ..."; } void QmitkPartialVolumeAnalysisView::ActionDrawRectangleTriggered() { bool checked = m_Controls->m_RectangleButton->isChecked(); if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarRectangle::Pointer figure = mitk::PlanarRectangle::New(); this->AddFigureToDataStorage(figure, QString("Rectangle%1").arg(++m_RectangleCounter)); MITK_INFO << "PlanarRectangle created ..."; } void QmitkPartialVolumeAnalysisView::ActionDrawPolygonTriggered() { bool checked = m_Controls->m_PolygonButton->isChecked(); if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); this->AddFigureToDataStorage(figure, QString("Polygon%1").arg(++m_PolygonCounter)); MITK_INFO << "PlanarPolygon created ..."; } void QmitkPartialVolumeAnalysisView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey, mitk::BaseProperty *property ) { mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); // Add custom property, if available if ( (propertyKey != NULL) && (property != NULL) ) { newNode->AddProperty( propertyKey, property ); } // figure drawn on the topmost layer / image this->GetDataStorage()->Add(newNode, m_SelectedImageNodes->GetNode() ); QList selectedNodes = this->GetDataManagerSelection(); for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } std::vector selectedPFNodes = m_SelectedPlanarFigureNodes->GetNodes(); for(unsigned int i = 0; i < selectedPFNodes.size(); i++) { selectedPFNodes[i]->SetSelected(false); } newNode->SetSelected(true); Select(newNode); } void QmitkPartialVolumeAnalysisView::PlanarFigureInitialized() { if(m_SelectedPlanarFigureNodes->GetNode().IsNull()) return; m_CurrentFigureNodeInitialized = true; this->Select(m_SelectedPlanarFigureNodes->GetNode()); m_Controls->m_CircleButton->setChecked(false); m_Controls->m_RectangleButton->setChecked(false); m_Controls->m_PolygonButton->setChecked(false); //this->GetActiveStdMultiWidget()->SetWidgetPlanesVisibility(true); this->RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::PlanarFigureFocus(mitk::DataNode* node) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (node->GetData()); if (_PlanarFigure) { FindRenderWindow(node); const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); // make node visible if (m_SelectedRenderWindow) { mitk::Point3D centerP = _PlaneGeometry->GetOrigin(); m_SelectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); m_SelectedRenderWindow->GetSliceNavigationController()->SelectSliceByPoint( centerP); } } } void QmitkPartialVolumeAnalysisView::FindRenderWindow(mitk::DataNode* node) { if (node && dynamic_cast (node->GetData())) { m_SelectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; foreach(QmitkRenderWindow * window, this->GetRenderWindowPart()->GetRenderWindows().values()) { if (!m_SelectedRenderWindow && node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, window->GetRenderer())) { m_SelectedRenderWindow = window; } } } } void QmitkPartialVolumeAnalysisView::OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) { if ( !m_Visible ) { return; } if ( nodes.empty() || nodes.size() > 1 ) { // Nothing to do: invalidate image, clear statistics, histogram, and GUI return; } Select(nodes.front()); } void QmitkPartialVolumeAnalysisView::Select( mitk::DataNode::Pointer node, bool clearMaskOnFirstArgNULL, bool clearImageOnFirstArgNULL ) { // Clear any unreferenced images this->RemoveOrphanImages(); bool somethingChanged = false; if(node.IsNull()) { somethingChanged = true; if(clearMaskOnFirstArgNULL) { if ( (m_SelectedImageMask.IsNotNull()) && (m_ImageMaskObserverTag >= 0) ) { m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); m_ImageMaskObserverTag = -1; } if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_PlanarFigureObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_PlanarFigureObserverTag = -1; } if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_InitializedObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_InitializedObserverTag ); m_InitializedObserverTag = -1; } m_SelectedPlanarFigure = NULL; m_SelectedPlanarFigureNodes->RemoveAllNodes(); m_CurrentFigureNodeInitialized = false; m_SelectedRenderWindow = 0; m_SelectedMaskNode = NULL; m_SelectedImageMask = NULL; } if(clearImageOnFirstArgNULL) { if ( (m_SelectedImage.IsNotNull()) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } m_SelectedImageNodes->RemoveAllNodes(); m_SelectedImage = NULL; m_IsTensorImage = false; m_FAImage = NULL; m_RDImage = NULL; m_ADImage = NULL; m_MDImage = NULL; m_CAImage = NULL; m_DirectionComp1Image = NULL; m_DirectionComp2Image = NULL; m_AngularErrorImage = NULL; m_Controls->m_SimilarAnglesFrame->setVisible(false); m_Controls->m_SimilarAnglesLabel->setVisible(false); } } else { typedef itk::SimpleMemberCommand< QmitkPartialVolumeAnalysisView > ITKCommandType; ITKCommandType::Pointer changeListener; changeListener = ITKCommandType::New(); changeListener->SetCallbackFunction( this, &QmitkPartialVolumeAnalysisView::RequestStatisticsUpdate ); // Get selected element mitk::TensorImage *selectedTensorImage = dynamic_cast< mitk::TensorImage * >( node->GetData() ); mitk::Image *selectedImage = dynamic_cast< mitk::Image * >( node->GetData() ); mitk::PlanarFigure *selectedPlanar = dynamic_cast< mitk::PlanarFigure * >( node->GetData() ); bool isMask = false; bool isImage = false; bool isPlanar = false; bool isTensorImage = false; if (selectedTensorImage != NULL) { isTensorImage = true; } else if(selectedImage != NULL) { node->GetPropertyValue("binary", isMask); isImage = !isMask; } else if ( (selectedPlanar != NULL) ) { isPlanar = true; } // image if(isImage && selectedImage->GetDimension()==3) { if(selectedImage != m_SelectedImage.GetPointer()) { somethingChanged = true; if ( (m_SelectedImage.IsNotNull()) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } *m_SelectedImageNodes = node; m_SelectedImage = selectedImage; m_IsTensorImage = false; m_FAImage = NULL; m_RDImage = NULL; m_ADImage = NULL; m_MDImage = NULL; m_CAImage = NULL; m_DirectionComp1Image = NULL; m_DirectionComp2Image = NULL; m_AngularErrorImage = NULL; // Add change listeners to selected objects m_ImageObserverTag = m_SelectedImage->AddObserver( itk::ModifiedEvent(), changeListener ); m_Controls->m_SimilarAnglesFrame->setVisible(false); m_Controls->m_SimilarAnglesLabel->setVisible(false); m_Controls->m_SelectedImageLabel->setText( m_SelectedImageNodes->GetNode()->GetName().c_str() ); } } //planar if(isPlanar) { if(selectedPlanar != m_SelectedPlanarFigure.GetPointer()) { MITK_INFO << "Planar selection changed"; somethingChanged = true; // Possibly previous change listeners if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_PlanarFigureObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_PlanarFigureObserverTag = -1; } if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_InitializedObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_InitializedObserverTag ); m_InitializedObserverTag = -1; } m_SelectedPlanarFigure = selectedPlanar; *m_SelectedPlanarFigureNodes = node; m_CurrentFigureNodeInitialized = selectedPlanar->IsPlaced(); m_SelectedMaskNode = NULL; m_SelectedImageMask = NULL; m_PlanarFigureObserverTag = m_SelectedPlanarFigure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), changeListener ); if(!m_CurrentFigureNodeInitialized) { typedef itk::SimpleMemberCommand< QmitkPartialVolumeAnalysisView > ITKCommandType; ITKCommandType::Pointer initializationCommand; initializationCommand = ITKCommandType::New(); // set the callback function of the member command initializationCommand->SetCallbackFunction( this, &QmitkPartialVolumeAnalysisView::PlanarFigureInitialized ); // add an observer m_InitializedObserverTag = selectedPlanar->AddObserver( mitk::EndPlacementPlanarFigureEvent(), initializationCommand ); } m_Controls->m_SelectedMaskLabel->setText( m_SelectedPlanarFigureNodes->GetNode()->GetName().c_str() ); PlanarFigureFocus(node); } } //mask if(isMask && selectedImage->GetDimension()==3) { if(selectedImage != m_SelectedImage.GetPointer()) { somethingChanged = true; if ( (m_SelectedImageMask.IsNotNull()) && (m_ImageMaskObserverTag >= 0) ) { m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); m_ImageMaskObserverTag = -1; } m_SelectedMaskNode = node; m_SelectedImageMask = selectedImage; m_SelectedPlanarFigure = NULL; m_SelectedPlanarFigureNodes->RemoveAllNodes(); m_ImageMaskObserverTag = m_SelectedImageMask->AddObserver( itk::ModifiedEvent(), changeListener ); m_Controls->m_SelectedMaskLabel->setText( m_SelectedMaskNode->GetName().c_str() ); } } //tensor image if(isTensorImage && selectedTensorImage->GetDimension()==3) { if(selectedImage != m_SelectedImage.GetPointer()) { somethingChanged = true; if ( (m_SelectedImage.IsNotNull()) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } *m_SelectedImageNodes = node; m_SelectedImage = selectedImage; m_IsTensorImage = true; ExtractTensorImages(selectedImage); // Add change listeners to selected objects m_ImageObserverTag = m_SelectedImage->AddObserver( itk::ModifiedEvent(), changeListener ); m_Controls->m_SimilarAnglesFrame->setVisible(true); m_Controls->m_SimilarAnglesLabel->setVisible(true); m_Controls->m_SelectedImageLabel->setText( m_SelectedImageNodes->GetNode()->GetName().c_str() ); } } } if(somethingChanged) { this->SetMeasurementInfoToRenderWindow(""); if(m_SelectedPlanarFigure.IsNull() && m_SelectedImageMask.IsNull() ) { m_Controls->m_SelectedMaskLabel->setText( "-" ); m_Controls->m_ResampleOptionsFrame->setEnabled(false); m_Controls->m_HistogramWidget->setEnabled(false); m_Controls->m_ClassSelector->setEnabled(false); m_Controls->m_DisplayHistogramCheckbox->setEnabled(false); m_Controls->m_AdvancedCheckbox->setEnabled(false); m_Controls->frame_7->setEnabled(false); } else { m_Controls->m_ResampleOptionsFrame->setEnabled(true); m_Controls->m_HistogramWidget->setEnabled(true); m_Controls->m_ClassSelector->setEnabled(true); m_Controls->m_DisplayHistogramCheckbox->setEnabled(true); m_Controls->m_AdvancedCheckbox->setEnabled(true); m_Controls->frame_7->setEnabled(true); } // Clear statistics / histogram GUI if nothing is selected if ( m_SelectedImage.IsNull() ) { m_Controls->m_PlanarFigureButtonsFrame->setEnabled(false); m_Controls->m_OpacityFrame->setEnabled(false); m_Controls->m_SelectedImageLabel->setText( "-" ); } else { m_Controls->m_PlanarFigureButtonsFrame->setEnabled(true); m_Controls->m_OpacityFrame->setEnabled(true); } if( m_SelectedImage.IsNull() || (m_SelectedPlanarFigure.IsNull() && m_SelectedImageMask.IsNull()) ) { m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; } else { this->RequestStatisticsUpdate(); } } } void QmitkPartialVolumeAnalysisView::ShowClusteringResults() { typedef itk::Image MaskImageType; mitk::Image::Pointer mask = 0; MaskImageType::Pointer itkmask = 0; if(m_IsTensorImage && m_Controls->m_SimilarAnglesSlider->value() != 0) { typedef itk::Image AngularErrorImageType; typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(m_AngularErrorImage); caster->Update(); typedef itk::BinaryThresholdImageFilter< AngularErrorImageType, MaskImageType > ThreshType; ThreshType::Pointer thresh = ThreshType::New(); thresh->SetUpperThreshold((90-m_Controls->m_SimilarAnglesSlider->value())*(PVA_PI/180.0)); thresh->SetInsideValue(1.0); thresh->SetInput(caster->GetOutput()); thresh->Update(); itkmask = thresh->GetOutput(); mask = mitk::Image::New(); mask->InitializeByItk(itkmask.GetPointer()); mask->SetVolume(itkmask->GetBufferPointer()); // GetDefaultDataStorage()->Remove(m_newnode); // m_newnode = mitk::DataNode::New(); // m_newnode->SetData(mask); // m_newnode->SetName("masking node"); // m_newnode->SetIntProperty( "layer", 1002 ); // GetDefaultDataStorage()->Add(m_newnode, m_SelectedImageNodes->GetNode()); } mitk::Image::Pointer clusteredImage; ClusteringType::Pointer clusterer = ClusteringType::New(); if(m_QuantifyClass==3) { if(m_IsTensorImage) { double *green_fa, *green_rd, *green_ad, *green_md; //double *greengray_fa, *greengray_rd, *greengray_ad, *greengray_md; double *gray_fa, *gray_rd, *gray_ad, *gray_md; //double *redgray_fa, *redgray_rd, *redgray_ad, *redgray_md; double *red_fa, *red_rd, *red_ad, *red_md; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(0); mitk::Image::ConstPointer imgToCluster = tmpImg; red_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->b, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(3); mitk::Image::ConstPointer imgToCluster3 = tmpImg; red_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentRGBClusteringResults->rgbChannels->b, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(4); mitk::Image::ConstPointer imgToCluster4 = tmpImg; red_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentRGBClusteringResults->rgbChannels->b, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(5); mitk::Image::ConstPointer imgToCluster5 = tmpImg; red_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentRGBClusteringResults->rgbChannels->b, mask); // clipboard QString clipboardText("FA\t%1\t%2\t\t%3\t%4\t\t%5\t%6\t"); clipboardText = clipboardText .arg(red_fa[0]).arg(red_fa[1]) .arg(gray_fa[0]).arg(gray_fa[1]) .arg(green_fa[0]).arg(green_fa[1]); QString clipboardText3("RD\t%1\t%2\t\t%3\t%4\t\t%5\t%6\t"); clipboardText3 = clipboardText3 .arg(red_rd[0]).arg(red_rd[1]) .arg(gray_rd[0]).arg(gray_rd[1]) .arg(green_rd[0]).arg(green_rd[1]); QString clipboardText4("AD\t%1\t%2\t\t%3\t%4\t\t%5\t%6\t"); clipboardText4 = clipboardText4 .arg(red_ad[0]).arg(red_ad[1]) .arg(gray_ad[0]).arg(gray_ad[1]) .arg(green_ad[0]).arg(green_ad[1]); QString clipboardText5("MD\t%1\t%2\t\t%3\t%4\t\t%5\t%6"); clipboardText5 = clipboardText5 .arg(red_md[0]).arg(red_md[1]) .arg(gray_md[0]).arg(gray_md[1]) .arg(green_md[0]).arg(green_md[1]); QApplication::clipboard()->setText(clipboardText+clipboardText3+clipboardText4+clipboardText5, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("%1 %2 %3 \n"); plainInfoText = plainInfoText .arg("Red ", 20) .arg("Gray ", 20) .arg("Green", 20); QString plainInfoText0("FA:%1 ± %2%3 ± %4%5 ± %6\n"); plainInfoText0 = plainInfoText0 .arg(red_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(red_fa[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(gray_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(gray_fa[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(green_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(green_fa[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText3("RDx10³:%1 ± %2%3 ± %4%5 ± %6\n"); plainInfoText3 = plainInfoText3 .arg(1000.0 * red_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_rd[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * gray_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * gray_rd[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * green_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * green_rd[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText4("ADx10³:%1 ± %2%3 ± %4%5 ± %6\n"); plainInfoText4 = plainInfoText4 .arg(1000.0 * red_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_ad[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * gray_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * gray_ad[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * green_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * green_ad[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText5("MDx10³:%1 ± %2%3 ± %4%5 ± %6"); plainInfoText5 = plainInfoText5 .arg(1000.0 * red_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_md[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * gray_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * gray_md[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * green_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * green_md[1], -10, 'g', 2, QLatin1Char( ' ' )); this->SetMeasurementInfoToRenderWindow(plainInfoText+plainInfoText0+plainInfoText3+plainInfoText4+plainInfoText5); } else { double* green; double* gray; double* red; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; red = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->r); green = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->g); gray = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->b); // clipboard QString clipboardText("%1\t%2\t\t%3\t%4\t\t%5\t%6"); clipboardText = clipboardText.arg(red[0]).arg(red[1]) .arg(gray[0]).arg(gray[1]) .arg(green[0]).arg(green[1]); QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("Red: %1 ± %2\nGray: %3 ± %4\nGreen: %5 ± %6"); plainInfoText = plainInfoText.arg(red[0]).arg(red[1]) .arg(gray[0]).arg(gray[1]) .arg(green[0]).arg(green[1]); this->SetMeasurementInfoToRenderWindow(plainInfoText); } clusteredImage = m_CurrentRGBClusteringResults->rgb; } else { if(m_IsTensorImage) { double *red_fa, *red_rd, *red_ad, *red_md; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(0); mitk::Image::ConstPointer imgToCluster = tmpImg; red_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentPerformClusteringResults->clusteredImage, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(3); mitk::Image::ConstPointer imgToCluster3 = tmpImg; red_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentPerformClusteringResults->clusteredImage, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(4); mitk::Image::ConstPointer imgToCluster4 = tmpImg; red_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentPerformClusteringResults->clusteredImage, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(5); mitk::Image::ConstPointer imgToCluster5 = tmpImg; red_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentPerformClusteringResults->clusteredImage, mask); // clipboard QString clipboardText("FA\t%1\t%2\t"); clipboardText = clipboardText .arg(red_fa[0]).arg(red_fa[1]); QString clipboardText3("RD\t%1\t%2\t"); clipboardText3 = clipboardText3 .arg(red_rd[0]).arg(red_rd[1]); QString clipboardText4("AD\t%1\t%2\t"); clipboardText4 = clipboardText4 .arg(red_ad[0]).arg(red_ad[1]); QString clipboardText5("MD\t%1\t%2\t"); clipboardText5 = clipboardText5 .arg(red_md[0]).arg(red_md[1]); QApplication::clipboard()->setText(clipboardText+clipboardText3+clipboardText4+clipboardText5, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("%1 \n"); plainInfoText = plainInfoText .arg("Red ", 20); QString plainInfoText0("FA:%1 ± %2\n"); plainInfoText0 = plainInfoText0 .arg(red_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(red_fa[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText3("RDx10³:%1 ± %2\n"); plainInfoText3 = plainInfoText3 .arg(1000.0 * red_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_rd[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText4("ADx10³:%1 ± %2\n"); plainInfoText4 = plainInfoText4 .arg(1000.0 * red_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_ad[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText5("MDx10³:%1 ± %2"); plainInfoText5 = plainInfoText5 .arg(1000.0 * red_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_md[1], -10, 'g', 2, QLatin1Char( ' ' )); this->SetMeasurementInfoToRenderWindow(plainInfoText+plainInfoText0+plainInfoText3+plainInfoText4+plainInfoText5); } else { double* quant; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; quant = clusterer->PerformQuantification(imgToCluster, m_CurrentPerformClusteringResults->clusteredImage); // clipboard QString clipboardText("%1\t%2"); clipboardText = clipboardText.arg(quant[0]).arg(quant[1]); QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("Measurement: %1 ± %2"); plainInfoText = plainInfoText.arg(quant[0]).arg(quant[1]); this->SetMeasurementInfoToRenderWindow(plainInfoText); } clusteredImage = m_CurrentPerformClusteringResults->displayImage; } if(mask.IsNotNull()) { typedef itk::Image,3> RGBImageType; typedef mitk::ImageToItk ClusterCasterType; ClusterCasterType::Pointer clCaster = ClusterCasterType::New(); clCaster->SetInput(clusteredImage); clCaster->Update(); clCaster->GetOutput(); typedef itk::MaskImageFilter< RGBImageType, MaskImageType, RGBImageType > MaskType; MaskType::Pointer masker = MaskType::New(); masker->SetInput1(clCaster->GetOutput()); masker->SetInput2(itkmask); masker->Update(); clusteredImage = mitk::Image::New(); clusteredImage->InitializeByItk(masker->GetOutput()); clusteredImage->SetVolume(masker->GetOutput()->GetBufferPointer()); } if(m_ClusteringResult.IsNotNull()) { this->GetDataStorage()->Remove(m_ClusteringResult); } m_ClusteringResult = mitk::DataNode::New(); m_ClusteringResult->SetBoolProperty("helper object", true); m_ClusteringResult->SetIntProperty( "layer", 1000 ); m_ClusteringResult->SetBoolProperty("texture interpolation", m_TexIsOn); m_ClusteringResult->SetData(clusteredImage); m_ClusteringResult->SetName("Clusterprobs"); this->GetDataStorage()->Add(m_ClusteringResult, m_SelectedImageNodes->GetNode()); if(m_SelectedPlanarFigure.IsNotNull() && m_SelectedPlanarFigureNodes->GetNode().IsNotNull()) { m_SelectedPlanarFigureNodes->GetNode()->SetIntProperty( "layer", 1001 ); } this->RequestRenderWindowUpdate(); } void QmitkPartialVolumeAnalysisView::UpdateStatistics() { MITK_INFO << "UpdateStatistics()"; if(!m_CurrentFigureNodeInitialized && m_SelectedPlanarFigure.IsNotNull()) { MITK_INFO << "Selected planar figure not initialized. No stats calculation performed."; return; } // Remove any cached images that are no longer referenced elsewhere this->RemoveOrphanImages(); QmitkStdMultiWidget *multiWidget = 0; QmitkStdMultiWidgetEditor * multiWidgetEdit = 0; multiWidgetEdit = dynamic_cast(this->GetRenderWindowPart()); if(multiWidgetEdit){ multiWidget = multiWidgetEdit->GetStdMultiWidget(); } if ( multiWidget == NULL ) { return; } if ( m_SelectedImage.IsNotNull() ) { // Check if a the selected image is a multi-channel image. If yes, statistics // cannot be calculated currently. if ( !m_IsTensorImage && m_SelectedImage->GetPixelType().GetNumberOfComponents() > 1 ) { QMessageBox::information( NULL, "Warning", "Non-tensor multi-component images not supported."); m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; return; } // Retrieve HistogramStatisticsCalculator from has map (or create a new one // for this image if non-existant) PartialVolumeAnalysisMapType::iterator it = m_PartialVolumeAnalysisMap.find( m_SelectedImage ); if ( it != m_PartialVolumeAnalysisMap.end() ) { m_CurrentStatisticsCalculator = it->second; MITK_INFO << "Retrieving StatisticsCalculator"; } else { m_CurrentStatisticsCalculator = mitk::PartialVolumeAnalysisHistogramCalculator::New(); m_CurrentStatisticsCalculator->SetPlanarFigureThickness(m_Controls->m_PlanarFiguresThickness->value()); if(m_IsTensorImage) { m_CurrentStatisticsCalculator->SetImage( m_CAImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_FAImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_DirectionComp1Image ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_DirectionComp2Image ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_RDImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_ADImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_MDImage ); } else { m_CurrentStatisticsCalculator->SetImage( m_SelectedImage ); } m_PartialVolumeAnalysisMap[m_SelectedImage] = m_CurrentStatisticsCalculator; MITK_INFO << "Creating StatisticsCalculator"; } std::string maskName; std::string maskType; unsigned int maskDimension; if ( m_SelectedImageMask.IsNotNull() ) { mitk::PixelType pixelType = m_SelectedImageMask->GetPixelType(); std::cout << pixelType.GetItkTypeAsString() << std::endl; if(pixelType.GetBitsPerComponent() == 16) { //convert from short to uchar typedef itk::Image ShortImageType; typedef itk::Image CharImageType; CharImageType::Pointer charImage; ShortImageType::Pointer shortImage; mitk::CastToItkImage(m_SelectedImageMask, shortImage); typedef itk::CastImageFilter ImageCasterType; ImageCasterType::Pointer caster = ImageCasterType::New(); caster->SetInput( shortImage ); caster->Update(); charImage = caster->GetOutput(); mitk::CastToMitkImage(charImage, m_SelectedImageMask); } m_CurrentStatisticsCalculator->SetImageMask( m_SelectedImageMask ); m_CurrentStatisticsCalculator->SetMaskingModeToImage(); maskName = m_SelectedMaskNode->GetName(); maskType = m_SelectedImageMask->GetNameOfClass(); maskDimension = 3; std::stringstream maskLabel; maskLabel << maskName; if ( maskDimension > 0 ) { maskLabel << " [" << maskDimension << "D " << maskType << "]"; } m_Controls->m_SelectedMaskLabel->setText( maskLabel.str().c_str() ); } else if ( m_SelectedPlanarFigure.IsNotNull() && m_SelectedPlanarFigureNodes->GetNode().IsNotNull()) { m_CurrentStatisticsCalculator->SetPlanarFigure( m_SelectedPlanarFigure ); m_CurrentStatisticsCalculator->SetMaskingModeToPlanarFigure(); maskName = m_SelectedPlanarFigureNodes->GetNode()->GetName(); maskType = m_SelectedPlanarFigure->GetNameOfClass(); maskDimension = 2; } else { m_CurrentStatisticsCalculator->SetMaskingModeToNone(); maskName = "-"; maskType = ""; maskDimension = 0; } bool statisticsChanged = false; bool statisticsCalculationSuccessful = false; // Initialize progress bar mitk::ProgressBar::GetInstance()->AddStepsToDo( 100 ); // Install listener for progress events and initialize progress bar typedef itk::SimpleMemberCommand< QmitkPartialVolumeAnalysisView > ITKCommandType; ITKCommandType::Pointer progressListener; progressListener = ITKCommandType::New(); progressListener->SetCallbackFunction( this, &QmitkPartialVolumeAnalysisView::UpdateProgressBar ); unsigned long progressObserverTag = m_CurrentStatisticsCalculator ->AddObserver( itk::ProgressEvent(), progressListener ); ClusteringType::ParamsType *cparams = 0; ClusteringType::ClusterResultType *cresult = 0; ClusteringType::HistType *chist = 0; try { m_CurrentStatisticsCalculator->SetNumberOfBins(m_Controls->m_NumberBins->text().toInt()); m_CurrentStatisticsCalculator->SetUpsamplingFactor(m_Controls->m_Upsampling->text().toDouble()); m_CurrentStatisticsCalculator->SetGaussianSigma(m_Controls->m_GaussianSigma->text().toDouble()); // Compute statistics statisticsChanged = m_CurrentStatisticsCalculator->ComputeStatistics( ); mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; if(imgToCluster.IsNotNull()) { // perform clustering const HistogramType *histogram = m_CurrentStatisticsCalculator->GetHistogram( ); if(histogram != NULL) { ClusteringType::Pointer clusterer = ClusteringType::New(); clusterer->SetStepsNumIntegration(200); clusterer->SetMaxIt(1000); mitk::Image::Pointer pFiberImg; if(m_QuantifyClass==3) { if(m_Controls->m_Quantiles->isChecked()) { m_CurrentRGBClusteringResults = clusterer->PerformRGBQuantiles(imgToCluster, histogram, m_Controls->m_q1->value(),m_Controls->m_q2->value()); } else { m_CurrentRGBClusteringResults = clusterer->PerformRGBClustering(imgToCluster, histogram); } pFiberImg = m_CurrentRGBClusteringResults->rgbChannels->r; cparams = m_CurrentRGBClusteringResults->params; cresult = m_CurrentRGBClusteringResults->result; chist = m_CurrentRGBClusteringResults->hist; } else { if(m_Controls->m_Quantiles->isChecked()) { m_CurrentPerformClusteringResults = clusterer->PerformQuantiles(imgToCluster, histogram, m_Controls->m_q1->value(),m_Controls->m_q2->value()); } else { m_CurrentPerformClusteringResults = clusterer->PerformClustering(imgToCluster, histogram, m_QuantifyClass); } pFiberImg = m_CurrentPerformClusteringResults->clusteredImage; cparams = m_CurrentPerformClusteringResults->params; cresult = m_CurrentPerformClusteringResults->result; chist = m_CurrentPerformClusteringResults->hist; } if(m_IsTensorImage) { m_AngularErrorImage = clusterer->CaculateAngularErrorImage( m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(1), m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(2), pFiberImg); // GetDefaultDataStorage()->Remove(m_newnode2); // m_newnode2 = mitk::DataNode::New(); // m_newnode2->SetData(m_AngularErrorImage); // m_newnode2->SetName(("AngularError")); // m_newnode2->SetIntProperty( "layer", 1003 ); // GetDefaultDataStorage()->Add(m_newnode2, m_SelectedImageNodes->GetNode()); // newnode = mitk::DataNode::New(); // newnode->SetData(m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(1)); // newnode->SetName(("Comp1")); // GetDefaultDataStorage()->Add(newnode, m_SelectedImageNodes->GetNode()); // newnode = mitk::DataNode::New(); // newnode->SetData(m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(2)); // newnode->SetName(("Comp2")); // GetDefaultDataStorage()->Add(newnode, m_SelectedImageNodes->GetNode()); } ShowClusteringResults(); } } statisticsCalculationSuccessful = true; } catch ( const std::runtime_error &e ) { QMessageBox::information( NULL, "Warning", e.what()); } catch ( const std::exception &e ) { MITK_ERROR << "Caught exception: " << e.what(); QMessageBox::information( NULL, "Warning", e.what()); } m_CurrentStatisticsCalculator->RemoveObserver( progressObserverTag ); // Make sure that progress bar closes mitk::ProgressBar::GetInstance()->Progress( 100 ); if ( statisticsCalculationSuccessful ) { if ( statisticsChanged ) { // Do not show any error messages m_CurrentStatisticsValid = true; } // m_Controls->m_HistogramWidget->SetHistogramModeToDirectHistogram(); m_Controls->m_HistogramWidget->SetParameters( cparams, cresult, chist ); // m_Controls->m_HistogramWidget->UpdateItemModelFromHistogram(); } else { m_Controls->m_SelectedMaskLabel->setText( "-" ); // Clear statistics and histogram m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; // If a (non-closed) PlanarFigure is selected, display a line profile widget if ( m_SelectedPlanarFigure.IsNotNull() ) { // TODO: enable line profile widget //m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 1 ); //m_Controls->m_LineProfileWidget->SetImage( m_SelectedImage ); //m_Controls->m_LineProfileWidget->SetPlanarFigure( m_SelectedPlanarFigure ); //m_Controls->m_LineProfileWidget->UpdateItemModelFromPath(); } } } } void QmitkPartialVolumeAnalysisView::SetMeasurementInfoToRenderWindow(const QString& text) { FindRenderWindow(m_SelectedPlanarFigureNodes->GetNode()); if(m_LastRenderWindow != m_SelectedRenderWindow) { if(m_LastRenderWindow) { QObject::disconnect( m_LastRenderWindow, SIGNAL( destroyed(QObject*) ) , this, SLOT( OnRenderWindowDelete(QObject*) ) ); } m_LastRenderWindow = m_SelectedRenderWindow; if(m_LastRenderWindow) { QObject::connect( m_LastRenderWindow, SIGNAL( destroyed(QObject*) ) , this, SLOT( OnRenderWindowDelete(QObject*) ) ); } } if(m_LastRenderWindow && m_SelectedPlanarFigureNodes->GetNode().IsNotNull()) { if (!text.isEmpty()) { m_MeasurementInfoAnnotation->SetText(1, text.toLatin1().data()); mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->InsertForegroundRenderer( m_MeasurementInfoRenderer, true); } else { if (mitk::VtkLayerController::GetInstance( m_LastRenderWindow->GetRenderWindow()) ->IsRendererInserted( m_MeasurementInfoRenderer)) mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->RemoveRenderer( m_MeasurementInfoRenderer); } } else { QmitkStdMultiWidget *multiWidget = 0; QmitkStdMultiWidgetEditor * multiWidgetEdit = 0; multiWidgetEdit = dynamic_cast(this->GetRenderWindowPart()); if(multiWidgetEdit){ multiWidget = multiWidgetEdit->GetStdMultiWidget(); } if ( multiWidget == NULL ) { return; } if (!text.isEmpty()) { m_MeasurementInfoAnnotation->SetText(1, text.toLatin1().data()); mitk::VtkLayerController::GetInstance(multiWidget->GetRenderWindow1()->GetRenderWindow())->InsertForegroundRenderer( m_MeasurementInfoRenderer, true); } else { if (mitk::VtkLayerController::GetInstance( multiWidget->GetRenderWindow1()->GetRenderWindow()) ->IsRendererInserted( m_MeasurementInfoRenderer)) mitk::VtkLayerController::GetInstance(multiWidget->GetRenderWindow1()->GetRenderWindow())->RemoveRenderer( m_MeasurementInfoRenderer); } } } void QmitkPartialVolumeAnalysisView::UpdateProgressBar() { mitk::ProgressBar::GetInstance()->Progress(); } void QmitkPartialVolumeAnalysisView::RequestStatisticsUpdate() { if ( !m_StatisticsUpdatePending ) { QApplication::postEvent( this, new QmitkRequestStatisticsUpdateEvent ); m_StatisticsUpdatePending = true; } } void QmitkPartialVolumeAnalysisView::RemoveOrphanImages() { PartialVolumeAnalysisMapType::iterator it = m_PartialVolumeAnalysisMap.begin(); while ( it != m_PartialVolumeAnalysisMap.end() ) { mitk::Image *image = it->first; mitk::PartialVolumeAnalysisHistogramCalculator *calculator = it->second; ++it; mitk::NodePredicateData::Pointer hasImage = mitk::NodePredicateData::New( image ); if ( this->GetDataStorage()->GetNode( hasImage ) == NULL ) { if ( m_SelectedImage == image ) { m_SelectedImage = NULL; m_SelectedImageNodes->RemoveAllNodes(); } if ( m_CurrentStatisticsCalculator == calculator ) { m_CurrentStatisticsCalculator = NULL; } m_PartialVolumeAnalysisMap.erase( image ); it = m_PartialVolumeAnalysisMap.begin(); } } } void QmitkPartialVolumeAnalysisView::ExtractTensorImages( mitk::Image::ConstPointer tensorimage) { typedef itk::Image< itk::DiffusionTensor3D, 3> TensorImageType; typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(tensorimage); caster->Update(); TensorImageType::Pointer image = caster->GetOutput(); typedef itk::TensorDerivedMeasurementsFilter MeasurementsType; MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::FA); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer fa = measurementsCalculator->GetOutput(); m_FAImage = mitk::Image::New(); m_FAImage->InitializeByItk(fa.GetPointer()); m_FAImage->SetVolume(fa->GetBufferPointer()); // mitk::DataNode::Pointer node = mitk::DataNode::New(); // node->SetData(m_FAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::CA); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer ca = measurementsCalculator->GetOutput(); m_CAImage = mitk::Image::New(); m_CAImage->InitializeByItk(ca.GetPointer()); m_CAImage->SetVolume(ca->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::RD); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer rd = measurementsCalculator->GetOutput(); m_RDImage = mitk::Image::New(); m_RDImage->InitializeByItk(rd.GetPointer()); m_RDImage->SetVolume(rd->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::AD); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer ad = measurementsCalculator->GetOutput(); m_ADImage = mitk::Image::New(); m_ADImage->InitializeByItk(ad.GetPointer()); m_ADImage->SetVolume(ad->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::RA); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer md = measurementsCalculator->GetOutput(); m_MDImage = mitk::Image::New(); m_MDImage->InitializeByItk(md.GetPointer()); m_MDImage->SetVolume(md->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); typedef DirectionsFilterType::OutputImageType DirImageType; DirectionsFilterType::Pointer dirFilter = DirectionsFilterType::New(); dirFilter->SetInput(image ); dirFilter->Update(); itk::ImageRegionIterator itd(dirFilter->GetOutput(), dirFilter->GetOutput()->GetLargestPossibleRegion()); itd = itd.Begin(); while( !itd.IsAtEnd() ) { DirImageType::PixelType direction = itd.Get(); direction[0] = fabs(direction[0]); direction[1] = fabs(direction[1]); direction[2] = fabs(direction[2]); itd.Set(direction); ++itd; } typedef itk::CartesianToPolarVectorImageFilter< DirImageType, DirImageType, true> C2PFilterType; C2PFilterType::Pointer cpFilter = C2PFilterType::New(); cpFilter->SetInput(dirFilter->GetOutput()); cpFilter->Update(); DirImageType::Pointer dir = cpFilter->GetOutput(); typedef itk::Image CompImageType; CompImageType::Pointer comp1 = CompImageType::New(); comp1->SetSpacing( dir->GetSpacing() ); // Set the image spacing comp1->SetOrigin( dir->GetOrigin() ); // Set the image origin comp1->SetDirection( dir->GetDirection() ); // Set the image direction comp1->SetRegions( dir->GetLargestPossibleRegion() ); comp1->Allocate(); CompImageType::Pointer comp2 = CompImageType::New(); comp2->SetSpacing( dir->GetSpacing() ); // Set the image spacing comp2->SetOrigin( dir->GetOrigin() ); // Set the image origin comp2->SetDirection( dir->GetDirection() ); // Set the image direction comp2->SetRegions( dir->GetLargestPossibleRegion() ); comp2->Allocate(); itk::ImageRegionConstIterator it(dir, dir->GetLargestPossibleRegion()); itk::ImageRegionIterator it1(comp1, comp1->GetLargestPossibleRegion()); itk::ImageRegionIterator it2(comp2, comp2->GetLargestPossibleRegion()); it = it.Begin(); it1 = it1.Begin(); it2 = it2.Begin(); while( !it.IsAtEnd() ) { it1.Set(it.Get()[1]); it2.Set(it.Get()[2]); ++it; ++it1; ++it2; } m_DirectionComp1Image = mitk::Image::New(); m_DirectionComp1Image->InitializeByItk(comp1.GetPointer()); m_DirectionComp1Image->SetVolume(comp1->GetBufferPointer()); m_DirectionComp2Image = mitk::Image::New(); m_DirectionComp2Image->InitializeByItk(comp2.GetPointer()); m_DirectionComp2Image->SetVolume(comp2->GetBufferPointer()); } void QmitkPartialVolumeAnalysisView::OnRenderWindowDelete(QObject * obj) { if(obj == m_LastRenderWindow) m_LastRenderWindow = 0; if(obj == m_SelectedRenderWindow) m_SelectedRenderWindow = 0; } bool QmitkPartialVolumeAnalysisView::event( QEvent *event ) { if ( event->type() == (QEvent::Type) QmitkRequestStatisticsUpdateEvent::StatisticsUpdateRequest ) { // Update statistics m_StatisticsUpdatePending = false; this->UpdateStatistics(); return true; } return false; } bool QmitkPartialVolumeAnalysisView::IsExclusiveFunctionality() const { return true; } void QmitkPartialVolumeAnalysisView::Activated() { MITK_INFO << "QmitkPartialVolumeAnalysisView:Activated"; //this->GetActiveStdMultiWidget()->SetWidgetPlanesVisibility(false); //this->GetActiveStdMultiWidget()->GetRenderWindow1()->FullScreenMode(true); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigure* figure = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; // finally add all nodes to the model for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } m_Visible = true; } void QmitkPartialVolumeAnalysisView::Deactivated() { MITK_INFO << "QmitkPartialVolumeAnalysisView:Deactivated"; } void QmitkPartialVolumeAnalysisView::ActivatedZombieView(berry::IWorkbenchPartReference::Pointer reference) { MITK_INFO << "QmitkPartialVolumeAnalysisView:ActivatedZombieView"; //this->GetActiveStdMultiWidget()->SetWidgetPlanesVisibility(true); this->SetMeasurementInfoToRenderWindow(""); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigure* figure = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; // finally add all nodes to the model for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(figureInteractor); } } m_Visible = false; } void QmitkPartialVolumeAnalysisView::Hidden() { } void QmitkPartialVolumeAnalysisView::Visible() { //this->OnSelectionChanged( this->Get, this->GetDataManagerSelection() ); } void QmitkPartialVolumeAnalysisView::SetFocus() { } void QmitkPartialVolumeAnalysisView::GreenRadio(bool checked) { if(checked) { m_Controls->m_PartialVolumeRadio->setChecked(false); m_Controls->m_BlueRadio->setChecked(false); m_Controls->m_AllRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(true); } m_QuantifyClass = 0; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::PartialVolumeRadio(bool checked) { if(checked) { m_Controls->m_GreenRadio->setChecked(false); m_Controls->m_BlueRadio->setChecked(false); m_Controls->m_AllRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(true); } m_QuantifyClass = 1; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::BlueRadio(bool checked) { if(checked) { m_Controls->m_PartialVolumeRadio->setChecked(false); m_Controls->m_GreenRadio->setChecked(false); m_Controls->m_AllRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(true); } m_QuantifyClass = 2; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::AllRadio(bool checked) { if(checked) { m_Controls->m_BlueRadio->setChecked(false); m_Controls->m_PartialVolumeRadio->setChecked(false); m_Controls->m_GreenRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(false); } m_QuantifyClass = 3; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::NumberBinsChangedSlider(int v ) { m_Controls->m_NumberBins->setText(QString("%1").arg(m_Controls->m_NumberBinsSlider->value()*5.0)); } void QmitkPartialVolumeAnalysisView::UpsamplingChangedSlider( int v) { m_Controls->m_Upsampling->setText(QString("%1").arg(m_Controls->m_UpsamplingSlider->value()/10.0)); } void QmitkPartialVolumeAnalysisView::GaussianSigmaChangedSlider(int v ) { m_Controls->m_GaussianSigma->setText(QString("%1").arg(m_Controls->m_GaussianSigmaSlider->value()/100.0)); } void QmitkPartialVolumeAnalysisView::SimilarAnglesChangedSlider(int v ) { m_Controls->m_SimilarAngles->setText(QString("%1°").arg(90-m_Controls->m_SimilarAnglesSlider->value())); ShowClusteringResults(); } void QmitkPartialVolumeAnalysisView::OpacityChangedSlider(int v ) { if(m_SelectedImageNodes->GetNode().IsNotNull()) { float opacImag = 1.0f-(v-5)/5.0f; opacImag = opacImag < 0 ? 0 : opacImag; m_SelectedImageNodes->GetNode()->SetFloatProperty("opacity", opacImag); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if(m_ClusteringResult.IsNotNull()) { float opacClust = v/5.0f; opacClust = opacClust > 1 ? 1 : opacClust; m_ClusteringResult->SetFloatProperty("opacity", opacClust); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkPartialVolumeAnalysisView::NumberBinsReleasedSlider( ) { RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::UpsamplingReleasedSlider( ) { RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::GaussianSigmaReleasedSlider( ) { RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::SimilarAnglesReleasedSlider( ) { } void QmitkPartialVolumeAnalysisView::ToClipBoard() { std::vector* > vals = m_Controls->m_HistogramWidget->m_Vals; QString clipboardText; for (std::vector* >::iterator it = vals.begin(); it != vals.end(); ++it) { for (std::vector::iterator it2 = (**it).begin(); it2 != (**it).end(); ++it2) { clipboardText.append(QString("%1 \t").arg(*it2)); } clipboardText.append(QString("\n")); } QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); } void QmitkPartialVolumeAnalysisView::PropertyChanged(const mitk::DataNode* /*node*/, const mitk::BaseProperty* /*prop*/) { } void QmitkPartialVolumeAnalysisView::NodeChanged(const mitk::DataNode* /*node*/) { } void QmitkPartialVolumeAnalysisView::NodeRemoved(const mitk::DataNode* node) { if (dynamic_cast(node->GetData())) this->GetDataStorage()->Remove(m_ClusteringResult); if( node == m_SelectedPlanarFigureNodes->GetNode().GetPointer() || node == m_SelectedMaskNode.GetPointer() ) { this->Select(NULL,true,false); SetMeasurementInfoToRenderWindow(""); } if( node == m_SelectedImageNodes->GetNode().GetPointer() ) { this->Select(NULL,false,true); SetMeasurementInfoToRenderWindow(""); } } void QmitkPartialVolumeAnalysisView::NodeAddedInDataStorage(const mitk::DataNode* node) { if(!m_Visible) return; mitk::DataNode* nonConstNode = const_cast(node); mitk::PlanarFigure* figure = dynamic_cast(nonConstNode->GetData()); if(figure) { // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", nonConstNode); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); // remove uninitialized old planars if( m_SelectedPlanarFigureNodes->GetNode().IsNotNull() && m_CurrentFigureNodeInitialized == false ) { mitk::Interactor::Pointer oldInteractor = m_SelectedPlanarFigureNodes->GetNode()->GetInteractor(); if(oldInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(oldInteractor); this->GetDataStorage()->Remove(m_SelectedPlanarFigureNodes->GetNode()); } } } void QmitkPartialVolumeAnalysisView::TextIntON() { if(m_ClusteringResult.IsNotNull()) { if(m_TexIsOn) { m_Controls->m_TextureIntON->setIcon(*m_IconTexOFF); } else { m_Controls->m_TextureIntON->setIcon(*m_IconTexON); } m_ClusteringResult->SetBoolProperty("texture interpolation", !m_TexIsOn); m_TexIsOn = !m_TexIsOn; this->RequestRenderWindowUpdate(); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.h index df2d207363..2ef65ee1dc 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.h @@ -1,281 +1,280 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 20:08:26 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QmitkPartialVolumeAnalysisView_H__INCLUDED) #define QmitkPartialVolumeAnalysisView_H__INCLUDED //#include "QmitkFunctionality.h" #include "ui_QmitkPartialVolumeAnalysisViewControls.h" #include #include #include // berry #include #include // itk #include #include "itkDiffusionTensorPrincipleDirectionImageFilter.h" #include // qmitk #include "QmitkStepperAdapter.h" #include "QmitkRenderWindow.h" // mitk #include "mitkPartialVolumeAnalysisHistogramCalculator.h" #include "mitkPlanarLine.h" #include #include "mitkDataStorageSelection.h" #include // vtk #include #include #include //#include "itkProcessObject.h" /*! \brief QmitkPartialVolumeAnalysis \sa QmitkFunctionality \ingroup Functionalities */ class QmitkPartialVolumeAnalysisView : public QmitkAbstractView, public mitk::IZombieViewPart//, public itk::ProcessObject { Q_OBJECT public: /*! \ Convenient typedefs */ typedef mitk::DataStorage::SetOfObjects ConstVector; typedef ConstVector::ConstPointer ConstVectorPointer; typedef ConstVector::ConstIterator ConstVectorIterator; typedef mitk::PartialVolumeAnalysisHistogramCalculator HistogramCalculatorType; typedef HistogramCalculatorType::HistogramType HistogramType; typedef mitk::PartialVolumeAnalysisClusteringCalculator ClusteringType; typedef itk::DiffusionTensorPrincipleDirectionImageFilter DirectionsFilterType; /*! \brief default constructor */ QmitkPartialVolumeAnalysisView(QObject *parent=0, const char *name=0); /*! \brief default destructor */ virtual ~QmitkPartialVolumeAnalysisView(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); bool IsExclusiveFunctionality() const; virtual bool event( QEvent *event ); virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes); virtual void Activated(); virtual void Deactivated(); virtual void ActivatedZombieView(berry::IWorkbenchPartReference::Pointer reference); virtual void Hidden(); virtual void Visible(); virtual void SetFocus(); bool AssertDrawingIsPossible(bool checked); virtual void NodeChanged(const mitk::DataNode* node); virtual void PropertyChanged(const mitk::DataNode* node, const mitk::BaseProperty* prop); virtual void NodeRemoved(const mitk::DataNode* node); virtual void NodeAddedInDataStorage(const mitk::DataNode* node); virtual void AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey = NULL, mitk::BaseProperty *property = NULL ); void PlanarFigureInitialized(); void PlanarFigureFocus(mitk::DataNode* node); void ShowClusteringResults(); static const std::string VIEW_ID; protected slots: void EstimateCircle(); void SetHistogramVisibility(); void SetAdvancedVisibility(); void NumberBinsChangedSlider(int v ); void UpsamplingChangedSlider( int v ); void GaussianSigmaChangedSlider( int v ); void SimilarAnglesChangedSlider(int v ); void OpacityChangedSlider(int v ); void NumberBinsReleasedSlider( ); void UpsamplingReleasedSlider( ); void GaussianSigmaReleasedSlider( ); void SimilarAnglesReleasedSlider( ); void ActionDrawEllipseTriggered(); void ActionDrawRectangleTriggered(); void ActionDrawPolygonTriggered(); void ToClipBoard(); void GreenRadio(bool checked); void PartialVolumeRadio(bool checked); void BlueRadio(bool checked); void AllRadio(bool checked); void OnRenderWindowDelete(QObject * obj); void TextIntON(); void ExportClusteringResults(); protected: //void StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ); /** \brief Issues a request to update statistics by sending an event to the * Qt event processing queue. * * Statistics update should only be executed after program execution returns * to the Qt main loop. This mechanism also prevents multiple execution of * updates where only one is required.*/ void RequestStatisticsUpdate(); /** \brief Recalculate statistics for currently selected image and mask and * update the GUI. */ void UpdateStatistics(); /** \brief Listener for progress events to update progress bar. */ void UpdateProgressBar(); /** \brief Removes any cached images which are no longer referenced elsewhere. */ void RemoveOrphanImages(); void Select( mitk::DataNode::Pointer node, bool clearMaskOnFirstArgNULL=false, bool clearImageOnFirstArgNULL=false ); void SetMeasurementInfoToRenderWindow(const QString& text); void FindRenderWindow(mitk::DataNode* node); void ExtractTensorImages( mitk::Image::ConstPointer tensorimage); typedef std::map< mitk::Image *, mitk::PartialVolumeAnalysisHistogramCalculator::Pointer > PartialVolumeAnalysisMapType; /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkPartialVolumeAnalysisViewControls *m_Controls; QmitkStepperAdapter* m_TimeStepperAdapter; unsigned int m_CurrentTime; QString m_Clipboard; // result text rendering vtkRenderer * m_MeasurementInfoRenderer; vtkCornerAnnotation *m_MeasurementInfoAnnotation; // Image and mask data mitk::DataStorageSelection::Pointer m_SelectedImageNodes; mitk::Image::Pointer m_SelectedImage; mitk::DataNode::Pointer m_SelectedMaskNode; mitk::Image::Pointer m_SelectedImageMask; mitk::DataStorageSelection::Pointer m_SelectedPlanarFigureNodes; mitk::PlanarFigure::Pointer m_SelectedPlanarFigure; bool m_IsTensorImage; mitk::Image::Pointer m_FAImage; mitk::Image::Pointer m_CAImage; mitk::Image::Pointer m_RDImage; mitk::Image::Pointer m_ADImage; mitk::Image::Pointer m_MDImage; // mitk::Image::Pointer m_DirectionImage; mitk::Image::Pointer m_DirectionComp1Image; mitk::Image::Pointer m_DirectionComp2Image; mitk::Image::Pointer m_AngularErrorImage; QmitkRenderWindow* m_SelectedRenderWindow; QmitkRenderWindow* m_LastRenderWindow; long m_ImageObserverTag; long m_ImageMaskObserverTag; long m_PlanarFigureObserverTag; // Hash map for associating one image statistics calculator with each iamge // (so that previously calculated histograms / statistics can be recovered // if a recalculation is not required) PartialVolumeAnalysisMapType m_PartialVolumeAnalysisMap; HistogramCalculatorType::Pointer m_CurrentStatisticsCalculator; bool m_CurrentStatisticsValid; bool m_StatisticsUpdatePending; bool m_GaussianSigmaChangedSliding; bool m_NumberBinsSliding; bool m_UpsamplingChangedSliding; bool m_Visible; mitk::DataNode::Pointer m_ClusteringResult; int m_EllipseCounter; int m_RectangleCounter; int m_PolygonCounter; unsigned int m_InitializedObserverTag; bool m_CurrentFigureNodeInitialized; int m_QuantifyClass; ClusteringType::HelperStructPerformRGBClusteringRetval* m_CurrentRGBClusteringResults; ClusteringType::HelperStructPerformClusteringRetval *m_CurrentPerformClusteringResults; // mitk::DataNode::Pointer m_newnode; // mitk::DataNode::Pointer m_newnode2; QIcon* m_IconTexOFF; QIcon* m_IconTexON; bool m_TexIsOn; }; #endif // !defined(QmitkPartialVolumeAnalysis_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp index 7ad470e8eb..10123892ec 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp @@ -1,443 +1,441 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "QmitkPreprocessingView.h" #include "mitkDiffusionImagingConfigure.h" // qt includes #include // itk includes #include "itkTimeProbe.h" #include "itkB0ImageExtractionImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "itkBrainMaskExtractionImageFilter.h" #include "itkCastImageFilter.h" #include "itkVectorContainer.h" #include // mitk includes #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include #include #include const std::string QmitkPreprocessingView::VIEW_ID = "org.mitk.views.preprocessing"; #define DI_INFO MITK_INFO("DiffusionImaging") typedef float TTensorPixelType; QmitkPreprocessingView::QmitkPreprocessingView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_DiffusionImage(NULL) { } QmitkPreprocessingView::QmitkPreprocessingView(const QmitkPreprocessingView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkPreprocessingView::~QmitkPreprocessingView() { } void QmitkPreprocessingView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkPreprocessingViewControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_MeasurementFrameTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); m_Controls->m_MeasurementFrameTable->verticalHeader()->setResizeMode(QHeaderView::Stretch); } } void QmitkPreprocessingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkPreprocessingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkPreprocessingView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ButtonAverageGradients), SIGNAL(clicked()), this, SLOT(AverageGradients()) ); connect( (QObject*)(m_Controls->m_ButtonExtractB0), SIGNAL(clicked()), this, SLOT(ExtractB0()) ); connect( (QObject*)(m_Controls->m_ButtonBrainMask), SIGNAL(clicked()), this, SLOT(BrainMask()) ); connect( (QObject*)(m_Controls->m_ModifyMeasurementFrame), SIGNAL(clicked()), this, SLOT(DoApplyMesurementFrame()) ); connect( (QObject*)(m_Controls->m_ReduceGradientsButton), SIGNAL(clicked()), this, SLOT(DoReduceGradientDirections()) ); connect( (QObject*)(m_Controls->m_ShowGradientsButton), SIGNAL(clicked()), this, SLOT(DoShowGradientDirections()) ); connect( (QObject*)(m_Controls->m_MirrorGradientToHalfSphereButton), SIGNAL(clicked()), this, SLOT(DoHalfSphereGradientDirections()) ); } } void QmitkPreprocessingView::OnSelectionChanged( std::vector nodes ) { bool foundDwiVolume = false; m_DiffusionImage = NULL; m_SelectedDiffusionNodes = mitk::DataStorage::SetOfObjects::New(); // iterate selection for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast*>(node->GetData()) ) { foundDwiVolume = true; m_DiffusionImage = dynamic_cast*>(node->GetData()); m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); m_SelectedDiffusionNodes->push_back(node); } } m_Controls->m_ButtonBrainMask->setEnabled(foundDwiVolume); m_Controls->m_ButtonAverageGradients->setEnabled(foundDwiVolume); m_Controls->m_ButtonExtractB0->setEnabled(foundDwiVolume); m_Controls->m_CheckExtractAll->setEnabled(foundDwiVolume); m_Controls->m_ModifyMeasurementFrame->setEnabled(foundDwiVolume); m_Controls->m_MeasurementFrameTable->setEnabled(foundDwiVolume); m_Controls->m_ReduceGradientsButton->setEnabled(foundDwiVolume); m_Controls->m_ShowGradientsButton->setEnabled(foundDwiVolume); m_Controls->m_MirrorGradientToHalfSphereButton->setEnabled(foundDwiVolume); if (foundDwiVolume) { vnl_matrix_fixed< double, 3, 3 > mf = m_DiffusionImage->GetMeasurementFrame(); for (int r=0; r<3; r++) for (int c=0; c<3; c++) { QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); delete item; item = new QTableWidgetItem(); item->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); item->setText(QString::number(mf.get(r,c))); m_Controls->m_MeasurementFrameTable->setItem(r,c,item); } m_Controls->m_GradientsLabel->setText(QString::number(m_DiffusionImage->GetNumDirections())); if (m_DiffusionImage->IsMultiBval()) m_Controls->m_BvalLabel->setText("Acquisition with multiple b-values!"); else m_Controls->m_BvalLabel->setText(QString::number(m_DiffusionImage->GetB_Value())); } else { for (int r=0; r<3; r++) for (int c=0; c<3; c++) { QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); delete item; item = new QTableWidgetItem(); m_Controls->m_MeasurementFrameTable->setItem(r,c,item); } m_Controls->m_GradientsLabel->setText("-"); m_Controls->m_BvalLabel->setText("-"); m_Controls->m_DiffusionImageLabel->setText("-"); } } void QmitkPreprocessingView::Activated() { QmitkFunctionality::Activated(); } void QmitkPreprocessingView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkPreprocessingView::DoHalfSphereGradientDirections() { if (m_DiffusionImage.IsNull()) return; GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetOriginalDirections(); for (int j=0; jSize(); j++) if (gradientContainer->at(j)[0]<0) gradientContainer->at(j) = -gradientContainer->at(j); } void QmitkPreprocessingView::DoApplyMesurementFrame() { if (m_DiffusionImage.IsNull()) return; vnl_matrix_fixed< double, 3, 3 > mf; for (int r=0; r<3; r++) for (int c=0; c<3; c++) { QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); if (!item) return; mf[r][c] = item->text().toDouble(); } m_DiffusionImage->SetMeasurementFrame(mf); } void QmitkPreprocessingView::DoShowGradientDirections() { if (m_DiffusionImage.IsNull()) return; GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetOriginalDirections(); mitk::PointSet::Pointer pointset = mitk::PointSet::New(); for (int j=0; jSize(); j++) { mitk::Point3D p; vnl_vector_fixed< double, 3 > v = gradientContainer->at(j); if (fabs(v[0])>0.001 || fabs(v[1])>0.001 || fabs(v[2])>0.001) { p[0] = v[0]; p[1] = v[1]; p[2] = v[2]; pointset->InsertPoint(j, p); } } mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(pointset); node->SetName("gradient directions"); node->SetProperty("pointsize", mitk::FloatProperty::New(0.05)); node->SetProperty("color", mitk::ColorProperty::New(1,0,0)); GetDefaultDataStorage()->Add(node); } void QmitkPreprocessingView::DoReduceGradientDirections() { if (m_DiffusionImage.IsNull()) return; typedef mitk::DiffusionImage DiffusionImageType; typedef itk::ReduceDirectionGradientsFilter FilterType; GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetOriginalDirections(); FilterType::Pointer filter = FilterType::New(); filter->SetInput(m_DiffusionImage->GetVectorImage()); filter->SetOriginalGradientDirections(gradientContainer); filter->SetNumGradientDirections(m_Controls->m_ReduceGradientsBox->value()); filter->Update(); DiffusionImageType::Pointer image = DiffusionImageType::New(); image->SetVectorImage( filter->GetOutput() ); image->SetB_Value(m_DiffusionImage->GetB_Value()); image->SetDirections(filter->GetGradientDirections()); image->SetOriginalDirections(filter->GetGradientDirections()); image->SetMeasurementFrame(m_DiffusionImage->GetMeasurementFrame()); image->InitializeFromVectorImage(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); imageNode->SetName("reduced_image"); GetDefaultDataStorage()->Add(imageNode); } void QmitkPreprocessingView::ExtractB0() { typedef mitk::DiffusionImage DiffusionImageType; typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; int nrFiles = m_SelectedDiffusionNodes->size(); if (!nrFiles) return; // call the extraction withou averaging if the check-box is checked if( this->m_Controls->m_CheckExtractAll->isChecked() ) { DoExtractBOWithoutAveraging(); return; } mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { DiffusionImageType* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // Extract image using found index typedef itk::B0ImageExtractionImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(vols->GetVectorImage()); filter->SetDirections(vols->GetDirections()); filter->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); mitkImage->InitializeByItk( filter->GetOutput() ); mitkImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( mitkImage ); node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0")); GetDefaultDataStorage()->Add(node); ++itemiter; } } void QmitkPreprocessingView::DoExtractBOWithoutAveraging() { // typedefs typedef mitk::DiffusionImage DiffusionImageType; typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; typedef itk::B0ImageExtractionToSeparateImageFilter< short, short> FilterType; // check number of selected objects, return if empty int nrFiles = m_SelectedDiffusionNodes->size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes->end() ); std::vector< mitk::DataNode::Pointer > nodes; while ( itemiter != itemiterend ) // for all items { DiffusionImageType* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // Extract image using found index FilterType::Pointer filter = FilterType::New(); filter->SetInput(vols->GetVectorImage()); filter->SetDirections(vols->GetDirections()); filter->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); mitkImage->InitializeByItk( filter->GetOutput() ); mitkImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( mitkImage ); node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0_ALL")); GetDefaultDataStorage()->Add(node); ++itemiter; } } void QmitkPreprocessingView::AverageGradients() { int nrFiles = m_SelectedDiffusionNodes->size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); vols->AverageRedundantGradients(m_Controls->m_Blur->value()); ++itemiter; } } void QmitkPreprocessingView::BrainMask() { int nrFiles = m_SelectedDiffusionNodes->size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes->end() ); while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // Extract image using found index typedef itk::B0ImageExtractionImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(vols->GetVectorImage()); filter->SetDirections(vols->GetDirections()); typedef itk::CastImageFilter, itk::Image > CastFilterType; CastFilterType::Pointer castfilter = CastFilterType::New(); castfilter->SetInput(filter->GetOutput()); typedef itk::BrainMaskExtractionImageFilter MaskFilterType; MaskFilterType::Pointer maskfilter = MaskFilterType::New(); maskfilter->SetInput(castfilter->GetOutput()); maskfilter->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); mitkImage->InitializeByItk( maskfilter->GetOutput() ); mitkImage->SetVolume( maskfilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( mitkImage ); node->SetProperty( "name", mitk::StringProperty::New(nodename + "_Mask")); GetDefaultDataStorage()->Add(node); ++itemiter; } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h index 10a1ca5dfc..4d6f101bb4 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h @@ -1,109 +1,107 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKPREPROCESSINGVIEW_H_INCLUDED #define _QMITKPREPROCESSINGVIEW_H_INCLUDED #include #include #include "ui_QmitkPreprocessingViewControls.h" #include "mitkDiffusionImage.h" typedef short DiffusionPixelType; struct PrpSelListener; /*! * \ingroup org_mitk_gui_qt_preprocessing_internal * * \brief QmitkPreprocessingView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkPreprocessingView : public QmitkFunctionality { friend struct PrpSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; typedef vnl_vector_fixed< double, 3 > GradientDirectionType; typedef itk::VectorContainer< unsigned int, GradientDirectionType > GradientDirectionContainerType; QmitkPreprocessingView(); QmitkPreprocessingView(const QmitkPreprocessingView& other); virtual ~QmitkPreprocessingView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); static const int nrconvkernels; protected slots: void AverageGradients(); void ExtractB0(); void BrainMask(); void DoApplyMesurementFrame(); void DoReduceGradientDirections(); void DoShowGradientDirections(); void DoHalfSphereGradientDirections(); protected: /** Called by ExtractB0 if check-box activated, extracts all b0 images without averaging */ void DoExtractBOWithoutAveraging(); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkPreprocessingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); mitk::DiffusionImage::Pointer m_DiffusionImage; mitk::DataStorage::SetOfObjects::Pointer m_SelectedDiffusionNodes; }; #endif // _QMITKPREPROCESSINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp index 7edbd04136..b9fa6b6cd2 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp @@ -1,796 +1,794 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "QmitkQBallReconstructionView.h" #include "mitkDiffusionImagingConfigure.h" // qt includes #include // itk includes #include "itkTimeProbe.h" // mitk includes #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "itkDiffusionQballReconstructionImageFilter.h" #include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" #include "itkVectorContainer.h" #include "mitkQBallImage.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "berryIStructuredSelection.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" #include const std::string QmitkQBallReconstructionView::VIEW_ID = "org.mitk.views.qballreconstruction"; #define DI_INFO MITK_INFO("DiffusionImaging") typedef float TTensorPixelType; const int QmitkQBallReconstructionView::nrconvkernels = 252; using namespace berry; struct QbrSelListener : ISelectionListener { berryObjectMacro(QbrSelListener); QbrSelListener(QmitkQBallReconstructionView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { bool foundDwiVolume = false; m_View->m_Controls->m_DiffusionImageLabel->setText("-"); // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("DiffusionImage").compare(node->GetData()->GetNameOfClass())==0) { foundDwiVolume = true; m_View->m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); } } } m_View->m_Controls->m_ButtonStandard->setEnabled(foundDwiVolume); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkQBallReconstructionView* m_View; }; QmitkQBallReconstructionView::QmitkQBallReconstructionView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { } QmitkQBallReconstructionView::QmitkQBallReconstructionView(const QmitkQBallReconstructionView& other) { Q_UNUSED(other); throw std::runtime_error("Copy constructor not implemented"); } //void QmitkQBallReconstructionView::OpactiyChanged(int value) //{ // if (m_CurrentSelection) // { // if (mitk::DataNodeObject::Pointer nodeObj = m_CurrentSelection->Begin()->Cast()) // { // mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // if(QString("DiffusionImage").compare(node->GetData()->GetNameOfClass())==0) // { // node->SetIntProperty("DisplayChannel", value); // mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // } // } // } //} // //void QmitkQBallReconstructionView::OpactiyActionChanged() //{ // if (m_CurrentSelection) // { // if (mitk::DataNodeObject::Pointer nodeObj = m_CurrentSelection->Begin()->Cast()) // { // mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // if(QString("DiffusionImage").compare(node->GetData()->GetNameOfClass())==0) // { // int displayChannel = 0.0; // if(node->GetIntProperty("DisplayChannel", displayChannel)) // { // m_OpacitySlider->setValue(displayChannel); // } // } // } // } // // MITK_INFO << "changed"; //} QmitkQBallReconstructionView::~QmitkQBallReconstructionView() { this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); } void QmitkQBallReconstructionView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkQBallReconstructionViewControls; m_Controls->setupUi(parent); this->CreateConnections(); QStringList items; items << "2" << "4" << "6" << "8" << "10" << "12"; m_Controls->m_QBallReconstructionMaxLLevelComboBox->addItems(items); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setCurrentIndex(1); MethodChoosen(m_Controls->m_QBallReconstructionMethodComboBox->currentIndex()); #ifndef DIFFUSION_IMAGING_EXTENDED m_Controls->m_QBallReconstructionMethodComboBox->removeItem(3); #endif AdvancedCheckboxClicked(); // define data type for combobox //m_Controls->m_ImageSelector->SetDataStorage( this->GetDefaultDataStorage() ); //m_Controls->m_ImageSelector->SetPredicate( mitk::NodePredicateDataType::New("DiffusionImage") ); } m_SelListener = berry::ISelectionListener::Pointer(new QbrSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } void QmitkQBallReconstructionView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkQBallReconstructionView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkQBallReconstructionView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ButtonStandard), SIGNAL(clicked()), this, SLOT(ReconstructStandard()) ); connect( (QObject*)(m_Controls->m_AdvancedCheckbox), SIGNAL(clicked()), this, SLOT(AdvancedCheckboxClicked()) ); connect( (QObject*)(m_Controls->m_QBallReconstructionMethodComboBox), SIGNAL(currentIndexChanged(int)), this, SLOT(MethodChoosen(int)) ); } } void QmitkQBallReconstructionView::OnSelectionChanged( std::vector nodes ) { } void QmitkQBallReconstructionView::Activated() { QmitkFunctionality::Activated(); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } void QmitkQBallReconstructionView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkQBallReconstructionView::ReconstructStandard() { int index = m_Controls->m_QBallReconstructionMethodComboBox->currentIndex(); #ifndef DIFFUSION_IMAGING_EXTENDED if(index>=3) { index = index + 1; } #endif switch(index) { case 0: { // Numerical Reconstruct(0,0); break; } case 1: { // Standard Reconstruct(1,0); break; } case 2: { // Solid Angle Reconstruct(1,6); break; } case 3: { // Constrained Solid Angle Reconstruct(1,7); break; } case 4: { // ADC Reconstruct(1,4); break; } case 5: { // Raw Signal Reconstruct(1,5); break; } } } void QmitkQBallReconstructionView::MethodChoosen(int method) { switch(method) { case 0: m_Controls->m_Description->setText("Numerical recon. (Tuch2004)"); break; case 1: m_Controls->m_Description->setText("Spherical harmonics recon. (Descoteaux2007)"); break; case 2: m_Controls->m_Description->setText("SH recon. with solid angle consideration (Aganj2009)"); break; case 3: m_Controls->m_Description->setText("SH solid angle with non-neg. constraint (Goh2009)"); break; case 4: m_Controls->m_Description->setText("SH recon. of the plain ADC-profiles"); break; case 5: m_Controls->m_Description->setText("SH recon. of the raw diffusion signal"); break; } } void QmitkQBallReconstructionView::AdvancedCheckboxClicked() { bool check = m_Controls-> m_AdvancedCheckbox->isChecked(); m_Controls->m_QBallReconstructionMaxLLevelTextLabel_2->setVisible(check); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setVisible(check); m_Controls->m_QBallReconstructionLambdaTextLabel_2->setVisible(check); m_Controls->m_QBallReconstructionLambdaLineEdit->setVisible(check); m_Controls->m_QBallReconstructionThresholdLabel_2->setVisible(check); m_Controls->m_QBallReconstructionThreasholdEdit->setVisible(check); m_Controls->m_OutputB0Image->setVisible(check); m_Controls->label_2->setVisible(check); //m_Controls->textLabel1_2->setVisible(check); //m_Controls->m_QBallReconstructionLambdaStepLineEdit->setVisible(check); //m_Controls->textLabel1_3->setVisible(check); m_Controls->frame_2->setVisible(check); } void QmitkQBallReconstructionView::Reconstruct(int method, int normalization) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); if(QString("DiffusionImage").compare(node->GetData()->GetNameOfClass())==0) { set->InsertElement(at++, node); } } } if(method == 0) { NumericalQBallReconstruction(set, normalization); } else { #if BOOST_VERSION / 100000 > 0 #if BOOST_VERSION / 100 % 1000 > 34 if(method == 1) { AnalyticalQBallReconstruction(set, normalization); } #else std::cout << "ERROR: Boost 1.35 minimum required" << std::endl; QMessageBox::warning(NULL,"ERROR","Boost 1.35 minimum required"); #endif #else std::cout << "ERROR: Boost 1.35 minimum required" << std::endl; QMessageBox::warning(NULL,"ERROR","Boost 1.35 minimum required"); #endif } } } void QmitkQBallReconstructionView::NumericalQBallReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); ++itemiter; // QBALL RECONSTRUCTION clock.Start(); MBI_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str()).toAscii()); typedef itk::DiffusionQballReconstructionImageFilter QballReconstructionImageFilterType; QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetGradientImage( vols->GetDirections(), vols->GetVectorImage() ); filter->SetBValue(vols->GetB_Value()); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->text().toFloat() ); switch(normalization) { case 0: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); break; } case 1: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO_B_VALUE); break; } case 2: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO); break; } case 3: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_NONE); break; } default: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); } } filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s." ; // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); //image->SetImportVolume( filter->GetOutput()->GetBufferPointer(), 0, 0, mitk::Image::ImportMemoryManagementType::ManageMemory ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_QN%1").arg(normalization); SetDefaultNodeProperties(node, newname.toStdString()); nodes.push_back(node); // B-Zero TO DATATREE if(m_Controls->m_OutputB0Image->isChecked()) { mitk::Image::Pointer image4 = mitk::Image::New(); image4->InitializeByItk( filter->GetBZeroImage().GetPointer() ); image4->SetVolume( filter->GetBZeroImage()->GetBufferPointer() ); mitk::DataNode::Pointer node4=mitk::DataNode::New(); node4->SetData( image4 ); node4->SetProperty( "name", mitk::StringProperty::New( QString(nodename.c_str()).append("_b0").toStdString()) ); nodes.push_back(node4); } mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toAscii()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex ; return ; } } void QmitkQBallReconstructionView::AnalyticalQBallReconstruction( mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->text().toFloat(); lambdas.push_back(minLambda); int nLambdas = lambdas.size(); QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles*nLambdas); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector* nodes = new std::vector(); while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name",nodename); itemiter++; // QBALL RECONSTRUCTION clock.Start(); MBI_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str()).toAscii()); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentIndex()) { case 0: { TemplatedAnalyticalQBallReconstruction<2>(vols, currentLambda, nodename, nodes, normalization); break; } case 1: { TemplatedAnalyticalQBallReconstruction<4>(vols, currentLambda, nodename, nodes, normalization); break; } case 2: { TemplatedAnalyticalQBallReconstruction<6>(vols, currentLambda, nodename, nodes, normalization); break; } case 3: { TemplatedAnalyticalQBallReconstruction<8>(vols, currentLambda, nodename, nodes, normalization); break; } case 4: { TemplatedAnalyticalQBallReconstruction<10>(vols, currentLambda, nodename, nodes, normalization); break; } case 5: { TemplatedAnalyticalQBallReconstruction<12>(vols, currentLambda, nodename, nodes, normalization); break; } } clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s." ; mitk::ProgressBar::GetInstance()->Progress(); } } std::vector::iterator nodeIt; for(nodeIt = nodes->begin(); nodeIt != nodes->end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); m_MultiWidget->RequestUpdate(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toAscii()); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex ; return ; } } template void QmitkQBallReconstructionView::TemplatedAnalyticalQBallReconstruction( mitk::DiffusionImage* vols, float lambda, std::string nodename, std::vector* nodes, int normalization) { typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetGradientImage( vols->GetDirections(), vols->GetVectorImage() ); filter->SetBValue(vols->GetB_Value()); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->text().toFloat() ); filter->SetLambda(lambda); switch(normalization) { case 0: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); break; } case 1: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO_B_VALUE); break; } case 2: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO); break; } case 3: { filter->SetNormalizationMethod(FilterType::QBAR_NONE); break; } case 4: { filter->SetNormalizationMethod(FilterType::QBAR_ADC_ONLY); break; } case 5: { filter->SetNormalizationMethod(FilterType::QBAR_RAW_SIGNAL); break; } case 6: { filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); break; } case 7: { filter->SetNormalizationMethod(FilterType::QBAR_NONNEG_SOLID_ANGLE); break; } default: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); } } filter->Update(); // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_QA%1").arg(normalization); SetDefaultNodeProperties(node, newname.toStdString()); nodes->push_back(node); // mitk::Image::Pointer image5 = mitk::Image::New(); // image5->InitializeByItk( filter->GetODFSumImage().GetPointer() ); // image5->SetVolume( filter->GetODFSumImage()->GetBufferPointer() ); // mitk::DataNode::Pointer node5=mitk::DataNode::New(); // node5->SetData( image5 ); // node5->SetProperty( "name", mitk::StringProperty::New( // QString(nodename.c_str()).append("_ODF").toStdString()) ); // nodes->push_back(node5); // B-Zero TO DATATREE if(m_Controls->m_OutputB0Image->isChecked()) { mitk::Image::Pointer image4 = mitk::Image::New(); image4->InitializeByItk( filter->GetBZeroImage().GetPointer() ); image4->SetVolume( filter->GetBZeroImage()->GetBufferPointer() ); mitk::DataNode::Pointer node4=mitk::DataNode::New(); node4->SetData( image4 ); node4->SetProperty( "name", mitk::StringProperty::New( QString(nodename.c_str()).append("_b0").toStdString()) ); nodes->push_back(node4); } } void QmitkQBallReconstructionView::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 500 ) ); node->SetProperty( "Scaling", mitk::FloatProperty::New( 1.0 ) ); node->SetProperty( "Normalization", mitk::OdfNormalizationMethodProperty::New()); node->SetProperty( "ScaleBy", mitk::OdfScaleByProperty::New()); node->SetProperty( "IndexParam1", mitk::FloatProperty::New(2)); node->SetProperty( "IndexParam2", mitk::FloatProperty::New(1)); node->SetProperty( "visible", mitk::BoolProperty::New( true ) ); node->SetProperty( "VisibleOdfs", mitk::BoolProperty::New( false ) ); node->SetProperty ("layer", mitk::IntProperty::New(100)); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); //node->SetProperty( "opacity", mitk::FloatProperty::New(1.0f) ); node->SetProperty( "name", mitk::StringProperty::New(name) ); } //node->SetProperty( "volumerendering", mitk::BoolProperty::New( false ) ); //node->SetProperty( "use color", mitk::BoolProperty::New( true ) ); //node->SetProperty( "texture interpolation", mitk::BoolProperty::New( true ) ); //node->SetProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); //node->SetProperty( "layer", mitk::IntProperty::New(0)); //node->SetProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); //node->SetOpacity(1.0f); //node->SetColor(1.0,1.0,1.0); //node->SetVisibility(true); //node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); //mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); //mitk::LevelWindow levelwindow; //// levelwindow.SetAuto( image ); //levWinProp->SetLevelWindow( levelwindow ); //node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); //// add a default rainbow lookup table for color mapping //if(!node->GetProperty("LookupTable")) //{ // mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); // vtkLookupTable* vtkLut = mitkLut->GetVtkLookupTable(); // vtkLut->SetHueRange(0.6667, 0.0); // vtkLut->SetTableRange(0.0, 20.0); // vtkLut->Build(); // mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); // mitkLutProp->SetLookupTable(mitkLut); // node->SetProperty( "LookupTable", mitkLutProp ); //} //if(!node->GetProperty("binary")) // node->SetProperty( "binary", mitk::BoolProperty::New( false ) ); //// add a default transfer function //mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); //node->SetProperty ( "TransferFunction", mitk::TransferFunctionProperty::New ( tf.GetPointer() ) ); //// set foldername as string property //mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New( name ); //node->SetProperty( "name", nameProp ); diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h index 9843de4102..cba5748ff2 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h @@ -1,122 +1,120 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKQBALLRECONSTRUCTIONVIEW_H_INCLUDED #define _QMITKQBALLRECONSTRUCTIONVIEW_H_INCLUDED #include #include #include "ui_QmitkQBallReconstructionViewControls.h" #include "mitkDiffusionImage.h" #include #include #include typedef short DiffusionPixelType; struct QbrSelListener; /*! * \ingroup org_mitk_gui_qt_qballreconstruction_internal * * \brief QmitkQBallReconstructionView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkQBallReconstructionView : public QmitkFunctionality { friend struct QbrSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkQBallReconstructionView(); QmitkQBallReconstructionView(const QmitkQBallReconstructionView& other); virtual ~QmitkQBallReconstructionView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); static const int nrconvkernels; protected slots: void ReconstructStandard(); //void ReconstructNormalized1(); //void ReconstructNormalized2(); //void ReconstructNonNormalized(); //void AnalyticallyReconstructStandard(); //void AnalyticallyReconstructSolidAngle(); //void AnalyticallyReconstructNonNegSolidAngle(); //void AnalyticallyReconstructAdc(); //void AnalyticallyReconstructRaw(); void AdvancedCheckboxClicked(); void MethodChoosen(int method); void Reconstruct(int method, int normalization); void NumericalQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization); void AnalyticalQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkQBallReconstructionViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; template void TemplatedAnalyticalQBallReconstruction(mitk::DiffusionImage* vols, float lambda, std::string nodename, std::vector* nodes, int normalization); void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; }; #endif // _QMITKQBALLRECONSTRUCTIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp index 6b079cbe23..4a03575226 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp @@ -1,280 +1,279 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include #include // Qmitk #include "QmitkStochasticFiberTrackingView.h" #include "QmitkStdMultiWidget.h" // Qt #include // MITK #include #include // VTK #include #include #include #include #include #include const std::string QmitkStochasticFiberTrackingView::VIEW_ID = "org.mitk.views.stochasticfibertracking"; const std::string id_DataManager = "org.mitk.views.datamanager"; using namespace berry; QmitkStochasticFiberTrackingView::QmitkStochasticFiberTrackingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_DiffusionImage( NULL ) , m_SeedRoi( NULL ) { } // Destructor QmitkStochasticFiberTrackingView::~QmitkStochasticFiberTrackingView() { } void QmitkStochasticFiberTrackingView::CreateQtPartControl( QWidget *parent ) { if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkStochasticFiberTrackingViewControls; m_Controls->setupUi( parent ); connect( m_Controls->commandLinkButton, SIGNAL(clicked()), this, SLOT(DoFiberTracking()) ); connect( m_Controls->m_SeedsPerVoxelSlider, SIGNAL(valueChanged(int)), this, SLOT(OnSeedsPerVoxelChanged(int)) ); connect( m_Controls->m_MaxCacheSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxCacheSizeChanged(int)) ); connect( m_Controls->m_MaxTractLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxTractLengthChanged(int)) ); } } void QmitkStochasticFiberTrackingView::OnSeedsPerVoxelChanged(int value) { m_Controls->m_SeedsPerVoxelLabel->setText(QString("Seeds per Voxel: ")+QString::number(value)); } void QmitkStochasticFiberTrackingView::OnMaxTractLengthChanged(int value) { m_Controls->m_MaxTractLengthLabel->setText(QString("Max. Tract Length: ")+QString::number(value)); } void QmitkStochasticFiberTrackingView::OnMaxCacheSizeChanged(int value) { m_Controls->m_MaxCacheSizeLabel->setText(QString("Max. Cache Size: ")+QString::number(value)+"GB"); } void QmitkStochasticFiberTrackingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkStochasticFiberTrackingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkStochasticFiberTrackingView::OnSelectionChanged( std::vector nodes ) { m_DiffusionImageNode = NULL; m_DiffusionImage = NULL; m_SeedRoi = NULL; m_Controls->m_DiffusionImageLabel->setText("-"); m_Controls->m_RoiImageLabel->setText("-"); if(nodes.empty()) return; for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { if( dynamic_cast*>(node->GetData()) ) { m_DiffusionImageNode = node; m_DiffusionImage = dynamic_cast*>(node->GetData()); m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); } else { bool isBinary = false; node->GetPropertyValue("binary", isBinary); if (isBinary) { m_SeedRoi = dynamic_cast(node->GetData()); m_Controls->m_RoiImageLabel->setText(node->GetName().c_str()); } } } } if(m_DiffusionImage.IsNotNull() && m_SeedRoi.IsNotNull()) m_Controls->commandLinkButton->setEnabled(true); else m_Controls->commandLinkButton->setEnabled(false); } void QmitkStochasticFiberTrackingView::DoFiberTracking() { /* get Gradients/Direction of dwi */ itk::VectorContainer< unsigned int, vnl_vector_fixed >::Pointer Pdir = m_DiffusionImage->GetDirections(); /* bValueContainer, Container includes b-values according to corresponding gradient-direction*/ PTFilterType::bValueContainerType::Pointer vecCont = PTFilterType::bValueContainerType::New(); /* for each gradient set b-Value; for 0-gradient set b-value eq. 0 */ for ( int i=0; i<(int)Pdir->size(); ++i) { vnl_vector_fixed valsGrad = Pdir->at(i); if (valsGrad.get(0) == 0 && valsGrad.get(1) == 0 && valsGrad.get(2) == 0) { //set 0-Gradient to bValue 0 vecCont->InsertElement(i,0); }else{ vecCont->InsertElement(i,m_DiffusionImage->GetB_Value()); } } /* define measurement frame (identity-matrix 3x3) */ PTFilterType::MeasurementFrameType measurement_frame = m_DiffusionImage->GetMeasurementFrame(); /* generate white matterImage (dummy?)*/ FloatImageType::Pointer wmImage = FloatImageType::New(); wmImage->SetSpacing( m_DiffusionImage->GetVectorImage()->GetSpacing() ); wmImage->SetOrigin( m_DiffusionImage->GetVectorImage()->GetOrigin() ); wmImage->SetDirection( m_DiffusionImage->GetVectorImage()->GetDirection() ); wmImage->SetLargestPossibleRegion( m_DiffusionImage->GetVectorImage()->GetLargestPossibleRegion() ); wmImage->SetBufferedRegion( wmImage->GetLargestPossibleRegion() ); wmImage->SetRequestedRegion( wmImage->GetLargestPossibleRegion() ); wmImage->Allocate(); itk::ImageRegionIterator ot(wmImage, wmImage->GetLargestPossibleRegion() ); while (!ot.IsAtEnd()) { ot.Set(1); ++ot; } /* init TractographyFilter */ PTFilterType::Pointer trackingFilter = PTFilterType::New(); trackingFilter->SetInput(m_DiffusionImage->GetVectorImage().GetPointer()); trackingFilter->SetbValues(vecCont); trackingFilter->SetGradients(Pdir); trackingFilter->SetMeasurementFrame(measurement_frame); trackingFilter->SetWhiteMatterProbabilityImageInput(wmImage); trackingFilter->SetTotalTracts(m_Controls->m_SeedsPerVoxelSlider->value()); trackingFilter->SetMaxLikelihoodCacheSize(m_Controls->m_MaxCacheSizeSlider->value()*1000); trackingFilter->SetMaxTractLength(m_Controls->m_MaxTractLengthSlider->value()); m_tractcontainer = PTFilterType::TractContainerType::New(); //itk::Image< char, 3 > mitk::ImageToItk< itk::Image< unsigned char, 3 > >::Pointer binaryImageToItk1 = mitk::ImageToItk< itk::Image< unsigned char, 3 > >::New(); binaryImageToItk1->SetInput( m_SeedRoi ); binaryImageToItk1->Update(); vtkSmartPointer vPoints = vtkSmartPointer::New(); vtkSmartPointer vCellArray = vtkSmartPointer::New(); itk::ImageRegionConstIterator< BinaryImageType > it(binaryImageToItk1->GetOutput(), binaryImageToItk1->GetOutput()->GetRequestedRegion()); it.Begin(); mitk::Geometry3D* geom = m_DiffusionImage->GetGeometry(); while(!it.IsAtEnd()) { itk::ImageConstIterator::PixelType tmpPxValue = it.Get(); if(tmpPxValue != 0){ mitk::Point3D point; itk::ImageRegionConstIterator< BinaryImageType >::IndexType seedIdx = it.GetIndex(); trackingFilter->SetSeedIndex(seedIdx); trackingFilter->Update(); /* get results from Filter */ /* write each single tract into member container */ PTFilterType::TractContainerType::Pointer container_tmp = trackingFilter->GetOutputTractContainer(); PTFilterType::TractContainerType::Iterator elIt = container_tmp->Begin(); PTFilterType::TractContainerType::Iterator end = container_tmp->End(); bool addTract = true; while( elIt != end ){ PTFilterType::TractContainerType::Element tract = elIt.Value(); PTFilterType::TractContainerType::Element::ObjectType::VertexListType::ConstPointer vertexlist = tract->GetVertexList(); vtkSmartPointer vPolyLine = vtkSmartPointer::New(); for( int j=0; j<(int)vertexlist->Size(); j++) { PTFilterType::TractContainerType::Element::ObjectType::VertexListType::Element vertex = vertexlist->GetElement(j); mitk::Point3D index; index[0] = (float)vertex[0]; index[1] = (float)vertex[1]; index[2] = (float)vertex[2]; if (geom->IsIndexInside(index)) { geom->IndexToWorld(index, point); vtkIdType id = vPoints->InsertNextPoint(point.GetDataPointer()); vPolyLine->GetPointIds()->InsertNextId(id); } else { addTract = false; break; } } if (addTract) vCellArray->InsertNextCell(vPolyLine); ++elIt; } } ++it; } vtkSmartPointer fiberPolyData = vtkSmartPointer::New(); fiberPolyData->SetPoints(vPoints); fiberPolyData->SetLines(vCellArray); mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(fiberPolyData); mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(fib); QString name(m_DiffusionImageNode->GetName().c_str()); name += "_FiberBundle"; fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h index d6857a757b..480bad4bef 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h @@ -1,103 +1,102 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkStochasticFiberTrackingView_h #define QmitkStochasticFiberTrackingView_h #include #include #include #include "ui_QmitkStochasticFiberTrackingViewControls.h" #include #include #include #include #include #include #include #include //define the input/output types typedef itk::VectorImage< short int, 3 > DWIVectorImageType; typedef itk::Image< float, 3 > FloatImageType; typedef itk::Image< unsigned int, 3 > CImageType; typedef itk::StochasticTractographyFilter< DWIVectorImageType, FloatImageType, CImageType > PTFilterType; typedef itk::DTITubeSpatialObject<3> DTITubeType; typedef itk::DTITubeSpatialObjectPoint<3> DTITubePointType; typedef itk::SceneSpatialObject<3> SceneSpatialObjectType; /*! \brief QmitkFiberTrackingView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkStochasticFiberTrackingView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkStochasticFiberTrackingView(); virtual ~QmitkStochasticFiberTrackingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: void DoFiberTracking(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkStochasticFiberTrackingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; protected slots: void OnSeedsPerVoxelChanged(int value); void OnMaxTractLengthChanged(int value); void OnMaxCacheSizeChanged(int value); private: mitk::Image::Pointer m_SeedRoi; mitk::DiffusionImage::Pointer m_DiffusionImage; mitk::DataNode::Pointer m_DiffusionImageNode; typedef itk::Image< unsigned char, 3 > BinaryImageType; PTFilterType::TractContainerType::Pointer m_tractcontainer; }; #endif // _QMITKFIBERTRACKINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.cpp index dafdc3f1f9..379c8791a6 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.cpp @@ -1,150 +1,149 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkTbssMetaTableModel.h" QmitkTbssMetaTableModel::QmitkTbssMetaTableModel(QObject *parent) : QAbstractTableModel(parent) { } QmitkTbssMetaTableModel::QmitkTbssMetaTableModel(QList< QPair > pairs, QObject *parent) : QAbstractTableModel(parent) { listOfPairs=pairs; } int QmitkTbssMetaTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return listOfPairs.size(); } int QmitkTbssMetaTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 2; } QVariant QmitkTbssMetaTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= listOfPairs.size() || index.row() < 0) return QVariant(); if (role == Qt::DisplayRole) { QPair pair = listOfPairs.at(index.row()); if (index.column() == 0) return pair.first; else if (index.column() == 1) return pair.second; } return QVariant(); } QVariant QmitkTbssMetaTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case 0: return tr("Image"); case 1: return tr("Filename"); default: return QVariant(); } } return QVariant(); } bool QmitkTbssMetaTableModel::insertRows(int position, int rows, const QModelIndex &index) { Q_UNUSED(index); beginInsertRows(QModelIndex(), position, position+rows-1); for (int row=0; row < rows; row++) { QPair pair("Image ", "Filename"); listOfPairs.insert(position, pair); } endInsertRows(); return true; } bool QmitkTbssMetaTableModel::removeRows(int position, int rows, const QModelIndex &index) { Q_UNUSED(index); beginRemoveRows(QModelIndex(), position, position+rows-1); for (int row=0; row < rows; ++row) { listOfPairs.removeAt(position); } endRemoveRows(); return true; } bool QmitkTbssMetaTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { int row = index.row(); QPair p = listOfPairs.value(row); if (index.column() == 0) p.first = value.toString(); else if (index.column() == 1) p.second = value.toString(); else return false; listOfPairs.replace(row, p); emit(dataChanged(index, index)); return true; } return false; } Qt::ItemFlags QmitkTbssMetaTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::ItemIsEnabled; return QAbstractTableModel::flags(index) | Qt::ItemIsEditable; } QList< QPair > QmitkTbssMetaTableModel::getList() { return listOfPairs; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.h index 112b33bc45..782b75e11a 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssMetaTableModel.h @@ -1,55 +1,54 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkTbssMetaTableModel_h #define QmitkTbssMetaTableModel_h #include #include #include #include #include class QmitkTbssMetaTableModel : public QAbstractTableModel { //Q_OBJECT public: QmitkTbssMetaTableModel(QObject *parent=0); QmitkTbssMetaTableModel(QList< QPair > listofPairs, QObject *parent=0); int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole); bool insertRows(int position, int rows, const QModelIndex &index=QModelIndex()); bool removeRows(int position, int rows, const QModelIndex &index=QModelIndex()); QList< QPair > getList(); private: QList< QPair > listOfPairs; }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.cpp index afd7fca2c8..baea439df5 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.cpp @@ -1,521 +1,520 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include #include #include #include // Qmitk #include "QmitkTbssSkeletonizationView.h" #include #include #include #include #include #include #include #include // Qt #include #include //vtk #include #include // Boost #include const std::string QmitkTbssSkeletonizationView::VIEW_ID = "org.mitk.views.tbssskeletonization"; using namespace berry; struct TbssSkeletonizationSelListener : ISelectionListener { berryObjectMacro(TbssSkeletonizationSelListener) TbssSkeletonizationSelListener(QmitkTbssSkeletonizationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { bool found3dImage = false; bool found4dImage = false; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types // from valid nodes mitk::BaseData* nodeData = node->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast(nodeData); if(img->GetDimension() == 3) { found3dImage = true; } else if(img->GetDimension() == 4) { found4dImage = true; } } } } } m_View->m_Controls->m_Skeletonize->setEnabled(found3dImage); m_View->m_Controls->m_Project->setEnabled(found3dImage && found4dImage); m_View->m_Controls->m_OutputMask->setEnabled(found3dImage && found4dImage); m_View->m_Controls->m_OutputDistanceMap->setEnabled(found3dImage && found4dImage); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkTbssSkeletonizationView* m_View; }; QmitkTbssSkeletonizationView::QmitkTbssSkeletonizationView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkTbssSkeletonizationView::~QmitkTbssSkeletonizationView() { } void QmitkTbssSkeletonizationView::OnSelectionChanged(std::vector nodes) { //datamanager selection changed if (!this->IsActivated()) return; } void QmitkTbssSkeletonizationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkTbssSkeletonizationViewControls; m_Controls->setupUi( parent ); this->CreateConnections(); } m_SelListener = berry::ISelectionListener::Pointer(new TbssSkeletonizationSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); m_IsInitialized = false; } void QmitkTbssSkeletonizationView::Activated() { QmitkFunctionality::Activated(); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } void QmitkTbssSkeletonizationView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkTbssSkeletonizationView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_Skeletonize), SIGNAL(clicked()), this, SLOT(Skeletonize() )); connect( (QObject*)(m_Controls->m_Project), SIGNAL(clicked()), this, SLOT(Project() )); } } void QmitkTbssSkeletonizationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkTbssSkeletonizationView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkTbssSkeletonizationView::Skeletonize() { typedef itk::SkeletonizationFilter SkeletonisationFilterType; SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New(); if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); mitk::Image::Pointer meanImage = mitk::Image::New(); for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // process only on valid nodes mitk::BaseData* nodeData = node->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast(nodeData); if(img->GetDimension() == 3) { meanImage = img; } } } } } // Calculate skeleton FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(meanImage, itkImg); skeletonizer->SetInput(itkImg); skeletonizer->Update(); FloatImageType::Pointer output = skeletonizer->GetOutput(); mitk::Image::Pointer mitkOutput = mitk::Image::New(); mitk::CastToMitkImage(output, mitkOutput); AddToDataStorage(mitkOutput, "all_FA_skeletonised"); } } void QmitkTbssSkeletonizationView::Project() { typedef itk::SkeletonizationFilter SkeletonisationFilterType; typedef itk::ProjectionFilter ProjectionFilterType; typedef itk::DistanceMapFilter DistanceMapFilterType; SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New(); if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); mitk::Image::Pointer meanImage = mitk::Image::New(); mitk::Image::Pointer subjects = mitk::Image::New(); for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // process only on valid nodes mitk::BaseData* nodeData = node->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast(nodeData); if(img->GetDimension() == 3) { meanImage = img; } else if(img->GetDimension() == 4) { subjects = img; } } } } } Float4DImageType::Pointer allFA = ConvertToItk(subjects); // Calculate skeleton FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(meanImage, itkImg); skeletonizer->SetInput(itkImg); skeletonizer->Update(); FloatImageType::Pointer output = skeletonizer->GetOutput(); mitk::Image::Pointer mitkOutput = mitk::Image::New(); mitk::CastToMitkImage(output, mitkOutput); AddToDataStorage(mitkOutput, "mean_FA_skeletonised"); // Retrieve direction image needed later by the projection filter DirectionImageType::Pointer directionImg = skeletonizer->GetVectorImage(); // Calculate distance image DistanceMapFilterType::Pointer distanceMapFilter = DistanceMapFilterType::New(); distanceMapFilter->SetInput(output); distanceMapFilter->Update(); FloatImageType::Pointer distanceMap = distanceMapFilter->GetOutput(); if(m_Controls->m_OutputDistanceMap->isChecked()) { mitk::Image::Pointer mitkDistance = mitk::Image::New(); mitk::CastToMitkImage(distanceMap, mitkDistance); AddToDataStorage(mitkDistance, "distance map"); } // Do projection // Ask a threshold to create a skeleton mask double threshold = -1.0; while(threshold == -1.0) { threshold = QInputDialog::getDouble(m_Controls->m_Skeletonize, tr("Specify the FA threshold"), tr("Threshold:"), QLineEdit::Normal, 0.2); if(threshold < 0.0 || threshold > 1.0) { QMessageBox msgBox; msgBox.setText("Please choose a value between 0 and 1"); msgBox.exec(); threshold = -1.0; } } typedef itk::BinaryThresholdImageFilter ThresholdFilterType; ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); thresholder->SetInput(output); thresholder->SetLowerThreshold(threshold); thresholder->SetUpperThreshold(std::numeric_limits::max()); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(1); thresholder->Update(); CharImageType::Pointer thresholdedImg = thresholder->GetOutput(); if(m_Controls->m_OutputMask->isChecked()) { mitk::Image::Pointer mitkThresholded = mitk::Image::New(); mitk::CastToMitkImage(thresholdedImg, mitkThresholded); std::string maskName = "skeleton_mask_at_" + boost::lexical_cast(threshold); AddToDataStorage(mitkThresholded, maskName); } typedef itk::ImageFileReader< CharImageType > CharReaderType; CharReaderType::Pointer reader = CharReaderType::New(); reader->SetFileName("/local/testing/LowerCingulum_1mm.nii.gz"); reader->Update(); CharImageType::Pointer cingulum = reader->GetOutput(); ProjectionFilterType::Pointer projectionFilter = ProjectionFilterType::New(); projectionFilter->SetDistanceMap(distanceMap); projectionFilter->SetDirections(directionImg); projectionFilter->SetAllFA(allFA); projectionFilter->SetTube(cingulum); projectionFilter->SetSkeleton(thresholdedImg); projectionFilter->Project(); Float4DImageType::Pointer projected = projectionFilter->GetProjections(); mitk::Image::Pointer mitkProjections = mitk::Image::New(); mitk::CastToMitkImage(projected, mitkProjections); AddToDataStorage(mitkProjections, "all_FA_projected"); } } void QmitkTbssSkeletonizationView::AddToDataStorage(mitk::Image* img, std::string name) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "name", mitk::StringProperty::New(name) ); result->SetData( img ); // add new image to data storage and set as active to ease further processing GetDefaultDataStorage()->Add( result ); } Float4DImageType::Pointer QmitkTbssSkeletonizationView::ConvertToItk(mitk::Image::Pointer image) { Float4DImageType::Pointer output = Float4DImageType::New(); mitk::Geometry3D* geo = image->GetGeometry(); mitk::Vector3D mitkSpacing = geo->GetSpacing(); mitk::Point3D mitkOrigin = geo->GetOrigin(); Float4DImageType::SpacingType spacing; spacing[0] = mitkSpacing[0]; spacing[1] = mitkSpacing[1]; spacing[2] = mitkSpacing[2]; spacing[3] = 1.0; // todo: check if spacing has length 4 Float4DImageType::PointType origin; origin[0] = mitkOrigin[0]; origin[1] = mitkOrigin[1]; origin[2] = mitkOrigin[2]; origin[3] = 0; Float4DImageType::SizeType size; size[0] = image->GetDimension(0); size[1] = image->GetDimension(1); size[2] = image->GetDimension(2); size[3] = image->GetDimension(3); Float4DImageType::DirectionType dir; vtkLinearTransform* lin = geo->GetVtkTransform(); vtkMatrix4x4 *m = lin->GetMatrix(); dir.Fill(0.0); for(int x=0; x<3; x++) { for(int y=0; y<3; y++) { dir[x][y] = m->GetElement(x,y); } } dir[3][3] = 1; output->SetSpacing(spacing); output->SetOrigin(origin); output->SetRegions(size); output->SetDirection(dir); output->Allocate(); if(image->GetDimension() == 4) { int timesteps = image->GetDimension(3); // iterate through the subjects and copy data to output for(int t=0; tGetDimension(0); x++) { for(int y=0; yGetDimension(1); y++) { for(int z=0; zGetDimension(2); z++) { itk::Index<4> ix4; ix4[0] = x; ix4[1] = y; ix4[2] = z; ix4[3] = t; mitk::Index3D ix; ix[0] = x; ix[1] = y; ix[2] = z; output->SetPixel(ix4, image->GetPixelValueByIndex(ix, t)); } } } } } return output; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.h index c6ee9e52d1..9993bf5975 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssSkeletonizationView.h @@ -1,123 +1,122 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkTbssSkeletonizationView_h #define QmitkTbssSkeletonizationView_h // Blueberry #include #include #include // itk #include "itkImage.h" #include "itkVectorImage.h" #include #include "ui_QmitkTbssSkeletonizationViewControls.h" typedef itk::Image FloatImageType; typedef itk::Image CharImageType; typedef itk::Image Float4DImageType; typedef itk::CovariantVector VectorType; typedef itk::Image DirectionImageType; struct TbssSkeletonizationSelListener; /*! \brief QmitkTbssSkeletonizationView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionalitymitkTbssWorkspaceManager \ingroup Functionalities */ class QmitkTbssSkeletonizationView : public QmitkFunctionality { friend struct TbssSkeletonizationSelListener; // this is needed for all Qt objesetupUicts that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkTbssSkeletonizationView(); virtual ~QmitkTbssSkeletonizationView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); protected slots: void Skeletonize(); void Project(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); void InitPointsets(); void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; bool m_IsInitialized; Ui::QmitkTbssSkeletonizationViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; void AddToDataStorage(mitk::Image* img, std::string name); Float4DImageType::Pointer ConvertToItk(mitk::Image::Pointer image); }; #endif // _QMITKTbssSkeletonizationVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.cpp index 6319490fff..f370d18098 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.cpp @@ -1,150 +1,149 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkTbssTableModel.h" QmitkTbssTableModel::QmitkTbssTableModel(QObject *parent) : QAbstractTableModel(parent) { } QmitkTbssTableModel::QmitkTbssTableModel(QList< QPair > pairs, QObject *parent) : QAbstractTableModel(parent) { listOfPairs=pairs; } int QmitkTbssTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return listOfPairs.size(); } int QmitkTbssTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 2; } QVariant QmitkTbssTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= listOfPairs.size() || index.row() < 0) return QVariant(); if (role == Qt::DisplayRole) { QPair pair = listOfPairs.at(index.row()); if (index.column() == 0) return pair.first; else if (index.column() == 1) return pair.second; } return QVariant(); } QVariant QmitkTbssTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case 0: return tr("Group"); case 1: return tr("Size"); default: return QVariant(); } } return QVariant(); } bool QmitkTbssTableModel::insertRows(int position, int rows, const QModelIndex &index) { Q_UNUSED(index); beginInsertRows(QModelIndex(), position, position+rows-1); for (int row=0; row < rows; row++) { QPair pair(" ", 0); listOfPairs.insert(position, pair); } endInsertRows(); return true; } bool QmitkTbssTableModel::removeRows(int position, int rows, const QModelIndex &index) { Q_UNUSED(index); beginRemoveRows(QModelIndex(), position, position+rows-1); for (int row=0; row < rows; ++row) { listOfPairs.removeAt(position); } endRemoveRows(); return true; } bool QmitkTbssTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { int row = index.row(); QPair p = listOfPairs.value(row); if (index.column() == 0) p.first = value.toString(); else if (index.column() == 1) p.second = value.toInt(); else return false; listOfPairs.replace(row, p); emit(dataChanged(index, index)); return true; } return false; } Qt::ItemFlags QmitkTbssTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::ItemIsEnabled; return QAbstractTableModel::flags(index) | Qt::ItemIsEditable; } QList< QPair > QmitkTbssTableModel::getList() { return listOfPairs; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.h index 3f900fd02b..29d6917865 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTbssTableModel.h @@ -1,53 +1,52 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkTbssTableModel_h #define QmitkTbssTableModel_h #include #include #include #include class QmitkTbssTableModel : public QAbstractTableModel { //Q_OBJECT public: QmitkTbssTableModel(QObject *parent=0); QmitkTbssTableModel(QList< QPair > listofPairs, QObject *parent=0); int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole); bool insertRows(int position, int rows, const QModelIndex &index=QModelIndex()); bool removeRows(int position, int rows, const QModelIndex &index=QModelIndex()); QList< QPair > getList(); private: QList< QPair > listOfPairs; }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp index 32c564d59f..9c33c46767 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp @@ -1,1421 +1,1419 @@ - /*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkTensorReconstructionView.h" #include "mitkDiffusionImagingConfigure.h" // qt includes #include #include #include #include #include // itk includes #include "itkTimeProbe.h" //#include "itkTensor.h" // mitk includes #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkTeemDiffusionTensor3DReconstructionImageFilter.h" #include "itkDiffusionTensor3DReconstructionImageFilter.h" #include "itkTensorImageToDiffusionImageFilter.h" #include "itkPointShell.h" #include "itkVector.h" #include "itkB0ImageExtractionImageFilter.h" #include "itkTensorReconstructionWithEigenvalueCorrectionFilter.h" //#include "itkFreeWaterEliminationFilter.h" #include "mitkProperties.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkDiffusionImageMapper.h" #include "mitkLookupTableProperty.h" #include "mitkLookupTable.h" #include "mitkImageStatisticsHolder.h" #include #include const std::string QmitkTensorReconstructionView::VIEW_ID = "org.mitk.views.tensorreconstruction"; #define DI_INFO MITK_INFO("DiffusionImaging") typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; using namespace berry; struct TrSelListener : ISelectionListener { berryObjectMacro(TrSelListener); TrSelListener(QmitkTensorReconstructionView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { /* // if(!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { bool foundDwiVolume = false; bool foundTensorVolume = false; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("DiffusionImage").compare(node->GetData()->GetNameOfClass())==0) { foundDwiVolume = true; } // only look at interesting types if(QString("TensorImage").compare(node->GetData()->GetNameOfClass())==0) { foundTensorVolume = true; } } } m_View->m_Controls->m_ItkReconstruction->setEnabled(foundDwiVolume); m_View->m_Controls->m_TeemReconstruction->setEnabled(foundDwiVolume); m_View->m_Controls->m_ReconstructionWithCorrection->setEnabled(foundDwiVolume); m_View->m_Controls->m_TensorsToDWIButton->setEnabled(foundTensorVolume); m_View->m_Controls->m_TensorsToQbiButton->setEnabled(foundTensorVolume); m_View->m_Controls->m_ResidualButton->setEnabled(foundDwiVolume && foundTensorVolume); m_View->m_Controls->m_PercentagesOfOutliers->setEnabled(foundDwiVolume && foundTensorVolume); m_View->m_Controls->m_PerSliceView->setEnabled(foundDwiVolume && foundTensorVolume); } */ } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkTensorReconstructionView* m_View; }; QmitkTensorReconstructionView::QmitkTensorReconstructionView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { m_DiffusionImages = mitk::DataStorage::SetOfObjects::New(); m_TensorImages = mitk::DataStorage::SetOfObjects::New(); } QmitkTensorReconstructionView::QmitkTensorReconstructionView(const QmitkTensorReconstructionView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkTensorReconstructionView::~QmitkTensorReconstructionView() { } void QmitkTensorReconstructionView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkTensorReconstructionViewControls; m_Controls->setupUi(parent); this->CreateConnections(); QStringList items; items << "LLS (Linear Least Squares)" << "MLE (Maximum Likelihood)" << "NLS (Nonlinear Least Squares)" << "WLS (Weighted Least Squares)"; m_Controls->m_TensorEstimationTeemEstimationMethodCombo->addItems(items); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->setCurrentIndex(0); m_Controls->m_TensorEstimationManualThreashold->setChecked(false); m_Controls->m_TensorEstimationTeemSigmaEdit->setText("NaN"); m_Controls->m_TensorEstimationTeemNumItsSpin->setValue(1); m_Controls->m_TensorEstimationTeemFuzzyEdit->setText("0.0"); m_Controls->m_TensorEstimationTeemMinValEdit->setText("1.0"); m_Controls->m_TensorEstimationTeemNumItsLabel_2->setEnabled(true); m_Controls->m_TensorEstimationTeemNumItsSpin->setEnabled(true); m_Controls->m_TensorsToDWIBValueEdit->setText("1000"); Advanced1CheckboxClicked(); Advanced2CheckboxClicked(); Advanced3CheckboxClicked(); TeemCheckboxClicked(); #ifndef DIFFUSION_IMAGING_EXTENDED m_Controls->m_TeemToggle->setVisible(false); #endif // define data type for combobox //m_Controls->m_ImageSelector->SetDataStorage( this->GetDefaultDataStorage() ); //m_Controls->m_ImageSelector->SetPredicate( mitk::NodePredicateDataType::New("DiffusionImage") ); } } void QmitkTensorReconstructionView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkTensorReconstructionView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkTensorReconstructionView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TeemToggle), SIGNAL(clicked()), this, SLOT(TeemCheckboxClicked()) ); connect( (QObject*)(m_Controls->m_ItkReconstruction), SIGNAL(clicked()), this, SLOT(ItkReconstruction()) ); connect( (QObject*)(m_Controls->m_TeemReconstruction), SIGNAL(clicked()), this, SLOT(TeemReconstruction()) ); connect( (QObject*)(m_Controls->m_ReconstructionWithCorrection), SIGNAL(clicked()), this, SLOT(ReconstructionWithCorrection()) ); connect( (QObject*)(m_Controls->m_TensorEstimationTeemEstimationMethodCombo), SIGNAL(currentIndexChanged(int)), this, SLOT(MethodChoosen(int)) ); connect( (QObject*)(m_Controls->m_Advanced1), SIGNAL(clicked()), this, SLOT(Advanced1CheckboxClicked()) ); connect( (QObject*)(m_Controls->m_Advanced2), SIGNAL(clicked()), this, SLOT(Advanced2CheckboxClicked()) ); connect( (QObject*)(m_Controls->m_Advanced3), SIGNAL(clicked()), this, SLOT(Advanced3CheckboxClicked()) ); connect( (QObject*)(m_Controls->m_TensorEstimationManualThreashold), SIGNAL(clicked()), this, SLOT(ManualThresholdClicked()) ); connect( (QObject*)(m_Controls->m_TensorsToDWIButton), SIGNAL(clicked()), this, SLOT(TensorsToDWI()) ); connect( (QObject*)(m_Controls->m_TensorsToQbiButton), SIGNAL(clicked()), this, SLOT(TensorsToQbi()) ); connect( (QObject*)(m_Controls->m_ResidualButton), SIGNAL(clicked()), this, SLOT(ResidualCalculation()) ); connect( (QObject*)(m_Controls->m_PerSliceView), SIGNAL(pointSelected(int, int)), this, SLOT(ResidualClicked(int, int)) ); } } void QmitkTensorReconstructionView::ResidualClicked(int slice, int volume) { // Use image coord to reset crosshair // Find currently selected diffusion image // Update Label // to do: This position should be modified in order to skip B0 volumes that are not taken into account // when calculating residuals // Find the diffusion image mitk::DiffusionImage* diffImage; mitk::DataNode::Pointer correctNode; mitk::Geometry3D* geometry; if (m_DiffusionImage.IsNotNull()) { diffImage = static_cast*>(m_DiffusionImage->GetData()); geometry = diffImage->GetGeometry(); // Remember the node whose display index must be updated correctNode = mitk::DataNode::New(); correctNode = m_DiffusionImage; } if(diffImage != NULL) { typedef vnl_vector_fixed< double, 3 > GradientDirectionType; typedef itk::VectorContainer< unsigned int, GradientDirectionType > GradientDirectionContainerType; GradientDirectionContainerType::Pointer dirs = diffImage->GetDirections(); for(int i=0; iSize() && i<=volume; i++) { GradientDirectionType grad = dirs->ElementAt(i); // check if image is b0 weighted if(fabs(grad[0]) < 0.001 && fabs(grad[1]) < 0.001 && fabs(grad[2]) < 0.001) { volume++; } } QString pos = "Volume: "; pos.append(QString::number(volume)); pos.append(", Slice: "); pos.append(QString::number(slice)); m_Controls->m_PositionLabel->setText(pos); if(correctNode) { int oldDisplayVal; correctNode->GetIntProperty("DisplayChannel", oldDisplayVal); std::string oldVal = QString::number(oldDisplayVal).toStdString(); std::string newVal = QString::number(volume).toStdString(); correctNode->SetIntProperty("DisplayChannel",volume); correctNode->SetSelected(true); this->FirePropertyChanged("DisplayChannel", oldVal, newVal); correctNode->UpdateOutputInformation(); mitk::Point3D p3 = m_MultiWidget->GetCrossPosition(); itk::Index<3> ix; geometry->WorldToIndex(p3, ix); // ix[2] = slice; mitk::Vector3D vec; vec[0] = ix[0]; vec[1] = ix[1]; vec[2] = slice; mitk::Vector3D v3New; geometry->IndexToWorld(vec, v3New); mitk::Point3D origin = geometry->GetOrigin(); mitk::Point3D p3New; p3New[0] = v3New[0] + origin[0]; p3New[1] = v3New[1] + origin[1]; p3New[2] = v3New[2] + origin[2]; m_MultiWidget->MoveCrossToPosition(p3New); m_MultiWidget->RequestUpdate(); } } } void QmitkTensorReconstructionView::TeemCheckboxClicked() { m_Controls->groupBox_3->setVisible(m_Controls-> m_TeemToggle->isChecked()); } void QmitkTensorReconstructionView::Advanced1CheckboxClicked() { bool check = m_Controls-> m_Advanced1->isChecked(); m_Controls->frame->setVisible(check); } void QmitkTensorReconstructionView::Advanced2CheckboxClicked() { bool check = m_Controls-> m_Advanced2->isChecked(); m_Controls->frame_2->setVisible(check); } void QmitkTensorReconstructionView::Advanced3CheckboxClicked() { bool check = m_Controls-> m_Advanced3->isChecked(); m_Controls->frame_6->setVisible(check); } void QmitkTensorReconstructionView::ManualThresholdClicked() { m_Controls->m_TensorReconstructionThreasholdEdit_2->setEnabled( m_Controls->m_TensorEstimationManualThreashold->isChecked()); } void QmitkTensorReconstructionView::Activated() { QmitkFunctionality::Activated(); } void QmitkTensorReconstructionView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkTensorReconstructionView::MethodChoosen(int method) { m_Controls->m_TensorEstimationTeemNumItsLabel_2->setEnabled(method==3); m_Controls->m_TensorEstimationTeemNumItsSpin->setEnabled(method==3); } void QmitkTensorReconstructionView::ResidualCalculation() { // Extract dwi and dti from current selection // In case of multiple selections, take the first one, since taking all combinations is not meaningful mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); mitk::DiffusionImage::Pointer diffImage = mitk::DiffusionImage::New(); TensorImageType::Pointer tensorImage; std::string nodename; if(m_DiffusionImage.IsNotNull()) { diffImage = static_cast*>(m_DiffusionImage->GetData()); } else return; if(m_TensorImage.IsNotNull()) { mitk::TensorImage* mitkVol; mitkVol = static_cast(m_TensorImage->GetData()); mitk::CastToItkImage(mitkVol, tensorImage); m_TensorImage->GetStringProperty("name", nodename); } else return; typedef itk::TensorImageToDiffusionImageFilter< TTensorPixelType, DiffusionPixelType > FilterType; FilterType::GradientListType gradientList; mitk::DiffusionImage::GradientDirectionContainerType* gradients = diffImage->GetDirections(); // Copy gradients vectors from gradients to gradientList for(int i=0; iSize(); i++) { mitk::DiffusionImage::GradientDirectionType vec = gradients->at(i); itk::Vector grad; grad[0] = vec[0]; grad[1] = vec[1]; grad[2] = vec[2]; gradientList.push_back(grad); } // Find the min and the max values from a baseline image mitk::ImageStatisticsHolder *stats = diffImage->GetStatistics(); //Initialize filter that calculates the modeled diffusion weighted signals FilterType::Pointer filter = FilterType::New(); filter->SetInput( tensorImage ); filter->SetBValue(diffImage->GetB_Value()); filter->SetGradientList(gradientList); filter->SetMin(stats->GetScalarValueMin()); filter->SetMax(500); filter->Update(); // TENSORS TO DATATREE mitk::DiffusionImage::Pointer image = mitk::DiffusionImage::New(); image->SetVectorImage( filter->GetOutput() ); image->SetB_Value(diffImage->GetB_Value()); image->SetDirections(gradientList); image->SetOriginalDirections(gradientList); image->InitializeFromVectorImage(); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); mitk::DiffusionImageMapper::SetDefaultProperties(node); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_dwi"); node->SetName(newname.toAscii()); GetDefaultDataStorage()->Add(node); std::vector b0Indices = image->GetB0Indices(); typedef itk::ResidualImageFilter ResidualImageFilterType; ResidualImageFilterType::Pointer residualFilter = ResidualImageFilterType::New(); residualFilter->SetInput(diffImage->GetVectorImage()); residualFilter->SetSecondDiffusionImage(image->GetVectorImage()); residualFilter->SetGradients(gradients); residualFilter->SetB0Index(b0Indices[0]); residualFilter->SetB0Threshold(30); residualFilter->Update(); itk::Image::Pointer residualImage = itk::Image::New(); residualImage = residualFilter->GetOutput(); mitk::Image::Pointer mitkResImg = mitk::Image::New(); mitk::CastToMitkImage(residualImage, mitkResImg); stats = mitkResImg->GetStatistics(); float min = stats->GetScalarValueMin(); float max = stats->GetScalarValueMax(); mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New(); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetTableRange(min, max); // If you don't want to use the whole color range, you can use // SetValueRange, SetHueRange, and SetSaturationRange lookupTable->Build(); int size = lookupTable->GetTable()->GetSize(); vtkSmartPointer reversedlookupTable = vtkSmartPointer::New(); reversedlookupTable->SetTableRange(min+1, max); reversedlookupTable->Build(); for(int i=0; i<256; i++) { double* rgba = reversedlookupTable->GetTableValue(255-i); lookupTable->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]); } lut->SetVtkLookupTable(lookupTable); lutProp->SetLookupTable(lut); // Create lookuptable mitk::DataNode::Pointer resNode=mitk::DataNode::New(); resNode->SetData( mitkResImg ); resNode->SetName("Residual Image"); resNode->SetProperty("LookupTable", lutProp); bool b; resNode->GetBoolProperty("use color", b); resNode->SetBoolProperty("use color", false); GetDefaultDataStorage()->Add(resNode); m_MultiWidget->RequestUpdate(); // Draw Graph std::vector means = residualFilter->GetMeans(); std::vector q1s = residualFilter->GetQ1(); std::vector q3s = residualFilter->GetQ3(); std::vector percentagesOfOUtliers = residualFilter->GetPercentagesOfOutliers(); m_Controls->m_ResidualAnalysis->SetMeans(means); m_Controls->m_ResidualAnalysis->SetQ1(q1s); m_Controls->m_ResidualAnalysis->SetQ3(q3s); m_Controls->m_ResidualAnalysis->SetPercentagesOfOutliers(percentagesOfOUtliers); if(m_Controls->m_PercentagesOfOutliers->isChecked()) { m_Controls->m_ResidualAnalysis->DrawPercentagesOfOutliers(); } else { m_Controls->m_ResidualAnalysis->DrawMeans(); } // Draw Graph for volumes per slice in the QGraphicsView std::vector< std::vector > outliersPerSlice = residualFilter->GetOutliersPerSlice(); int xSize = outliersPerSlice.size(); if(xSize == 0) { return; } int ySize = outliersPerSlice[0].size(); // Find maximum in outliersPerSlice double maxOutlier= 0.0; for(int i=0; imaxOutlier) { maxOutlier = outliersPerSlice[i][j]; } } } // Create some QImage QImage qImage(xSize, ySize, QImage::Format_RGB32); QImage legend(1, 256, QImage::Format_RGB32); QRgb value; vtkSmartPointer lookup = vtkSmartPointer::New(); lookup->SetTableRange(0.0, maxOutlier); lookup->Build(); reversedlookupTable->SetTableRange(0, maxOutlier); reversedlookupTable->Build(); for(int i=0; i<256; i++) { double* rgba = reversedlookupTable->GetTableValue(255-i); lookup->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]); } // Fill qImage for(int i=0; iMapValue(out); int r, g, b; r = _rgba[0]; g = _rgba[1]; b = _rgba[2]; value = qRgb(r, g, b); qImage.setPixel(i,j,value); } } for(int i=0; i<256; i++) { double* rgba = lookup->GetTableValue(i); int r, g, b; r = rgba[0]*255; g = rgba[1]*255; b = rgba[2]*255; value = qRgb(r, g, b); legend.setPixel(0,255-i,value); } QString upper = QString::number(maxOutlier, 'g', 3); upper.append(" %"); QString lower = QString::number(0.0); lower.append(" %"); m_Controls->m_UpperLabel->setText(upper); m_Controls->m_LowerLabel->setText(lower); QGraphicsScene* scene = new QGraphicsScene; QGraphicsScene* scene2 = new QGraphicsScene; QPixmap pixmap(QPixmap::fromImage(qImage)); QGraphicsPixmapItem *item = new QGraphicsPixmapItem( pixmap, 0, scene); item->scale(10.0, 3.0); QPixmap pixmap2(QPixmap::fromImage(legend)); QGraphicsPixmapItem *item2 = new QGraphicsPixmapItem( pixmap2, 0, scene2); item2->scale(20.0, 1.0); m_Controls->m_PerSliceView->SetResidualPixmapItem(item); m_Controls->m_PerSliceView->setScene(scene); m_Controls->m_LegendView->setScene(scene2); m_Controls->m_PerSliceView->show(); m_Controls->m_PerSliceView->repaint(); m_Controls->m_LegendView->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ); m_Controls->m_LegendView->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ); m_Controls->m_LegendView->show(); m_Controls->m_LegendView->repaint(); } void QmitkTensorReconstructionView::ItkReconstruction() { Reconstruct(0); } void QmitkTensorReconstructionView::TeemReconstruction() { Reconstruct(1); } void QmitkTensorReconstructionView::ReconstructionWithCorrection() { Reconstruct(2); } void QmitkTensorReconstructionView::Reconstruct(int method) { if(method == 0) ItkTensorReconstruction(m_DiffusionImages); if(method == 1) TeemTensorReconstruction(m_DiffusionImages); if(method == 2) { TensorReconstructionWithCorr(m_DiffusionImages); } } void QmitkTensorReconstructionView::TensorReconstructionWithCorr (mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { typedef mitk::DiffusionImage DiffusionImageType; DiffusionImageType* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); ++itemiter; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Tensor reconstruction with correction for negative eigenvalues"; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Tensor reconstruction for %s", nodename.c_str()).toAscii()); typedef itk::TensorReconstructionWithEigenvalueCorrectionFilter< DiffusionPixelType, TTensorPixelType > ReconstructionFilter; float b0Threshold = m_Controls->m_ReconstructionThreshold->text().toFloat(); ReconstructionFilter::Pointer reconFilter = ReconstructionFilter::New(); reconFilter->SetGradientImage( vols->GetDirections(), vols->GetVectorImage() ); reconFilter->SetBValue(vols->GetB_Value()); reconFilter->SetB0Threshold(b0Threshold); reconFilter->Update(); typedef itk::Image, 3> TensorImageType; TensorImageType::Pointer outputTensorImg = reconFilter->GetOutput(); typedef itk::ImageRegionIterator TensorImageIteratorType; TensorImageIteratorType tensorIt(outputTensorImg, outputTensorImg->GetRequestedRegion()); tensorIt.GoToBegin(); int negatives = 0; while(!tensorIt.IsAtEnd()) { typedef itk::DiffusionTensor3D TensorType; TensorType tensor = tensorIt.Get(); TensorType::EigenValuesArrayType ev; tensor.ComputeEigenValues(ev); for(unsigned int i=0; iInitializeByItk( outputTensorImg.GetPointer() ); image->SetVolume( outputTensorImg->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_dti"); SetDefaultNodeProperties(node, newname.toStdString()); nodes.push_back(node); // Corrected diffusion image typedef itk::VectorImage ImageType; ImageType::Pointer correctedVols = reconFilter->GetVectorImage(); DiffusionImageType::Pointer correctedDiffusion = DiffusionImageType::New(); correctedDiffusion->SetVectorImage(correctedVols); correctedDiffusion->SetDirections(vols->GetDirections()); correctedDiffusion->SetB_Value(vols->GetB_Value()); correctedDiffusion->SetOriginalDirections(vols->GetDirections()); correctedDiffusion->InitializeFromVectorImage(); mitk::DataNode::Pointer diffNode=mitk::DataNode::New(); diffNode->SetData( correctedDiffusion ); QString diffname; diffname = diffname.append(nodename.c_str()); diffname = diffname.append("corrDiff"); SetDefaultNodeProperties(diffNode, diffname.toStdString()); nodes.push_back(diffNode); // B0 mask as used in tensorreconstructionwithcorrectionfilter typedef itk::Image MaskImageType; MaskImageType::Pointer mask = reconFilter->GetMask(); mitk::Image::Pointer mitkMask; mitk::CastToMitkImage(mask, mitkMask); mitk::DataNode::Pointer maskNode=mitk::DataNode::New(); maskNode->SetData( mitkMask ); QString maskname; maskname = maskname.append(nodename.c_str()); maskname = maskname.append("_mask"); SetDefaultNodeProperties(maskNode, maskname.toStdString()); nodes.push_back(maskNode); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toAscii()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex ; return ; } } void QmitkTensorReconstructionView::ItkTensorReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); ++itemiter; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Tensor reconstruction for %s", nodename.c_str()).toAscii()); typedef itk::DiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); tensorReconstructionFilter->SetGradientImage( vols->GetDirections(), vols->GetVectorImage() ); tensorReconstructionFilter->SetBValue(vols->GetB_Value()); tensorReconstructionFilter->SetThreshold( m_Controls->m_TensorReconstructionThreasholdEdit->text().toFloat() ); tensorReconstructionFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // TENSORS TO DATATREE mitk::TensorImage::Pointer image = mitk::TensorImage::New(); typedef itk::Image, 3> TensorImageType; TensorImageType::Pointer tensorImage; tensorImage = tensorReconstructionFilter->GetOutput(); // Check the tensor for negative eigenvalues if(m_Controls->m_CheckNegativeEigenvalues->isChecked()) { typedef itk::ImageRegionIterator TensorImageIteratorType; TensorImageIteratorType tensorIt(tensorImage, tensorImage->GetRequestedRegion()); tensorIt.GoToBegin(); while(!tensorIt.IsAtEnd()) { typedef itk::DiffusionTensor3D TensorType; //typedef itk::Tensor TensorType2; TensorType tensor = tensorIt.Get(); // TensorType2 tensor2; /* for(int i=0; i SymEigenSystemType; SymEigenSystemType eig (tensor2.GetVnlMatrix()); for(unsigned int i=0; iInitializeByItk( tensorImage.GetPointer() ); image->SetVolume( tensorReconstructionFilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_dti"); SetDefaultNodeProperties(node, newname.toStdString()); nodes.push_back(node); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toAscii()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex ; return ; } } void QmitkTensorReconstructionView::TeemTensorReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); ++itemiter; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Teem Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Teem Tensor reconstruction for %s", nodename.c_str()).toAscii()); typedef mitk::TeemDiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); tensorReconstructionFilter->SetInput( vols ); if(!m_Controls->m_TensorEstimationTeemSigmaEdit->text().contains(QString("NaN"))) tensorReconstructionFilter->SetSigma( m_Controls->m_TensorEstimationTeemSigmaEdit->text().toFloat() ); switch(m_Controls->m_TensorEstimationTeemEstimationMethodCombo->currentIndex()) { // items << "LLS (Linear Least Squares)" //<< "MLE (Maximum Likelihood)" //<< "NLS (Nonlinear Least Squares)" //<< "WLS (Weighted Least Squares)"; case 0: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsLLS); break; case 1: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsMLE); break; case 2: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsNLS); break; case 3: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsWLS); break; default: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsLLS); } tensorReconstructionFilter->SetNumIterations( m_Controls->m_TensorEstimationTeemNumItsSpin->value() ); if(m_Controls->m_TensorEstimationManualThreashold->isChecked()) tensorReconstructionFilter->SetConfidenceThreshold( m_Controls->m_TensorReconstructionThreasholdEdit_2->text().toDouble() ); tensorReconstructionFilter->SetConfidenceFuzzyness( m_Controls->m_TensorEstimationTeemFuzzyEdit->text().toFloat() ); tensorReconstructionFilter->SetMinPlausibleValue( m_Controls->m_TensorEstimationTeemMinValEdit->text().toDouble() ); tensorReconstructionFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s." ; // TENSORS TO DATATREE mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( tensorReconstructionFilter->GetOutputItk() ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_dtix"); SetDefaultNodeProperties(node2, newname.toStdString()); nodes.push_back(node2); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toAscii()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex ; return ; } } void QmitkTensorReconstructionView::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 500 ) ); node->SetProperty( "Scaling", mitk::FloatProperty::New( 1.0 ) ); node->SetProperty( "Normalization", mitk::OdfNormalizationMethodProperty::New()); node->SetProperty( "ScaleBy", mitk::OdfScaleByProperty::New()); node->SetProperty( "IndexParam1", mitk::FloatProperty::New(2)); node->SetProperty( "IndexParam2", mitk::FloatProperty::New(1)); node->SetProperty( "visible", mitk::BoolProperty::New( true ) ); node->SetProperty( "VisibleOdfs", mitk::BoolProperty::New( false ) ); node->SetProperty ("layer", mitk::IntProperty::New(100)); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); //node->SetProperty( "opacity", mitk::FloatProperty::New(1.0f) ); node->SetProperty( "name", mitk::StringProperty::New(name) ); } //node->SetProperty( "volumerendering", mitk::BoolProperty::New( false ) ); //node->SetProperty( "use color", mitk::BoolProperty::New( true ) ); //node->SetProperty( "texture interpolation", mitk::BoolProperty::New( true ) ); //node->SetProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); //node->SetProperty( "layer", mitk::IntProperty::New(0)); //node->SetProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); //node->SetOpacity(1.0f); //node->SetColor(1.0,1.0,1.0); //node->SetVisibility(true); //node->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); //mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); //mitk::LevelWindow levelwindow; //// levelwindow.SetAuto( image ); //levWinProp->SetLevelWindow( levelwindow ); //node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); //// add a default rainbow lookup table for color mapping //if(!node->GetProperty("LookupTable")) //{ // mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); // vtkLookupTable* vtkLut = mitkLut->GetVtkLookupTable(); // vtkLut->SetHueRange(0.6667, 0.0); // vtkLut->SetTableRange(0.0, 20.0); // vtkLut->Build(); // mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); // mitkLutProp->SetLookupTable(mitkLut); // node->SetProperty( "LookupTable", mitkLutProp ); //} //if(!node->GetProperty("binary")) // node->SetProperty( "binary", mitk::BoolProperty::New( false ) ); //// add a default transfer function //mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); //node->SetProperty ( "TransferFunction", mitk::TransferFunctionProperty::New ( tf.GetPointer() ) ); //// set foldername as string property //mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New( name ); //node->SetProperty( "name", nameProp ); void QmitkTensorReconstructionView::TensorsToDWI() { DoTensorsToDWI(m_TensorImages); } void QmitkTensorReconstructionView::TensorsToQbi() { for (int i=0; isize(); i++) { mitk::DataNode::Pointer tensorImageNode = m_TensorImages->at(i); MITK_INFO << "starting Q-Ball estimation"; typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; TensorImageType::Pointer itkvol = TensorImageType::New(); mitk::CastToItkImage(dynamic_cast(tensorImageNode->GetData()), itkvol); typedef itk::TensorImageToQBallImageFilter< TTensorPixelType, TTensorPixelType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( itkvol ); filter->Update(); typedef itk::Vector OutputPixelType; typedef itk::Image OutputImageType; mitk::QBallImage::Pointer image = mitk::QBallImage::New(); OutputImageType::Pointer outimg = filter->GetOutput(); image->InitializeByItk( outimg.GetPointer() ); image->SetVolume( outimg->GetBufferPointer() ); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(tensorImageNode->GetName().c_str()); newname = newname.append("_qbi"); node->SetName(newname.toAscii()); GetDefaultDataStorage()->Add(node); } } void QmitkTensorReconstructionView::OnSelectionChanged( std::vector nodes ) { if ( !this->IsVisible() ) return; m_DiffusionImages = mitk::DataStorage::SetOfObjects::New(); m_TensorImages = mitk::DataStorage::SetOfObjects::New(); bool foundDwiVolume = false; bool foundTensorVolume = false; m_Controls->m_DiffusionImageLabel->setText("-"); m_Controls->m_TensorImageLabel->setText("-"); m_DiffusionImage = NULL; m_TensorImage = NULL; // iterate selection for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNull()) continue; // only look at interesting types if(dynamic_cast*>(node->GetData())) { foundDwiVolume = true; m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); m_DiffusionImages->push_back(node); m_DiffusionImage = node; } else if(dynamic_cast(node->GetData())) { foundTensorVolume = true; m_Controls->m_TensorImageLabel->setText(node->GetName().c_str()); m_TensorImages->push_back(node); m_TensorImage = node; } } m_Controls->m_ItkReconstruction->setEnabled(foundDwiVolume); m_Controls->m_TeemReconstruction->setEnabled(foundDwiVolume); m_Controls->m_ReconstructionWithCorrection->setEnabled(foundDwiVolume); m_Controls->m_TensorsToDWIButton->setEnabled(foundTensorVolume); m_Controls->m_TensorsToQbiButton->setEnabled(foundTensorVolume); m_Controls->m_ResidualButton->setEnabled(foundDwiVolume && foundTensorVolume); m_Controls->m_PercentagesOfOutliers->setEnabled(foundDwiVolume && foundTensorVolume); m_Controls->m_PerSliceView->setEnabled(foundDwiVolume && foundTensorVolume); } template std::vector > QmitkTensorReconstructionView::MakeGradientList() { std::vector > retval; vnl_matrix_fixed* U = itk::PointShell >::DistributePointShell(); for(int i=0; i v; v[0] = U->get(0,i); v[1] = U->get(1,i); v[2] = U->get(2,i); retval.push_back(v); } // Add 0 vector for B0 itk::Vector v; v.Fill(0.0); retval.push_back(v); return retval; } void QmitkTensorReconstructionView::DoTensorsToDWI (mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { std::string nodename; (*itemiter)->GetStringProperty("name", nodename); mitk::TensorImage* vol = static_cast((*itemiter)->GetData()); ++itemiter; typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; TensorImageType::Pointer itkvol = TensorImageType::New(); mitk::CastToItkImage(vol, itkvol); typedef itk::TensorImageToDiffusionImageFilter< TTensorPixelType, DiffusionPixelType > FilterType; FilterType::GradientListType gradientList; switch(m_Controls->m_TensorsToDWINumDirsSelect->currentIndex()) { case 0: gradientList = MakeGradientList<12>(); break; case 1: gradientList = MakeGradientList<42>(); break; case 2: gradientList = MakeGradientList<92>(); break; case 3: gradientList = MakeGradientList<162>(); break; case 4: gradientList = MakeGradientList<252>(); break; case 5: gradientList = MakeGradientList<362>(); break; case 6: gradientList = MakeGradientList<492>(); break; case 7: gradientList = MakeGradientList<642>(); break; case 8: gradientList = MakeGradientList<812>(); break; case 9: gradientList = MakeGradientList<1002>(); break; default: gradientList = MakeGradientList<92>(); } double bVal = m_Controls->m_TensorsToDWIBValueEdit->text().toDouble(); // DWI ESTIMATION clock.Start(); MBI_INFO << "DWI Estimation "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "DWI Estimation for %s", nodename.c_str()).toAscii()); FilterType::Pointer filter = FilterType::New(); filter->SetInput( itkvol ); filter->SetBValue(bVal); filter->SetGradientList(gradientList); //filter->SetNumberOfThreads(1); filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // TENSORS TO DATATREE mitk::DiffusionImage::Pointer image = mitk::DiffusionImage::New(); image->SetVectorImage( filter->GetOutput() ); image->SetB_Value(bVal); image->SetDirections(gradientList); image->SetOriginalDirections(gradientList); image->InitializeFromVectorImage(); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DiffusionImageMapper::SetDefaultProperties(node); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_dwi"); node->SetName(newname.toAscii()); nodes.push_back(node); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toAscii()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex ; return ; } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.h index afbe6f821d..8674cece14 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.h @@ -1,127 +1,125 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKTENSORRECONSTRUCTIONVIEW_H_INCLUDED #define _QMITKTENSORRECONSTRUCTIONVIEW_H_INCLUDED #include #include #include "ui_QmitkTensorReconstructionViewControls.h" #include #include typedef short DiffusionPixelType; struct TrSelListener; /*! * \ingroup org_mitk_gui_qt_tensorreconstruction_internal * * \brief QmitkTensorReconstructionView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkTensorReconstructionView : public QmitkFunctionality { friend struct TrSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkTensorReconstructionView(); QmitkTensorReconstructionView(const QmitkTensorReconstructionView& other); virtual ~QmitkTensorReconstructionView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); static const int nrconvkernels; protected slots: void TensorsToQbi(); void TensorsToDWI(); void DoTensorsToDWI(mitk::DataStorage::SetOfObjects::Pointer inImages); void TeemCheckboxClicked(); void Advanced1CheckboxClicked(); void Advanced2CheckboxClicked(); void Advanced3CheckboxClicked(); void ManualThresholdClicked(); void MethodChoosen(int method); void Reconstruct(int method); void TeemReconstruction(); void ItkReconstruction(); void ReconstructionWithCorrection(); void ResidualCalculation(); void ResidualClicked(int slice, int volume); protected: void ItkTensorReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages); void TeemTensorReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages); void TensorReconstructionWithCorr (mitk::DataStorage::SetOfObjects::Pointer inImages); void OnSelectionChanged( std::vector nodes ); Ui::QmitkTensorReconstructionViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; template std::vector > MakeGradientList() ; template void TemplatedAnalyticalTensorReconstruction(mitk::DiffusionImage* vols, float lambda, std::string nodename, std::vector* nodes, int normalization); void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); mitk::DataNode::Pointer m_DiffusionImage; mitk::DataNode::Pointer m_TensorImage; mitk::DataStorage::SetOfObjects::Pointer m_DiffusionImages; mitk::DataStorage::SetOfObjects::Pointer m_TensorImages; }; #endif // _QMITKTENSORRECONSTRUCTIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.cpp index 4ec33c8f57..eef9ccd480 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.cpp @@ -1,1498 +1,1497 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" // Qmitk #include "QmitkTractbasedSpatialStatisticsView.h" #include "QmitkStdMultiWidget.h" #include "mitkDataNodeObject.h" #include // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "vtkFloatArray.h" #include "vtkLinearTransform.h" #include "vtkPoints.h" #include "mitkSurface.h" #include #include "vtkArrowSource.h" #include "vtkUnstructuredGrid.h" #include "vtkPointData.h" #include #include #include #include #include #include "mitkITKImageImport.h" // #include "mitkImageMapperGL2D.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkImageAccessByItk.h" #include "mitkTensorImage.h" #include "itkDiffusionTensor3D.h" #define SEARCHSIGMA 10 /* length in linear voxel dimens { // create new ones m_PointSetNode = mitk::PointSet::New();ions */ #define MAXSEARCHLENGTH (3*SEARCHSIGMA) const std::string QmitkTractbasedSpatialStatisticsView::VIEW_ID = "org.mitk.views.tractbasedspatialstatistics"; using namespace berry; struct TbssSelListener : ISelectionListener { berryObjectMacro(TbssSelListener) TbssSelListener(QmitkTractbasedSpatialStatisticsView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { bool foundTbssRoi = false; bool foundTbss = false; bool found3dImage = false; bool found4dImage = false; bool foundFiberBundle = false; mitk::TbssRoiImage* roiImage; mitk::TbssImage* image; mitk::Image* img; mitk::FiberBundleX* fib; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types // check for valid data mitk::BaseData* nodeData = node->GetData(); if( nodeData ) { if(QString("TbssRoiImage").compare(nodeData->GetNameOfClass())==0) { foundTbssRoi = true; roiImage = static_cast(nodeData); } else if (QString("TbssImage").compare(nodeData->GetNameOfClass())==0) { foundTbss = true; image = static_cast(nodeData); } else if(QString("Image").compare(nodeData->GetNameOfClass())==0) { img = static_cast(nodeData); if(img->GetDimension() == 3) { found3dImage = true; } else if(img->GetDimension() == 4) { found4dImage = true; } } else if (QString("FiberBundleX").compare(nodeData->GetNameOfClass())==0) { foundFiberBundle = true; fib = static_cast(nodeData); } } // end CHECK nodeData != NULL } } m_View->m_Controls->m_CreateRoi->setEnabled(found3dImage); m_View->m_Controls->m_ImportFsl->setEnabled(found4dImage); if(found3dImage) { m_View->InitPointsets(); } if(foundTbss && foundTbssRoi) { m_View->Plot(image, roiImage); } if(found3dImage == true && foundFiberBundle) { m_View->PlotFiberBundle(fib, img); } } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkTractbasedSpatialStatisticsView* m_View; }; QmitkTractbasedSpatialStatisticsView::QmitkTractbasedSpatialStatisticsView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkTractbasedSpatialStatisticsView::~QmitkTractbasedSpatialStatisticsView() { } void QmitkTractbasedSpatialStatisticsView::OnSelectionChanged(std::vector nodes) { //datamanager selection changed if (!this->IsActivated()) return; // Get DataManagerSelection if (!this->GetDataManagerSelection().empty()) { mitk::DataNode::Pointer sourceImageNode = this->GetDataManagerSelection().front(); mitk::Image::Pointer sourceImage = dynamic_cast(sourceImageNode->GetData()); if (!sourceImage) { m_Controls->m_TbssImageLabel->setText( QString( sourceImageNode->GetName().c_str() ) + " is no image" ); return; } // set Text m_Controls->m_TbssImageLabel->setText( QString( sourceImageNode->GetName().c_str() ) + " (" + QString::number(sourceImage->GetDimension()) + "D)" ); } else { m_Controls->m_TbssImageLabel->setText("Please select an image"); } } void QmitkTractbasedSpatialStatisticsView::InitPointsets() { // Check if PointSetStart exsits, if not create it. m_P1 = this->GetDefaultDataStorage()->GetNamedNode("PointSetNode"); if (m_PointSetNode) { //m_PointSetNode = dynamic_cast(m_P1->GetData()); return; } if ((!m_P1) || (!m_PointSetNode)) { // create new ones m_PointSetNode = mitk::PointSet::New(); m_P1 = mitk::DataNode::New(); m_P1->SetData( m_PointSetNode ); m_P1->SetProperty( "name", mitk::StringProperty::New( "PointSet" ) ); m_P1->SetProperty( "opacity", mitk::FloatProperty::New( 1 ) ); m_P1->SetProperty( "helper object", mitk::BoolProperty::New(false) ); // CHANGE if wanted m_P1->SetProperty( "pointsize", mitk::FloatProperty::New( 0.1 ) ); m_P1->SetColor( 1.0, 0.0, 0.0 ); this->GetDefaultDataStorage()->Add(m_P1); m_Controls->m_PointWidget->SetPointSetNode(m_P1); m_Controls->m_PointWidget->SetMultiWidget(GetActiveStdMultiWidget()); } } void QmitkTractbasedSpatialStatisticsView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkTractbasedSpatialStatisticsViewControls; m_Controls->setupUi( parent ); this->CreateConnections(); } m_SelListener = berry::ISelectionListener::Pointer(new TbssSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); m_IsInitialized = false; // Table for the FSL TBSS import m_GroupModel = new QmitkTbssTableModel(); m_Controls->m_GroupInfo->setModel(m_GroupModel); } void QmitkTractbasedSpatialStatisticsView::Activated() { QmitkFunctionality::Activated(); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } void QmitkTractbasedSpatialStatisticsView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkTractbasedSpatialStatisticsView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_CreateRoi), SIGNAL(clicked()), this, SLOT(CreateRoi()) ); connect( (QObject*)(m_Controls->m_ImportFsl), SIGNAL(clicked()), this, SLOT(TbssImport()) ); connect( (QObject*)(m_Controls->m_AddGroup), SIGNAL(clicked()), this, SLOT(AddGroup()) ); connect( (QObject*)(m_Controls->m_RemoveGroup), SIGNAL(clicked()), this, SLOT(RemoveGroup()) ); connect( (QObject*)(m_Controls->m_Clipboard), SIGNAL(clicked()), this, SLOT(CopyToClipboard()) ); connect( m_Controls->m_RoiPlotWidget->m_PlotPicker, SIGNAL(selected(const QwtDoublePoint&)), SLOT(Clicked(const QwtDoublePoint&) ) ); connect( m_Controls->m_RoiPlotWidget->m_PlotPicker, SIGNAL(moved(const QwtDoublePoint&)), SLOT(Clicked(const QwtDoublePoint&) ) ); } } void QmitkTractbasedSpatialStatisticsView::CopyToClipboard() { std::vector > vals = m_Controls->m_RoiPlotWidget->GetVals(); QString clipboardText; for (std::vector >::iterator it = vals.begin(); it != vals.end(); ++it) { for (std::vector::iterator it2 = (*it).begin(); it2 != (*it).end(); ++it2) { clipboardText.append(QString("%1 \t").arg(*it2)); double d = *it2; std::cout << d <setText(clipboardText, QClipboard::Clipboard); } void QmitkTractbasedSpatialStatisticsView::RemoveGroup() { QTableView *temp = static_cast(m_Controls->m_GroupInfo); // QSortFilterProxyModel *proxy = static_cast(temp->model()); QItemSelectionModel *selectionModel = temp->selectionModel(); QModelIndexList indices = selectionModel->selectedRows(); QModelIndex index; foreach(index, indices) { int row = index.row(); m_GroupModel->removeRows(row, 1, QModelIndex()); } } std::string QmitkTractbasedSpatialStatisticsView::ReadFile(std::string whatfile) { std::string s = "Select a" + whatfile; QFileDialog* w = new QFileDialog(this->m_Controls->m_ImportFsl, QString(s.c_str()) ); w->setFileMode(QFileDialog::ExistingFiles); w->setDirectory("/home"); if(whatfile == "gradient image") { w->setNameFilter("Tbss gradient images (*.tgi)"); } // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) { return ""; MITK_INFO << "Failed to load"; } QStringList filenames = w->selectedFiles(); if (filenames.size() > 0) { std::string retval = filenames.at(0).toStdString(); return retval; } return ""; } void QmitkTractbasedSpatialStatisticsView::AddGroup() { QString group("Group"); int number = 0; QPair pair(group, number); QList< QPair >list = m_GroupModel->getList(); if(!list.contains(pair)) { m_GroupModel->insertRows(0, 1, QModelIndex()); QModelIndex index = m_GroupModel->index(0, 0, QModelIndex()); m_GroupModel->setData(index, group, Qt::EditRole); index = m_GroupModel->index(0, 1, QModelIndex()); m_GroupModel->setData(index, number, Qt::EditRole); } else { //QMessageBox::information(this, "Duplicate name"); } } void QmitkTractbasedSpatialStatisticsView::TbssImport() { // Read groups from the interface mitk::TbssImporter::Pointer importer = mitk::TbssImporter::New(); QList< QPair >list = m_GroupModel->getList(); if(list.size() == 0) { QMessageBox msgBox; msgBox.setText("No study group information has been set yet."); msgBox.exec(); return; } std::vector < std::pair > groups; for(int i=0; i pair = list.at(i); std::string s = pair.first.toStdString(); int n = pair.second; std::pair p; p.first = s; p.second = n; groups.push_back(p); } importer->SetGroupInfo(groups); std::string minfo = m_Controls->m_MeasurementInfo->text().toStdString(); importer->SetMeasurementInfo(minfo); std::string name = ""; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { mitk::Image* img = static_cast(node->GetData()); if(img->GetDimension() == 4) { importer->SetImportVolume(img); name = node->GetName(); } } } } mitk::TbssImage::Pointer tbssImage; tbssImage = importer->Import(); name += "_tbss"; AddTbssToDataStorage(tbssImage, name); } void QmitkTractbasedSpatialStatisticsView::AddTbssToDataStorage(mitk::Image* image, std::string name) { mitk::LevelWindow levelwindow; levelwindow.SetAuto( image ); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); levWinProp->SetLevelWindow( levelwindow ); mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "name", mitk::StringProperty::New(name) ); result->SetData( image ); result->SetProperty( "levelwindow", levWinProp ); // add new image to data storage and set as active to ease further processing GetDefaultDataStorage()->Add( result ); // show the results mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkTractbasedSpatialStatisticsView::Clicked(const QwtDoublePoint& pos) { if(m_Roi.size() > 0 && m_CurrentGeometry != NULL) { int index = (int)pos.x(); index = std::max(0, index); index = std::min(index, (int)m_Roi.size()); itk::Index<3> ix = m_Roi.at(index); mitk::Vector3D i; i[0] = ix[0]; i[1] = ix[1]; i[2] = ix[2]; mitk::Vector3D w; m_CurrentGeometry->IndexToWorld(i, w); mitk::Point3D origin = m_CurrentGeometry->GetOrigin(); mitk::Point3D p; p[0] = w[0] + origin[0]; p[1] = w[1] + origin[1]; p[2] = w[2] + origin[2]; m_MultiWidget->MoveCrossToPosition(p); m_Controls->m_RoiPlotWidget->drawBar(index); } } void QmitkTractbasedSpatialStatisticsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkTractbasedSpatialStatisticsView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkTractbasedSpatialStatisticsView::AdjustPlotMeasure(const QString & text) { berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } void QmitkTractbasedSpatialStatisticsView::Clustering() { /* // Create a mask using the distance map typedef itk::ImageFileReader< VectorImageType > DirectionReader; DirectionReader::Pointer directionReader = DirectionReader::New(); directionReader->SetFileName(m_TbssWorkspaceManager.GetInputDir().toStdString() + "/tbss/" + m_TbssWorkspaceManager.GetGradient().toStdString()); directionReader->Update(); VectorImageType::Pointer directions = directionReader->GetOutput(); FloatReaderType::Pointer distMapReader = FloatReaderType::New(); distMapReader->SetFileName(m_TbssWorkspaceManager.GetInputDir().toStdString() + "/stats/" + m_TbssWorkspaceManager.GetDistanceMap().toStdString()); distMapReader->Update(); FloatImageType::Pointer distanceMap = distMapReader->GetOutput(); std::string line; std::string path = "/mnt/E130-Projekte/NeuroDiffusion/BRAM DTI/TBSS/rois/cc.txt"; std::ifstream file(path.c_str()); std::vector< itk::Index< 3 > > roi; if(file.is_open()) { while(getline(file,line)) { std::vector tokens; Tokenize(line, tokens); itk::Index<3> ix; ix[0] = atoi(tokens[0].c_str()); ix[1] = atoi(tokens[1].c_str()); ix[2] = atoi(tokens[2].c_str()); roi.push_back(ix); } } if(roi.size() == 0) { return; } // Some code from the projection algorithm of tbss to create a mask std::vector< std::vector< itk::Index< 3 > > > rois; for(int j=0; j > indices; FloatImageType::SizeType size = distanceMap->GetLargestPossibleRegion().GetSize(); bool roiDone = false; while(!roiDone && j ix = roi[j]; int x=ix[0]; int y=ix[1]; int z=ix[2]; VectorImageType::PixelType dir = directions->GetPixel(ix); indices.push_back(ix); for(int iters=0;iters<2;iters++) { float distance=0; for(int d=1;d=size[0] && dy<=size[1] && dz<=size[2]) { d=MAXSEARCHLENGTH; } else if(distanceMap->GetPixel(ix)>=distance) { distance = distanceMap->GetPixel(ix); indices.push_back(ix); } else{ d=MAXSEARCHLENGTH; } } } j++; } // Create a mask from indices UCharImageType::Pointer maskItk = UCharImageType::New(); maskItk->SetRegions(distanceMap->GetRequestedRegion()); maskItk->SetDirection(distanceMap->GetDirection()); maskItk->SetSpacing(distanceMap->GetSpacing()); maskItk->SetOrigin(distanceMap->GetOrigin()); maskItk->Allocate(); // For every point on the roi create a mask and feed it to the partial voluming algorithm //maskItk->FillBuffer(0); // Create a bounding box from current ROI int xMin = numeric_limits::max(); int yMin = numeric_limits::max(); int zMin = numeric_limits::max(); int xMax = numeric_limits::min(); int yMax = numeric_limits::min(); int zMax = numeriUCharImageType::Pointer newMask = UCharImageType::New();c_limits::min(); for(int i=0; i ix = indices[i]; if(ix[0] < xMin) xMin=ix[0]; if(ix[1] < yMin) yMin=ix[1]; if(ix[2] < zMin) zMin=ix[2]; if(ix[0] > xMax) xMax=ix[0]; if(ix[1] > yMax) yMax=ix[1]; if(ix[2] > zMax) zMax=ix[2]; } FloatImageType::PointType origin = distanceMap->GetOrigin(); CharImageType::PointType originMask; originMask[0] = origin[0] + xMin; originMask[1] = origin[1] + -yMin; originMask[2] = origin[2] + zMin; CharImageType::RegionType region; CharImageType::RegionType::SizeType s; s[0] = xMax-xMin + 1; s[1] = yMax-yMin + 1; s[2] = zMax-zMin + 1; region.SetSize(s); UCharImageType::Pointer newMask = UCharImageType::New(); newMask->SetSpacing( distanceMap->GetSpacing() ); // Set the image spacing newMask->SetOrigin( originMask ); // Set the image origin newMask->SetDirection( distanceMap->GetDirection() ); // Set the image direction newMask->SetRegions( region ); newMask->Allocate(); newMask->FillBuffer(0); for(int i=0; i ix = indices[i]; itk::Point< double, 3 > point; itk::Index< 3 > index; distanceMap->TransformIndexToPhysicalPoint (ix, point); newMask->TransformPhysicalPointToIndex(point, index); newMask->SetPixel(index, 1); } */ /* UCharImageType::Pointer newMask = UCharImageType::New(); UCharReaderType::Pointer cReader = UCharReaderType::New(); cReader->SetFileName("/mnt/E130-Projekte/NeuroDiffusion/BRAM DTI/ClusteringFornix/fornix_central_maxFA_path_Dilated_by_3.nrrd"); cReader->Update(); newMask = cReader->GetOutput(); // mitk::DataNode::Pointer maskNode = readNode("itk image/mnt/E130-Projekte/NeuroDiffusion/BRAM DTI/TBSS/clusterMasks/area2.nii"); // mitk::Image::Pointer mask = dynamic_cast(maskNode->GetData()); mitk::Image::Pointer mask; mitk::CastToMitkImage(newMask, mask); typedef mitk::PartialVolumeAnalysisHistogramCalculator HistorgramCalculator; typedef mitk::PartialVolumeAnalysisClusteringCalculator ClusteringType; typedef HistorgramCalculator::HistogramType HistogramType; HistorgramCalculator::Pointer histogramCalculator = HistorgramCalculator::New(); // Make list of subjects std::vector paths; paths.push_back("/mnt/E130-Projekte/NeuroDiffusion/BRAM DTI/TBSS/FA/SORTEDBYCONDITION/FA/subset"); // paths.push_back("/mnt/E130-Projekte/NeuroDiffusion/BRAM DTI/TBSS/FA/SORTEDBYCONDITION/AXD/"); for(int j=0; j values; for(int i=0; i(node->GetData()); histogramCalculator->SetImage(image); histogramCalculator->SetImageMask( mask ); histogramCalculator->SetMaskingModeToImage(); histogramCalculator->SetNumberOfBins(25); histogramCalculator->SetUpsamplingFactor(5); histogramCalculator->SetGaussianSigma(0.0); histogramCalculator->SetForceUpdate(true); bool statisticsChanged = histogramCalculator->ComputeStatistics( ); ClusteringType::ParamsType *cparams = 0; ClusteringType::ClusterResultType *cresult = 0; ClusteringType::HistType *chist = 0; ClusteringType::HelperStructPerformClusteringRetval *currentPerformClusteringResults; try{ mitk::Image* tmpImg = histogramCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; if(imgToCluster.IsNotNull()) { // perform clustering const HistogramType *histogram = histogramCalculator->GetHistogram( ); ClusteringType::Pointer clusterer = ClusteringType::New(); clusterer->SetStepsNumIntegration(200); clusterer->SetMaxIt(1000); mitk::Image::Pointer pFiberImg; currentPerformClusteringResults = clusterer->PerformClustering(imgToCluster, histogram, 2); pFiberImg = currentPerformClusteringResults->clusteredImage; cparams = currentPerformClusteringResults->params; cresult = currentPerformClusteringResults->result; chist = currentPerformClusteringResults->hist; // m_Controls->m_HistogramWidget->SetParameters( // cparams, cresult, chist ); std::vector *xVals = chist->GetXVals(); std::vector *fiberVals = new std::vector(cresult->GetFiberVals()); double fiberFA = 0.0; double weights = 0.0; // std::cout << "x, y, fiber, nonFiber, mixed, combi" << std::endl; for(int k=0; ksize(); ++k) { fiberFA += xVals->at(k) * fiberVals->at(k); weights += fiberVals->at(k); } fiberFA = fiberFA / weights; std::cout << "FA: " << fiberFA << std::endl; values.push_back(fiberFA); } } catch ( const std::runtime_error &e ) { std::cout << "noooooooooooooooooooooooooooooooo!"; } //MITK_INFO << "number of voxels: " << indices.size(); } std::vector::iterator it = values.begin(); while(it!=values.end()) { std::cout << *it << std::endl; ++it; } }*/ } void QmitkTractbasedSpatialStatisticsView::CreateRoi() { // It is important to load the MeanFASkeletonMask image in MITK to make sure that point selection and // pathfinding is done on the same image //string filename = m_TbssWorkspaceManager.GetInputDir().toStdString() + "/stats/" + m_TbssWorkspaceManager.GetMeanFASkeletonMask().toStdString(); // Implement a way to obtain skeleton and skeletonFA without sml workspace double threshold = QInputDialog::getDouble(m_Controls->m_CreateRoi, tr("Set an FA threshold"), tr("Threshold:"), QLineEdit::Normal, 0.2); mitk::Image::Pointer image; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { mitk::Image* img = static_cast(node->GetData()); if(img->GetDimension() == 3) { image = img; } } } } if(image.IsNull()) { return; } mitk::TractAnalyzer analyzer; analyzer.SetInputImage(image); analyzer.SetThreshold(threshold); int n = 0; if(m_PointSetNode.IsNotNull()) { n = m_PointSetNode->GetSize(); if(n==0) { QMessageBox msgBox; msgBox.setText("No points have been set yet."); msgBox.exec(); } } else{ QMessageBox msgBox; msgBox.setText("No points have been set yet."); msgBox.exec(); } std::string pathDescription = ""; std::vector< itk::Index<3> > totalPath; if(n>0) { for(int i=0; iGetPoint(i); mitk::Point3D p2 = m_PointSetNode->GetPoint(i+1); itk::Index<3> StartPoint; mitk::ProgressBar::GetInstance()->Progress(); itk::Index<3> EndPoint; image->GetGeometry()->WorldToIndex(p,StartPoint); image->GetGeometry()->WorldToIndex(p2,EndPoint); MITK_INFO << "create roi"; analyzer.BuildGraph(StartPoint, EndPoint); std::vector< itk::Index<3> > path = analyzer.GetPath(); for(std::vector< itk::Index<3> >::iterator it = path.begin(); it != path.end(); it++) { itk::Index<3> ix = *it; if (!(ix==EndPoint)) { mitk::ProgressBar::GetInstance()->Progress(); totalPath.push_back(ix); std::stringstream ss; ss << ix[0] << " " << ix[1] << " " << ix[2] << "\n"; pathDescription += ss.str(); } else { // Only when dealing with the last segment the last point should be added. This one will not occur // as the first point of the next roi segment. if(i == (n-2)) { totalPath.push_back(EndPoint); std::stringstream ss; ss << EndPoint[0] << " " << EndPoint[1] << " " << EndPoint[2] << "\n"; pathDescription += ss.str(); } } } } m_Controls->m_PathTextEdit->setPlainText(QString(pathDescription.c_str())); FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(image, itkImg); CharImageType::Pointer roiImg = CharImageType::New(); roiImg->SetRegions(itkImg->GetLargestPossibleRegion().GetSize()); roiImg->SetOrigin(itkImg->GetOrigin()); roiImg->SetSpacing(itkImg->GetSpacing()); roiImg->SetDirection(itkImg->GetDirection()); roiImg->Allocate(); roiImg->FillBuffer(0); std::vector< itk::Index<3> > roi; std::vector< itk::Index<3> >::iterator it; for(it = totalPath.begin(); it != totalPath.end(); it++) { itk::Index<3> ix = *it; roiImg->SetPixel(ix, 1); roi.push_back(ix); } mitk::TbssRoiImage::Pointer tbssRoi = mitk::TbssRoiImage::New(); //mitk::CastToTbssImage(m_CurrentRoi.GetPointer(), tbssRoi); tbssRoi->SetRoi(roi); tbssRoi->SetImage(roiImg); tbssRoi->SetStructure(m_Controls->m_Structure->text().toStdString()); tbssRoi->InitializeFromImage(); // mitk::Image::Pointer tbssRoi = mitk::Image::New(); //mitk::CastToTbssImage(m_CurrentRoi.GetPointer(), tbssRoi); // mitk::CastToMitkImage(roiImg, tbssRoi); AddTbssToDataStorage(tbssRoi, m_Controls->m_RoiName->text().toStdString()); } } void QmitkTractbasedSpatialStatisticsView::PlotFiberBundle(mitk::FiberBundleX *fib, mitk::Image* img) { int num = fib->GetNumFibers(); std::cout << "number of fibers: " << num << std::endl; vtkSmartPointer fiberPolyData = fib->GetFiberPolyData(); vtkCellArray* lines = fiberPolyData->GetLines(); lines->InitTraversal(); int lineSize = lines->GetSize(); std::cout << "line size: " << lineSize << std::cout; typedef itk::Point PointType; typedef std::vector< PointType> TractType; typedef std::vector< TractType > TractContainerType; TractContainerType tracts; for( int fiberID( 0 ); fiberID < num; fiberID++ ) { vtkIdType numPointsInCell(0); vtkIdType* pointsInCell(NULL); lines->GetNextCell ( numPointsInCell, pointsInCell ); TractType singleTract; for( int pointInCellID( 0 ); pointInCellID < numPointsInCell ; pointInCellID++) { // push back point double *p = fiberPolyData->GetPoint( pointsInCell[ pointInCellID ] ); PointType point; point[0] = p[0]; point[1] = p[1]; point[2] = p[2]; singleTract.push_back( point ); } tracts.push_back(singleTract); } m_Controls->m_RoiPlotWidget->PlotFiberBundles(tracts, img); } void QmitkTractbasedSpatialStatisticsView::Plot(mitk::TbssImage* image, mitk::TbssRoiImage* roiImage) { if(m_Controls->m_TabWidget->currentWidget() == m_Controls->m_MeasureTAB) { std::vector< itk::Index<3> > roi = roiImage->GetRoi(); m_Roi = roi; m_CurrentGeometry = image->GetGeometry(); std::string resultfile = ""; /* if(image->GetPreprocessedFA()) { resultFile = image->GetPreprocessedFAFile(); } */ std::string structure = roiImage->GetStructure(); //m_View->m_CurrentGeometry = image->GetGeometry(); m_Controls->m_RoiPlotWidget->SetGroups(image->GetGroupInfo()); // Check for preprocessed results to save time //if(resultfile == "") // { // Need to calculate the results using the 4D volume // Can save the time this takes if there are results available already //std::string type = m_Controls->m_MeasureType->itemText(m_Controls->m_MeasureType->currentIndex()).toStdString(); m_Controls->m_RoiPlotWidget->SetProjections(image->GetImage()); // } m_Controls->m_RoiPlotWidget->SetRoi(roi); m_Controls->m_RoiPlotWidget->SetStructure(structure); m_Controls->m_RoiPlotWidget->SetMeasure( image->GetMeasurementInfo() ); m_Controls->m_RoiPlotWidget->DrawProfiles(resultfile); } } void QmitkTractbasedSpatialStatisticsView::Masking() { //QString filename = m_Controls->m_WorkingDirectory->text(); QString filename = "E:/Experiments/tbss"; QString faFiles = filename + "/AxD"; QString maskFiles = filename + "/bin_masks"; QDirIterator faDirIt(faFiles, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories); QDirIterator maskDirIt(maskFiles, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories); std::vector faFilenames; std::vector maskFilenames; std::vector outputFilenames; while(faDirIt.hasNext() && maskDirIt.hasNext()) { faDirIt.next(); maskDirIt.next(); if((faDirIt.fileInfo().completeSuffix() == "nii" || faDirIt.fileInfo().completeSuffix() == "mhd" || faDirIt.fileInfo().completeSuffix() == "nii.gz") && (maskDirIt.fileInfo().completeSuffix() == "nii" || maskDirIt.fileInfo().completeSuffix() == "mhd" || maskDirIt.fileInfo().completeSuffix() == "nii.gz")) { faFilenames.push_back(faDirIt.filePath().toStdString()); outputFilenames.push_back(faDirIt.fileName().toStdString()); maskFilenames.push_back(maskDirIt.filePath().toStdString()); } } std::vector::iterator faIt = faFilenames.begin(); std::vector::iterator maskIt = maskFilenames.begin(); std::vector::iterator outputIt = outputFilenames.begin(); // Now multiply all FA images with their corresponding masks QString outputDir = filename; while(faIt != faFilenames.end() && maskIt != maskFilenames.end() && outputIt != outputFilenames.end()) { std::cout << "Mask " << *faIt << " with " << *maskIt << std::endl; typedef itk::MultiplyImageFilter MultiplicationFilterType; FloatReaderType::Pointer floatReader = FloatReaderType::New(); CharReaderType::Pointer charReader = CharReaderType::New(); floatReader->SetFileName(*faIt); //floatReader->Update(); //FloatImageType::Pointer faImage = floatReader->GetOutput(); charReader->SetFileName(*maskIt); //charReader->Update(); // CharImageType::Pointer maskImage = charReader->GetOutput(); MultiplicationFilterType::Pointer multiplicationFilter = MultiplicationFilterType::New(); multiplicationFilter->SetInput1(floatReader->GetOutput()); multiplicationFilter->SetInput2(charReader->GetOutput()); multiplicationFilter->Update(); //FloatImageType::Pointer maskedImage = FloatImageType::New(); //maskedImage = MultiplicationFilter->GetOutput(); FloatWriterType::Pointer floatWriter = FloatWriterType::New(); std::string s = faFiles.toStdString().append("/"+*outputIt); floatWriter->SetFileName(s.c_str()); floatWriter->SetInput(multiplicationFilter->GetOutput()); floatWriter->Update(); ++faIt; ++maskIt; ++outputIt; } } VectorImageType::Pointer QmitkTractbasedSpatialStatisticsView::ConvertToVectorImage(mitk::Image::Pointer mitkImage) { VectorImageType::Pointer vecImg = VectorImageType::New(); mitk::Geometry3D* geo = mitkImage->GetGeometry(); mitk::Vector3D spacing = geo->GetSpacing(); mitk::Point3D origin = geo->GetOrigin(); VectorImageType::SpacingType vecSpacing; vecSpacing[0] = spacing[0]; vecSpacing[1] = spacing[1]; vecSpacing[2] = spacing[2]; VectorImageType::PointType vecOrigin; vecOrigin[0] = origin[0]; vecOrigin[1] = origin[1]; vecOrigin[2] = origin[2]; VectorImageType::SizeType size; size[0] = mitkImage->GetDimension(0); size[1] = mitkImage->GetDimension(1); size[2] = mitkImage->GetDimension(2); vecImg->SetSpacing(vecSpacing); vecImg->SetOrigin(vecOrigin); vecImg->SetRegions(size); vecImg->SetVectorLength(mitkImage->GetDimension(3)); vecImg->Allocate(); for(int x=0; x pixel = vecImg->GetPixel(ix); for (int t=0; tGetPixelValueByIndex(ix, t); pixel.SetElement(t, f); } vecImg->SetPixel(ix, pixel); } } } return vecImg; } /* void QmitkTractbasedSpatialStatisticsView::InitializeGridByVectorImage() { // Read vector image from file typedef itk::ImageFileReader< FloatVectorImageType > VectorReaderType; VectorReaderType::Pointer vectorReader = VectorReaderType::New(); vectorReader->SetFileName("E:\\tbss\\testing\\Gradient.mhd"); vectorReader->Update(); FloatVectorImageType::Pointer directions = vectorReader->GetOutput(); // Read roi from file. CharReaderType::Pointer roiReader = CharReaderType::New(); roiReader->SetFileName("E:\\tbss\\testing\\debugging skeletonization\\segment2.mhd"); roiReader->Update(); CharImageType::Pointer roi = roiReader->GetOutput(); DoInitializeGridByVectorImage(directions, roi, std::string("directions")); } void QmitkTractbasedSpatialStatisticsView::DoInitializeGridByVectorImage(FloatVectorImageType::Pointer vectorpic, CharImageType::Pointer roi, std::string name) { //vtkStructuredGrid* grid = vtkStructuredGrid::New(); itk::Matrix itkdirection = vectorpic->GetDirection(); itk::Matrix itkinversedirection = itk::Matrix(itkdirection.GetInverse()); std::vector GridPoints; vtkPoints *points = vtkPoints::New(); mitk::Geometry3D::Pointer geom = mitk::Geometry3D::New(); vtkLinearTransform *vtktransform; vtkLinearTransform *inverse; mitk::Image::Pointer geomget = mitk::Image::New(); geomget->InitializeByItk(vectorpic.GetPointer()); geom = geomget->GetGeometry(); vtktransform = geom->GetVtkTransform(); inverse = vtktransform->GetLinearInverse(); vtkFloatArray * directions = vtkFloatArray::New(); directions->SetName("Vectors"); directions->SetNumberOfComponents(3); // Iterator for the vector image itk::ImageRegionIterator it_input(vectorpic, vectorpic->GetLargestPossibleRegion()); FloatVectorType nullvector; nullvector.Fill(0); double lengthsum = 0; int id = 0; // Iterator for the roi itk::ImageRegionIterator roiIt(roi, roi->GetLargestPossibleRegion()); roiIt.GoToBegin(); for(it_input.GoToBegin(); !( it_input.IsAtEnd() || roiIt.IsAtEnd() ); ++it_input) { //VectorType val = it_input.Value(); if(it_input.Value() != nullvector && roiIt.Get() != 0) { //itk::Point point; mitk::Point3D mitkpoint, mitkworldpoint; mitk::Point3D mitkendpoint, mitkworldendpoint; mitk::Vector3D mitkvector, mitktransvector; itk::Point direction = it_input.Value().GetDataPointer(); //itk::Index<3> in_input = it_input.GetIndex(); //itk::ContinuousIndex cindirection; FloatVectorType transvec = it_input.Value(); mitkvector[0] = transvec[0]; mitkvector[1] = transvec[1]; mitkvector[2] = transvec[2]; //mitkvector[2] = 0.0; mitkpoint[0] = it_input.GetIndex()[0]; mitkpoint[1] = it_input.GetIndex()[1]; mitkpoint[2] = it_input.GetIndex()[2]; mitkendpoint[0] = mitkpoint[0] + mitkvector[0]; mitkendpoint[1] = mitkpoint[1] + mitkvector[1]; mitkendpoint[2] = mitkpoint[2] + mitkvector[2]; //mitkpoint.setXYZ((ScalarType)point[0],(ScalarType)point[1],(ScalarType)point[2]); geom->IndexToWorld(mitkpoint, mitkworldpoint); geom->IndexToWorld(mitkendpoint, mitkworldendpoint); mitktransvector[0] = mitkworldendpoint[0] - mitkworldpoint[0]; mitktransvector[1] = mitkworldendpoint[1] - mitkworldpoint[1]; mitktransvector[2] = mitkworldendpoint[2] - mitkworldpoint[2]; lengthsum += mitktransvector.GetNorm(); directions->InsertTuple3(id,mitktransvector[0],mitktransvector[1],mitktransvector[2]); points->InsertPoint(id,mitkworldpoint[0],mitkworldpoint[1],mitkworldpoint[2]); id++; //for (unsigned short loop = 0; (loop < 20) && (!it_input.IsAtEnd()); loop++) //{ // ++it_input; //} if(it_input.IsAtEnd()) { break; } } ++roiIt; } double meanlength = lengthsum / id; vtkGlyph3D* glyph = vtkGlyph3D::New(); vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New(); ugrid->SetPoints(points); ugrid->GetPointData()->SetVectors(directions); glyph->SetInput(ugrid); glyph->SetScaleModeToScaleByVector(); glyph->SetScaleFactor(0.5); glyph->SetColorModeToColorByScalar(); //glyph->ClampingOn(); vtkArrowSource* arrow = vtkArrowSource::New(); if(meanlength > 5) {arrow->SetTipLength(0);arrow->SetTipRadius(0);} arrow->SetShaftRadius(0.03/meanlength); //arrow->SetTipRadius(0.05/meanlength); glyph->SetSource(arrow->GetOutput()); glyph->Update(); mitk::Surface::Pointer glyph_surface = mitk::Surface::New(); glyph_surface->SetVtkPolyData(glyph->GetOutput()); glyph_surface->UpdateOutputInformation(); mitk::DataNode::Pointer gridNode = mitk::DataNode::New(); gridNode->SetProperty( "name", mitk::StringProperty::New(name.c_str()) ); //m_GridNode->SetProperty( "color" , m_GridColor); gridNode->SetProperty( "visible", mitk::BoolProperty::New(true) ); gridNode->SetProperty( "segmentation", mitk::BoolProperty::New(true) ); gridNode->SetProperty( "ID-Tag", mitk::StringProperty::New("grid") ); gridNode->SetProperty( "shader", mitk::StringProperty::New("mitkShaderLightning") ); gridNode->SetData( glyph_surface ); GetDefaultDataStorage()->Add(gridNode); } */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.h index b1fe665ff6..f1f0f0340f 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTractbasedSpatialStatisticsView.h @@ -1,260 +1,259 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkTractbasedSpatialStatisticsView_h #define QmitkTractbasedSpatialStatisticsView_h #include #include #include #include #include "ui_QmitkTractbasedSpatialStatisticsViewControls.h" #include #include #include #include #include #include #include #include #include #include "QmitkTbssTableModel.h" #include "QmitkTbssMetaTableModel.h" #include typedef short DiffusionPixelType; typedef itk::Image CharImageType; typedef itk::Image UCharImageType; typedef itk::Image Float4DImageType; typedef itk::Image FloatImageType; typedef itk::Vector IntVectorType; //typedef itk::VectorImage DirectionImageType; typedef itk::VectorImage VectorImageType; typedef itk::ImageFileReader< CharImageType > CharReaderType; typedef itk::ImageFileReader< UCharImageType > UCharReaderType; typedef itk::ImageFileWriter< CharImageType > CharWriterType; typedef itk::ImageFileReader< FloatImageType > FloatReaderType; typedef itk::ImageFileWriter< FloatImageType > FloatWriterType; typedef itk::ImageFileReader< Float4DImageType > Float4DReaderType; typedef itk::ImageFileWriter< Float4DImageType > Float4DWriterType; struct TbssSelListener; /*! \brief QmitkTractbasedSpatialStatisticsView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionalitymitkTbssWorkspaceManager \ingroup Functionalities */ class QmitkTractbasedSpatialStatisticsView : public QmitkFunctionality { friend struct TbssSelListener; // this is needed for all Qt objesetupUicts that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkTractbasedSpatialStatisticsView(); virtual ~QmitkTractbasedSpatialStatisticsView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); protected slots: //void OutputValues(); // void InitializeGridByVectorImage(); void Masking(); void CreateRoi(); void Clustering(); void AdjustPlotMeasure(const QString & text); void Clicked(const QwtDoublePoint& pos); void TbssImport(); void AddGroup(); void RemoveGroup(); void CopyToClipboard(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); void Plot(mitk::TbssImage*, mitk::TbssRoiImage*); void PlotFiberBundle(mitk::FiberBundleX* fib, mitk::Image* img); void InitPointsets(); void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; bool m_IsInitialized; mitk::PointSet::Pointer m_PointSetNode; mitk::DataNode::Pointer m_P1; Ui::QmitkTractbasedSpatialStatisticsViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; std::vector SortPoints(CharImageType::Pointer roi, CharImageType::IndexType currentPoint); bool PointVisited(std::vector points, CharImageType::IndexType point); // Modifies the current point by reference and returns true if no more points need to be visited CharImageType::IndexType FindNextPoint(std::vector pointsVisited, CharImageType::IndexType currentPoint, CharImageType::Pointer roi, bool &ready); //void DoInitializeGridByVectorImage(FloatVectorImageType::Pointer vectorpic, CharImageType::Pointer roi ,std::string name); // Tokenizer needed for the roi files void Tokenize(const std::string& str, std::vector& tokens, const std::string& delimiters = " ") { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } mitk::DataNode::Pointer readNode(std::string f) { mitk::DataNode::Pointer node; mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); try { nodeReader->SetFileName(f); nodeReader->Update(); node = nodeReader->GetOutput(); } catch(...) { MITK_ERROR << "Could not read file"; return NULL; } return node; } /*template < typename TPixel, unsigned int VImageDimension > void ToITK4D( itk::Image* inputImage, Float4DImageType::Pointer& outputImage );*/ std::string ReadFile(std::string whatfile); std::vector< itk::Index<3> > m_Roi; std::string m_CurrentStructure; mitk::Geometry3D* m_CurrentGeometry; QmitkTbssTableModel* m_GroupModel; void AddTbssToDataStorage(mitk::Image* image, std::string name); mitk::TbssImage::Pointer m_CurrentTbssMetaImage; VectorImageType::Pointer ConvertToVectorImage(mitk::Image::Pointer mitkImg); }; #endif // _QMITKTRACTBASEDSPATIALSTATISTICSVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp index fbefa1c7b5..0f15fd1fce 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp @@ -1,2500 +1,2499 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2008-04-01 10:52:29 +0200 (Di, 01 Apr 2008) $ -Version: $Revision: 13934 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "itkTimeProbe.h" #include "QmitkDiffusionTensorEstimation.h" #include "QmitkDiffusionTensorEstimationControls.h" #include #include "QmitkDataTreeComboBox.h" #include "QmitkDataTreeListView.h" #include "QmitkStdMultiWidget.h" #include "QmitkDiffusionTensorIcon.h" #include #include "QmitkPropertyViewFactory.h" #include #include #include #include #include #include #include // properties #include "mitkStringProperty.h" #include "mitkProperties.h" #include "mitkMaterialProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkLookupTableProperty.h" #include "mitkLookupTable.h" #include "mitkTransferFunctionProperty.h" #include "mitkGridRepresentationProperty.h" #include "mitkGridVolumeMapperProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkVectorImageMapper2D.h" #include "mitkOdfVtkMapper2D.h" #include "itkOrientedImage.h" #include "itkVectorImage.h" #include "itkImageSeriesReader.h" #include "itkImageFileWriter.h" #include "itkExceptionObject.h" #include "itkDiffusionTensor3DReconstructionImageFilter.h" #include "itkDiffusionTensor3D.h" #include "itkTensorFractionalAnisotropyImageFilter.h" #include "itkTensorRelativeAnisotropyImageFilter.h" #include "itkGDCMSeriesFileNames.h" #include "itkImageRegionConstIterator.h" #include "itkRescaleIntensityImageFilter.h" #include "itkDiffusionQballReconstructionImageFilter.h" #include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" #include "itkPointShell.h" #include "itkRGBPixel.h" #include "itkOrientationDistributionFunction.h" #include "itkDiffusionQballPrincipleDirectionsImageFilter.h" #include "itkDiffusionQballGeneralizedFaImageFilter.h" #include "itkShiftScaleImageFilter.h" #include "itkDiffusionQballPrepareVisualizationImageFilter.h" #include "itkDiffusionTensorPrincipleDirectionImageFilter.h" #include "itkDiffusionQballSphericalDeconvolutionImageFilter.h" #include "itkVectorImagesAngularErrorImageFilter.h" #include "mitkDicomDiffusionVolumeHeaderReader.h" #include "mitkGroupDiffusionHeadersFilter.h" #include "mitkDicomDiffusionVolumesReader.h" #include "mitkNrrdDiffusionVolumesWriter.h" #include "mitkNrrdDiffusionVolumesReader.h" #include "mitkDiffusionVolumes.h" #include "mitkDataTreeFilterFunctions.h" #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkTeemDiffusionTensor3DReconstructionImageFilter.h" #include "mitkSurface.h" #include "mitkDataNodeFactory.h" #include "vtkPolyData.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkDelaunay2D.h" #include "vtkCleanPolyData.h" #include "vtkAppendPolyData.h" #include "mitkImageCast.h" #include #include #include #define _USE_MATH_DEFINES #include #define DIFF_EST_PI M_PI typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; typedef itk::VectorImage< DiffusionPixelType, 3 > DiffusionImageType; //CAST_N_VEC(3) //CAST_N_VEC(42) //CAST_N_VEC(92) //CAST_N_VEC(162) //CAST_N_VEC(252) //CAST_N_VEC(362) //CAST_N_VEC(492) //CAST_N_VEC(642) //CAST_N_VEC(812) //CAST_N_VEC(1002) const int QmitkDiffusionTensorEstimation::odfsize = 252; const int QmitkDiffusionTensorEstimation::nrconvkernels = 252; // Compile-time Square Root Computation: ceil(sqrt(N)) template struct Root; template struct Root { static const int root = Mid; }; template struct Root { static const int mean = (Low + High)/2; static const bool down = (mean * mean >= Size); static const int root = Root::root; }; QmitkDiffusionTensorEstimation::QmitkDiffusionTensorEstimation(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); m_FilterInitialized = false; } QmitkDiffusionTensorEstimation::~QmitkDiffusionTensorEstimation() {} QWidget * QmitkDiffusionTensorEstimation::CreateMainWidget(QWidget *parent) { if ( m_MultiWidget == NULL ) { m_MultiWidget = new QmitkStdMultiWidget( parent ); } return m_MultiWidget; } QWidget * QmitkDiffusionTensorEstimation::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkDiffusionTensorEstimationControls(parent); } m_Controls->m_TensorEstimationTeemErrorImage->setChecked(false); m_Controls->m_TensorEstimationTeemSigmaEdit->setText("NaN"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("LLS (Linear Least Squares)"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("MLE (Maximum Likelihood)"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("NLS (Nonlinear Least Squares)"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("WLS (Weighted Least Squares)"); m_Controls->m_TensorEstimationTeemNumItsSpin->setValue(1); m_Controls->m_TensorEstimationTeemConfThresholdEdit->setText("NaN"); m_Controls->m_TensorEstimationTeemFuzzyEdit->setText("0.0"); m_Controls->m_TensorEstimationTeemMinValEdit->setText("1.0"); m_Controls->m_QBallReconstructionThreasholdEdit->setText("0.0"); m_Controls->m_QBallStandardAlgorithmsOrderSpinbox->setValue(0); m_Controls->m_QBallStandardAlgorithmsProbThreshEdit->setText(QString::number(1.0/double(odfsize))); m_Controls->m_QBallReconstructionNumberThreadsSpinbox->setValue(4); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("2") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("4") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("6") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("8") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setCurrentItem( 3 ); m_Controls->m_QBallReconstructionNumberThreadsAnalyticalSpinbox->setValue(4); m_Controls->m_QBallReconstructionThreasholdAnalyticalEdit->setText("0.0"); m_Controls->m_QBallReconstructionLambdaLineEdit->setText("0.006"); m_Controls->m_QBallStandardAlgorithmsNumberThreadsSpinbox->setValue(4); m_Controls->m_QBallStandardAlgorithmsDeconvNumberThreadsSpinbox->setValue(4); m_Controls->m_QBallStandardAlgorithmsDeconvolutionThreshEdit->setText("0.1"); m_Controls->m_QBallStandardAlgorithmsDeconvolutionAngResThresholdEdit->setText("15"); m_Controls->m_QBallStandardAlgorithmsGFAParam1->setText("2"); m_Controls->m_QBallStandardAlgorithmsGFAParam2->setText("1"); return m_Controls; } void QmitkDiffusionTensorEstimation::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TensorEstimationButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorEstimationButton())); connect( (QObject*)(m_Controls->m_QBallReconstructionButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallReconstructionButton())); connect( (QObject*)(m_Controls->m_QBallReconstructionAnalyticalButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallReconstructionAnalyticalButton())); connect( (QObject*)(m_Controls->m_TensorEstimationTeemEstimateButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorEstimationTeemEstimateButton())); connect( (QObject*)(m_Controls->m_TensorVolumesSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorVolumesSaveButton())); connect( (QObject*)(m_Controls->m_TensorVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorVolumesLoadButton())); connect( (QObject*)(m_Controls->m_TensorVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_StandardAlgorithmsFAButton), SIGNAL(clicked()),(QObject*) this, SLOT(StandardAlgorithmsFAButton())); connect( (QObject*)(m_Controls->m_StandardAlgorithmsRAButton), SIGNAL(clicked()),(QObject*) this, SLOT(StandardAlgorithmsRAButton())); connect( (QObject*)(m_Controls->m_StandardAlgorithmsDirectionButton), SIGNAL(clicked()),(QObject*) this, SLOT(StandardAlgorithmsDirectionButton())); connect( (QObject*)(m_Controls->m_QBallVolumesSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesSaveButton())); connect( (QObject*)(m_Controls->m_QBallVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesLoadButton())); connect( (QObject*)(m_Controls->m_QBallVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_QBallStandardAlgorithmsDirectionButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallStandardAlgorithmsDirectionButton())); connect( (QObject*)(m_Controls->m_QBallStandardAlgorithmsDeconvolutionButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallStandardAlgorithmsDeconvolutionButton())); connect( (QObject*)(m_Controls->m_QBallStandardAlgorithmsGFAButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallStandardAlgorithmsGFAButton())); connect( (QObject*)(m_Controls->m_QBallVolumesVisualizeSelectedButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesVisualizeSelectedButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesSaveButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesLoadButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesAngularErrorButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesAngularErrorButton())); connect( (QObject*)(m_Controls->m_DiffusionVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumesLoadButton())); connect( (QObject*)(m_Controls->m_DiffusionVolumeSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumeSaveButton())); connect( (QObject*)(m_Controls->m_DiffusionVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_TensorEstimationDiffusionVolumesSelectAllButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumesSelectAll())); } } QAction * QmitkDiffusionTensorEstimation::CreateAction(QActionGroup *parent) { //action = new QAction( tr( "Brain Atrophy" ), pixmap, tr( "BrainAtrophy" ), 0, parent, "BrainAtrophy" ); QImage icon = qembed_findImage("QmitkDiffusionTensorEstimation"); QPixmap pixmap(icon); QAction* action; action = new QAction( tr( "Diffusion Tensor Estimation" ), pixmap, tr( "QmitkDiffusionTensorEstimation menu" ), 0, parent, "QmitkDiffusionTensorEstimation" ); return action; } void QmitkDiffusionTensorEstimation::TreeChanged() { m_Controls->m_TensorEstimationDiffusionVolumesSelector->Update(); m_Controls->m_TensorVolumesSelector->Update(); m_Controls->m_QBallVolumesSelector->Update(); m_Controls->m_DirectionVolumesSelector->Update(); if(m_DiffusionVolumesDataTreeFilter &&m_DiffusionVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_TensorEstimationButton->setEnabled(true); m_Controls->m_QBallReconstructionButton->setEnabled(true); m_Controls->m_QBallReconstructionAnalyticalButton->setEnabled(true); } else { m_Controls->m_QBallReconstructionButton->setEnabled(false); m_Controls->m_QBallReconstructionAnalyticalButton->setEnabled(false); m_Controls->m_TensorEstimationButton->setEnabled(false); } if(m_TensorVolumesDataTreeFilter && m_TensorVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_TensorVolumesSaveButton->setEnabled(true); m_Controls->m_TensorVolumesRemoveButton->setEnabled(true); } else { m_Controls->m_TensorVolumesSaveButton->setEnabled(false); m_Controls->m_TensorVolumesRemoveButton->setEnabled(false); } if(m_QballVolumesDataTreeFilter && m_QballVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_QBallVolumesSaveButton->setEnabled(true); m_Controls->m_QBallVolumesRemoveButton->setEnabled(true); m_Controls->m_QBallVolumesVisualizeSelectedButton->setEnabled(true); } else { m_Controls->m_QBallVolumesSaveButton->setEnabled(false); m_Controls->m_QBallVolumesRemoveButton->setEnabled(false); m_Controls->m_QBallVolumesVisualizeSelectedButton->setEnabled(false); } if(m_DirectionVolumesDataTreeFilter && m_DirectionVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_DirectionVolumesSaveButton->setEnabled(true); m_Controls->m_DirectionVolumesRemoveButton->setEnabled(true); } else { m_Controls->m_DirectionVolumesSaveButton->setEnabled(false); m_Controls->m_DirectionVolumesRemoveButton->setEnabled(false); } if(m_DirectionVolumesDataTreeFilter && m_DirectionVolumesDataTreeFilter->GetItems()->Size() > 1) { m_Controls->m_DirectionVolumesAngularErrorButton->setEnabled(true); } else { m_Controls->m_DirectionVolumesAngularErrorButton->setEnabled(false); } } void QmitkDiffusionTensorEstimation::Activated() { QmitkFunctionality::Activated(); if (m_FilterInitialized) return; // diffusion volumes filter m_DiffusionVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_DiffusionVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::MULTI_SELECT); m_DiffusionVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_DiffusionVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataType >() ); // show diffusion volumes mitk::DataTreeFilter::PropertyList visible_props; visible_props.push_back("name"); m_DiffusionVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList property_labels; property_labels.push_back("Diffusion Volumes"); m_DiffusionVolumesDataTreeFilter->SetPropertiesLabels(property_labels); m_Controls->m_TensorEstimationDiffusionVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_TensorEstimationDiffusionVolumesSelector->SetFilter( m_DiffusionVolumesDataTreeFilter ); m_Controls->m_TensorEstimationDiffusionVolumesSelector->SetAutoUpdate( false ); m_Controls->m_TensorEstimationDiffusionVolumesSelector->setStretchedColumn(1); // tensor volumes filter m_TensorVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_TensorVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::SINGLE_SELECT); m_TensorVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_TensorVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataTypeWithBoolProperty("IsTensorVolume") ); // show tensor volumes m_TensorVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList tensor_property_labels; tensor_property_labels.push_back("Tensor Volumes"); m_TensorVolumesDataTreeFilter->SetPropertiesLabels(tensor_property_labels); m_Controls->m_TensorVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_TensorVolumesSelector->SetFilter( m_TensorVolumesDataTreeFilter ); m_Controls->m_TensorVolumesSelector->SetAutoUpdate( false ); m_Controls->m_TensorVolumesSelector->setStretchedColumn(1); // qBall volumes filter m_QballVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_QballVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::MULTI_SELECT); m_QballVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_QballVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataTypeWithBoolProperty("IsQBallVolume") ); m_QballVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList qball_property_labels; qball_property_labels.push_back("Q-Ball Volumes"); m_QballVolumesDataTreeFilter->SetPropertiesLabels(qball_property_labels); m_Controls->m_QBallVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_QBallVolumesSelector->SetFilter( m_QballVolumesDataTreeFilter ); m_Controls->m_QBallVolumesSelector->SetAutoUpdate( false ); m_Controls->m_QBallVolumesSelector->setStretchedColumn(1); // direction volumes filter m_DirectionVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_DirectionVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::MULTI_SELECT); m_DirectionVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_DirectionVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataTypeWithBoolProperty("IsDirectionVolume") ); m_DirectionVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList direction_property_labels; direction_property_labels.push_back("Direction Volumes"); m_DirectionVolumesDataTreeFilter->SetPropertiesLabels(direction_property_labels); m_Controls->m_DirectionVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_DirectionVolumesSelector->SetFilter( m_DirectionVolumesDataTreeFilter ); m_Controls->m_DirectionVolumesSelector->SetAutoUpdate( false ); m_Controls->m_DirectionVolumesSelector->setStretchedColumn(1); m_FilterInitialized = true; TreeChanged(); } void QmitkDiffusionTensorEstimation::TensorVolumesSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::Image::Pointer tensorVol = static_cast(selectedItem->GetNode()->GetData()); TensorImageType::Pointer itkTensorVol = TensorImageType::New(); mitk::CastToItkImage(tensorVol, itkTensorVol); // SELECT FILE DIALOG std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING TENSORS TO FILE MBI_INFO << "Writing tensors "; typedef itk::ImageFileWriter TensorWriterType; TensorWriterType::Pointer tensorWriter = TensorWriterType::New(); tensorWriter->SetFileName(filename.ascii()); tensorWriter->SetInput(itkTensorVol); tensorWriter->Update(); } void QmitkDiffusionTensorEstimation::TensorVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING TENSOR VOLUME typedef itk::ImageFileReader ReaderType; ReaderType::Pointer tensorReader = ReaderType::New(); tensorReader->SetFileName(filename); try { tensorReader->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } // Tensorvolume mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( tensorReader->GetOutput() ); image->SetVolume( tensorReader->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); node->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); TreeChanged(); } } void QmitkDiffusionTensorEstimation::TensorVolumesRemoveButton() { m_TensorVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::QBallVolumesSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_QballVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::Image::Pointer qBallVol = static_cast(selectedItem->GetNode()->GetData()); if( !qBallVol)return; typedef itk::Image,3 > IType; IType::Pointer itkQBallVol = IType::New(); mitk::CastToItkImage(qBallVol, itkQBallVol); typedef itk::VectorImage VarVecImgType; VarVecImgType::Pointer vecImg = VarVecImgType::New(); vecImg->SetSpacing( itkQBallVol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkQBallVol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkQBallVol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkQBallVol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( itkQBallVol->GetLargestPossibleRegion() ); vecImg->SetVectorLength(odfsize); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionIterator it (itkQBallVol, itkQBallVol->GetLargestPossibleRegion() ); it = it.Begin(); MBI_DEBUG << it.Get(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { itk::Vector vec = it.Get(); VarVecImgType::PixelType varvec(vec.GetDataPointer(), odfsize); ot.Set(varvec); ++ot; } // SELECT FILE DIALOG std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING TENSORS TO FILE MBI_INFO << "Writing data "; typedef itk::ImageFileWriter QBallWriterType; QBallWriterType::Pointer qballWriter = QBallWriterType::New(); qballWriter->SetFileName(filename.ascii()); qballWriter->SetInput(vecImg); qballWriter->Update(); } void QmitkDiffusionTensorEstimation::QBallVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING TENSOR VOLUME typedef itk::Image,3 > IVType; typedef itk::ImageFileReader ReaderType; ReaderType::Pointer qballReader = ReaderType::New(); qballReader->SetFileName(filename); try { qballReader->Update(); } catch (itk::ExceptionObject e) { MBI_LOG << e; } //itk::ImageRegionConstIterator it (qballReader->GetOutput(), qballReader->GetOutput()->GetLargestPossibleRegion() ); //it = it.Begin(); //std::cout << it.Get() << std::endl; // Tensorvolume mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( qballReader->GetOutput() ); image->SetVolume( qballReader->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); node->SetProperty( "visible", mitk::BoolProperty::New( false ) ); TreeChanged(); } } void QmitkDiffusionTensorEstimation::QBallVolumesRemoveButton() { m_QballVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::QBallVolumesVisualizeSelectedButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_QballVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); // PREPARE FOR VISUALIZATION clock.Start(); MBI_INFO << "Preparing for Visualization "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Preparing for Visualization of %s", nodename.c_str())); typedef itk::DiffusionQballPrepareVisualizationImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itkvol); filter->SetNumberOfThreads(4); switch(m_Controls->m_QBallVolumesVisualizeNormalizationMethod->currentItem()) { case 0: { filter->SetNormalizationMethod(FilterType::PV_MIN_MAX); break; } case 1: { filter->SetNormalizationMethod(FilterType::PV_NONE); break; } case 2: { filter->SetNormalizationMethod(FilterType::PV_MAX); break; } case 3: { filter->SetNormalizationMethod(FilterType::PV_GLOBAL_MAX); break; } case 4: { filter->SetNormalizationMethod(FilterType::PV_MIN_MAX_INVERT); break; } default: { filter->SetNormalizationMethod(FilterType::PV_MIN_MAX); break; } } if(m_Controls->m_QBallVolumesVisualizeScaleGfaCheckbox->isChecked() ) { typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; filter->SetDoScaleGfa(true); float p1 = m_Controls->m_QBallStandardAlgorithmsGFAParam1->text().toFloat(); float p2 = m_Controls->m_QBallStandardAlgorithmsGFAParam2->text().toFloat(); switch(m_Controls->m_QBallStandardAlgorithmsGFAMethod->currentItem()) { case 0: filter->SetScaleByGfaType(GfaFilterType::GFA_STANDARD); break; case 1: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILES_HIGH_LOW); break; case 2: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILE_HIGH); break; case 3: filter->SetScaleByGfaType(GfaFilterType::GFA_MAX_ODF_VALUE); break; case 4: filter->SetScaleByGfaType(GfaFilterType::GFA_DECONVOLUTION_COEFFS); break; case 5: filter->SetScaleByGfaType(GfaFilterType::GFA_MIN_MAX_NORMALIZED_STANDARD); break; case 6: filter->SetScaleByGfaType(GfaFilterType::GFA_NORMALIZED_ENTROPY); break; case 7: filter->SetScaleByGfaType(GfaFilterType::GFA_NEMATIC_ORDER_PARAMETER); break; case 8: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILES_LOW_HIGH); break; case 9: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILE_LOW); break; case 10: filter->SetScaleByGfaType(GfaFilterType::GFA_MIN_ODF_VALUE); break; case 11: filter->SetScaleByGfaType(GfaFilterType::GFA_STD_BY_MAX); break; case 12: filter->SetScaleByGfaType(GfaFilterType::GFA_PRINCIPLE_CURVATURE); filter->SetGfaParam1(p1); break; case 13: filter->SetScaleByGfaType(GfaFilterType::GFA_GENERALIZED_GFA); filter->SetGfaParam1(p1); filter->SetGfaParam2(p2); break; default: filter->SetScaleByGfaType(GfaFilterType::GFA_STANDARD); } } filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // VIZ TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename.append(" Viz")); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 1500 ) ); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); node->SetProperty( "layer", mitk::IntProperty::New( 1 ) ); node->SetProperty( "global_scaling", mitk::FloatProperty::New( 1.0 ) ); mitk::OdfVtkMapper2D::Pointer odfMapper = mitk::OdfVtkMapper2D::New(); node->SetMapper(1,odfMapper); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::DirectionVolumesSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_DirectionVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::Image::Pointer vol = static_cast(selectedItem->GetNode()->GetData()); if( !vol)return; typedef itk::Image,3 > IType; IType::Pointer itkVol = IType::New(); mitk::CastToItkImage(vol, itkVol); typedef itk::VectorImage VarVecImgType; VarVecImgType::Pointer vecImg = VarVecImgType::New(); vecImg->SetSpacing( itkVol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkVol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkVol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkVol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( itkVol->GetLargestPossibleRegion() ); vecImg->SetVectorLength(3); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionIterator it (itkVol, itkVol->GetLargestPossibleRegion() ); it = it.Begin(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { itk::Vector vec = it.Get(); VarVecImgType::PixelType varvec(vec.GetDataPointer(), 3); ot.Set(varvec); ++ot; } // SELECT FILE DIALOG std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING TENSORS TO FILE MBI_INFO << "Writing data "; typedef itk::ImageFileWriter WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename.ascii()); writer->SetInput(vecImg); writer->Update(); } void QmitkDiffusionTensorEstimation::DirectionVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING VOLUME typedef itk::Image,3 > IType; typedef itk::ImageFileReader ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(filename); try { reader->Update(); } catch (itk::ExceptionObject e) { MBI_INFO << e << std::endl; } // Tensorvolume mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( reader->GetOutput() ); image->SetVolume( reader->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); node->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); mitk::VectorImageMapper2D::Pointer mapper = mitk::VectorImageMapper2D::New(); node->SetMapper(1,mapper); TreeChanged(); } } void QmitkDiffusionTensorEstimation::DirectionVolumesRemoveButton() { m_DirectionVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::TensorEstimationTeemEstimateButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); itemiter++; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Teem Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Teem Tensor reconstruction for %s", nodename.c_str())); typedef mitk::TeemDiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); tensorReconstructionFilter->SetInput( vols ); tensorReconstructionFilter->SetEstimateErrorImage( m_Controls->m_TensorEstimationTeemErrorImage->isChecked() ); if(!m_Controls->m_TensorEstimationTeemSigmaEdit->text().contains(QString("NaN"))) tensorReconstructionFilter->SetSigma( m_Controls->m_TensorEstimationTeemSigmaEdit->text().toFloat() ); switch(m_Controls->m_TensorEstimationTeemEstimationMethodCombo->currentItem()) { case 0: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsLLS); break; case 1: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsNLS); break; case 2: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsWLS); break; case 3: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsMLE); break; default: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsLLS); } tensorReconstructionFilter->SetNumIterations( m_Controls->m_TensorEstimationTeemNumItsSpin->value() ); if(!m_Controls->m_TensorEstimationTeemConfThresholdEdit->text().contains(QString("NaN"))) tensorReconstructionFilter->SetConfidenceThreshold( m_Controls->m_TensorEstimationTeemConfThresholdEdit->text().toDouble() ); tensorReconstructionFilter->SetConfidenceFuzzyness( m_Controls->m_TensorEstimationTeemFuzzyEdit->text().toFloat() ); tensorReconstructionFilter->SetMinPlausibleValue( m_Controls->m_TensorEstimationTeemMinValEdit->text().toDouble() ); tensorReconstructionFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // TENSORS TO DATATREE //mitk::DataNode::Pointer node=mitk::DataNode::New(); //node->SetData( tensorReconstructionFilter->GetOutput() ); //mitk::DataStorage::GetInstance()->Add(node); //SetDefaultNodeProperties(node, nodename.append(" tensors")); //node->SetProperty( "IsConfidenceTensorVolume", mitk::BoolProperty::New( true ) ); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( tensorReconstructionFilter->GetOutputItk() ); SetDefaultNodeProperties(node2, nodename.append(" (itk)")); node2->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); nodes.push_back(node2); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); mitk::ProgressBar::GetInstance()->Progress(); TreeChanged(); m_Controls->update(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } void QmitkDiffusionTensorEstimation::TensorEstimationButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); itemiter++; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Tensor reconstruction for %s", nodename.c_str())); typedef itk::DiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); tensorReconstructionFilter->SetGradientImage( vols->GetDirections(), vols->GetImage() ); tensorReconstructionFilter->SetNumberOfThreads( m_Controls->m_TensorEstimationNumberThreadsSpinbox->value() ); tensorReconstructionFilter->SetBValue(vols->GetB_Value()); tensorReconstructionFilter->SetThreshold( m_Controls->m_TensorEstimationThreasholdEdit->text().toFloat() ); tensorReconstructionFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // TENSORS TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( tensorReconstructionFilter->GetOutput() ); image->SetVolume( tensorReconstructionFilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename.append(" tensors")); node->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); nodes.push_back(node); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); mitk::ProgressBar::GetInstance()->Progress(); TreeChanged(); m_Controls->update(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } void QmitkDiffusionTensorEstimation::QBallReconstructionButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); ++itemiter; // QBALL RECONSTRUCTION clock.Start(); MBI_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str())); typedef itk::DiffusionQballReconstructionImageFilter< DiffusionPixelType, DiffusionPixelType, TTensorPixelType, odfsize> //int NOdfDirections = 162, QballReconstructionImageFilterType; QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetGradientImage( vols->GetDirections(), vols->GetImage() ); filter->SetNumberOfThreads( m_Controls->m_QBallReconstructionNumberThreadsSpinbox->value() ); filter->SetBValue(vols->GetB_Value()); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->text().toFloat() ); int normalization = m_Controls->m_QBallReconstructionPostprocessingMethod->currentItem(); switch(normalization) { case 0: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); break; } case 1: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO_B_VALUE); break; } case 2: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO); break; } case 3: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_NONE); break; } default: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); } } filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s." << std::endl; // ODFs TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); //image->SetImportVolume( filter->GetOutput()->GetBufferPointer(), 0, 0, mitk::Image::ImportMemoryManagementType::ManageMemory ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_QN%1").arg(normalization); SetDefaultNodeProperties(node, newname.ascii()); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); nodes.push_back(node); // B-Zero TO DATATREE mitk::Image::Pointer image4 = mitk::Image::New(); image4->InitializeByItk( filter->GetBZeroImage().GetPointer() ); image4->SetVolume( filter->GetBZeroImage()->GetBufferPointer() ); mitk::DataNode::Pointer node4=mitk::DataNode::New(); node4->SetData( image4 ); SetDefaultNodeProperties(node4, nodename.append("B0")); nodes.push_back(node4); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } template void QmitkDiffusionTensorEstimation::ReconstructAnalytically( mitk::DiffusionVolumes* vols, float lambda, std::string nodename, std::vector* nodes) { typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetGradientImage( vols->GetDirections(), vols->GetImage() ); filter->SetNumberOfThreads( m_Controls->m_QBallReconstructionNumberThreadsAnalyticalSpinbox->value() ); filter->SetBValue(vols->GetB_Value()); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdAnalyticalEdit->text().toFloat() ); filter->SetLambda(lambda); filter->SetAdcProfileOnly(m_Controls->m_QBallReconstructionAdcOnlyCheckbox->isChecked()); int normalization = m_Controls->m_QBallReconstructionPostprocessingMethodAnalytical->currentItem(); switch(normalization) { case 0: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); break; } case 1: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO_B_VALUE); break; } case 2: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO); break; } case 3: { filter->SetNormalizationMethod(FilterType::QBAR_NONE); break; } default: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); } } filter->Update(); // ODFs TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); nodes->push_back(node); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_QA%1").arg(normalization); SetDefaultNodeProperties(node, newname.ascii()); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); // B-Zero TO DATATREE mitk::Image::Pointer image4 = mitk::Image::New(); image4->InitializeByItk( filter->GetBZeroImage().GetPointer() ); image4->SetVolume( filter->GetBZeroImage()->GetBufferPointer() ); mitk::DataNode::Pointer node4=mitk::DataNode::New(); node4->SetData( image4 ); nodes->push_back(node4); SetDefaultNodeProperties(node4, nodename.append("B0")); } void QmitkDiffusionTensorEstimation::QBallReconstructionAnalyticalButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->text().toFloat(); if(m_Controls->m_QBallReconstructionLambdaMultiCheckbox->isChecked()) { float stepLambda = m_Controls->m_QBallReconstructionLambdaStepLineEdit->text().toFloat(); float maxLambda = m_Controls->m_QBallReconstructionLambdaMaxLineEdit->text().toFloat(); for(float l=minLambda; lAddStepsToDo(nrFiles*nLambdas); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector* nodes = new std::vector(); while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); itemiter++; // QBALL RECONSTRUCTION clock.Start(); MBI_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str())); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentItem()) { case 0: { ReconstructAnalytically<2>(vols, currentLambda, nodename, nodes); break; } case 1: { ReconstructAnalytically<4>(vols, currentLambda, nodename, nodes); break; } case 2: { ReconstructAnalytically<6>(vols, currentLambda, nodename, nodes); break; } case 3: { ReconstructAnalytically<8>(vols, currentLambda, nodename, nodes); break; } } clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; mitk::ProgressBar::GetInstance()->Progress(); } } std::vector::iterator nodeIt; for(nodeIt = nodes->begin(); nodeIt != nodes->end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } void QmitkDiffusionTensorEstimation::StandardAlgorithmsFAButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; mitk::Image* vol = static_cast(item->GetNode()->GetData()); itk::Image::Pointer itkvol = itk::Image::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); // COMPUTE FA clock.Start(); MBI_INFO << "Computing FA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing FA for %s", nodename.c_str())); typedef TensorPixelType::RealValueType RealValueType; typedef itk::Image< RealValueType, 3 > FAImageType; typedef itk::TensorFractionalAnisotropyImageFilter< TensorImageType, FAImageType > FAFilterType; FAFilterType::Pointer fractionalAnisotropyFilter = FAFilterType::New(); fractionalAnisotropyFilter->SetInput( itkvol ); typedef itk::ShiftScaleImageFilter ShiftScaleFilterType; ShiftScaleFilterType::Pointer multi = ShiftScaleFilterType::New(); multi->SetShift(0); multi->SetScale(200);//itk::NumericTraits::max() multi->SetInput(fractionalAnisotropyFilter->GetOutput()); multi->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // FA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( multi->GetOutput() ); image->SetVolume( multi->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename.append(" FA")); node->SetProperty( "IsFAVolume", mitk::BoolProperty::New( true ) ); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::StandardAlgorithmsRAButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; mitk::Image* vol = static_cast(item->GetNode()->GetData()); itk::Image::Pointer itkvol = itk::Image::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); // COMPUTE RA clock.Start(); MBI_INFO << "Computing RA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing RA for %s", nodename.c_str())); typedef TensorPixelType::RealValueType RealValueType; typedef itk::Image< RealValueType, 3 > RAImageType; typedef itk::TensorRelativeAnisotropyImageFilter< TensorImageType, RAImageType > RAFilterType; RAFilterType::Pointer relativeAnisotropyFilter = RAFilterType::New(); relativeAnisotropyFilter->SetInput( itkvol ); relativeAnisotropyFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // FA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( relativeAnisotropyFilter->GetOutput() ); image->SetVolume( relativeAnisotropyFilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename.append(" RA")); node->SetProperty( "IsRAVolume", mitk::BoolProperty::New( true ) ); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::StandardAlgorithmsDirectionButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::DiffusionTensor3D TensorType; typedef itk::Image TensorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); TensorImgType::Pointer itkvol = TensorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); clock.Start(); MBI_INFO << "Computing Diffusion Direction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing Diffusion Direction for %s", nodename.c_str())); typedef itk::DiffusionTensorPrincipleDirectionImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itkvol); filter->SetNumberOfThreads(4); filter->Update(); itk::ImageRegionIterator it (filter->GetOutput(), filter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); // VECTORFIELD MBI_DEBUG << "Converting to Vectorfield"; typedef itk::Image, 3> VecImgType2; VecImgType2::Pointer vecImg5 = VecImgType2::New(); vecImg5->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg5->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg5->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg5->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg5->SetBufferedRegion( vecImg5->GetLargestPossibleRegion() ); vecImg5->Allocate(); itk::ImageRegionIterator ot5 (vecImg5, vecImg5->GetLargestPossibleRegion() ); ot5 = ot5.Begin(); typedef FilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); itk::Vector pix; TTensorPixelType uvec[3] = {(TTensorPixelType)(vec[0]),(TTensorPixelType)(vec[1]),(TTensorPixelType)(vec[2])}; //TTensorPixelType uvec[3] = {(TTensorPixelType)(vec[1]),(TTensorPixelType)(-vec[0]),(TTensorPixelType)(vec[2])}; pix = uvec; ot5.Set(pix); ++ot5; } // Vectors TO DATATREE mitk::Image::Pointer image5 = mitk::Image::New(); image5->InitializeByItk( vecImg5.GetPointer() ); image5->SetVolume( vecImg5->GetBufferPointer() ); mitk::DataNode::Pointer node5=mitk::DataNode::New(); node5->SetData( image5 ); node5->SetName( nodename.append(" vecs").c_str()); mitk::DataStorage::GetInstance()->Add(node5); node5->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); node5->SetProperty( "NormalizeVecs", mitk::BoolProperty::New( true ) ); node5->SetProperty( "Scale", mitk::FloatProperty::New( 1.0 ) ); node5->SetProperty( "LineWidth", mitk::FloatProperty::New( 1 ) ); mitk::VectorImageMapper2D::Pointer vecMapper5 = mitk::VectorImageMapper2D::New(); node5->SetMapper(1,vecMapper5); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::QBallStandardAlgorithmsGFAButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::ItemSet* selectedItems = m_QballVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast((*itemiter)->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = (*itemiter)->GetProperty("name"); ++itemiter; float p1 = m_Controls->m_QBallStandardAlgorithmsGFAParam1->text().toFloat(); float p2 = m_Controls->m_QBallStandardAlgorithmsGFAParam2->text().toFloat(); // COMPUTE RA clock.Start(); MBI_INFO << "Computing GFA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing GFA for %s", nodename.c_str())); typedef OdfVectorType::ValueType RealValueType; typedef itk::Image< RealValueType, 3 > RAImageType; typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(4); double scale = 1; std::string newname; newname.append(nodename); newname.append(" GFA"); switch(m_Controls->m_QBallStandardAlgorithmsGFAMethod->currentItem()) { case 0: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); newname.append("00"); scale = 200.0; break; } case 1: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILES_HIGH_LOW); newname.append("01"); scale = 200.0; break; } case 2: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILE_HIGH); newname.append("02"); scale = 200.0; break; } case 3: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MAX_ODF_VALUE); newname.append("03"); scale = 200.0; break; } case 4: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_DECONVOLUTION_COEFFS); newname.append("04"); scale = 200.0; break; } case 5: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MIN_MAX_NORMALIZED_STANDARD); newname.append("05"); scale = 200.0; break; } case 6: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_NORMALIZED_ENTROPY); newname.append("06"); break; } case 7: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_NEMATIC_ORDER_PARAMETER); newname.append("07"); scale = 200.0; break; } case 8: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILES_LOW_HIGH); newname.append("08"); scale = 200.0; break; } case 9: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILE_LOW); newname.append("09"); scale = 200.0; break; } case 10: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MIN_ODF_VALUE); newname.append("10"); scale = 200.0; break; } case 11: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_STD_BY_MAX); newname.append("11"); scale = 200.0; break; } case 12: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_PRINCIPLE_CURVATURE); newname.append("12"); gfaFilter->SetParam1(p1); scale = 200.0; break; } case 13: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_GENERALIZED_GFA); QString paramString; paramString = paramString.append(" K%1P%2").arg(p1).arg(p2); newname.append("13").append(paramString.ascii()); gfaFilter->SetParam1(p1); gfaFilter->SetParam2(p2); scale = 200.0; break; } default: { newname.append("0"); gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); scale = 200.0; } } gfaFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; typedef itk::Image ImgType; ImgType::Pointer img = ImgType::New(); img->SetSpacing( gfaFilter->GetOutput()->GetSpacing() ); // Set the image spacing img->SetOrigin( gfaFilter->GetOutput()->GetOrigin() ); // Set the image origin img->SetDirection( gfaFilter->GetOutput()->GetDirection() ); // Set the image direction img->SetLargestPossibleRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion()); img->SetBufferedRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion() ); img->Allocate(); itk::ImageRegionIterator ot (img, img->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionConstIterator it (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { GfaFilterType::OutputImageType::PixelType val = it.Get(); ot.Set(val * scale); ++ot; } // GFA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( img.GetPointer() ); image->SetVolume( img->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); nodes.push_back(node); SetDefaultNodeProperties(node, newname.c_str()); node->SetProperty( "IsGFAVolume", mitk::BoolProperty::New( true ) ); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::QBallStandardAlgorithmsDirectionButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_QballVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); clock.Start(); MBI_INFO << "Computing Diffusion Direction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing Diffusion Direction for %s", nodename.c_str())); typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(4); gfaFilter->Update(); itk::ImageRegionIterator itGfa (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); itGfa = itGfa.Begin(); int numdir = m_Controls->m_QBallStandardAlgorithmsOrderSpinbox->value(); typedef itk::DiffusionQballPrincipleDirectionsImageFilter PrincipleDirectionsFilterType; PrincipleDirectionsFilterType::Pointer principleDirectionsFilter = PrincipleDirectionsFilterType::New(); principleDirectionsFilter->SetThreshold(m_Controls->m_QBallStandardAlgorithmsProbThreshEdit->text().toFloat()); principleDirectionsFilter->SetNrDirectionToExtract(numdir); principleDirectionsFilter->SetInput(itkvol); principleDirectionsFilter->SetNumberOfThreads(m_Controls->m_QBallStandardAlgorithmsNumberThreadsSpinbox->value()); principleDirectionsFilter->SetMultiplyGfa(false); principleDirectionsFilter->Update(); itk::ImageRegionIterator it (principleDirectionsFilter->GetOutput(), principleDirectionsFilter->GetOutput()->GetLargestPossibleRegion() ); if(numdir == 0) { MBI_INFO << "Converting to RGB"; typedef itk::Image, 3> VecImgType; VecImgType::Pointer vecImg = VecImgType::New(); vecImg->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( vecImg->GetLargestPossibleRegion() ); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); typedef PrincipleDirectionsFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); itk::RGBPixel pix; vec*=200*itGfa.Get(); vec[0] = abs(vec[0]); vec[1] = abs(vec[1]); vec[2] = abs(vec[2]); if(vec[0] > 255 || vec[1] > 255 || vec[2] > 255) { // should never get in here double max = vec[0]; max = maxInitializeByItk( vecImg.GetPointer() ); image2->SetVolume( vecImg->GetBufferPointer() ); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( image2 ); mitk::DataStorage::GetInstance()->Add(node2); switch(numdir) { case 0: { SetDefaultNodeProperties(node2, nodename.append(" PD0")); break; } case 1: { SetDefaultNodeProperties(node2, nodename.append(" PD1")); } case 2: { SetDefaultNodeProperties(node2, nodename.append(" PD2")); } default: { SetDefaultNodeProperties(node2, nodename.append(" PDn")); } } node2->SetProperty( "IsRGBVolume", mitk::BoolProperty::New( true ) ); } // VECTORFIELD MBI_DEBUG << "Converting to Vectorfield"; typedef itk::Image, 3> VecImgType2; VecImgType2::Pointer vecImg5 = VecImgType2::New(); vecImg5->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg5->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg5->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg5->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg5->SetBufferedRegion( vecImg5->GetLargestPossibleRegion() ); vecImg5->Allocate(); itk::ImageRegionIterator ot5 (vecImg5, vecImg5->GetLargestPossibleRegion() ); ot5 = ot5.Begin(); typedef PrincipleDirectionsFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); itk::Vector pix; TTensorPixelType uvec[3] = {(TTensorPixelType)(vec[0]),(TTensorPixelType)(vec[1]),(TTensorPixelType)(vec[2])}; pix = uvec; ot5.Set(pix); ++ot5; } // Vectors TO DATATREE mitk::Image::Pointer image5 = mitk::Image::New(); image5->InitializeByItk( vecImg5.GetPointer() ); image5->SetVolume( vecImg5->GetBufferPointer() ); mitk::DataNode::Pointer node5=mitk::DataNode::New(); node5->SetData( image5 ); mitk::DataStorage::GetInstance()->Add(node5); switch(numdir) { case 0: { SetDefaultNodeProperties(node5, nodename.append(" Vec0")); break; } case 1: { SetDefaultNodeProperties(node5, nodename.append(" Vec1")); } case 2: { SetDefaultNodeProperties(node5, nodename.append(" Vec2")); } default: { SetDefaultNodeProperties(node5, nodename.append(" Vecn")); } } node5->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); node5->SetProperty( "NormalizeVecs", mitk::BoolProperty::New( true ) ); node5->SetProperty( "Scale", mitk::FloatProperty::New( 0.8 ) ); node5->SetProperty( "LineWidth", mitk::FloatProperty::New( 3 ) ); mitk::VectorImageMapper2D::Pointer vecMapper5 = mitk::VectorImageMapper2D::New(); node5->SetMapper(1,vecMapper5); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::QBallStandardAlgorithmsDeconvolutionButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_QballVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); clock.Start(); MBI_INFO << "Computing Diffusion Direction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing Diffusion Direction for %s", nodename.c_str())); typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(4); gfaFilter->Update(); itk::ImageRegionIterator itGfa (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); itGfa = itGfa.Begin(); int numdirs = m_Controls->m_QBallStandardAlgorithmsDeconvolutionSpinbox->value(); //vnl_matrix_fixed* kernels // = new vnl_matrix_fixed(); //itk::ImageRegionIterator inIt(itkvol, itkvol->GetLargestPossibleRegion()); //inIt.GoToBegin(); //for(int i=0; i DeconvolutionFilterType; DeconvolutionFilterType::Pointer devonvolutionFilter = DeconvolutionFilterType::New(); devonvolutionFilter->SetFractionalThreshold(m_Controls->m_QBallStandardAlgorithmsDeconvolutionThreshEdit->text().toFloat()); if(!m_Controls->m_QBallStandardAlgorithmsDeconvolutionAngResThresholdEdit->text().contains(QString("NaN"))) { float angRes = m_Controls->m_QBallStandardAlgorithmsDeconvolutionAngResThresholdEdit->text().toFloat(); angRes /= 360/DIFF_EST_PI; devonvolutionFilter->SetAngularResolutionThreshold(angRes); } devonvolutionFilter->SetSamplingQuantileStart(m_Controls->m_QBallStandardAlgorithmsDeconvQuantStart->text().toFloat()); devonvolutionFilter->SetSamplingQuantileStep(m_Controls->m_QBallStandardAlgorithmsDeconvQuantStep->text().toFloat()); devonvolutionFilter->SetMinimumNumberOfSamples(m_Controls->m_QBallStandardAlgorithmsDeconvQuantMinNr->text().toInt()); devonvolutionFilter->SetIterateQuantiles(m_Controls->m_QBallStandardAlgorithmsDeconvQuantMulti->isChecked()); devonvolutionFilter->SetNrDirectionsToExtract(numdirs); devonvolutionFilter->SetInput(itkvol); devonvolutionFilter->SetNumberOfThreads(m_Controls->m_QBallStandardAlgorithmsDeconvNumberThreadsSpinbox->value()); devonvolutionFilter->SetGfaImage(gfaFilter->GetOutput()); //devonvolutionFilter->SetPresetConvolutionKernels(kernels); devonvolutionFilter->Update(); for(int i=0; i it (devonvolutionFilter->GetOutput(i), devonvolutionFilter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); if(i==0) { MBI_INFO << "Converting to RGB"; typedef itk::Image, 3> VecImgType; VecImgType::Pointer vecImg = VecImgType::New(); vecImg->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( vecImg->GetLargestPossibleRegion() ); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); typedef DeconvolutionFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); vnl_vector_fixed vnlvec = vec.GetVnlVector(); TTensorPixelType len = vnlvec.two_norm(); vnlvec = vnlvec.normalize(); itk::RGBPixel pix; vnlvec*=200*itGfa.Get(); vnlvec[0] = abs(vnlvec[0]); vnlvec[1] = abs(vnlvec[1]); vnlvec[2] = abs(vnlvec[2]); if(vnlvec[0] > 255 || vnlvec[1] > 255 || vnlvec[2] > 255) { //should never get in here double max = vnlvec[0]; max = maxInitializeByItk( vecImg.GetPointer() ); image2->SetVolume( vecImg->GetBufferPointer() ); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( image2 ); mitk::DataStorage::GetInstance()->Add(node2); switch(i) { case 0: { SetDefaultNodeProperties(node2, nodename.append(" PD0")); break; } case 1: { SetDefaultNodeProperties(node2, nodename.append(" PD1")); break; } case 2: { SetDefaultNodeProperties(node2, nodename.append(" PD2")); break; } default: { SetDefaultNodeProperties(node2, nodename.append(" PDn")); break; } } node2->SetProperty( "IsRGBVolume", mitk::BoolProperty::New( true ) ); } // VECTORFIELD MBI_INFO << "Converting to Vectorfield"; typedef itk::Image, 3> VecImgType2; VecImgType2::Pointer vecImg5 = VecImgType2::New(); vecImg5->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg5->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg5->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg5->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg5->SetBufferedRegion( vecImg5->GetLargestPossibleRegion() ); vecImg5->Allocate(); itk::ImageRegionIterator ot5 (vecImg5, vecImg5->GetLargestPossibleRegion() ); ot5 = ot5.Begin(); typedef DeconvolutionFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); vnl_vector_fixed vnlvec = vec.GetVnlVector(); vnlvec = vnlvec.normalize(); itk::Vector pix; TTensorPixelType uvec[3] = {(TTensorPixelType)(vnlvec[0]),(TTensorPixelType)(vnlvec[1]),(TTensorPixelType)(vnlvec[2])}; pix = uvec; ot5.Set(pix); ++ot5; } // Vectors TO DATATREE mitk::Image::Pointer image5 = mitk::Image::New(); image5->InitializeByItk( vecImg5.GetPointer() ); image5->SetVolume( vecImg5->GetBufferPointer() ); mitk::DataNode::Pointer node5=mitk::DataNode::New(); node5->SetData( image5 ); mitk::DataStorage::GetInstance()->Add(node5); switch(i) { case 0: { SetDefaultNodeProperties(node5, nodename.append(" Vec0")); break; } case 1: { SetDefaultNodeProperties(node5, nodename.append(" Vec1")); break; } case 2: { SetDefaultNodeProperties(node5, nodename.append(" Vec2")); break; } default: { SetDefaultNodeProperties(node5, nodename.append(" Vecn")); break; } } node5->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); node5->SetProperty( "NormalizeVecs", mitk::BoolProperty::New( true ) ); node5->SetProperty( "Scale", mitk::FloatProperty::New( 0.8 ) ); node5->SetProperty( "LineWidth", mitk::FloatProperty::New( 3 ) ); mitk::VectorImageMapper2D::Pointer vecMapper5 = mitk::VectorImageMapper2D::New(); node5->SetMapper(1,vecMapper5); } m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "volumerendering", mitk::BoolProperty::New( false ) ); node->SetProperty( "use color", mitk::BoolProperty::New( true ) ); node->SetProperty( "texture interpolation", mitk::BoolProperty::New( true ) ); node->SetProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); node->SetProperty( "layer", mitk::IntProperty::New(0)); node->SetProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); node->SetOpacity(1.0f); node->SetColor(1.0,1.0,1.0); node->SetVisibility(true); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; // levelwindow.SetAuto( image ); levWinProp->SetLevelWindow( levelwindow ); node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); // add a default rainbow lookup table for color mapping if(!node->GetProperty("LookupTable")) { mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); vtkLookupTable* vtkLut = mitkLut->GetVtkLookupTable(); vtkLut->SetHueRange(0.6667, 0.0); vtkLut->SetTableRange(0.0, 20.0); vtkLut->Build(); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty( "LookupTable", mitkLutProp ); } if(!node->GetProperty("binary")) node->SetProperty( "binary", mitk::BoolProperty::New( false ) ); // add a default transfer function mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); node->SetProperty ( "TransferFunction", mitk::TransferFunctionProperty::New ( tf.GetPointer() ) ); // set foldername as string property mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New( name ); node->SetProperty( "name", nameProp ); } void QmitkDiffusionTensorEstimation::DirectionVolumesAngularErrorButton() { try { const mitk::DataTreeFilter::ItemSet* selectedItems = m_DirectionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (nrFiles != 2) return; mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::Image::Pointer vol1 = static_cast((*itemiter)->GetNode()->GetData()); if( !vol1)return; std::string nodename1 = (*itemiter)->GetProperty("name"); itemiter++; mitk::Image::Pointer vol2 = static_cast((*itemiter)->GetNode()->GetData()); if( !vol2)return; std::string nodename2 = (*itemiter)->GetProperty("name"); typedef itk::Image,3 > IType; IType::Pointer itkVol1 = IType::New(); mitk::CastToItkImage(vol1, itkVol1); IType::Pointer itkVol2 = IType::New(); mitk::CastToItkImage(vol2, itkVol2); typedef itk::VectorImagesAngularErrorImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itkVol1); filter->SetImage2(itkVol2.GetPointer()); filter->SetNumberOfThreads(4); filter->Update(); // Angluar Error TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename1.append(" ").append(nodename2).append(" ERR")); node->SetProperty( "IsErrorVolume", mitk::BoolProperty::New( true ) ); TreeChanged(); m_Controls->update(); QString status; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished computing Angular Error")); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } //void QmitkDiffusionTensorEstimation::DwiStandardAlgorithmsGFAButton() //{ // // itk::TimeProbe clock; // QString status; // const mitk::DataTreeFilter::Item* item // = m_DiffusionVolumesDataTreeFilter->GetSelectedItem(); // if(!item)return; // // typedef itk::Vector OdfVectorType; // typedef itk::Image OdfVectorImgType; // mitk::Image* vol = // static_cast(item->GetNode()->GetData()); // OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); // mitk::CastToItkImage(vol, itkvol); // std::string nodename = item->GetProperty("name"); // // // COMPUTE RA // clock.Start(); // std::cout << "Computing GFA "; // mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( // "Computing GFA for %s", nodename.c_str())); // typedef OdfVectorType::ValueType RealValueType; // typedef itk::Image< RealValueType, 3 > RAImageType; // typedef itk::DiffusionQballGeneralizedFaImageFilter // GfaFilterType; // GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); // gfaFilter->SetInput(itkvol); // gfaFilter->SetNumberOfThreads(4); // switch(m_Controls->m_QBallStandardAlgorithmsGFAMethodSpinbox->value()) // { // case 1: // { // gfaFilter->SetComputationMethod(GfaFilterType::STANDARD); // break; // } // case 2: // { // gfaFilter->SetComputationMethod(GfaFilterType::QUANTILES_HIGH_LOW); // break; // } // case 3: // { // gfaFilter->SetComputationMethod(GfaFilterType::QUANTILES_MIDDLE); // break; // } // case 4: // { // gfaFilter->SetComputationMethod(GfaFilterType::MAX_ODF_VALUE); // break; // } // case 5: // { // gfaFilter->SetComputationMethod(GfaFilterType::DECONVOLUTION_COEFFS); // break; // } // default: // { // gfaFilter->SetComputationMethod(GfaFilterType::STANDARD); // } // } // gfaFilter->Update(); // clock.Stop(); // std::cout << "took " << clock.GetMeanTime() << "s." << std::endl; // // typedef itk::Image ImgType; // ImgType::Pointer img = ImgType::New(); // img->SetSpacing( gfaFilter->GetOutput()->GetSpacing() ); // Set the image spacing // img->SetOrigin( gfaFilter->GetOutput()->GetOrigin() ); // Set the image origin // img->SetDirection( gfaFilter->GetOutput()->GetDirection() ); // Set the image direction // img->SetLargestPossibleRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion()); // img->SetBufferedRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion() ); // img->Allocate(); // itk::ImageRegionIterator ot (img, img->GetLargestPossibleRegion() ); // ot = ot.Begin(); // itk::ImageRegionConstIterator it // (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); // it = it.Begin(); // // for (it = it.Begin(); !it.IsAtEnd(); ++it) // { // GfaFilterType::OutputImageType::PixelType val = it.Get(); // ot.Set(val * 200); // ++ot; // } // // // // GFA TO DATATREE // mitk::Image::Pointer image = mitk::Image::New(); // image->InitializeByItk( img.GetPointer() ); // image->SetVolume( img->GetBufferPointer() ); // mitk::DataNode::Pointer node=mitk::DataNode::New(); // node->SetData( image ); // mitk::DataStorage::GetInstance()->Add(node); // SetDefaultNodeProperties(node, nodename.append(" GFA")); // node->SetProperty( "IsGFAVolume", mitk::BoolProperty::New( true ) ); // // mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); // // m_DataTreeIterator->GetTree()->Modified(); // m_MultiWidget->RequestUpdate(); // TreeChanged(); // m_Controls->update(); // //} void QmitkDiffusionTensorEstimation::DiffusionVolumeSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_DiffusionVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::DiffusionVolumes::Pointer diffVolumes = static_cast*>(selectedItem->GetNode()->GetData()); std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); // SELECT FILE DIALOG //QFileDialog::getSaveFileName() //QFileDialog* w = new QFileDialog( this->m_Controls, "Select Nrrd Outputfile", TRUE ); //w->setMode( QFileDialog::AnyFile ); //w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); //w->setName(qName); //if ( w->exec() != QDialog::Accepted ) // return; //QString filename = w->selectedFile(); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING DWIs TO NRRD VOLUME typedef mitk::NrrdDiffusionVolumesWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->SetInput( diffVolumes->GetImage() ); nrrdWriter->SetDirections(diffVolumes->GetDirections()); nrrdWriter->SetB_Value(diffVolumes->GetB_Value()); nrrdWriter->SetFileName(filename.ascii()); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { MBI_INFO << e; } } void QmitkDiffusionTensorEstimation::DiffusionVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING NRRD DWI VOLUMES typedef mitk::NrrdDiffusionVolumesReader ReaderType; ReaderType::Pointer nrrdReader = ReaderType::New(); nrrdReader->SetFileName(filename); try { nrrdReader->Update(); // DWI TO DATATREE typedef mitk::DiffusionVolumes DiffVolumesType; DiffVolumesType::Pointer diffVolumes = DiffVolumesType::New(); diffVolumes->SetDirections(nrrdReader->GetDiffusionVectors()); diffVolumes->SetB_Value(nrrdReader->GetB_Value()); diffVolumes->SetImage(nrrdReader->GetOutput()); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( diffVolumes ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); TreeChanged(); } catch (itk::ExceptionObject e) { MBI_INFO << e; } } } void QmitkDiffusionTensorEstimation::DiffusionVolumesRemoveButton() { m_DiffusionVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::DiffusionVolumesSelectAll() { const mitk::DataTreeFilter::ItemList* items = m_DiffusionVolumesDataTreeFilter->GetItems(); mitk::DataTreeFilter::ConstItemIterator itemiter( items->Begin() ); mitk::DataTreeFilter::ConstItemIterator itemiterend( items->End() ); while ( itemiter != itemiterend ) { m_DiffusionVolumesDataTreeFilter->SelectItem(*itemiter); ++itemiter; } } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.h index a2cdeaa81b..739c950eba 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.h @@ -1,164 +1,163 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2007-12-11 15:15:45 +0100 (Di, 11 Dez 2007) $ -Version: $Revision: 13136 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QmitkDiffusionTensorEstimation_H__INCLUDED) #define QmitkDiffusionTensorEstimation_H__INCLUDED #include "QmitkFunctionality.h" #include "mitkDiffusionVolumes.h" class QmitkStdMultiWidget; class QmitkDiffusionTensorEstimationControls; typedef short DiffusionPixelType; /*! \brief QmitkDiffusionTensorEstimation One needs to reimplement the methods CreateControlWidget(..), CreateMainWidget(..) and CreateAction(..) from QmitkFunctionality. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkDiffusionTensorEstimation : public QmitkFunctionality { Q_OBJECT public: /*! \brief default constructor */ QmitkDiffusionTensorEstimation(QObject *parent=0, const char *name=0, QmitkStdMultiWidget *mitkStdMultiWidget = NULL, mitk::DataTreeIteratorBase* dataIt = NULL); /*! \brief default destructor */ virtual ~QmitkDiffusionTensorEstimation(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual QWidget * CreateControlWidget(QWidget *parent); /*! \brief method for creating the applications main widget */ virtual QWidget * CreateMainWidget(QWidget * parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief method for creating an QAction object, i.e. button & menu entry @param parent the parent QWidget */ virtual QAction * CreateAction(QActionGroup *parent); virtual void Activated(); protected slots: void TreeChanged(); void TensorVolumesSaveButton(); void TensorVolumesLoadButton(); void TensorVolumesRemoveButton(); void QBallVolumesSaveButton(); void QBallVolumesLoadButton(); void QBallVolumesRemoveButton(); void DirectionVolumesSaveButton(); void DirectionVolumesLoadButton(); void DirectionVolumesRemoveButton(); void DirectionVolumesAngularErrorButton(); void TensorEstimationTeemEstimateButton(); void QBallReconstructionButton(); void QBallReconstructionAnalyticalButton(); void TensorEstimationButton(); void StandardAlgorithmsFAButton(); void StandardAlgorithmsRAButton(); void StandardAlgorithmsDirectionButton(); void QBallStandardAlgorithmsDirectionButton(); void QBallStandardAlgorithmsDeconvolutionButton(); void QBallStandardAlgorithmsGFAButton(); void QBallVolumesVisualizeSelectedButton(); void DiffusionVolumeSaveButton(); void DiffusionVolumesLoadButton(); void DiffusionVolumesRemoveButton(); void DiffusionVolumesSelectAll(); //void DwiStandardAlgorithmsGFAButton(); void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); protected: /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * controls containing sliders for scrolling through the slices */ QmitkDiffusionTensorEstimationControls * m_Controls; mitk::DataTreeFilter::Pointer m_DiffusionVolumesDataTreeFilter; mitk::DataTreeFilter::Pointer m_TensorVolumesDataTreeFilter; mitk::DataTreeFilter::Pointer m_QballVolumesDataTreeFilter; mitk::DataTreeFilter::Pointer m_DirectionVolumesDataTreeFilter; bool m_FilterInitialized; static const int odfsize; static const int nrconvkernels; template void ReconstructAnalytically(mitk::DiffusionVolumes* vols, float lambda, std::string nodename, std::vector* nodes); }; #endif // !defined(QmitkDiffusionTensorEstimation_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.cpp index fb0987da02..c37e460b33 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.cpp @@ -1,38 +1,37 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionImagingAppApplication.h" #include #include "QmitkDiffusionImagingAppWorkbenchAdvisor.h" int QmitkDiffusionImagingAppApplication::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); int code = berry::PlatformUI::CreateAndRunWorkbench(display, new QmitkDiffusionImagingAppWorkbenchAdvisor()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void QmitkDiffusionImagingAppApplication::Stop() { } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.h index 89d15a0bdb..8514f0eec2 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppApplication.h @@ -1,42 +1,41 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDiffusionImagingAppAPPLICATION_H_ #define QMITKDiffusionImagingAppAPPLICATION_H_ #include class QmitkDiffusionImagingAppApplication : public QObject, public berry::IApplication { Q_OBJECT Q_INTERFACES(berry::IApplication) public: QmitkDiffusionImagingAppApplication() {} QmitkDiffusionImagingAppApplication(const QmitkDiffusionImagingAppApplication& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDiffusionImagingAppApplication() {} int Start(); void Stop(); }; #endif /*QMITKDiffusionImagingAppAPPLICATION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp index 0e93f5e6c6..0e1ab92512 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp @@ -1,80 +1,79 @@ -/*========================================================================= +/*=================================================================== - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fri, 23 Oct 2009) $ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionImagingAppWorkbenchAdvisor.h" #include "internal/QmitkDiffusionApplicationPlugin.h" #include #include #include #include #include #include const std::string QmitkDiffusionImagingAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.diffusionimagingapp.perspectives.welcome"; void QmitkDiffusionImagingAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkDiffusionImagingAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { std::vector perspExcludeList; perspExcludeList.push_back( std::string("org.blueberry.uitest.util.EmptyPerspective") ); perspExcludeList.push_back( std::string("org.blueberry.uitest.util.EmptyPerspective2") ); perspExcludeList.push_back( std::string("org.mitk.coreapp.defaultperspective") ); perspExcludeList.push_back( std::string("org.mitk.extapp.defaultperspective") ); perspExcludeList.push_back( std::string("org.mitk.perspectives.publicdiffusionimaging") ); perspExcludeList.push_back( std::string("org.mitk.perspectives.diffusionimaginginternal") ); // Exclude the help perspective from org.blueberry.ui.qt.help from // the normal perspective list. // The perspective gets a dedicated menu entry in the help menu perspExcludeList.push_back("org.blueberry.perspectives.help"); std::vector viewExcludeList; configurer->SetInitialSize(berry::Point(1000,770)); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->ShowViewMenuItem(false); advisor->ShowNewWindowMenuItem(false); advisor->ShowClosePerspectiveMenuItem(false); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowPerspectiveToolbar(true); advisor->ShowVersionInfo(false); advisor->ShowMitkVersionInfo(false); advisor->SetProductName("MITK Diffusion"); advisor->SetWindowIcon(":/org.mitk.gui.qt.diffusionimagingapp/app-icon.png"); return advisor; } std::string QmitkDiffusionImagingAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h index a166b59cef..fbd50ba6f2 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h @@ -1,40 +1,39 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDIFFUSIONIMAGINGAPPWORKBENCHADVISOR_H_ #define QMITKDIFFUSIONIMAGINGAPPWORKBENCHADVISOR_H_ #include class QmitkDiffusionImagingAppWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const std::string WELCOME_PERSPECTIVE_ID; // = "org.mitk.qt.diffusionimagingapp.defaultperspective" void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); std::string GetInitialWindowPerspectiveId(); }; #endif /* QMITKDIFFUSIONIMAGINGAPPWORKBENCHADVISOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.cpp index 5efb4d200f..8e8cc4645c 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.cpp @@ -1,50 +1,49 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppConnectomicsPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppConnectomicsPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.brainnetworkanalysis"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.brainnetworkanalysis"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.h index 6b7f8b5603..99f702990f 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppConnectomicsPerspective_H_ #define QmitkDIAppConnectomicsPerspective_H_ #include class QmitkDIAppConnectomicsPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppConnectomicsPerspective() {} QmitkDIAppConnectomicsPerspective(const QmitkDIAppConnectomicsPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppConnectomicsPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppConnectomicsPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.cpp index baac1e86b0..2db8b6f1dd 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.cpp @@ -1,50 +1,49 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppDicomImportPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppDicomImportPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.diffusiondicomimport"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusiondicomimport"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.h index 186a27a6c8..a387d90c64 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppDicomImportPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppDicomImportPerspective_H_ #define QmitkDIAppDicomImportPerspective_H_ #include class QmitkDIAppDicomImportPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppDicomImportPerspective() {} QmitkDIAppDicomImportPerspective(const QmitkDIAppDicomImportPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppDicomImportPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppDicomImportPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.cpp index addad485c7..e03ad86c59 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.cpp @@ -1,57 +1,56 @@ -/*========================================================================= +/*=================================================================== - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppFiberTractographyPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppFiberTractographyPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.gibbstracking"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.gibbstracking"); lo->SetCloseable(false); left->AddView("org.mitk.views.stochasticfibertracking"); lo = layout->GetViewLayout("org.mitk.views.stochasticfibertracking"); lo->SetCloseable(false); left->AddView("org.mitk.views.fiberprocessing"); lo = layout->GetViewLayout("org.mitk.views.fiberprocessing"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.h index 44f9d6059e..8858364599 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppFiberTractographyPerspective_H_ #define QmitkDIAppFiberTractographyPerspective_H_ #include class QmitkDIAppFiberTractographyPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppFiberTractographyPerspective() {} QmitkDIAppFiberTractographyPerspective(const QmitkDIAppFiberTractographyPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppFiberTractographyPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppFiberTractographyPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp index 4312801f92..ccdcd4eb0e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp @@ -1,49 +1,48 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppIVIMPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppIVIMPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.ivim"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.ivim"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.h index 7db712d20b..8ebecffb2c 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppIVIMPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppIVIMPerspective_H_ #define QmitkDIAppIVIMPerspective_H_ #include class QmitkDIAppIVIMPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppIVIMPerspective() {} QmitkDIAppIVIMPerspective(const QmitkDIAppIVIMPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppIVIMPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppIVIMPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.cpp index 348c0140ff..e5c2caca7a 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.cpp @@ -1,62 +1,61 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppPreprocessingReconstructionPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppPreprocessingReconstructionPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.diffusionpreprocessing"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusionpreprocessing"); lo->SetCloseable(false); left->AddView("org.mitk.views.tensorreconstruction"); lo = layout->GetViewLayout("org.mitk.views.tensorreconstruction"); lo->SetCloseable(false); left->AddView("org.mitk.views.qballreconstruction"); lo = layout->GetViewLayout("org.mitk.views.qballreconstruction"); lo->SetCloseable(false); left->AddView("org.mitk.views.odfdetails"); lo = layout->GetViewLayout("org.mitk.views.odfdetails"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.h index b33a7af1a3..ed712d4a6e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppPreprocessingReconstructionPerspective_H_ #define QmitkDIAppPreprocessingReconstructionPerspective_H_ #include class QmitkDIAppPreprocessingReconstructionPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppPreprocessingReconstructionPerspective() {} QmitkDIAppPreprocessingReconstructionPerspective(const QmitkDIAppPreprocessingReconstructionPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppPreprocessingReconstructionPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppPreprocessingReconstructionPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.cpp index fe24f22c44..13187115af 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.cpp @@ -1,66 +1,65 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppQuantificationPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppQuantificationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.segmentation"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.segmentation"); lo->SetCloseable(false); left->AddView("org.mitk.views.partialvolumeanalysisview"); lo = layout->GetViewLayout("org.mitk.views.partialvolumeanalysisview"); lo->SetCloseable(false); left->AddView("org.mitk.views.diffusionquantification"); lo = layout->GetViewLayout("org.mitk.views.diffusionquantification"); lo->SetCloseable(false); left->AddView("org.mitk.views.measurement"); lo = layout->GetViewLayout("org.mitk.views.measurement"); lo->SetCloseable(false); left->AddView("org.mitk.views.imagestatistics"); lo = layout->GetViewLayout("org.mitk.views.imagestatistics"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.h index 12a292c9c8..8e310e070c 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppQuantificationPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppQuantificationPerspective_H_ #define QmitkDIAppQuantificationPerspective_H_ #include class QmitkDIAppQuantificationPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppQuantificationPerspective() {} QmitkDIAppQuantificationPerspective(const QmitkDIAppQuantificationPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppQuantificationPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppQuantificationPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.cpp index 23496a7508..7e79190c26 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.cpp @@ -1,54 +1,53 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppScreenshotsMoviesPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppScreenshotsMoviesPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.screenshotmaker"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.screenshotmaker"); lo->SetCloseable(false); left->AddView("org.mitk.views.moviemaker"); lo = layout->GetViewLayout("org.mitk.views.moviemaker"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.h index bad34a1f90..64eef02b01 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppScreenshotsMoviesPerspective_H_ #define QmitkDIAppScreenshotsMoviesPerspective_H_ #include class QmitkDIAppScreenshotsMoviesPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppScreenshotsMoviesPerspective() {} QmitkDIAppScreenshotsMoviesPerspective(const QmitkDIAppScreenshotsMoviesPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppScreenshotsMoviesPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppScreenshotsMoviesPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.cpp index a54aac2f96..c25a6b35de 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.cpp @@ -1,50 +1,49 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppTBSSPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppTBSSPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.tractbasedspatialstatistics"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.tractbasedspatialstatistics"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.h index 51a3ecdc13..1154ef54b7 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTBSSPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppTBSSPerspective_H_ #define QmitkDIAppTBSSPerspective_H_ #include class QmitkDIAppTBSSPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppTBSSPerspective() {} QmitkDIAppTBSSPerspective(const QmitkDIAppTBSSPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppTBSSPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppTBSSPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.cpp index fcd0d3dc94..c63353b001 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.cpp @@ -1,49 +1,48 @@ -/*========================================================================= +/*=================================================================== - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppTrackingEvaluationPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppTrackingEvaluationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mitk.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mitk.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.artificialqballevaluation"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.artificialqballevaluation"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.h index 327ae819be..f02251a351 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppTrackingEvaluationPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= +/*=================================================================== - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppTrackingEvaluationPerspective_H_ #define QmitkDIAppTrackingEvaluationPerspective_H_ #include class QmitkDIAppTrackingEvaluationPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppTrackingEvaluationPerspective() {} QmitkDIAppTrackingEvaluationPerspective(const QmitkDIAppTrackingEvaluationPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppTrackingEvaluationPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppTrackingEvaluationPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.cpp index 658cade236..293d5b33ec 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.cpp @@ -1,50 +1,49 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDIAppVolumeVisualizationPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppVolumeVisualizationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.volumevisualization"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.volumevisualization"); lo->SetCloseable(false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.h index df8ed2af55..0713734e25 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkDIAppVolumeVisualizationPerspective_H_ #define QmitkDIAppVolumeVisualizationPerspective_H_ #include class QmitkDIAppVolumeVisualizationPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDIAppVolumeVisualizationPerspective() {} QmitkDIAppVolumeVisualizationPerspective(const QmitkDIAppVolumeVisualizationPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDIAppVolumeVisualizationPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QmitkDIAppVolumeVisualizationPerspective_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp index 7698b378f6..4a4595e4a4 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp @@ -1,50 +1,49 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionImagingAppPerspective.h" #include "berryIViewLayout.h" void QmitkDiffusionImagingAppPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .4f, "org.mbi.diffusionimaginginternal.leftcontrols"); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.h index 0bbb807407..b8d575bcd7 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDIFFUSIONIMAGINGAPPPERSPECTIVE_H_ #define QMITKDIFFUSIONIMAGINGAPPPERSPECTIVE_H_ #include class QmitkDiffusionImagingAppPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDiffusionImagingAppPerspective() {} QmitkDiffusionImagingAppPerspective(const QmitkDiffusionImagingAppPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDiffusionImagingAppPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QMITKDIFFUSIONIMAGINGAPPPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.cpp index 6a59624ce5..8dabd25575 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.cpp @@ -1,22 +1,21 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkWelcomePerspective.h" void QmitkWelcomePerspective::CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/) { } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.h index 2239700630..772287e162 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/Perspectives/QmitkWelcomePerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKWelcomePERSPECTIVE_H_ #define QMITKWelcomePERSPECTIVE_H_ #include class QmitkWelcomePerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkWelcomePerspective() {} QmitkWelcomePerspective(const QmitkWelcomePerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkWelcomePerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/); }; #endif /* QMITKWelcomePERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.cpp index 3fe48a15dd..babcbcbfd4 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.cpp @@ -1,109 +1,108 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionApplicationPlugin.h" #include "src/QmitkDiffusionImagingAppApplication.h" #include "src/internal/Perspectives/QmitkWelcomePerspective.h" #include "src/internal/QmitkDiffusionImagingAppIntroPart.h" #include "src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.h" #include "src/internal/Perspectives/QmitkDIAppConnectomicsPerspective.h" #include "src/internal/Perspectives/QmitkDIAppDicomImportPerspective.h" #include "src/internal/Perspectives/QmitkDIAppFiberTractographyPerspective.h" #include "src/internal/Perspectives/QmitkDIAppIVIMPerspective.h" #include "src/internal/Perspectives/QmitkDIAppPreprocessingReconstructionPerspective.h" #include "src/internal/Perspectives/QmitkDIAppQuantificationPerspective.h" #include "src/internal/Perspectives/QmitkDIAppScreenshotsMoviesPerspective.h" #include "src/internal/Perspectives/QmitkDIAppTBSSPerspective.h" #include "src/internal/Perspectives/QmitkDIAppVolumeVisualizationPerspective.h" #include #include #include #include #include #include #include QmitkDiffusionApplicationPlugin* QmitkDiffusionApplicationPlugin::inst = 0; QmitkDiffusionApplicationPlugin::QmitkDiffusionApplicationPlugin() { inst = this; } QmitkDiffusionApplicationPlugin::~QmitkDiffusionApplicationPlugin() { } QmitkDiffusionApplicationPlugin* QmitkDiffusionApplicationPlugin::GetDefault() { return inst; } void QmitkDiffusionApplicationPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkDiffusionImagingAppApplication, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDiffusionImagingAppIntroPart, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDiffusionImagingAppPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkWelcomePerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppConnectomicsPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppDicomImportPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppFiberTractographyPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppIVIMPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppPreprocessingReconstructionPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppQuantificationPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppScreenshotsMoviesPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppTBSSPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppVolumeVisualizationPerspective, context) ctkServiceReference cmRef = context->getServiceReference(); ctkConfigurationAdmin* configAdmin = 0; if (cmRef) { configAdmin = context->getService(cmRef); } // Use the CTK Configuration Admin service to configure the BlueBerry help system if (configAdmin) { ctkConfigurationPtr conf = configAdmin->getConfiguration("org.blueberry.services.help", QString()); ctkDictionary helpProps; helpProps.insert("homePage", "qthelp://org.mitk.gui.qt.diffusionimagingapp/bundle/index.html"); conf->update(helpProps); context->ungetService(cmRef); } else { MITK_WARN << "Configuration Admin service unavailable, cannot set home page url."; } } ctkPluginContext* QmitkDiffusionApplicationPlugin::GetPluginContext() const { return context; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_diffusionimagingapp, QmitkDiffusionApplicationPlugin) diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h index adf4523b93..e1b251d8d7 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h @@ -1,53 +1,52 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDIFFUSIONAPPLICATIONPLUGIN_H_ #define QMITKDIFFUSIONAPPLICATIONPLUGIN_H_ #include #include #include class QmitkDiffusionApplicationPlugin : public QObject, public berry::AbstractUICTKPlugin { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: QmitkDiffusionApplicationPlugin(); ~QmitkDiffusionApplicationPlugin(); static QmitkDiffusionApplicationPlugin* GetDefault(); ctkPluginContext* GetPluginContext() const; void start(ctkPluginContext*); QString GetQtHelpCollectionFile() const; private: static QmitkDiffusionApplicationPlugin* inst; ctkPluginContext* context; }; #endif /* QMITKDIFFUSIONAPPLICATIONPLUGIN_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp index c12bf82cdf..cf460ef9c1 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp @@ -1,212 +1,211 @@ -/*========================================================================= +/*=================================================================== - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDiffusionImagingAppIntroPart.h" #include "mitkNodePredicateDataType.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef QT_WEBKIT #include #include #endif #include #include #include #include #include #include #include "QmitkDiffusionApplicationPlugin.h" #include "mitkDataStorageEditorInput.h" #include #include "mitkBaseDataIOFactory.h" #include "mitkSceneIO.h" #include "mitkProgressBar.h" #include "mitkDataNodeFactory.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" QmitkDiffusionImagingAppIntroPart::QmitkDiffusionImagingAppIntroPart() : m_Controls(NULL) { berry::IPreferences::Pointer workbenchPrefs = QmitkDiffusionApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } QmitkDiffusionImagingAppIntroPart::~QmitkDiffusionImagingAppIntroPart() { // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPreferences::Pointer workbenchPrefs = QmitkDiffusionApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } else { berry::IPreferences::Pointer workbenchPrefs = QmitkDiffusionApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } // if workbench is not closing (Just welcome screen closing), open last used perspective if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId() == "org.mitk.diffusionimagingapp.perspectives.welcome" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp"); if (perspective) { this->GetIntroSite()->GetPage()->SetPerspective(perspective); } } } void QmitkDiffusionImagingAppIntroPart::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkWelcomeScreenViewControls; m_Controls->setupUi(parent); #ifdef QT_WEBKIT // create a QWebView as well as a QWebPage and QWebFrame within the QWebview m_view = new QWebView(parent); m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkdiffusionimagingappwelcomeview.html"), QUrl::TolerantMode ); m_view->load( urlQtResource ); // adds the webview as a widget parent->layout()->addWidget(m_view); this->CreateConnections(); #else parent->layout()->addWidget(new QLabel("

Please install Qt with the WebKit option to see cool pictures!

")); #endif } } #ifdef QT_WEBKIT void QmitkDiffusionImagingAppIntroPart::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_view->page()), SIGNAL(linkClicked(const QUrl& )), this, SLOT(DelegateMeTo(const QUrl& )) ); } } void QmitkDiffusionImagingAppIntroPart::DelegateMeTo(const QUrl& showMeNext) { QString scheme = showMeNext.scheme(); QByteArray urlHostname = showMeNext.encodedHost(); QByteArray urlPath = showMeNext.encodedPath(); QByteArray dataset = showMeNext.encodedQueryItemValue("dataset"); QByteArray clear = showMeNext.encodedQueryItemValue("clear"); if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ; // if the scheme is set to mitk, it is to be tested which action should be applied if (scheme.contains(QString("mitk")) ) { if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ; // searching for the perspective keyword within the host name if(urlHostname.contains(QByteArray("perspectives")) ) { // the simplified method removes every whitespace // ( whitespace means any character for which the standard C++ isspace() method returns true) urlPath = urlPath.simplified(); QString tmpPerspectiveId(urlPath.data()); tmpPerspectiveId.replace(QString("/"), QString("") ); std::string perspectiveId = tmpPerspectiveId.toStdString(); // is working fine as long as the perspective id is valid, if not the application crashes GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() ); // search the Workbench for opened StdMultiWidgets to ensure the focus does not stay on the welcome screen and is switched to // an StdMultiWidget if one available mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); berry::IEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput( service->GetActiveDataStorage() ); // the solution is not clean, but the dependency to the StdMultiWidget was removed in order to fix a crash problem // as described in Bug #11715 // This is the correct way : use the static string ID variable // berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->FindEditors( editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID ); // QuickFix: we use the same string for an local variable const std::string stdEditorID = "org.mitk.editors.stdmultiwidget"; // search for opened StdMultiWidgetEditors std::vector editorList = GetIntroSite()->GetPage()->FindEditors( editorInput, stdEditorID, 1 ); // if an StdMultiWidgetEditor open was found, give focus to it if(editorList.size()) { GetIntroSite()->GetPage()->Activate( editorList[0]->GetPart(true) ); } } } // if the scheme is set to http, by default no action is performed, if an external webpage needs to be // shown it should be implemented below else if (scheme.contains(QString("http")) ) { QDesktopServices::openUrl(showMeNext); // m_view->load( ) ; } else if(scheme.contains("qrc")) { m_view->load(showMeNext); } } #endif void QmitkDiffusionImagingAppIntroPart::StandbyStateChanged(bool standby) { } void QmitkDiffusionImagingAppIntroPart::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.h index b49accd2c4..dccb5e319f 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.h @@ -1,95 +1,94 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDIFFUSIONIMAGINGAPPINTROPART_H_ #define QMITKDIFFUSIONIMAGINGAPPINTROPART_H_ #include #include #include /** * \ingroup org_mitk_gui_qt_welcomescreen_internal * \brief QmitkWelcomeScreenView * The WelcomeView Module is an helpful feature to people new to MITK. The main idea is to provide first * information about the particular working modes of the 3 M-3 application suited to specific medical working task. * Links to external documentation or information pages such as the mitk.org homepage are thinkable but have * not been implemented yet. The WelcomeView is realized by making use of the QTWebKit Module. The Qt WebKit module * provides an HTML browser engine that makes it easy to embed web content into native applications, and to enhance * web content with native controls. * For the welcome view of the application the QWebView, QWebPage classes have been used. The shown WelcomeView * html start page is styled by an external css stylesheet. The required resources as well as the html pages are integrated * into the QtResource system. The QT resource system allows the storage of files like html pages, css pages, jpgs etc. * as binaries within the executable. * This minimizes the risk of loosing resource files as well as the risk of getting files deleted. In order to use the Qt * resource system the resource files have to be added to the associated qrt resource file list. * Due to time issues the html pages of the welcome view do make use of jpegs with hotspots to switch * into the particular working modes. < * Nevertheless the foundation is set to design more complex html pages. The Q::WebPage gives options to set a * LinkDelegationPolicy. The used policy defines how links to external or internal resources are handled. To fit our needs * the delegate all links policy is used. This requires all external as well as internal links of the html pages to be handle * explicitly. In order to change mitk working modes (perspectives) a mitk url scheme has been designed. The url scheme * is set to mitk. The url host provides information about what's next to do. In our case, the case of switching to a * particular working mode the host is set to perspectives. The followed path provides information about the perspective id. * (e.g. mitk//::mitk.perspectives/org.mitk.qt.defaultperspective) The the generic design of the mitk url scheme allows to * execute other task depending on the mitk url host. * \sa QmitkWelcomePage Editor */ class QWebView ; class QmitkDiffusionImagingAppIntroPart : public berry::QtIntroPart { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: QmitkDiffusionImagingAppIntroPart(); QmitkDiffusionImagingAppIntroPart(const QmitkDiffusionImagingAppIntroPart& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDiffusionImagingAppIntroPart(); virtual void CreateQtPartControl(QWidget *parent); void StandbyStateChanged(bool standby); void SetFocus(); #ifdef QT_WEBKIT virtual void CreateConnections(); protected slots: void DelegateMeTo(const QUrl& ShowMeNext); #endif protected: Ui::QmitkWelcomeScreenViewControls* m_Controls; QWebView* m_view; }; #endif /* QMITKDIFFUSIONIMAGINGAPPINTROPART_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.cpp index b11d2b7e6e..34211c13a0 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.cpp @@ -1,140 +1,138 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkNavigationButtonsView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" #include "mitkDiffusionImage.h" #include "mitkPlanarFigure.h" #include "mitkFiberBundle.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFiberBundleInteractor.h" #include "mitkPlanarFigureInteractor.h" #include "mitkGlobalInteraction.h" #include "mitkGeometry2D.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" #include "itkTractsToProbabilityImageFilter.h" #include "qwidgetaction.h" #include "qcolordialog.h" const std::string QmitkNavigationButtonsView::VIEW_ID = "org.mitk.views.NavigationButtonsview"; using namespace berry; QmitkNavigationButtonsView::QmitkNavigationButtonsView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), { } QmitkNavigationButtonsView::QmitkNavigationButtonsView(const QmitkNavigationButtonsView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkNavigationButtonsView::~QmitkNavigationButtonsView() { this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); } void QmitkNavigationButtonsView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkNavigationButtonsViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkNavigationButtonsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkNavigationButtonsView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkNavigationButtonsView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); } } void QmitkNavigationButtonsView::Activated() { QmitkFunctionality::Activated(); } void QmitkNavigationButtonsView::Deactivated() { QmitkFunctionality::Deactivated(); } int QmitkNavigationButtonsView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkNavigationButtonsView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return m_FoundSingleOdfImage ? 120 : 80; } else { return preferredResult; } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.h index c9fbb661b3..fa2b2ac063 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkNavigationButtonsView.h @@ -1,163 +1,161 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKNavigationButtonsView_H_INCLUDED #define _QMITKNavigationButtonsView_H_INCLUDED #include #include #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include "berryISizeProvider.h" #include "ui_QmitkNavigationButtonsViewControls.h" #include "mitkEnumerationProperty.h" /*! * \ingroup org_mitk_gui_qt_diffusionquantification_internal * * \brief QmitkNavigationButtonsView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkNavigationButtonsView : public QmitkFunctionality//, public berry::ISizeProvider { friend struct CvpSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkNavigationButtonsView(); QmitkNavigationButtonsView(const QmitkNavigationButtonsView& other); virtual ~QmitkNavigationButtonsView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); mitk::DataStorage::SetOfObjects::Pointer ActiveSet(std::string); void SetBoolProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,bool); void SetIntProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,int); void SetFloatProp(mitk::DataStorage::SetOfObjects::Pointer,std::string,float); void SetLevelWindowProp(mitk::DataStorage::SetOfObjects::Pointer,std::string,mitk::LevelWindow); void SetEnumProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,mitk::EnumerationProperty::Pointer); virtual int GetSizeFlags(bool width); virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); protected slots: void DisplayIndexChanged(int); void TextIntON(); void Reinit(); void VisibleOdfsON(int view); void VisibleOdfsON_S(); void VisibleOdfsON_T(); void VisibleOdfsON_C(); void ShowMaxNumberChanged(); void NormalizationDropdownChanged(int); void ScalingFactorChanged(double); void AdditionalScaling(int); void IndexParam1Changed(double); void IndexParam2Changed(double); void OpacityChanged(double,double); void ScalingCheckbox(); void OnThickSlicesModeSelected( QAction* action ); void OnTSNumChanged(int num); void OnMenuAboutToShow (); void BundleRepresentationWire(); void BundleRepresentationTube(); void BundleRepresentationColor(); void PlanarFigureFocus(); void SetInteractor(); void PFWidth(int); void PFColor(); void PFColor3D(); void LineWidthChanged(int); void TubeRadiusChanged(int); void Heatmap(); void Welcome(); protected: Ui::QmitkNavigationButtonsViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; bool m_FoundSingleOdfImage; bool m_IsInitialized; QIcon* m_IconTexOFF; QIcon* m_IconTexON; QIcon* m_IconGlyOFF_T; QIcon* m_IconGlyON_T; QIcon* m_IconGlyOFF_C; QIcon* m_IconGlyON_C; QIcon* m_IconGlyOFF_S; QIcon* m_IconGlyON_S; bool m_TexIsOn; bool m_GlyIsOn_T; bool m_GlyIsOn_C; bool m_GlyIsOn_S; int currentThickSlicesMode; QLabel* m_TSLabel; QMenu* m_MyMenu; // for planarfigure and bundle handling: mitk::DataNode* m_SelectedNode; mitk::DataNode* m_CurrentPickingNode; }; #endif // _QMITKNavigationButtonsView_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.cpp index 8c965fd7a9..8a752ef18b 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.cpp @@ -1,38 +1,37 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDTIAtlasAppApplication.h" #include #include "QmitkDTIAtlasAppWorkbenchAdvisor.h" int QmitkDTIAtlasAppApplication::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); int code = berry::PlatformUI::CreateAndRunWorkbench(display, new QmitkDTIAtlasAppWorkbenchAdvisor()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void QmitkDTIAtlasAppApplication::Stop() { } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.h index b7d5eeebfa..1e5c12e879 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppApplication.h @@ -1,42 +1,41 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDTIAtlasAppAPPLICATION_H_ #define QMITKDTIAtlasAppAPPLICATION_H_ #include class QmitkDTIAtlasAppApplication : public QObject, public berry::IApplication { Q_OBJECT Q_INTERFACES(berry::IApplication) public: QmitkDTIAtlasAppApplication() {} QmitkDTIAtlasAppApplication(const QmitkDTIAtlasAppApplication& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDTIAtlasAppApplication() {} int Start(); void Stop(); }; #endif /*QMITKDTIAtlasAppAPPLICATION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp index 9e53cb1d72..7a70a9105b 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp @@ -1,112 +1,111 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fri, 23 Oct 2009) $ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDTIAtlasAppWorkbenchAdvisor.h" #include "internal/QmitkDTIAtlasAppApplicationPlugin.h" #include #include #include #include #include #include const std::string QmitkDTIAtlasAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.dtiatlasapp.perspectives.welcome"; void QmitkDTIAtlasAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); // TODO This should go into the products plugin_customization.ini file (when // the product and branding support is finished, see bug 2146). // This will not work anymore, if bug 2822 is fixed. berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); prefService->GetSystemPreferences()->Put(berry::WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, berry::WorkbenchPreferenceConstants::RIGHT); QString collectionFile = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetQtHelpCollectionFile(); if (!collectionFile.isEmpty()) { // berry::QtAssistantUtil::SetHelpCollectionFile(collectionFile); // berry::QtAssistantUtil::SetDefaultHelpUrl("qthelp://org.mitk.gui.qt.dtiatlasapp/bundle/index.html"); typedef std::vector BundleContainer; BundleContainer bundles = berry::Platform::GetBundles(); berry::QtAssistantUtil::RegisterQCHFiles(bundles); } } berry::WorkbenchWindowAdvisor* QmitkDTIAtlasAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { std::vector perspExcludeList; perspExcludeList.push_back( std::string("org.mitk.dtiatlasapp.perspectives.welcome") ); perspExcludeList.push_back( std::string("org.mitk.perspectives.diffusionimaginginternal") ); perspExcludeList.push_back( std::string("org.mitk.perspectives.publicdiffusionimaging") ); perspExcludeList.push_back( std::string("org.mitk.extapp.defaultperspective") ); perspExcludeList.push_back( std::string("org.mitk.coreapp.defaultperspective") ); std::vector viewExcludeList; viewExcludeList.push_back( std::string("org.mitk.views.partialvolumeanalysis") ); viewExcludeList.push_back( std::string("org.mitk.views.globalfibertracking") ); viewExcludeList.push_back( std::string("org.mitk.views.tractbasedspatialstatistics") ); viewExcludeList.push_back( std::string("org.mitk.views.fibertracking") ); viewExcludeList.push_back( std::string("org.mitk.views.ivim") ); viewExcludeList.push_back( std::string("org.mitk.views.qballreconstruction") ); viewExcludeList.push_back( std::string("org.mitk.views.diffusiondicomimport") ); viewExcludeList.push_back( std::string("org.mitk.views.diffusionpreprocessing") ); viewExcludeList.push_back( std::string("org.mitk.views.diffusionquantification") ); viewExcludeList.push_back( std::string("org.mitk.views.tensorreconstruction") ); viewExcludeList.push_back( std::string("org.mitk.views.perspectiveswitcher") ); viewExcludeList.push_back( std::string("org.mitk.views.basicimageprocessing") ); viewExcludeList.push_back( std::string("org.mitk.views.fiberbundleoperations") ); viewExcludeList.push_back( std::string("org.mitk.views.measurement") ); viewExcludeList.push_back( std::string("org.mitk.views.moviemaker") ); viewExcludeList.push_back( std::string("org.mitk.views.odfdetails") ); viewExcludeList.push_back( std::string("org.mitk.views.propertylistview") ); viewExcludeList.push_back( std::string("org.mitk.views.screenshotmaker") ); viewExcludeList.push_back( std::string("org.mitk.views.segmentation") ); viewExcludeList.push_back( std::string("org.mitk.views.imagestatistics") ); // viewExcludeList.push_back( std::string("org.mitk.views.controlvisualizationpropertiesview") ); viewExcludeList.push_back( std::string("org.mitk.views.volumevisualization") ); viewExcludeList.push_back( std::string("org.mitk.views.simplemeasurement") ); configurer->SetShowPerspectiveBar(false); configurer->SetInitialSize(berry::Point(1000,770)); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowVersionInfo(false); advisor->ShowMitkVersionInfo(false); advisor->SetProductName("based on MITK Diffusion Imaging App"); advisor->SetWindowIcon(":/org.mitk.gui.qt.dtiatlasapp/app-icon.png"); return advisor; } std::string QmitkDTIAtlasAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h index b87e2706fc..84de3310f2 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h @@ -1,40 +1,39 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDTIATLASAPPWORKBENCHADVISOR_H_ #define QMITKDTIATLASAPPWORKBENCHADVISOR_H_ #include class QmitkDTIAtlasAppWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const std::string WELCOME_PERSPECTIVE_ID; // = "org.mitk.qt.dtiatlasapp.defaultperspective" void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); std::string GetInitialWindowPerspectiveId(); }; #endif /* QMITKDTIATLASAPPWORKBENCHADVISOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp index 8689d718d7..4e354b39fd 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp @@ -1,122 +1,121 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDTIAtlasAppApplicationPlugin.h" #include #include #include #include "src/QmitkDTIAtlasAppApplication.h" #include "src/internal/QmitkDTIAtlasAppIntroPart.h" #include "src/internal/QmitkDTIAtlasAppPerspective.h" #include "src/internal/QmitkWelcomePerspective.h" #include #include QmitkDTIAtlasAppApplicationPlugin* QmitkDTIAtlasAppApplicationPlugin::inst = 0; QmitkDTIAtlasAppApplicationPlugin::QmitkDTIAtlasAppApplicationPlugin() : pluginListener(0) { inst = this; } QmitkDTIAtlasAppApplicationPlugin::~QmitkDTIAtlasAppApplicationPlugin() { delete pluginListener; } QmitkDTIAtlasAppApplicationPlugin* QmitkDTIAtlasAppApplicationPlugin::GetDefault() { return inst; } void QmitkDTIAtlasAppApplicationPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkDTIAtlasAppApplication, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDTIAtlasAppIntroPart, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDTIAtlasAppPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkWelcomePerspective, context) // QString collectionFile = GetQtHelpCollectionFile(); // berry::QtAssistantUtil::SetHelpCollectionFile(collectionFile); // berry::QtAssistantUtil::SetDefaultHelpUrl("qthelp://org.mitk.gui.qt.dtiatlasapp/bundle/index.html"); delete pluginListener; pluginListener = new berry::QCHPluginListener(context); context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // register all QCH files from all the currently installed plugins pluginListener->processPlugins(); } QString QmitkDTIAtlasAppApplicationPlugin::GetQtHelpCollectionFile() const { if (!helpCollectionFile.isEmpty()) { return helpCollectionFile; } QString collectionFilename; QString na("n/a"); // if (na != MITK_REVISION) // collectionFilename = "MitkDTIAtlasAppQtHelpCollection_" MITK_REVISION ".qhc"; // else collectionFilename = "MitkDTIAtlasAppQtHelpCollection.qhc"; QFileInfo collectionFileInfo = context->getDataFile(collectionFilename); QFileInfo pluginFileInfo = QFileInfo(QUrl(context->getPlugin()->getLocation()).toLocalFile()); if (!collectionFileInfo.exists() || pluginFileInfo.lastModified() > collectionFileInfo.lastModified()) { // extract the qhc file from the plug-in QByteArray content = context->getPlugin()->getResource(collectionFilename); if (content.isEmpty()) { BERRY_WARN << "Could not get plug-in resource: " << collectionFilename.toStdString(); } else { QFile file(collectionFileInfo.absoluteFilePath()); file.open(QIODevice::WriteOnly); file.write(content); file.close(); } } if (QFile::exists(collectionFileInfo.absoluteFilePath())) { helpCollectionFile = collectionFileInfo.absoluteFilePath(); } return helpCollectionFile; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_dtiatlasapp, QmitkDTIAtlasAppApplicationPlugin) diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h index ea5f4e2e3f..08f35a961d 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h @@ -1,58 +1,57 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDTIATLASAPPAPPLICATIONPLUGIN_H_ #define QMITKDTIATLASAPPAPPLICATIONPLUGIN_H_ #include #include #include #include class QmitkDTIAtlasAppApplicationPlugin : public QObject, public berry::AbstractUICTKPlugin { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: QmitkDTIAtlasAppApplicationPlugin(); ~QmitkDTIAtlasAppApplicationPlugin(); static QmitkDTIAtlasAppApplicationPlugin* GetDefault(); ctkPluginContext* GetPluginContext() const; void start(ctkPluginContext*); QString GetQtHelpCollectionFile() const; private: static QmitkDTIAtlasAppApplicationPlugin* inst; ctkPluginContext* context; berry::QCHPluginListener* pluginListener; mutable QString helpCollectionFile; }; // QmitkDTIAtlasAppApplicationPlugin #endif // QMITKDTIATLASAPPAPPLICATIONPLUGIN_H_ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp index 512e8ef5d7..5e8321a126 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp @@ -1,294 +1,293 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDTIAtlasAppIntroPart.h" #include "mitkNodePredicateDataType.h" #include #include #include #include #include #include #include #include #include #include #include #ifdef QT_WEBKIT #include #include #endif #include #include #include #include #include #include #include "QmitkStdMultiWidget.h" #include "QmitkStdMultiWidgetEditor.h" #include "QmitkDTIAtlasAppApplicationPlugin.h" #include "mitkDataStorageEditorInput.h" #include "mitkBaseDataIOFactory.h" #include "mitkSceneIO.h" #include "mitkProgressBar.h" #include "mitkDataNodeFactory.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" QmitkDTIAtlasAppIntroPart::QmitkDTIAtlasAppIntroPart() : m_Controls(NULL) { berry::IPreferences::Pointer workbenchPrefs = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } QmitkDTIAtlasAppIntroPart::~QmitkDTIAtlasAppIntroPart() { // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPreferences::Pointer workbenchPrefs = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } else { berry::IPreferences::Pointer workbenchPrefs = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } // if workbench is not closing (Just welcome screen closing), open last used perspective if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId() == "org.mitk.dtiatlasapp.perspectives.welcome" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.dtiatlasapp.perspectives.dtiatlasapp"); if (perspective) { this->GetIntroSite()->GetPage()->SetPerspective(perspective); } } } void QmitkDTIAtlasAppIntroPart::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkWelcomeScreenViewControls; m_Controls->setupUi(parent); #ifdef QT_WEBKIT // create a QWebView as well as a QWebPage and QWebFrame within the QWebview m_view = new QWebView(parent); m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkdtiatlasappwelcomeview.html"), QUrl::TolerantMode ); m_view->load( urlQtResource ); // adds the webview as a widget parent->layout()->addWidget(m_view); this->CreateConnections(); #else parent->layout()->addWidget(new QLabel("

Please install Qt with the WebKit option to see cool pictures!

")); #endif } } #ifdef QT_WEBKIT void QmitkDTIAtlasAppIntroPart::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_view->page()), SIGNAL(linkClicked(const QUrl& )), this, SLOT(DelegateMeTo(const QUrl& )) ); } } void QmitkDTIAtlasAppIntroPart::DelegateMeTo(const QUrl& showMeNext) { QString scheme = showMeNext.scheme(); QByteArray urlHostname = showMeNext.encodedHost(); QByteArray urlPath = showMeNext.encodedPath(); QByteArray dataset = showMeNext.encodedQueryItemValue("dataset"); QByteArray clear = showMeNext.encodedQueryItemValue("clear"); if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ; // if the scheme is set to mitk, it is to be tested which action should be applied if (scheme.contains(QString("mitk")) ) { if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ; // searching for the perspective keyword within the host name if(urlHostname.contains(QByteArray("perspectives")) ) { // the simplified method removes every whitespace // ( whitespace means any character for which the standard C++ isspace() method returns true) urlPath = urlPath.simplified(); QString tmpPerspectiveId(urlPath.data()); tmpPerspectiveId.replace(QString("/"), QString("") ); std::string perspectiveId = tmpPerspectiveId.toStdString(); // is working fine as long as the perspective id is valid, if not the application crashes GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() ); mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID); QmitkStdMultiWidgetEditor::Pointer multiWidgetEditor; mitk::DataStorage::Pointer dataStorage; if (editor.Cast().IsNull()) { editorInput = new mitk::DataStorageEditorInput(); dataStorage = editorInput->GetDataStorageReference()->GetDataStorage(); } else { multiWidgetEditor = editor.Cast(); multiWidgetEditor->GetStdMultiWidget()->RequestUpdate(); dataStorage = multiWidgetEditor->GetEditorInput().Cast()->GetDataStorageReference()->GetDataStorage(); } bool dsmodified = false; QString *fileName = new QString(dataset.data()); if ( fileName->right(5) == ".mitk" ) { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); QString *sClear = new QString(clear.data()); if ( sClear->right(4) == "true" ) { clearDataStorageFirst = true; } mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( fileName->toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); dsmodified = true; mitk::ProgressBar::GetInstance()->Progress(2); } else { mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); try { nodeReader->SetFileName(fileName->toLocal8Bit().data()); nodeReader->Update(); for ( unsigned int i = 0 ; i < nodeReader->GetNumberOfOutputs( ); ++i ) { mitk::DataNode::Pointer node; node = nodeReader->GetOutput(i); if ( node->GetData() != NULL ) { dataStorage->Add(node); dsmodified = true; } } } catch(...) { MITK_INFO << "Could not open file!"; } } if(dataStorage.IsNotNull() && dsmodified) { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = dataStorage->GetSubset(pred); if(rs->Size() > 0) { // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = dataStorage->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } } } // searching for the load if(urlHostname.contains(QByteArray("perspectives")) ) { // the simplified method removes every whitespace // ( whitespace means any character for which the standard C++ isspace() method returns true) urlPath = urlPath.simplified(); QString tmpPerspectiveId(urlPath.data()); tmpPerspectiveId.replace(QString("/"), QString("") ); std::string perspectiveId = tmpPerspectiveId.toStdString(); // is working fine as long as the perspective id is valid, if not the application crashes GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() ); mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); GetIntroSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID); } else { MITK_INFO << "Unkown mitk action keyword (see documentation for mitk links)" ; } } // if the scheme is set to http, by default no action is performed, if an external webpage needs to be // shown it should be implemented below else if (scheme.contains(QString("http")) ) { QDesktopServices::openUrl(showMeNext); // m_view->load( ) ; } else if(scheme.contains("qrc")) { m_view->load(showMeNext); } } #endif void QmitkDTIAtlasAppIntroPart::StandbyStateChanged(bool standby) { } void QmitkDTIAtlasAppIntroPart::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.h index fa8aad7a15..273dd5aa6d 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.h @@ -1,95 +1,94 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date$ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDTIATLASAPPINTROPART_H_ #define QMITKDTIATLASAPPINTROPART_H_ #include #include #include /** * \ingroup org_mitk_gui_qt_welcomescreen_internal * \brief QmitkWelcomeScreenView * The WelcomeView Module is an helpful feature to people new to MITK. The main idea is to provide first * information about the particular working modes of the 3 M-3 application suited to specific medical working task. * Links to external documentation or information pages such as the mitk.org homepage are thinkable but have * not been implemented yet. The WelcomeView is realized by making use of the QTWebKit Module. The Qt WebKit module * provides an HTML browser engine that makes it easy to embed web content into native applications, and to enhance * web content with native controls. * For the welcome view of the application the QWebView, QWebPage classes have been used. The shown WelcomeView * html start page is styled by an external css stylesheet. The required resources as well as the html pages are integrated * into the QtResource system. The QT resource system allows the storage of files like html pages, css pages, jpgs etc. * as binaries within the executable. * This minimizes the risk of loosing resource files as well as the risk of getting files deleted. In order to use the Qt * resource system the resource files have to be added to the associated qrt resource file list. * Due to time issues the html pages of the welcome view do make use of jpegs with hotspots to switch * into the particular working modes. < * Nevertheless the foundation is set to design more complex html pages. The Q::WebPage gives options to set a * LinkDelegationPolicy. The used policy defines how links to external or internal resources are handled. To fit our needs * the delegate all links policy is used. This requires all external as well as internal links of the html pages to be handle * explicitly. In order to change mitk working modes (perspectives) a mitk url scheme has been designed. The url scheme * is set to mitk. The url host provides information about what's next to do. In our case, the case of switching to a * particular working mode the host is set to perspectives. The followed path provides information about the perspective id. * (e.g. mitk//::mitk.perspectives/org.mitk.qt.defaultperspective) The the generic design of the mitk url scheme allows to * execute other task depending on the mitk url host. * \sa QmitkWelcomePage Editor */ class QWebView ; class QmitkDTIAtlasAppIntroPart : public berry::QtIntroPart { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: QmitkDTIAtlasAppIntroPart(); QmitkDTIAtlasAppIntroPart(const QmitkDTIAtlasAppIntroPart& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDTIAtlasAppIntroPart(); virtual void CreateQtPartControl(QWidget *parent); void StandbyStateChanged(bool standby); void SetFocus(); #ifdef QT_WEBKIT virtual void CreateConnections(); protected slots: void DelegateMeTo(const QUrl& ShowMeNext); #endif protected: Ui::QmitkWelcomeScreenViewControls* m_Controls; QWebView* m_view; }; #endif /* QMITKDTIATLASAPPINTROPART_H_ */ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp index afe9359a71..c007a839ad 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp @@ -1,90 +1,89 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDTIAtlasAppPerspective.h" #include "berryIViewLayout.h" void QmitkDTIAtlasAppPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { std::string editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .5f, "org.mitk.views.datamanager"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .8f, "org.mitk.views.controlvisualizationpropertiesview"); // berry::IFolderLayout::Pointer left = // layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", // berry::IPageLayout::BOTTOM, 0.2f, "org.mitk.views.controlvisualizationpropertiesview"); // layout->AddStandaloneView("org.mitk.views.perspectiveswitcher", // false, berry::IPageLayout::BOTTOM, 0.99f, "org.mbi.diffusionimaginginternal.leftcontrols"); //////////////////////////////////////// // public views go here //////////////////////////////////////// // left->AddView("org.mitk.views.fiberbundleoperations"); // berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.fiberbundleoperations"); // lo->SetCloseable(false); // left->AddView("org.mitk.views.diffusionpreprocessing"); // berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusionpreprocessing"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.tensorreconstruction"); // lo = layout->GetViewLayout("org.mitk.views.tensorreconstruction"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.qballreconstruction"); // lo = layout->GetViewLayout("org.mitk.views.qballreconstruction"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.diffusionquantification"); // lo = layout->GetViewLayout("org.mitk.views.diffusionquantification"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.diffusiondicomimport"); // lo = layout->GetViewLayout("org.mitk.views.diffusiondicomimport"); // lo->SetCloseable(true); //////////////////////////////////////// // end public views //////////////////////////////////////// // berry::IFolderLayout::Pointer right = // layout->CreateFolder("org.mbi.diffusionimaginginternal.rightcontrols", berry::IPageLayout::RIGHT, 0.5f, editorArea); //////////////////////////////////////// // internal views go here //////////////////////////////////////// // right->AddView("org.mitk.views.globalfibertracking"); // right->AddView("org.mitk.views.partialvolumeanalysis"); // right->AddView("org.mitk.views.ivim"); // right->AddView("org.mitk.views.tractbasedspatialstatistics"); // right->AddView("org.mitk.views.fibertracking"); //////////////////////////////////////// // end internal views //////////////////////////////////////// } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.h index 88d647d859..fb5ceaa697 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDTIATLASAPPPERSPECTIVE_H_ #define QMITKDTIATLASAPPPERSPECTIVE_H_ #include class QmitkDTIAtlasAppPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkDTIAtlasAppPerspective() {} QmitkDTIAtlasAppPerspective(const QmitkDTIAtlasAppPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkDTIAtlasAppPerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QMITKDTIATLASAPPPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.cpp index 56f47ba707..450a6c54db 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.cpp @@ -1,947 +1,945 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkNavigationButtonsView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" #include "mitkDiffusionImage.h" #include "mitkPlanarFigure.h" #include "mitkFiberBundle.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFiberBundleInteractor.h" #include "mitkPlanarFigureInteractor.h" #include "mitkGlobalInteraction.h" #include "mitkGeometry2D.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" #include "itkTractsToProbabilityImageFilter.h" #include "qwidgetaction.h" #include "qcolordialog.h" const std::string QmitkNavigationButtonsView::VIEW_ID = "org.mitk.views.NavigationButtonsview"; using namespace berry; QmitkNavigationButtonsView::QmitkNavigationButtonsView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), { } QmitkNavigationButtonsView::QmitkNavigationButtonsView(const QmitkNavigationButtonsView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkNavigationButtonsView::~QmitkNavigationButtonsView() { this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); } void QmitkNavigationButtonsView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkNavigationButtonsViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkNavigationButtonsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkNavigationButtonsView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkNavigationButtonsView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); } } void QmitkNavigationButtonsView::Activated() { QmitkFunctionality::Activated(); } void QmitkNavigationButtonsView::Deactivated() { QmitkFunctionality::Deactivated(); } int QmitkNavigationButtonsView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkNavigationButtonsView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return m_FoundSingleOdfImage ? 120 : 80; } else { return preferredResult; } } mitk::DataStorage::SetOfObjects::Pointer QmitkNavigationButtonsView::ActiveSet(std::string classname) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); if(QString(classname.c_str()).compare(node->GetData()->GetNameOfClass())==0) { set->InsertElement(at++, node); } } } return set; } return 0; } void QmitkNavigationButtonsView::SetBoolProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, bool value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetBoolProperty(name.c_str(), value); ++itemiter; } } } void QmitkNavigationButtonsView::SetIntProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, int value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty(name.c_str(), value); ++itemiter; } } } void QmitkNavigationButtonsView::SetFloatProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, float value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetFloatProperty(name.c_str(), value); ++itemiter; } } } void QmitkNavigationButtonsView::SetLevelWindowProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::LevelWindow value) { if(set.IsNotNull()) { mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(value); mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), prop); ++itemiter; } } } void QmitkNavigationButtonsView::SetEnumProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::EnumerationProperty::Pointer value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), value); ++itemiter; } } } void QmitkNavigationButtonsView::DisplayIndexChanged(int dispIndex) { QString label = "Channel %1"; label = label.arg(dispIndex); m_Controls->label_channel->setText(label); mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("DiffusionImage"); if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty("DisplayChannel", dispIndex); ++itemiter; } //m_MultiWidget->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkNavigationButtonsView::Reinit() { if (m_CurrentSelection) { mitk::DataNodeObject::Pointer nodeObj = m_CurrentSelection->Begin()->Cast(); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkNavigationButtonsView::TextIntON() { if(m_TexIsOn) { m_Controls->m_TextureIntON->setIcon(*m_IconTexOFF); } else { m_Controls->m_TextureIntON->setIcon(*m_IconTexON); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("DiffusionImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("TensorImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("QBallImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("Image"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); m_TexIsOn = !m_TexIsOn; if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::VisibleOdfsON_S() { if(m_GlyIsOn_S) { m_Controls->m_VisibleOdfsON_S->setIcon(*m_IconGlyOFF_S); } else { m_Controls->m_VisibleOdfsON_S->setIcon(*m_IconGlyON_S); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetBoolProp(set,"VisibleOdfs_S", !m_GlyIsOn_S); set = ActiveSet("TensorImage"); SetBoolProp(set,"VisibleOdfs_S", !m_GlyIsOn_S); m_GlyIsOn_S = !m_GlyIsOn_S; VisibleOdfsON(0); } void QmitkNavigationButtonsView::VisibleOdfsON_T() { if(m_GlyIsOn_T) { m_Controls->m_VisibleOdfsON_T->setIcon(*m_IconGlyOFF_T); } else { m_Controls->m_VisibleOdfsON_T->setIcon(*m_IconGlyON_T); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetBoolProp(set,"VisibleOdfs_T", !m_GlyIsOn_T); set = ActiveSet("TensorImage"); SetBoolProp(set,"VisibleOdfs_T", !m_GlyIsOn_T); m_GlyIsOn_T = !m_GlyIsOn_T; VisibleOdfsON(1); } void QmitkNavigationButtonsView::VisibleOdfsON_C() { if(m_GlyIsOn_C) { m_Controls->m_VisibleOdfsON_C->setIcon(*m_IconGlyOFF_C); } else { m_Controls->m_VisibleOdfsON_C->setIcon(*m_IconGlyON_C); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetBoolProp(set,"VisibleOdfs_C", !m_GlyIsOn_C); set = ActiveSet("TensorImage"); SetBoolProp(set,"VisibleOdfs_C", !m_GlyIsOn_C); m_GlyIsOn_C = !m_GlyIsOn_C; VisibleOdfsON(2); } void QmitkNavigationButtonsView::VisibleOdfsON(int view) { if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::ShowMaxNumberChanged() { int maxNr = m_Controls->m_ShowMaxNumber->value(); if ( maxNr < 1 ) { m_Controls->m_ShowMaxNumber->setValue( 1 ); maxNr = 1; } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetIntProp(set,"ShowMaxNumber", maxNr); set = ActiveSet("TensorImage"); SetIntProp(set,"ShowMaxNumber", maxNr); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::NormalizationDropdownChanged(int normDropdown) { typedef mitk::OdfNormalizationMethodProperty PropType; PropType::Pointer normMeth = PropType::New(); switch(normDropdown) { case 0: normMeth->SetNormalizationToMinMax(); break; case 1: normMeth->SetNormalizationToMax(); break; case 2: normMeth->SetNormalizationToNone(); break; case 3: normMeth->SetNormalizationToGlobalMax(); break; default: normMeth->SetNormalizationToMinMax(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::ScalingFactorChanged(double scalingFactor) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"Scaling", scalingFactor); set = ActiveSet("TensorImage"); SetFloatProp(set,"Scaling", scalingFactor); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::AdditionalScaling(int additionalScaling) { typedef mitk::OdfScaleByProperty PropType; PropType::Pointer scaleBy = PropType::New(); switch(additionalScaling) { case 0: scaleBy->SetScaleByNothing(); break; case 1: scaleBy->SetScaleByGFA(); //m_Controls->params_frame->setVisible(true); break; #ifdef DIFFUSION_IMAGING_EXTENDED case 2: scaleBy->SetScaleByPrincipalCurvature(); // commented in for SPIE paper, Principle curvature scaling //m_Controls->params_frame->setVisible(true); break; #endif default: scaleBy->SetScaleByNothing(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::IndexParam1Changed(double param1) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam1", param1); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam1", param1); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::IndexParam2Changed(double param2) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam2", param2); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam2", param2); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::OpacityChanged(double l, double u) { mitk::LevelWindow olw; olw.SetRangeMinMax(l*255, u*255); mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("TensorImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("Image"); SetLevelWindowProp(set,"opaclevelwindow", olw); m_Controls->m_OpacityMinFaLabel->setText(QString::number(l,'f',2) + " : " + QString::number(u,'f',2)); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkNavigationButtonsView::ScalingCheckbox() { m_Controls->m_ScalingFrame->setVisible( m_Controls->m_ScalingCheckbox->isChecked()); } void QmitkNavigationButtonsView::BundleRepresentationWire() { if(m_SelectedNode) { int width = m_Controls->m_LineWidth->value(); m_SelectedNode->SetProperty("LineWidth",mitk::IntProperty::New(width)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(15)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(18)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(1)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(2)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(3)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(4)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkNavigationButtonsView::BundleRepresentationTube() { if(m_SelectedNode) { float radius = m_Controls->m_TubeRadius->value() / 100.0; m_SelectedNode->SetProperty("TubeRadius",mitk::FloatProperty::New(radius)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(17)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(13)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(16)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkNavigationButtonsView::BundleRepresentationColor() { if(m_SelectedNode) { QColor color = QColorDialog::getColor(); m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(14)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(3)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkNavigationButtonsView::PlanarFigureFocus() { if(m_SelectedNode) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (m_SelectedNode->GetData()); if (_PlanarFigure) { QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); if (m_SelectedNode->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); mitk::VnlVector normal = _PlaneGeometry->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry1 = RenderWindow1->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane1 = dynamic_cast( worldGeometry1.GetPointer() ); mitk::VnlVector normal1 = _Plane1->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry2 = RenderWindow2->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane2 = dynamic_cast( worldGeometry2.GetPointer() ); mitk::VnlVector normal2 = _Plane2->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry3 = RenderWindow3->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane3 = dynamic_cast( worldGeometry3.GetPointer() ); mitk::VnlVector normal3 = _Plane3->GetNormalVnl(); normal[0] = fabs(normal[0]); normal[1] = fabs(normal[1]); normal[2] = fabs(normal[2]); normal1[0] = fabs(normal1[0]); normal1[1] = fabs(normal1[1]); normal1[2] = fabs(normal1[2]); normal2[0] = fabs(normal2[0]); normal2[1] = fabs(normal2[1]); normal2[2] = fabs(normal2[2]); normal3[0] = fabs(normal3[0]); normal3[1] = fabs(normal3[1]); normal3[2] = fabs(normal3[2]); double ang1 = angle(normal, normal1); double ang2 = angle(normal, normal2); double ang3 = angle(normal, normal3); if(ang1 < ang2 && ang1 < ang3) { selectedRenderWindow = RenderWindow1; } else { if(ang2 < ang3) { selectedRenderWindow = RenderWindow2; } else { selectedRenderWindow = RenderWindow3; } } // make node visible if (selectedRenderWindow) { mitk::Point3D centerP = _PlaneGeometry->GetOrigin(); selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); selectedRenderWindow->GetSliceNavigationController()->SelectSliceByPoint( centerP); } } // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(m_SelectedNode->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", m_SelectedNode); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); m_SelectedNode->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); } } void QmitkNavigationButtonsView::SetInteractor() { typedef std::vector Container; Container _NodeSet = this->GetDataManagerSelection(); mitk::DataNode* node = 0; mitk::FiberBundle* bundle = 0; mitk::FiberBundleInteractor::Pointer bundleInteractor = 0; // finally add all nodes to the model for(Container::const_iterator it=_NodeSet.begin(); it!=_NodeSet.end() ; it++) { node = const_cast(*it); bundle = dynamic_cast(node->GetData()); if(bundle) { bundleInteractor = dynamic_cast(node->GetInteractor()); if(bundleInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(bundleInteractor); if(!m_Controls->m_Crosshair->isChecked()) { m_Controls->m_Crosshair->setChecked(false); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::ArrowCursor); m_CurrentPickingNode = 0; } else { m_Controls->m_Crosshair->setChecked(true); bundleInteractor = mitk::FiberBundleInteractor::New("FiberBundleInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(bundleInteractor); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::CrossCursor); m_CurrentPickingNode = node; } } } } void QmitkNavigationButtonsView::PFWidth(int w) { double width = w/10.0; m_SelectedNode->SetProperty("planarfigure.line.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.outline.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.helperline.width", mitk::FloatProperty::New(width) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QString label = "Width %1"; label = label.arg(width); m_Controls->label_pfwidth->setText(label); } void QmitkNavigationButtonsView::PFColor() { QColor color = QColorDialog::getColor(); m_Controls->m_PFColor->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_PFColor->setStyleSheet(styleSheet); m_SelectedNode->SetProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); // m_SelectedNode->SetProperty( "planarfigure.hover.markerline.color", mitk::ColorProperty::New(0.0,1.0,0.0) ); // m_SelectedNode->SetProperty( "planarfigure.hover.marker.color", mitk::ColorProperty::New(0.0,1.0,0.0) ); // m_SelectedNode->SetProperty( "planarfigure.selected.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); // m_SelectedNode->SetProperty( "planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); // m_SelectedNode->SetProperty( "planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); // m_SelectedNode->SetProperty( "planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); // m_SelectedNode->SetProperty( "planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkNavigationButtonsView::PFColor3D() { QColor color = QColorDialog::getColor(); m_Controls->m_PFColor3D->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_PFColor3D->setStyleSheet(styleSheet); m_SelectedNode->SetProperty( "color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkNavigationButtonsView::Heatmap() { if(m_SelectedNode) { mitk::FiberBundle* bundle = dynamic_cast(m_SelectedNode->GetData()); if(!bundle) return; /////////////////////////////// // Generate unsigned char Image typedef unsigned char OutPixType2; // run generator typedef itk::Image< float, 3 > WMPImageType; typedef itk::TractsToProbabilityImageFilter ImageGeneratorType2; ImageGeneratorType2::Pointer generator = ImageGeneratorType2::New(); //generator->SetInput(NULL); generator->SetFiberBundle(bundle); generator->SetInvertImage(false); generator->SetUpsamplingFactor(2); generator->SetBinaryEnvelope(false); generator->Update(); // get result typedef itk::Image OutType2; OutType2::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img2 = mitk::Image::New(); img2->InitializeByItk(outImg.GetPointer()); img2->SetVolume(outImg->GetBufferPointer()); // to datastorage mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img2); QString name(m_SelectedNode->GetName().c_str()); name += "_heatmap"; node->SetName(name.toStdString()); node->SetVisibility(true); GetDataStorage()->Add(node); } } void QmitkNavigationButtonsView::LineWidthChanged(int w) { m_SelectedNode->SetIntProperty("LineWidth", w); QString label = "Width %1"; label = label.arg(w); m_Controls->label_linewidth->setText(label); } void QmitkNavigationButtonsView::TubeRadiusChanged(int r) { m_SelectedNode->SetFloatProperty("TubeRadius", (float) r / 100.0); QString label = "Radius %1"; label = label.arg(r / 100.0); m_Controls->label_tuberadius->setText(label); } void QmitkNavigationButtonsView::Welcome() { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( GetSite()->GetWorkbenchWindow(), false); } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.h index c9fbb661b3..fa2b2ac063 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkNavigationButtonsView.h @@ -1,163 +1,161 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKNavigationButtonsView_H_INCLUDED #define _QMITKNavigationButtonsView_H_INCLUDED #include #include #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include "berryISizeProvider.h" #include "ui_QmitkNavigationButtonsViewControls.h" #include "mitkEnumerationProperty.h" /*! * \ingroup org_mitk_gui_qt_diffusionquantification_internal * * \brief QmitkNavigationButtonsView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkNavigationButtonsView : public QmitkFunctionality//, public berry::ISizeProvider { friend struct CvpSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkNavigationButtonsView(); QmitkNavigationButtonsView(const QmitkNavigationButtonsView& other); virtual ~QmitkNavigationButtonsView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); mitk::DataStorage::SetOfObjects::Pointer ActiveSet(std::string); void SetBoolProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,bool); void SetIntProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,int); void SetFloatProp(mitk::DataStorage::SetOfObjects::Pointer,std::string,float); void SetLevelWindowProp(mitk::DataStorage::SetOfObjects::Pointer,std::string,mitk::LevelWindow); void SetEnumProp (mitk::DataStorage::SetOfObjects::Pointer,std::string,mitk::EnumerationProperty::Pointer); virtual int GetSizeFlags(bool width); virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); protected slots: void DisplayIndexChanged(int); void TextIntON(); void Reinit(); void VisibleOdfsON(int view); void VisibleOdfsON_S(); void VisibleOdfsON_T(); void VisibleOdfsON_C(); void ShowMaxNumberChanged(); void NormalizationDropdownChanged(int); void ScalingFactorChanged(double); void AdditionalScaling(int); void IndexParam1Changed(double); void IndexParam2Changed(double); void OpacityChanged(double,double); void ScalingCheckbox(); void OnThickSlicesModeSelected( QAction* action ); void OnTSNumChanged(int num); void OnMenuAboutToShow (); void BundleRepresentationWire(); void BundleRepresentationTube(); void BundleRepresentationColor(); void PlanarFigureFocus(); void SetInteractor(); void PFWidth(int); void PFColor(); void PFColor3D(); void LineWidthChanged(int); void TubeRadiusChanged(int); void Heatmap(); void Welcome(); protected: Ui::QmitkNavigationButtonsViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; bool m_FoundSingleOdfImage; bool m_IsInitialized; QIcon* m_IconTexOFF; QIcon* m_IconTexON; QIcon* m_IconGlyOFF_T; QIcon* m_IconGlyON_T; QIcon* m_IconGlyOFF_C; QIcon* m_IconGlyON_C; QIcon* m_IconGlyOFF_S; QIcon* m_IconGlyON_S; bool m_TexIsOn; bool m_GlyIsOn_T; bool m_GlyIsOn_C; bool m_GlyIsOn_S; int currentThickSlicesMode; QLabel* m_TSLabel; QMenu* m_MyMenu; // for planarfigure and bundle handling: mitk::DataNode* m_SelectedNode; mitk::DataNode* m_CurrentPickingNode; }; #endif // _QMITKNavigationButtonsView_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.cpp index 6a59624ce5..8dabd25575 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.cpp @@ -1,22 +1,21 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkWelcomePerspective.h" void QmitkWelcomePerspective::CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/) { } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.h index 2239700630..772287e162 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkWelcomePerspective.h @@ -1,42 +1,41 @@ -/*========================================================================= - - Program: BlueBerry Platform - Language: C++ - Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ - Version: $Revision: 19652 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKWelcomePERSPECTIVE_H_ #define QMITKWelcomePERSPECTIVE_H_ #include class QmitkWelcomePerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkWelcomePerspective() {} QmitkWelcomePerspective(const QmitkWelcomePerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkWelcomePerspective() {} void CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/); }; #endif /* QMITKWelcomePERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.examples/src/ExamplesDll.h b/Plugins/org.mitk.gui.qt.examples/src/ExamplesDll.h index e04968b9fb..8f52ff5525 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/ExamplesDll.h +++ b/Plugins/org.mitk.gui.qt.examples/src/ExamplesDll.h @@ -1,43 +1,42 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _EXAMPLES_EXPORT_DLL_H_ #define _EXAMPLES_EXPORT_DLL_H_ // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the org_mitk_gui_qt_examples_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // org_mitk_gui_qt_examples_EXPORTS functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && !defined(MITK_STATIC) #if defined(org_mitk_gui_qt_examples_EXPORTS) #define EXAMPLES_EXPORT __declspec(dllexport) #else #define EXAMPLES_EXPORT __declspec(dllimport) #endif #endif #if !defined(EXAMPLES_EXPORT) #define EXAMPLES_EXPORT #endif #endif /*_EXAMPLES_EXPORT_DLL_H_*/ diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp index 6274909895..8343670d6d 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp @@ -1,284 +1,283 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkColourImageProcessingView.h" #include "mitkColourImageProcessor.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include "QmitkPiecewiseFunctionCanvas.h" #include "QmitkColorTransferFunctionCanvas.h" #include #include const std::string QmitkColourImageProcessingView::VIEW_ID = "org.mitk.views.colourimageprocessing"; QmitkColourImageProcessingView::QmitkColourImageProcessingView() : QmitkFunctionality(), m_MultiWidget(NULL) { m_Controls=NULL; m_Color[0]= 255; m_Color[1]= 0; m_Color[2]= 0; } QmitkColourImageProcessingView::~QmitkColourImageProcessingView() { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemoveSelectionListener(m_SelectionListener); } void QmitkColourImageProcessingView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkColourImageProcessingViewControls; m_Controls->setupUi(parent); connect( m_Controls->m_ConvertImageToRGBA, SIGNAL( clicked(bool) ),this, SLOT( OnConvertToRGBAImage() )); connect( m_Controls->m_ConvertImageMaskToRGBA, SIGNAL( clicked(bool) ),this, SLOT( OnConvertToRGBAImage() )); connect( m_Controls->m_ConvertImageMaskColorToRGBA, SIGNAL( clicked(bool) ),this, SLOT( OnConvertImageMaskColorToRGBAImage() )); connect( m_Controls->m_ColorButton, SIGNAL( clicked(bool) ),this, SLOT( OnChangeColor() )); connect( m_Controls->m_CombineRGBAButton, SIGNAL( clicked(bool) ),this, SLOT( OnCombineRGBA() )); m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); } m_SelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter (this, &QmitkColourImageProcessingView::SelectionChanged)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->AddSelectionListener(m_SelectionListener); } void QmitkColourImageProcessingView::SelectionChanged( berry::IWorkbenchPart::Pointer, berry::ISelection::ConstPointer selection ) { mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); if(_DataNodeSelection.IsNotNull()) { std::vector selectedNodes; mitk::DataNodeObject* _DataNodeObject = 0; for(mitk::DataNodeSelection::iterator it = _DataNodeSelection->Begin();it != _DataNodeSelection->End(); ++it) { _DataNodeObject = dynamic_cast((*it).GetPointer()); if(_DataNodeObject) { mitk::DataNode::Pointer node = _DataNodeObject->GetDataNode(); if( node.IsNotNull() && dynamic_cast(node->GetData())&&dynamic_cast(node->GetData())->GetDimension()>=3 ) selectedNodes.push_back( node ); } } mitk::DataNode::Pointer node; if(selectedNodes.size() > 0) node=selectedNodes[0]; if( node.IsNotNull() ) { m_SelectedNode = node; m_Controls->m_NoImageSelectedLabel->hide(); m_Controls->m_ImageSelectedLabel->show(); std::string infoText = std::string("Selected Image: ") + node->GetName(); if(selectedNodes.size() > 1) { mitk::DataNode::Pointer node2; node2=selectedNodes[1]; m_SelectedNode2=node2; infoText = infoText + " and " + node2->GetName(); } else { m_SelectedNode2= 0; } m_Controls->m_ImageSelectedLabel->setText( QString( infoText.c_str() ) ); } else { m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); m_SelectedNode = 0; m_SelectedNode2= 0; } } } void QmitkColourImageProcessingView::OnConvertToRGBAImage() { if(m_SelectedNode.IsNull()) return; mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(m_SelectedNode->GetProperty("TransferFunction")); if(transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if(tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if(m_SelectedNode2.IsNotNull()) { RGBAImageResult = CImageProcessor.convertWithBinaryToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),dynamic_cast(m_SelectedNode2->GetData()),tf); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),tf); } if (!RGBAImageResult) { QMessageBox::warning(NULL, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData( RGBAImageResult ); dtn->SetName(m_SelectedNode->GetName() + "_RGBA"); this->GetDefaultDataStorage()->Add( dtn ); // add as a child, because the segmentation "derives" from the original MITK_INFO << "convertToRGBAImage finish"; } void QmitkColourImageProcessingView::OnConvertImageMaskColorToRGBAImage( ) { if(m_SelectedNode.IsNull()) return; mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(m_SelectedNode->GetProperty("TransferFunction")); if(transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if(tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if(m_SelectedNode2.IsNotNull()) { RGBAImageResult = CImageProcessor.convertWithBinaryAndColorToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),dynamic_cast(m_SelectedNode2->GetData()),tf, m_Color); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),tf); } if (!RGBAImageResult) { QMessageBox::warning(NULL, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData( RGBAImageResult ); dtn->SetName(m_SelectedNode->GetName() + "_RGBA"); this->GetDefaultDataStorage()->Add( dtn ); // add as a child, because the segmentation "derives" from the original } void QmitkColourImageProcessingView::OnChangeColor( ) { QColor color = QColorDialog::getColor(); if (color.spec() == 0) { color.setRed(255); color.setGreen(0); color.setBlue(0); } m_Color[0]= color.red(); m_Color[1]= color.green(); m_Color[2]= color.blue(); m_Controls->m_ColorButton->setStyleSheet(QString("background-color:rgb(%1,%2, %3)").arg(color.red()).arg(color.green()).arg(color.blue())); } void QmitkColourImageProcessingView::OnCombineRGBA( ) { if(m_SelectedNode.IsNull()) return; if(m_SelectedNode2.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; RGBAImageResult = CImageProcessor.combineRGBAImage(dynamic_cast(m_SelectedNode->GetData()),dynamic_cast(m_SelectedNode2->GetData())); MITK_INFO <<"RGBAImage Result"; mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData( RGBAImageResult ); this->GetDefaultDataStorage()->Add( dtn ); // add as a child, because the segmentation "derives" from the original } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.h b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.h index d7b4fc8996..94cdb8c11c 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.h @@ -1,84 +1,83 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ #ifndef _QMITKCOLOURIMAGEPROCESSINGVIEW_H_INCLUDED #define _QMITKCOLOURIMAGEPROCESSINGVIEW_H_INCLUDED #include #include #include #include #include "mitkDataStorage.h" #include #include #include #include "ui_QmitkColourImageProcessingViewControls.h" class QmitkColourImageProcessingView : public QmitkFunctionality { Q_OBJECT public: static const std::string VIEW_ID; QmitkColourImageProcessingView(); QmitkColourImageProcessingView(const QmitkColourImageProcessingView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkColourImageProcessingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void SelectionChanged(berry::IWorkbenchPart::Pointer part, berry::ISelection::ConstPointer selection); protected slots: void OnConvertToRGBAImage(); void OnConvertImageMaskColorToRGBAImage(); void OnCombineRGBA(); void OnChangeColor(); protected: Ui::QmitkColourImageProcessingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; berry::ISelectionListener::Pointer m_SelectionListener; private: mitk::WeakPointer m_SelectedNode; mitk::WeakPointer m_SelectedNode2; int m_Color[3]; }; #endif // _QMITKCOLOURIMAGEPROCESSINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.cpp index fb01309531..878f000b11 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.cpp @@ -1,980 +1,979 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ #include "mitkColourImageProcessor.h" #include #include #include namespace mitk { mitkColourImageProcessor::mitkColourImageProcessor() { } mitkColourImageProcessor::~mitkColourImageProcessor() { } template class ScalarToRGBAConverter { const T *dataPtr; unsigned char *tmpPtr; int sizeX; int sizeY; int sizeZ; int sizeXY; int sizeXm1; int sizeYm1; int sizeZm1; mitk::TransferFunction::Pointer tf; public: ScalarToRGBAConverter( const T *_dataPtr,unsigned char *_tmpPtr,int _sizeX,int _sizeY,int _sizeZ,mitk::TransferFunction::Pointer _tf ) { dataPtr=_dataPtr; tmpPtr=_tmpPtr; sizeX=_sizeX; sizeY=_sizeY; sizeZ=_sizeZ; sizeXY=sizeX*sizeY; sizeXm1=sizeX-1; sizeYm1=sizeY-1; sizeZm1=sizeZ-1; tf=_tf; } inline float sample(int x,int y,int z) { return float(dataPtr[ x + y * sizeX + z * sizeXY ]); } inline int clamp(int x) { if(x<0) x=0; else if(x>255) x=255; return x; } inline void write(int x,int y,int z,float grayValue,float gx,float gy,float gz) { /* gx /= aspect[0]; gy /= aspect[1]; gz /= aspect[2]; */ // Compute the gradient magnitude float t = sqrtf( gx*gx + gy*gy + gz*gz ); int doff = x + y * sizeX + z * sizeXY; vtkPiecewiseFunction* opacityTransferFunction = tf->GetScalarOpacityFunction(); vtkPiecewiseFunction* gradientTransferFunction = tf->GetGradientOpacityFunction(); vtkColorTransferFunction* colorTransferFunction = tf->GetColorTransferFunction(); double rgb[3]; colorTransferFunction->GetColor( double(grayValue), rgb); double opacity= opacityTransferFunction->GetValue( double(grayValue) ); opacity *= gradientTransferFunction->GetValue( double(0.5f*t) ); tmpPtr[doff*4+0] = int( rgb[0]*255 + 0.5 ); tmpPtr[doff*4+1] = int( rgb[1]*255 + 0.5 ); tmpPtr[doff*4+2] = int( rgb[2]*255 + 0.5 ); tmpPtr[doff*4+3] = int( opacity*255 + 0.5 ); } inline void compute(int x,int y,int z) { float grayValue = sample(x,y,z); float gx,gy,gz; gx = sample(x+1,y,z) - sample(x-1,y,z); gy = sample(x,y+1,z) - sample(x,y-1,z); gz = sample(x,y,z+1) - sample(x,y,z-1); write( x, y, z, grayValue, gx, gy, gz ); } inline void computeClamp(int x,int y,int z) { float grayValue = sample(x,y,z); float gx,gy,gz; if(x==0) gx = 2.0f * ( sample(x+1,y,z) - grayValue ); else if(x==sizeXm1) gx = 2.0f * ( grayValue - sample(x-1,y,z) ); else gx = sample(x+1,y,z) - sample(x-1,y,z); if(y==0) gy = 2.0f * ( sample(x,y+1,z) - grayValue ); else if(y==sizeYm1) gy = 2.0f * ( grayValue - sample(x,y-1,z) ); else gy = sample(x,y+1,z) - sample(x,y-1,z); if(z==0) gz = 2.0f * ( sample(x,y,z+1) - grayValue ); else if(z==sizeZm1) gz = 2.0f * ( grayValue - sample(x,y,z-1) ); else gz = sample(x,y,z+1) - sample(x,y,z-1); write( x, y, z, grayValue, gx, gy, gz ); } inline void compute1D(int y,int z) { int x; x=0; computeClamp(x,y,z); x++; while(x mitk::Image::Pointer mitkColourImageProcessor::ScalarToRGBA( itk::Image* input , mitk::TransferFunction::Pointer tf) { const TType *inputData=input->GetBufferPointer(); typename itk::Image::SizeType ioSize = input->GetLargestPossibleRegion().GetSize(); MITK_INFO << "size input image: " << ioSize[0] << ", " << ioSize[1] << ", " << ioSize[2]; MITK_INFO << "size voxel: " << ioSize[0] * ioSize[1] * ioSize[2]; int voxel = ioSize[0] * ioSize[1] * ioSize[2]; unsigned char* RGBABuffer = new unsigned char[4*voxel]; // Convert volume { ScalarToRGBAConverter strc(inputData,RGBABuffer,ioSize[0],ioSize[1],ioSize[2],tf); strc.fillSlices(); } // Create MITK Image out of the raw data { mitk::Image::Pointer image = mitk::Image::New(); unsigned int dimensions[ 3 ]; dimensions[ 0 ] = ioSize[0]; dimensions[ 1 ] = ioSize[1]; dimensions[ 2 ] = ioSize[2]; mitk::PixelType pixelType( MakePixelType() ); image->Initialize( pixelType, 3, dimensions ); image->SetImportChannel( RGBABuffer, 0, Image::ManageMemory ); return image; } } mitk::Image::Pointer mitkColourImageProcessor::convertToRGBAImage( mitk::Image::Pointer mitkInput , mitk::TransferFunction::Pointer tf ) { MITK_INFO << "convertToRGBAImage" ; mitk::Image::Pointer mitkResult= mitk::Image::New(); if (mitkInput->GetPixelType().GetTypeId() == typeid(unsigned char)) { //cast to itkImage itk::Image< unsigned char, 3 >::Pointer itkInput; mitk::CastToItkImage(mitkInput,itkInput); mitkResult = ScalarToRGBA(itkInput, tf); } else if (mitkInput->GetPixelType().GetTypeId() == typeid(short)) { //cast to itkImage itk::Image< short, 3 >::Pointer itkInput; mitk::CastToItkImage(mitkInput,itkInput); mitkResult = ScalarToRGBA(itkInput, tf); } else { MITK_ERROR << "unsupported pixel type"; return NULL; } mitkResult->SetSpacing( mitkInput->GetGeometry()->GetSpacing() ); return mitkResult; } template class ScalarBinaryToRGBAConverter { const T *dataPtr; const B *data2Ptr; unsigned char *tmpPtr; int sizeX; int sizeY; int sizeZ; int sizeXY; int sizeXm1; int sizeYm1; int sizeZm1; mitk::TransferFunction::Pointer tf; public: ScalarBinaryToRGBAConverter( const T *_dataPtr,const B *_data2Ptr,unsigned char *_tmpPtr,int _sizeX,int _sizeY,int _sizeZ,mitk::TransferFunction::Pointer _tf ) { dataPtr=_dataPtr; data2Ptr=_data2Ptr; tmpPtr=_tmpPtr; sizeX=_sizeX; sizeY=_sizeY; sizeZ=_sizeZ; sizeXY=sizeX*sizeY; sizeXm1=sizeX-1; sizeYm1=sizeY-1; sizeZm1=sizeZ-1; tf=_tf; } inline float sample(int x,int y,int z) { return float(dataPtr[ x + y * sizeX + z * sizeXY ]); } inline bool sampleBinary(int x,int y,int z) { return data2Ptr[ x + y * sizeX + z * sizeXY ]; } inline int clamp(int x) { if(x<0) x=0; else if(x>255) x=255; return x; } inline void write(int x,int y,int z,float grayValue,float gx,float gy,float gz) { if(sampleBinary(x,y,z)) { /* gx /= aspect[0]; gy /= aspect[1]; gz /= aspect[2]; */ // Compute the gradient magnitude float t = sqrtf( gx*gx + gy*gy + gz*gz ); int doff = x + y * sizeX + z * sizeXY; vtkPiecewiseFunction* opacityTransferFunction = tf->GetScalarOpacityFunction(); vtkPiecewiseFunction* gradientTransferFunction = tf->GetGradientOpacityFunction(); vtkColorTransferFunction* colorTransferFunction = tf->GetColorTransferFunction(); double rgb[3]; colorTransferFunction->GetColor( double(grayValue), rgb); double opacity= opacityTransferFunction->GetValue( double(grayValue) ); opacity *= gradientTransferFunction->GetValue( double(0.5f*t) ); tmpPtr[doff*4+0] = int( rgb[0]*255 + 0.5 ); tmpPtr[doff*4+1] = int( rgb[1]*255 + 0.5 ); tmpPtr[doff*4+2] = int( rgb[2]*255 + 0.5 ); tmpPtr[doff*4+3] = int( opacity*255 + 0.5 ); } else { int doff = x + y * sizeX + z * sizeXY; tmpPtr[doff*4+0] = 0; tmpPtr[doff*4+1] = 0; tmpPtr[doff*4+2] = 0; tmpPtr[doff*4+3] = 0; } } inline void compute(int x,int y,int z) { float grayValue = sample(x,y,z); float gx,gy,gz; gx = sample(x+1,y,z) - sample(x-1,y,z); gy = sample(x,y+1,z) - sample(x,y-1,z); gz = sample(x,y,z+1) - sample(x,y,z-1); write( x, y, z, grayValue, gx, gy, gz ); } inline void computeClamp(int x,int y,int z) { float grayValue = sample(x,y,z); float gx,gy,gz; if(x==0) gx = 2.0f * ( sample(x+1,y,z) - grayValue ); else if(x==sizeXm1) gx = 2.0f * ( grayValue - sample(x-1,y,z) ); else gx = sample(x+1,y,z) - sample(x-1,y,z); if(y==0) gy = 2.0f * ( sample(x,y+1,z) - grayValue ); else if(y==sizeYm1) gy = 2.0f * ( grayValue - sample(x,y-1,z) ); else gy = sample(x,y+1,z) - sample(x,y-1,z); if(z==0) gz = 2.0f * ( sample(x,y,z+1) - grayValue ); else if(z==sizeZm1) gz = 2.0f * ( grayValue - sample(x,y,z-1) ); else gz = sample(x,y,z+1) - sample(x,y,z-1); write( x, y, z, grayValue, gx, gy, gz ); } inline void compute1D(int y,int z) { int x; x=0; computeClamp(x,y,z); x++; while(x mitk::Image::Pointer mitkColourImageProcessor::ScalarAndBinaryToRGBA(itk::Image* input ,itk::Image* input2 , mitk::TransferFunction::Pointer tf) { const TType *inputData=input->GetBufferPointer(); const BType *input2Data=input2->GetBufferPointer(); typename itk::Image::SizeType ioSize = input->GetLargestPossibleRegion().GetSize(); MITK_INFO << "size input image: " << ioSize[0] << ", " << ioSize[1] << ", " << ioSize[2]; MITK_INFO << "size voxel: " << ioSize[0] * ioSize[1] * ioSize[2]; int voxel= ioSize[0] * ioSize[1] * ioSize[2]; unsigned char* RGBABuffer = new unsigned char[4*voxel]; //for(int i=0;i strc(inputData,input2Data,RGBABuffer,ioSize[0],ioSize[1],ioSize[2],tf); strc.fillSlices(); } // Create MITK Image out of the raw data { mitk::Image::Pointer image = mitk::Image::New(); unsigned int dimensions[ 3 ]; dimensions[ 0 ] = ioSize[0]; dimensions[ 1 ] = ioSize[1]; dimensions[ 2 ] = ioSize[2]; mitk::PixelType pixelType( MakePixelType() ); image->Initialize( pixelType, 3, dimensions ); image->SetImportChannel( RGBABuffer, 0, Image::ManageMemory ); return image; } } mitk::Image::Pointer mitkColourImageProcessor::convertWithBinaryToRGBAImage( mitk::Image::Pointer input1 ,mitk::Image::Pointer input2 , mitk::TransferFunction::Pointer tf ) { MITK_INFO << "convertWithBinaryToRGBAImage" ; itk::Image< short, 3 >::Pointer inputCT; itk::Image< unsigned char, 3 >::Pointer inputBinary; if (input1->GetPixelType().GetTypeId() == typeid(unsigned char) && input2->GetPixelType().GetTypeId() == typeid(short)) { mitk::CastToItkImage(input1,inputBinary); mitk::CastToItkImage(input2,inputCT); } else if (input1->GetPixelType().GetTypeId() == typeid(short) && input2->GetPixelType().GetTypeId() == typeid(unsigned char)) { mitk::CastToItkImage(input1,inputCT); mitk::CastToItkImage(input2,inputBinary); } else { MITK_ERROR << "unsupported pixel type"; return 0; } return ScalarAndBinaryToRGBA(inputCT,inputBinary, tf); } ////////////////////////////////////////// template class ScalarBinaryColorToRGBAConverter { const T *dataPtr; const B *data2Ptr; unsigned char *tmpPtr; int sizeX; int sizeY; int sizeZ; int sizeXY; int sizeXm1; int sizeYm1; int sizeZm1; mitk::TransferFunction::Pointer tf; int *color; public: ScalarBinaryColorToRGBAConverter( const T *_dataPtr,const B *_data2Ptr,unsigned char *_tmpPtr,int _sizeX,int _sizeY,int _sizeZ,mitk::TransferFunction::Pointer _tf ,int *_color) { dataPtr=_dataPtr; data2Ptr=_data2Ptr; tmpPtr=_tmpPtr; sizeX=_sizeX; sizeY=_sizeY; sizeZ=_sizeZ; sizeXY=sizeX*sizeY; sizeXm1=sizeX-1; sizeYm1=sizeY-1; sizeZm1=sizeZ-1; tf=_tf; color = _color; } inline float sample(int x,int y,int z) { return float(dataPtr[ x + y * sizeX + z * sizeXY ]); } inline bool sampleBinary(int x,int y,int z) { return data2Ptr[ x + y * sizeX + z * sizeXY ]; } inline int clamp(int x) { if(x<0) x=0; else if(x>255) x=255; return x; } inline void write(int x,int y,int z,float grayValue,float gx,float gy,float gz) { if(sampleBinary(x,y,z)) { /* gx /= aspect[0]; gy /= aspect[1]; gz /= aspect[2]; */ // Compute the gradient magnitude float t = sqrtf( gx*gx + gy*gy + gz*gz ); int doff = x + y * sizeX + z * sizeXY; vtkPiecewiseFunction* opacityTransferFunction = tf->GetScalarOpacityFunction(); vtkPiecewiseFunction* gradientTransferFunction = tf->GetGradientOpacityFunction(); vtkColorTransferFunction* colorTransferFunction = tf->GetColorTransferFunction(); double rgb[3]; colorTransferFunction->GetColor( double(grayValue), rgb); double opacity= opacityTransferFunction->GetValue( double(grayValue) ); opacity *= gradientTransferFunction->GetValue( double(0.5f*t) ); tmpPtr[doff*4+0] = int( rgb[0]*255 + 0.5 ); tmpPtr[doff*4+1] = int( rgb[1]*255 + 0.5 ); tmpPtr[doff*4+2] = int( rgb[2]*255 + 0.5 ); tmpPtr[doff*4+3] = int( opacity*255 + 0.5 ); tmpPtr[doff*4+0] = color[0]; tmpPtr[doff*4+1] = color[1]; tmpPtr[doff*4+2] = color[2]; } else { int doff = x + y * sizeX + z * sizeXY; tmpPtr[doff*4+0] = 0; tmpPtr[doff*4+1] = 0; tmpPtr[doff*4+2] = 0; tmpPtr[doff*4+3] = 0; } } inline void compute(int x,int y,int z) { float grayValue = sample(x,y,z); float gx,gy,gz; gx = sample(x+1,y,z) - sample(x-1,y,z); gy = sample(x,y+1,z) - sample(x,y-1,z); gz = sample(x,y,z+1) - sample(x,y,z-1); write( x, y, z, grayValue, gx, gy, gz ); } inline void computeClamp(int x,int y,int z) { float grayValue = sample(x,y,z); float gx,gy,gz; if(x==0) gx = 2.0f * ( sample(x+1,y,z) - grayValue ); else if(x==sizeXm1) gx = 2.0f * ( grayValue - sample(x-1,y,z) ); else gx = sample(x+1,y,z) - sample(x-1,y,z); if(y==0) gy = 2.0f * ( sample(x,y+1,z) - grayValue ); else if(y==sizeYm1) gy = 2.0f * ( grayValue - sample(x,y-1,z) ); else gy = sample(x,y+1,z) - sample(x,y-1,z); if(z==0) gz = 2.0f * ( sample(x,y,z+1) - grayValue ); else if(z==sizeZm1) gz = 2.0f * ( grayValue - sample(x,y,z-1) ); else gz = sample(x,y,z+1) - sample(x,y,z-1); write( x, y, z, grayValue, gx, gy, gz ); } inline void compute1D(int y,int z) { int x; x=0; computeClamp(x,y,z); x++; while(x mitk::Image::Pointer mitkColourImageProcessor::ScalarAndBinaryAndColorToRGBA(itk::Image* input ,itk::Image* input2 , mitk::TransferFunction::Pointer tf, int * color) { const TType *inputData=input->GetBufferPointer(); const BType *input2Data=input2->GetBufferPointer(); typename itk::Image::SizeType ioSize = input->GetLargestPossibleRegion().GetSize(); MITK_INFO << "size input image: " << ioSize[0] << ", " << ioSize[1] << ", " << ioSize[2]; MITK_INFO << "size voxel: " << ioSize[0] * ioSize[1] * ioSize[2]; int voxel= ioSize[0] * ioSize[1] * ioSize[2]; unsigned char* RGBABuffer = new unsigned char[4*voxel]; //for(int i=0;i strc(inputData,input2Data,RGBABuffer,ioSize[0],ioSize[1],ioSize[2],tf,color); strc.fillSlices(); } // Create MITK Image out of the raw data { mitk::Image::Pointer image = mitk::Image::New(); unsigned int dimensions[ 3 ]; dimensions[ 0 ] = ioSize[0]; dimensions[ 1 ] = ioSize[1]; dimensions[ 2 ] = ioSize[2]; mitk::PixelType pixelType( MakePixelType() ); image->Initialize( pixelType, 3, dimensions ); image->SetImportChannel( RGBABuffer, 0, Image::ManageMemory ); return image; } } mitk::Image::Pointer mitkColourImageProcessor::convertWithBinaryAndColorToRGBAImage( mitk::Image::Pointer input1 ,mitk::Image::Pointer input2 , mitk::TransferFunction::Pointer tf , int * color) { MITK_INFO << "convertWithBinaryToRGBAImage" ; itk::Image< short, 3 >::Pointer inputCT; itk::Image< unsigned char, 3 >::Pointer inputBinary; if (input1->GetPixelType().GetTypeId() == typeid(unsigned char) && input2->GetPixelType().GetTypeId() == typeid(short)) { mitk::CastToItkImage(input1,inputBinary); mitk::CastToItkImage(input2,inputCT); } else if (input1->GetPixelType().GetTypeId() == typeid(short) && input2->GetPixelType().GetTypeId() == typeid(unsigned char)) { mitk::CastToItkImage(input1,inputCT); mitk::CastToItkImage(input2,inputBinary); } else { MITK_ERROR << "unsupported pixel type"; return 0; } return ScalarAndBinaryAndColorToRGBA(inputCT,inputBinary, tf,color); } static inline int clamp(int x) { if(x<0) x=0; else if(x>255) x=255; return x; } mitk::Image::Pointer mitkColourImageProcessor::CombineRGBAImage( unsigned char* input ,unsigned char* input2, int sizeX,int sizeY,int sizeZ ) { int voxel= sizeX*sizeY*sizeZ; unsigned char* RGBABuffer = new unsigned char[4*voxel]; // Convert volume { for( int r=0;r 1.0f) cor = 1.0f/sum; fac1 *= cor; fac2 *= cor; result[0]= clamp(int(fac1 * rgbaInput1[0] + fac2 * rgbaInput2[0] + 0.5f)); result[1]= clamp(int(fac1 * rgbaInput1[1] + fac2 * rgbaInput2[1] + 0.5f)); result[2]= clamp(int(fac1 * rgbaInput1[2] + fac2 * rgbaInput2[2] + 0.5f)); result[3]= clamp(int(fac1 * rgbaInput1[3] + fac2 * rgbaInput2[3] + 0.5f)); */ if( rgbaInput1[3] ) { result[0]= rgbaInput1[0]; result[1]= rgbaInput1[1]; result[2]= rgbaInput1[2]; result[3]= rgbaInput1[3]; } else { result[0]= rgbaInput2[0]; result[1]= rgbaInput2[1]; result[2]= rgbaInput2[2]; result[3]= rgbaInput2[3]; } RGBABuffer[r*4+0]= result[0]; RGBABuffer[r*4+1]= result[1]; RGBABuffer[r*4+2]= result[2]; RGBABuffer[r*4+3]= result[3]; } } // Create MITK Image out of the raw data { mitk::Image::Pointer image = mitk::Image::New(); unsigned int dimensions[ 3 ]; dimensions[ 0 ] = sizeX; dimensions[ 1 ] = sizeY; dimensions[ 2 ] = sizeZ; mitk::PixelType pixelType( MakePixelType() ); image->Initialize( pixelType, 3, dimensions ); image->SetImportChannel( RGBABuffer, 0, Image::ManageMemory ); return image; } } mitk::Image::Pointer mitkColourImageProcessor::combineRGBAImage( mitk::Image::Pointer input1 , mitk::Image::Pointer input2) { RGBAImage::Pointer itk1,itk2; unsigned char *data1=(unsigned char *)input1->GetData(); unsigned char *data2=(unsigned char *)input2->GetData(); unsigned int *dim = input1->GetDimensions(); return CombineRGBAImage(data1,data2,dim[0],dim[1],dim[2]); } }//end namespace mitk diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.h b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.h index b08c1a5f82..4cac440d91 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/mitkColourImageProcessor.h @@ -1,67 +1,66 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKCOLOURIMAGEPROCESSOR_H #define MITKCOLOURIMAGEPROCESSOR_H #include #include #include #include #include namespace mitk { class mitkColourImageProcessor { public: typedef itk::RGBAPixel RGBAPixel; typedef itk::Image RGBAImage; mitkColourImageProcessor(); ~mitkColourImageProcessor () ; mitk::Image::Pointer convertToRGBAImage( mitk::Image::Pointer input , mitk::TransferFunction::Pointer tf ); mitk::Image::Pointer convertWithBinaryToRGBAImage( mitk::Image::Pointer input1 , mitk::Image::Pointer input2 , mitk::TransferFunction::Pointer tf ); mitk::Image::Pointer convertWithBinaryAndColorToRGBAImage( mitk::Image::Pointer input1 , mitk::Image::Pointer input2 , mitk::TransferFunction::Pointer tf, int* color ); mitk::Image::Pointer combineRGBAImage( mitk::Image::Pointer input1 , mitk::Image::Pointer input2); private: template mitk::Image::Pointer ScalarToRGBA(itk::Image* input , mitk::TransferFunction::Pointer tf); template mitk::Image::Pointer ScalarAndBinaryToRGBA(itk::Image* input ,itk::Image* input2 , mitk::TransferFunction::Pointer tf); template mitk::Image::Pointer ScalarAndBinaryAndColorToRGBA(itk::Image* input ,itk::Image* input2 , mitk::TransferFunction::Pointer tf, int * color); mitk::Image::Pointer CombineRGBAImage( unsigned char* input ,unsigned char* input2, int sizeX,int sizeY,int sizeZ ); }; }//end namespace mitk #endif /* MITKCOLOURIMAGEPROCESSOR_H */ diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp index 4015abcd1c..4298af5078 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp @@ -1,240 +1,239 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 15417 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkIsoSurface.h" //#include //GUI //#include //image //MITK headers #include #include #include #include //Qmitk headers #include #include #include //Qt-GUI headers #include #include #include #include #include #include #include QmitkIsoSurface::QmitkIsoSurface(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality() , m_Controls(NULL), m_MitkImage(NULL), m_SurfaceCounter(0) { //SetAvailability(true); } //QWidget * QmitkIsoSurface::CreateMainWidget(QWidget *) //{ // return NULL; //} //QWidget * QmitkIsoSurface::CreateControlWidget(QWidget *parent) //{ // if (m_Controls == NULL) // { // m_Controls = new QmitkIsoSurfaceControls(parent); // } // return m_Controls; //} void QmitkIsoSurface::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkIsoSurfaceControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_ImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->m_ImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); berry::IPreferences::Pointer prefs = this->GetPreferences(); if(prefs.IsNotNull()) m_Controls->thresholdLineEdit->setText(QString::fromStdString(prefs->Get("defaultThreshold", "0"))); } } void QmitkIsoSurface::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_ImageSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode*)), this, SLOT(ImageSelected(const mitk::DataNode*)) ); connect( m_Controls->createSurfacePushButton, SIGNAL(clicked()), this, SLOT(CreateSurface()) ); } } //QAction * QmitkIsoSurface::CreateAction(QActionGroup *parent) //{ // QAction* action; // action = new QAction( tr( "IsoSurface" ), QPixmap((const char**)isoSurface_xpm), tr( "IsoSurface" ), 0, parent, "IsoSurface" ); // return action; //} void QmitkIsoSurface::DataStorageChanged() { //m_Controls->m_ImageSelector->Update(); } void QmitkIsoSurface::ImageSelected(const mitk::DataNode* item) { // nothing selected (NULL selection) if( item == 0 || item->GetData() == 0 ) return; m_MitkImage = dynamic_cast (item->GetData()); } void QmitkIsoSurface::CreateSurface() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); if(m_MitkImage != NULL) { //Value Gauss //float gsDev = 1.5; //Value for DecimatePro float targetReduction = 0.05; //ImageToSurface Instance mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode(); /* mitk::DataTreeIteratorClone iteratorOnImageToBeSkinExtracted; iteratorOnImageToBeSkinExtracted = m_Controls->m_ImageSelector->GetFilter()->GetIteratorToSelectedItem(); if(iteratorOnImageToBeSkinExtracted.IsNull()) { iteratorOnImageToBeSkinExtracted = CommonFunctionality::GetIteratorToFirstImage(m_DataTreeIterator.GetPointer()); } */ mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout<<"NULL Pointer for ManualSegmentationToSurfaceFilter"<SetInput( m_MitkImage ); filter->SetGaussianStandardDeviation( 0.5 ); filter->SetUseGaussianImageSmooth( true ); filter->SetThreshold( getThreshold()); //if( Gauss ) --> TH manipulated for vtkMarchingCube filter->SetTargetReduction( targetReduction ); int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys(); if(numOfPolys>2000000) { QApplication::restoreOverrideCursor(); if(QMessageBox::question(NULL, "CAUTION!!!", "The number of polygons is greater than 2 000 000. If you continue, the program might crash. How do you want to go on?", "Proceed anyway!", "Cancel immediately! (maybe you want to insert an other threshold)!",QString::null,0 ,1)==1) { return; } QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetData( filter->GetOutput() ); int layer = 0; ++m_SurfaceCounter; std::ostringstream buffer; buffer << m_SurfaceCounter; std::string surfaceNodeName = "Surface " + buffer.str(); node->GetIntProperty("layer", layer); surfaceNode->SetIntProperty("layer", layer+1); surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true)); surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName)); /* mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator; bool isSurface = false; while(!(iteratorClone->IsAtEnd())&&(isSurface == false)) { iteratorClone->Get()->GetBoolProperty("Surface", isSurface); if(isSurface == false) { ++iteratorClone; } } iteratorClone= iteratorOnImageToBeSkinExtracted; iteratorClone->Add(surfaceNode); iteratorClone->GetTree()->Modified(); */ this->GetDefaultDataStorage()->Add(surfaceNode, node); mitk::Surface::Pointer surface = filter->GetOutput(); //to show surfaceContur surfaceNode->SetColor( m_RainbowColor.GetNextColor() ); surfaceNode->SetVisibility(true); this->GetActiveStdMultiWidget()->RequestUpdate(); }//if m_MitkImage != NULL QApplication::restoreOverrideCursor(); } float QmitkIsoSurface::getThreshold() { return m_Controls->thresholdLineEdit->text().toFloat(); } void QmitkIsoSurface::StdMultiWidgetAvailable( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { m_Parent->setEnabled(true); } void QmitkIsoSurface::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); } QmitkIsoSurface::~QmitkIsoSurface() { berry::IPreferences::Pointer prefs = this->GetPreferences(); if(prefs.IsNotNull()) prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text().toStdString()); } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.h b/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.h index 6d4c1c7c10..f61f8cf5fb 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.h @@ -1,122 +1,121 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 13136 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QMITK_ISOSURFACE_H__INCLUDED) #define QMITK_ISOSURFACE_H__INCLUDED #include "QmitkFunctionality.h" #include "mitkColorSequenceRainbow.h" #include "mitkDataStorage.h" #include "ui_QmitkIsoSurfaceControls.h" //class QmitkStdMultiWidget; //class QmitkIsoSurfaceControls; /*! \brief IsoSurface \sa QmitkFunctionality \ingroup org_mitk_gui_qt_isosurface_internal */ class QmitkIsoSurface : public QmitkFunctionality { Q_OBJECT public: /*! \brief default constructor */ QmitkIsoSurface(QObject *parent=0, const char *name=0); virtual ~QmitkIsoSurface(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ //virtual QWidget * CreateControlWidget(QWidget *parent); virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the applications main widget */ //virtual QWidget * CreateMainWidget(QWidget * parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief method for creating an QAction object, i.e. button & menu entry @param parent the parent QWidget */ //virtual QAction * CreateAction(QActionGroup *parent); /// /// Called when a StdMultiWidget is available. /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available. /// virtual void StdMultiWidgetNotAvailable(); protected slots: virtual void DataStorageChanged(); /* * just an example slot for the example TreeNodeSelector widget */ void ImageSelected(const mitk::DataNode* item); /*! \brief method for creating a surface object */ void CreateSurface(); protected: /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ //QmitkStdMultiWidget * m_MultiWidget; /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkIsoSurfaceControls * m_Controls; /*! * image which is used to create the surface */ mitk::Image* m_MitkImage; /*! * read thresholdvalue from GUI and convert it to float */ float getThreshold(); /*! * variable to count Surfaces and give it to name */ int m_SurfaceCounter; mitk::ColorSequenceRainbow m_RainbowColor; }; #endif // !defined(QMITK_ISOSURFACE_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.cpp index 27b1653034..c94108fdef 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.cpp @@ -1,306 +1,305 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 17332 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkSimpleExampleView.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateNot.h" #include "mitkProperties.h" #include #include #include #include #include #include "vtkImageWriter.h" #include "vtkPNGWriter.h" #include "vtkJPEGWriter.h" #include "vtkRenderLargeImage.h" const std::string QmitkSimpleExampleView::VIEW_ID = "org.mitk.views.simpleexample"; QmitkSimpleExampleView::QmitkSimpleExampleView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_NavigatorsInitialized(false) { } QmitkSimpleExampleView::QmitkSimpleExampleView(const QmitkSimpleExampleView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkSimpleExampleView::~QmitkSimpleExampleView() { } void QmitkSimpleExampleView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkSimpleExampleViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkSimpleExampleView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; new QmitkStepperAdapter(m_Controls->sliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample"); new QmitkStepperAdapter(m_Controls->sliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); new QmitkStepperAdapter(m_Controls->sliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); new QmitkStepperAdapter(m_Controls->sliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); new QmitkStepperAdapter(m_Controls->movieNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample"); } void QmitkSimpleExampleView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkSimpleExampleView::CreateConnections() { if ( m_Controls ) { connect(m_Controls->stereoSelect, SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) ); connect(m_Controls->reInitializeNavigatorsButton, SIGNAL(clicked()), this, SLOT(initNavigators()) ); connect(m_Controls->genMovieButton, SIGNAL(clicked()), this, SLOT(generateMovie()) ); connect(m_Controls->m_RenderWindow1Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow1Clicked()) ); connect(m_Controls->m_RenderWindow2Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow2Clicked()) ); connect(m_Controls->m_RenderWindow3Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow3Clicked()) ); connect(m_Controls->m_RenderWindow4Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow4Clicked()) ); connect(m_Controls->m_TakeScreenshotBtn, SIGNAL(clicked()), this, SLOT(OnTakeScreenshot()) ); connect(m_Controls->m_TakeHighResScreenShotBtn, SIGNAL(clicked()), this, SLOT(OnTakeHighResolutionScreenshot()) ); } } void QmitkSimpleExampleView::Activated() { QmitkFunctionality::Activated(); } void QmitkSimpleExampleView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkSimpleExampleView::initNavigators() { /* get all nodes that have not set "includeInBoundingBox" to false */ mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); /* calculate bounding geometry of these nodes */ mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs); /* initialize the views to the bounding geometry */ m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(bounds); //m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(GetDefaultDataStorage()); } void QmitkSimpleExampleView::generateMovie() { QmitkRenderWindow* movieRenderWindow = GetMovieRenderWindow(); //mitk::Stepper::Pointer stepper = multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(); mitk::Stepper::Pointer stepper = movieRenderWindow->GetSliceNavigationController()->GetSlice(); mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New(); if (movieGenerator.IsNotNull()) { movieGenerator->SetStepper( stepper ); movieGenerator->SetRenderer( mitk::BaseRenderer::GetInstance(movieRenderWindow->GetRenderWindow()) ); QString movieFileName = QFileDialog::getSaveFileName(0, "Choose a file name", QString(), "Movie (*.avi)"); if (!movieFileName.isEmpty()) { movieGenerator->SetFileName( movieFileName.toStdString().c_str() ); movieGenerator->WriteMovie(); } } } void QmitkSimpleExampleView::stereoSelectionChanged( int id ) { /* From vtkRenderWindow.h tells us about stereo rendering: Set/Get what type of stereo rendering to use. CrystalEyes mode uses frame-sequential capabilities available in OpenGL to drive LCD shutter glasses and stereo projectors. RedBlue mode is a simple type of stereo for use with red-blue glasses. Anaglyph mode is a superset of RedBlue mode, but the color output channels can be configured using the AnaglyphColorMask and the color of the original image can be (somewhat maintained using AnaglyphColorSaturation; the default colors for Anaglyph mode is red-cyan. Interlaced stereo mode produces a composite image where horizontal lines alternate between left and right views. StereoLeft and StereoRight modes choose one or the other stereo view. Dresden mode is yet another stereoscopic interleaving. */ vtkRenderWindow * vtkrenderwindow = m_MultiWidget->mitkWidget4->GetRenderWindow(); // note: foreground vtkRenderers (at least the department logo renderer) produce errors in stereoscopic visualization. // Therefore, we disable the logo visualization during stereo rendering. switch(id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); m_MultiWidget->DisableDepartmentLogo(); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); m_MultiWidget->DisableDepartmentLogo(); break; } mitk::BaseRenderer::GetInstance(m_MultiWidget->mitkWidget4->GetRenderWindow())->SetMapperID(2); m_MultiWidget->RequestUpdate(); } QmitkRenderWindow* QmitkSimpleExampleView::GetMovieRenderWindow() { //check which RenderWindow should be used to generate the movie, e.g. which button is toggled if(m_Controls->m_RenderWindow1Button->isChecked()) { return m_MultiWidget->mitkWidget1; } else if(m_Controls->m_RenderWindow2Button->isChecked()) { return m_MultiWidget->mitkWidget2; } else if(m_Controls->m_RenderWindow3Button->isChecked()) { return m_MultiWidget->mitkWidget3; } else if(m_Controls->m_RenderWindow4Button->isChecked()) { return m_MultiWidget->mitkWidget4; } else //as default take widget1 { return m_MultiWidget->mitkWidget1; } } void QmitkSimpleExampleView::OnRenderWindow1Clicked() { m_Controls->m_RenderWindow2Button->setChecked(false); m_Controls->m_RenderWindow3Button->setChecked(false); m_Controls->m_RenderWindow4Button->setChecked(false); } void QmitkSimpleExampleView::OnRenderWindow2Clicked() { m_Controls->m_RenderWindow1Button->setChecked(false); m_Controls->m_RenderWindow3Button->setChecked(false); m_Controls->m_RenderWindow4Button->setChecked(false); } void QmitkSimpleExampleView::OnRenderWindow3Clicked() { m_Controls->m_RenderWindow2Button->setChecked(false); m_Controls->m_RenderWindow1Button->setChecked(false); m_Controls->m_RenderWindow4Button->setChecked(false); } void QmitkSimpleExampleView::OnRenderWindow4Clicked() { m_Controls->m_RenderWindow2Button->setChecked(false); m_Controls->m_RenderWindow3Button->setChecked(false); m_Controls->m_RenderWindow1Button->setChecked(false); } void QmitkSimpleExampleView::OnTakeHighResolutionScreenshot() { QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)"); // only works correctly for 3D RenderWindow vtkRenderer* renderer = m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, 4, fileName); } void QmitkSimpleExampleView::OnTakeScreenshot() { QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)"); QmitkRenderWindow* renWin = this->GetMovieRenderWindow(); if (renWin == NULL) return; vtkRenderer* renderer = renWin->GetRenderer()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, 1, fileName); } void QmitkSimpleExampleView::TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName) { if ((renderer == NULL) ||(magnificationFactor < 1) || fileName.isEmpty()) return; bool doubleBuffering( renderer->GetRenderWindow()->GetDoubleBuffer() ); renderer->GetRenderWindow()->DoubleBufferOff(); vtkImageWriter* fileWriter; QFileInfo fi(fileName); QString suffix = fi.suffix(); if (suffix.compare("png", Qt::CaseInsensitive) == 0) { fileWriter = vtkPNGWriter::New(); } else // default is jpeg { vtkJPEGWriter* w = vtkJPEGWriter::New(); w->SetQuality(100); w->ProgressiveOff(); fileWriter = w; } vtkRenderLargeImage* magnifier = vtkRenderLargeImage::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(magnificationFactor); //magnifier->Update(); fileWriter->SetInput(magnifier->GetOutput()); fileWriter->SetFileName(fileName.toLatin1()); // vtkRenderLargeImage has problems with different layers, therefore we have to // temporarily deactivate all other layers. // we set the background to white, because it is nicer than black... double oldBackground[3]; renderer->GetBackground(oldBackground); double white[] = {1.0, 1.0, 1.0}; renderer->SetBackground(white); m_MultiWidget->DisableColoredRectangles(); m_MultiWidget->DisableDepartmentLogo(); m_MultiWidget->DisableGradientBackground(); fileWriter->Write(); fileWriter->Delete(); m_MultiWidget->EnableColoredRectangles(); m_MultiWidget->EnableDepartmentLogo(); m_MultiWidget->EnableGradientBackground(); renderer->SetBackground(oldBackground); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.h b/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.h index d1ac1a164c..06c1c114b0 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/simpleexample/QmitkSimpleExampleView.h @@ -1,104 +1,103 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 17332 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKSIMPLEEXAMPLEVIEW_H_INCLUDED #define _QMITKSIMPLEEXAMPLEVIEW_H_INCLUDED #include #include #include "ui_QmitkSimpleExampleViewControls.h" #include /*! * \ingroup org_mitk_gui_qt_simpleexample_internal * * \brief QmitkSimpleExampleView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkSimpleExampleView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkSimpleExampleView(); QmitkSimpleExampleView(const QmitkSimpleExampleView& other); virtual ~QmitkSimpleExampleView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /*! qt slot for event processing from a qt widget defining the stereo mode of widget 4 */ void stereoSelectionChanged(int id); /*! initialize the transversal, sagittal, coronal and temporal slider according to the image dimensions */ void initNavigators(); /*! generate a movie as *.avi from the active render window */ void generateMovie(); /*! return the renderwindow of which the movie shall be created, what depends on the toggled button */ QmitkRenderWindow* GetMovieRenderWindow(); void OnRenderWindow1Clicked(); void OnRenderWindow2Clicked(); void OnRenderWindow3Clicked(); void OnRenderWindow4Clicked(); void OnTakeHighResolutionScreenshot(); ///< takes screenshot of the 3D window in 4x resolution of the render window void OnTakeScreenshot(); ///< takes screenshot of the selected render window protected: Ui::QmitkSimpleExampleViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; void TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName); ///< writes a screenshot in JPEG or PNG format to the file fileName bool m_NavigatorsInitialized; }; #endif // _QMITKSIMPLEEXAMPLEVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp index c4e1e2f543..9da2795ed5 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp @@ -1,193 +1,192 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-06-18 16:47:58 +0200 (Thu, 18 Jun 2009) $ -Version: $Revision: 15412 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkSimpleMeasurement.h" // #include #include #include #include #include #include #include #include #include /* QmitkSimpleMeasurement::QmitkSimpleMeasurement(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); } */ QmitkSimpleMeasurement::~QmitkSimpleMeasurement() { } void QmitkSimpleMeasurement::Activated() { std::vector selection = this->GetDataManagerSelection(); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::Deactivated() { std::vector selection; this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::AddDistanceSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New("distance")); _CurrentPointSetNode->SetProperty("show distances", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPointSetNodes.push_back( _CurrentPointSetNode ); // make new selection std::vector selection; selection.push_back( _CurrentPointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::AddAngleSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New("angle")); _CurrentPointSetNode->SetProperty("show angles", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPointSetNodes.push_back( _CurrentPointSetNode ); // make new selection std::vector selection; selection.push_back( _CurrentPointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::AddPathSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New("path")); _CurrentPointSetNode->SetProperty("show distances", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("show angles", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPointSetNodes.push_back( _CurrentPointSetNode ); // make new selection std::vector selection; selection.push_back( _CurrentPointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::CreateQtPartControl( QWidget* parent ) { m_Controls = new Ui::QmitkSimpleMeasurementControls; m_Controls->setupUi(parent); connect( (QObject*)(m_Controls->pbDistance), SIGNAL(clicked()),(QObject*) this, SLOT(AddDistanceSimpleMeasurement()) ); connect( (QObject*)(m_Controls->pbAngle), SIGNAL(clicked()),(QObject*) this, SLOT(AddAngleSimpleMeasurement()) ); connect( (QObject*)(m_Controls->pbPath), SIGNAL(clicked()),(QObject*) this, SLOT(AddPathSimpleMeasurement()) ); } void QmitkSimpleMeasurement::OnSelectionChanged( std::vector nodes ) { mitk::DataNode* selectedNode = 0; if(nodes.size() > 0) selectedNode = nodes.front(); mitk::PointSet* pointSet = 0; if(selectedNode) pointSet = dynamic_cast ( selectedNode->GetData() ); // something else was selected. remove old interactor if (m_PointSetInteractor.IsNotNull()) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_PointSetInteractor); } bool pointsetCreatedByThis = false; // only go further if a pointset was selected if(pointSet) { // see if this pointset was created by us std::vector::iterator it = std::find( m_CreatedPointSetNodes.begin() , m_CreatedPointSetNodes.end(), selectedNode); if(it != m_CreatedPointSetNodes.end()) pointsetCreatedByThis = true; } // do nothing if it was not created by us or it is no pointset node or we are not activated if(pointsetCreatedByThis && this->IsActivated()) { // otherwise: set text and add interactor for the pointset m_Controls->selectedPointSet->setText( QString::fromStdString(selectedNode->GetName()) ); mitk::PointSetInteractor::Pointer newPointSetInteractor = mitk::PointSetInteractor::New("pointsetinteractor", selectedNode); mitk::GlobalInteraction::GetInstance()->AddInteractor(newPointSetInteractor); m_PointSetInteractor = newPointSetInteractor; float green[] = { 0, 255, 0 }; float red[] = { 255, 0, 0 }; selectedNode->SetColor(green); if(m_SelectedPointSetNode.IsNotNull()) m_SelectedPointSetNode->SetColor(red); m_SelectedPointSetNode = selectedNode; } else { // revert text m_Controls->selectedPointSet->setText( "None" ); } } bool QmitkSimpleMeasurement::IsExclusiveFunctionality() const { return true; } void QmitkSimpleMeasurement::NodeRemoved( const mitk::DataNode* node ) { // remove a node if it is destroyed from our created array std::vector::iterator it = std::find( m_CreatedPointSetNodes.begin() , m_CreatedPointSetNodes.end(), node); if(it != m_CreatedPointSetNodes.end()) m_CreatedPointSetNodes.erase(it); } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.h b/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.h index 0e0858c963..87ec06a1dc 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.h @@ -1,102 +1,101 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-03-21 14:46:24 +0100 (Sat, 21 Mar 2009) $ -Version: $Revision: 15412 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QMITK_MEASUREMENT_H__INCLUDED) #define QMITK_MEASUREMENT_H__INCLUDED //#include "QmitkFunctionality.h" #include #include #include #include #include #include "ui_QmitkSimpleMeasurementControls.h" class QmitkStdMultiWidget; //!mm //class QmitkSimpleMeasurementControls; //! /*! \brief SimpleMeasurement Allows to measure distances, angles, etc. \sa QmitkFunctionality \ingroup org_mitk_gui_qt_simplemeasurement_internal */ class QmitkSimpleMeasurement : public QmitkFunctionality { Q_OBJECT public: QmitkSimpleMeasurement() {} QmitkSimpleMeasurement(const QmitkSimpleMeasurement& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkSimpleMeasurement(); virtual void Activated(); virtual void Deactivated(); virtual bool IsExclusiveFunctionality() const; /// /// Called when the selection in the workbench changed /// virtual void OnSelectionChanged(std::vector nodes); virtual void NodeRemoved(const mitk::DataNode* node); protected: // Pseudo Ctor void CreateQtPartControl(QWidget* parent); protected slots: void AddDistanceSimpleMeasurement(); void AddAngleSimpleMeasurement(); void AddPathSimpleMeasurement(); protected: /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkSimpleMeasurementControls * m_Controls; /* * Interactor for performing the simplemeasurements. */ mitk::WeakPointer m_PointSetInteractor; /* * Interactor for performing the simplemeasurements. */ mitk::WeakPointer m_SelectedPointSetNode; /* * Node representing the PointSet last created. It is used to delete empty point sets. */ std::vector m_CreatedPointSetNodes; }; #endif // !defined(QMITK_MEASUREMENT_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.cpp index 02c8489098..2ecbce01aa 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.cpp @@ -1,194 +1,193 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkViewInitializationView.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFocusManager.h" #include "mitkGlobalInteraction.h" #include "itkCommand.h" #include const std::string QmitkViewInitializationView::VIEW_ID = "org.mitk.views.viewinitialization"; QmitkViewInitializationView::QmitkViewInitializationView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { m_CommandTag = 0; } QmitkViewInitializationView::~QmitkViewInitializationView() { } void QmitkViewInitializationView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkViewInitializationViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkViewInitializationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkViewInitializationView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkViewInitializationView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->pbApply), SIGNAL(clicked()),(QObject*) this, SLOT(OnApply()) ); connect( (QObject*)(m_Controls->pbReset), SIGNAL(clicked()),(QObject*) this, SLOT(OnResetAll()) ); } } void QmitkViewInitializationView::Activated() { //init render window selector (List Widget) this->InitRenderWindowSelector(); QmitkFunctionality::Activated(); } void QmitkViewInitializationView::Deactivated() { mitk::FocusManager* fm = mitk::GlobalInteraction::GetInstance()->GetFocusManager(); fm->RemoveObserver(m_CommandTag); QmitkFunctionality::Deactivated(); } void QmitkViewInitializationView::OnApply() { mitk::SliceNavigationController::ViewDirection viewDirection( mitk::SliceNavigationController::Transversal ); if( m_Controls->rbTransversal->isChecked() ) viewDirection = mitk::SliceNavigationController::Transversal; else if( m_Controls->rbFrontal->isChecked()) viewDirection = mitk::SliceNavigationController::Frontal; else if( m_Controls->rbSagittal->isChecked() ) viewDirection = mitk::SliceNavigationController::Sagittal; vtkRenderWindow* renderwindow = this->GetSelectedRenderWindow(); if(renderwindow != NULL) { mitk::BaseRenderer::GetInstance(renderwindow)->GetSliceNavigationController()->Update(viewDirection, m_Controls->cbTop->isChecked(), m_Controls->cbFrontSide->isChecked(), m_Controls->cbRotated->isChecked() ); mitk::BaseRenderer::GetInstance(renderwindow)->GetDisplayGeometry()->Fit(); } } void QmitkViewInitializationView::OnResetAll() { /* calculate bounding geometry of these nodes */ mitk::TimeSlicedGeometry::Pointer bounds = this->GetDefaultDataStorage()->ComputeBoundingGeometry3D(); /* initialize the views to the bounding geometry */ mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } vtkRenderWindow* QmitkViewInitializationView::GetSelectedRenderWindow() { int selectedItem = m_Controls->m_lbRenderWindows->currentRow(); int itemNumber = 0; mitk::BaseRenderer::BaseRendererMapType::iterator mapit; for(mapit = mitk::BaseRenderer::baseRendererMap.begin(); mapit != mitk::BaseRenderer::baseRendererMap.end(); mapit++, itemNumber++) { if(itemNumber==selectedItem) break; } if(itemNumber==selectedItem) { return (*mapit).first; } return NULL; } void QmitkViewInitializationView::InitRenderWindowSelector() { itk::SimpleMemberCommand::Pointer updateRendererListCommand = itk::SimpleMemberCommand::New(); updateRendererListCommand->SetCallbackFunction( this, &QmitkViewInitializationView::UpdateRendererList ); mitk::FocusManager* fm = mitk::GlobalInteraction::GetInstance()->GetFocusManager(); m_CommandTag = fm->AddObserver(mitk::FocusEvent(), updateRendererListCommand); this->UpdateRendererList(); } void QmitkViewInitializationView::UpdateRendererList() { vtkRenderWindow* focusedRenderWindow = NULL; mitk::FocusManager* fm = mitk::GlobalInteraction::GetInstance()->GetFocusManager(); mitk::BaseRenderer::ConstPointer br = fm->GetFocused(); if (br.IsNotNull()) { focusedRenderWindow = br->GetRenderWindow(); } int selectedItem = -1; int itemNumber = 0; m_Controls->m_lbRenderWindows->clear(); for(mitk::BaseRenderer::BaseRendererMapType::iterator mapit = mitk::BaseRenderer::baseRendererMap.begin(); mapit != mitk::BaseRenderer::baseRendererMap.end(); mapit++, itemNumber++) { if( (*mapit).second->GetName()) { m_Controls->m_lbRenderWindows->addItem(QString((*mapit).second->GetName())); if(focusedRenderWindow==(*mapit).first) selectedItem = itemNumber; } } if (selectedItem>=0) { m_Controls->m_lbRenderWindows->setCurrentRow(selectedItem); } else { m_Controls->m_lbRenderWindows->clearSelection(); } } diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.h b/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.h index bb82bc17ca..e92177369b 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/viewinitialization/QmitkViewInitializationView.h @@ -1,93 +1,92 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKVIEWINITIALIZATIONVIEW_H_INCLUDED #define _QMITKVIEWINITIALIZATIONVIEW_H_INCLUDED #include #include #include "vtkRenderWindow.h" #include "ui_QmitkViewInitializationViewControls.h" /*! * \ingroup org_mitk_gui_qt_viewinitialization_internal * * \brief QmitkViewInitializationView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkViewInitializationView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkViewInitializationView(); virtual ~QmitkViewInitializationView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected: vtkRenderWindow* GetSelectedRenderWindow(); void InitRenderWindowSelector(); void UpdateRendererList(); protected slots: virtual void OnApply(); virtual void OnResetAll(); protected: Ui::QmitkViewInitializationViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; unsigned long m_CommandTag; }; #endif // _QMITKVIEWINITIALIZATIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.cpp index d8bbfc347f..0cbfdd4d98 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.cpp @@ -1,424 +1,423 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkVolumetryView.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include "itkImage.h" #include #include "mitkDataNode.h" #include "mitkRenderingManager.h" #include "mitkVolumeCalculator.h" #include #include #include const std::string QmitkVolumetryView::VIEW_ID = "org.mitk.views.volumetry"; QmitkVolumetryView::QmitkVolumetryView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { //m_DataStorage = this->GetDefaultDataStorage(); } QmitkVolumetryView::~QmitkVolumetryView() { } void QmitkVolumetryView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkVolumetryViewControls; m_Controls->setupUi(parent); this->CreateConnections(); // define data type for combobox m_Controls->m_ImageSelector->SetDataStorage( this->GetDefaultDataStorage() ); m_Controls->m_ImageSelector->SetPredicate( mitk::NodePredicateDataType::New("Image") ); } } void QmitkVolumetryView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkVolumetryView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkVolumetryView::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_ImageSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode*)), this, SLOT(OnImageSelected(const mitk::DataNode*)) ); //connect( (QObject*)(m_Controls->m_Button), SIGNAL(clicked()), this, SLOT(DoSomething()) ); connect( (QObject*)(m_Controls->m_ThresholdSlider), SIGNAL(valueChanged(int)), this, SLOT(OnThresholdSliderChanged(int)) ); //connect( (QObject*)(m_Controls->m_ThresholdLineEdit), SIGNAL(valueChanged(int)), this, SLOT(OnThresholdLineEdit(int)) ); //connect( (QObject*)(m_Controls->m_TextEdit), SIGNAL(valueChanged(int)), this, SLOT(OnTextEditChanged(int)) ); connect( (QObject*)(m_Controls->m_CalcButton), SIGNAL(clicked()), this, SLOT(OnCalculateVolume()) ); connect( (QObject*)(m_Controls->m_TimeSeriesButton), SIGNAL(clicked()), this, SLOT(OnTimeSeriesButtonClicked()) ); connect( (QObject*)(m_Controls->m_SaveCsvButton), SIGNAL(clicked()), this, SLOT(OnSaveCsvButtonClicked()) ); } } void QmitkVolumetryView::Activated() { QmitkFunctionality::Activated(); } void QmitkVolumetryView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkVolumetryView::OnImageSelected(const mitk::DataNode* item) { // nothing selected (NULL selection) if( item == NULL || item->GetData() == NULL ) return; if( item->GetData()->GetSource().IsNull() ) { m_SelectedDataNode = 0; return; } m_SelectedDataNode = const_cast(item); std::cout << "Selected mitk::Image at address " << m_SelectedDataNode->GetData() << std::endl; if(item == m_OverlayNode.GetPointer()) return; if (m_OverlayNode) { this->GetDefaultDataStorage()->Remove(m_OverlayNode); // remove it from the tree //mitk::DataTreeIteratorClone overlayIt = mitk::DataTreeHelper::FindIteratorToNode(m_DataTreeIteratorClone->GetTree(),m_OverlayNode); //if (overlayIt.IsNotNull()) { overlayIt->Remove(); } m_OverlayNode = NULL; } this->CreateOverlayChild(); //std::string name; //if (node->GetName(name)) //{ // // m_TreeNodeNameLabel->setText( name.c_str() ); //} m_Controls->m_CalcButton->setEnabled(false); m_Controls->m_TimeSeriesButton->setEnabled(false); m_Controls->m_SaveCsvButton->setEnabled(false); m_Controls->m_TextEdit->clear(); if (m_SelectedDataNode.IsNotNull() ) { mitk::Image* image = dynamic_cast(m_SelectedDataNode->GetData()); image->Update(); if (image && image->IsInitialized()) { if (image->GetDimension() == 4) { m_Controls->m_TimeSeriesButton->setEnabled(true); } else { m_Controls->m_CalcButton->setEnabled(true); } int minVal = (int)image->GetScalarValue2ndMin(); int maxVal = (int)image->GetScalarValueMaxNoRecompute(); if (minVal == maxVal) --minVal; m_Controls->m_ThresholdSlider->setMinimum(minVal); m_Controls->m_ThresholdSlider->setMaximum(maxVal); m_Controls->m_ThresholdSlider->setEnabled(true); this->UpdateSlider(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } //void QmitkVolumetryView::DoSomething() //{ // mitk::DataNode* node = m_Controls->m_ImageSelector->GetSelectedNode(); // if (!node) // { // // Nothing selected. Inform the user and return // QMessageBox::information( NULL, "Template functionality", "Please load and select an image before starting some action."); // return; // } // // // here we have a valid mitk::DataNode // // // a node itself is not very useful, we need its data item (the image) // mitk::BaseData* data = node->GetData(); // if (data) // { // // test if this data item is really an image or not (could also be a surface or something totally different) // mitk::Image* image = dynamic_cast( data ); // if (image) // { // std::string name("(no name)"); // node->GetName(name); // // QMessageBox::information( NULL, "Image processing", // QString( "Doing something to '%1'" ).arg(name.c_str()) ); // // // at this point anything can be done using the mitk::Image image. // } // } //} //void QmitkVolumetryView::SetDataNode(const mitk::DataNode* node) //{ // if(node == m_OverlayNode.GetPointer()) // return; // m_SelectedDataNode = node; // is the non-const m_SelectedDataNode needed anyway? // if (m_OverlayNode) // { // // remove it from the tree // mitk::DataTreeIteratorClone overlayIt = mitk::DataTreeHelper::FindIteratorToNode(m_DataTreeIteratorClone->GetTree(),m_OverlayNode); // if (overlayIt.IsNotNull()) { overlayIt->Remove(); } // m_OverlayNode = NULL; // } // CreateOverlayChild(); // std::string name; // if (node->GetName(name)) // { // // m_TreeNodeNameLabel->setText( name.c_str() ); // } // m_CalcButton->setEnabled(false); // m_TimeSeriesButton->setEnabled(false); // m_SaveCsvButton->setEnabled(false); // m_TextEdit->clear(); // // if (m_SelectedDataNode) // { // mitk::Image* image = dynamic_cast(m_SelectedDataNode->GetData()); // image->Update(); // if (image && image->IsInitialized()) // { // if (image->GetDimension() == 4) // { // m_TimeSeriesButton->setEnabled(true); // } // else // { // m_CalcButton->setEnabled(true); // } // int minVal = (int)image->GetScalarValue2ndMin(); // int maxVal = (int)image->GetScalarValueMaxNoRecompute(); // if (minVal == maxVal) // --minVal; // m_ThresholdSlider->setMinValue(minVal); // m_ThresholdSlider->setMaxValue(maxVal); // m_ThresholdSlider->setEnabled(true); // UpdateSlider(); // mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // } // } //} void QmitkVolumetryView::OnCalculateVolume() { if (m_SelectedDataNode.IsNotNull() ) { mitk::Image* image = dynamic_cast(m_SelectedDataNode->GetData()); if (image) { std::cout << "Dimension:" << image->GetDimension() << std::endl; std::cout << "Dimension[3]:" << image->GetDimension(3) << std::endl; mitk::VolumeCalculator::Pointer volCalc = mitk::VolumeCalculator::New(); volCalc->SetImage(image); volCalc->SetThreshold(m_Controls->m_ThresholdSlider->value()); volCalc->ComputeVolume(); std::stringstream vs; vs << volCalc->GetVolume() << " ml"; m_Controls->m_Result->setText(vs.str().c_str() ); } } } void QmitkVolumetryView::OnTimeSeriesButtonClicked() { if (m_SelectedDataNode.IsNotNull() ) { mitk::Image* image = dynamic_cast(m_SelectedDataNode->GetData()); if (image) { mitk::VolumeCalculator::Pointer volCalc = mitk::VolumeCalculator::New(); volCalc->SetImage(image); volCalc->SetThreshold(m_Controls->m_ThresholdSlider->value()); volCalc->ComputeVolume(); std::vector volumes = volCalc->GetVolumes(); std::stringstream vs; int timeStep = 0; for (std::vector::iterator it = volumes.begin(); it != volumes.end(); it++) { vs << timeStep++ << "\t" << *it << std::endl; } m_Controls->m_TextEdit->setText(vs.str().c_str()); m_Controls->m_TextEdit->setTabStopWidth(20); m_Controls->m_SaveCsvButton->setEnabled(true); } } } const mitk::DataNode* QmitkVolumetryView::GetImageNode() { return m_SelectedDataNode; } void QmitkVolumetryView::UpdateSlider() { if (m_SelectedDataNode.IsNotNull() && dynamic_cast(m_SelectedDataNode->GetData())) { int intSliderValue = (int)m_Controls->m_ThresholdSlider->value(); QString stringSliderValue; stringSliderValue.setNum(intSliderValue); m_Controls->m_ThresholdLineEdit->setText(stringSliderValue); } } void QmitkVolumetryView::UpdateSliderLabel() { int sliderValue = atoi(m_Controls->m_ThresholdLineEdit->text().toLatin1()); m_Controls->m_ThresholdSlider->setValue(sliderValue); this->UpdateSlider(); } void QmitkVolumetryView::OnThresholdSliderChanged( int value) { if (m_OverlayNode) { m_OverlayNode->SetLevelWindow(mitk::LevelWindow(value,1)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->UpdateSlider(); } } void QmitkVolumetryView::CreateOverlayChild() { if (m_SelectedDataNode.IsNotNull()) { m_OverlayNode = mitk::DataNode::New(); mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New("volume threshold overlay image" ); m_OverlayNode->SetProperty( "reslice interpolation", m_SelectedDataNode->GetProperty("reslice interpolation") ); m_OverlayNode->SetProperty( "name", nameProp ); m_OverlayNode->SetData(m_SelectedDataNode->GetData()); m_OverlayNode->SetColor(0.0,1.0,0.0); m_OverlayNode->SetOpacity(.25); int layer = 0; m_SelectedDataNode->GetIntProperty("layer", layer); m_OverlayNode->SetIntProperty("layer", layer+1); m_OverlayNode->SetLevelWindow(mitk::LevelWindow(m_Controls->m_ThresholdSlider->value(),1)); this->GetDefaultDataStorage()->Add(m_OverlayNode); //// hack!!! //mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIteratorClone; //while ( !iteratorClone->IsAtEnd() ) //{ // mitk::DataNode::Pointer node = iteratorClone->Get(); // if ( node == m_SelectedDataNode ) // { // iteratorClone->Add(m_OverlayNode); // break; // } // ++iteratorClone; //} } } mitk::DataNode* QmitkVolumetryView::GetOverlayNode() { return m_OverlayNode; } mitk::Image* QmitkVolumetryView::GetImage() { return dynamic_cast(m_SelectedDataNode->GetData()); } void QmitkVolumetryView::OnSaveCsvButtonClicked() { static QString lastSavePath = QDir::homePath(); QString s = QFileDialog::getSaveFileName( this->m_Parent, "Save as..", lastSavePath, "CSV Files (*.csv)"); /*"Save file dialog" "Choose a filename to save under" );*/ if (! s.isEmpty()) { lastSavePath = s; QFile saveFile(s); if ( saveFile.open(QIODevice::WriteOnly)) { QTextStream stream( &saveFile ); stream << m_Controls->m_TextEdit->toPlainText().replace('\t',';'); saveFile.close(); } else { // QMessageBox::critical(NULL,"Save Error!",QString("Saving of CSV failed! Couldn't open output file \"") + saveFile + QString("\""),QMessageBox:Ok,QMessageBox::NoButton); //QMessageBox::critical(NULL,"Save Error!","Saving of CSV failed! Couldn't open output file \"" + saveFile.name() +"\"",QMessageBox::Ok,QMessageBox::NoButton); } } } diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.h b/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.h index e090d2d82e..1787300c92 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.h +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/volumetry/QmitkVolumetryView.h @@ -1,121 +1,120 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ #ifndef _QMITKVOLUMETRYVIEW_H_INCLUDED #define _QMITKVOLUMETRYVIEW_H_INCLUDED #include #include #include "ui_QmitkVolumetryViewControls.h" /*! * \ingroup org_mitk_gui_qt_volumetry_internal * * \brief QmitkVolumetryView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkVolumetryView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkVolumetryView(); QmitkVolumetryView(const QmitkVolumetryView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkVolumetryView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected: mitk::Image* GetImage(); mitk::DataNode* GetOverlayNode(); void CreateOverlayChild(); void UpdateSliderLabel(); void UpdateSlider(); const mitk::DataNode* GetImageNode(); protected slots: void OnCalculateVolume(); void OnTimeSeriesButtonClicked(); void OnThresholdSliderChanged( int value ); void OnSaveCsvButtonClicked(); void OnImageSelected(const mitk::DataNode* item); protected: Ui::QmitkVolumetryViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; /// store weak pointer of the DataNode mitk::WeakPointer m_SelectedDataNode; mitk::DataNode::Pointer m_OverlayNode; mitk::DataStorage::Pointer m_DataStorage; }; #endif // _QMITKVOLUMETRYVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp index 72cc851284..40e9c7f37b 100644 --- a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp +++ b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp @@ -1,59 +1,58 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-06-18 16:47:58 +0200 (Thu, 18 Jun 2009) $ -Version: $Revision: 15412 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkVideoPlayer.h" #include #include #include #include QmitkVideoPlayer::QmitkVideoPlayer() : m_VideoSource(0) , m_VideoBackground( new QmitkVideoBackground(m_VideoSource) ) { } QmitkVideoPlayer::~QmitkVideoPlayer() { // save video preferences } bool QmitkVideoPlayer::IsExclusiveFunctionality() const { return false; } void QmitkVideoPlayer::CreateQtPartControl( QWidget* parent ) { // retrieve old preferences m_VideoSource = mitk::OpenCVVideoSource::New(); m_VideoBackground = new QmitkVideoBackground(m_VideoSource); m_VideoBackground->setParent(parent); QVBoxLayout* layout = new QVBoxLayout; m_OpenCVVideoControls = new QmitkOpenCVVideoControls(m_VideoBackground, this->GetActiveStdMultiWidget()); layout->addWidget( m_OpenCVVideoControls ); parent->setLayout( layout ); } void QmitkVideoPlayer::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { m_OpenCVVideoControls->SetStdMultiWidget( &stdMultiWidget ); } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.h b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.h index 3cc38deb63..58b3a9b670 100644 --- a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.h +++ b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.h @@ -1,53 +1,52 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-03-21 14:46:24 +0100 (Sat, 21 Mar 2009) $ -Version: $Revision: 15412 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QmitkVideoPlayer_h) #define QmitkVideoPlayer_h #include #include class QmitkVideoBackground; class QmitkOpenCVVideoControls; /*! \brief Allows to play videos with OpenCV */ class QmitkVideoPlayer: public QmitkFunctionality { Q_OBJECT public: QmitkVideoPlayer(); QmitkVideoPlayer(const QmitkVideoPlayer& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkVideoPlayer(); virtual bool IsExclusiveFunctionality() const; virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); protected: // Pseudo Ctor void CreateQtPartControl(QWidget* parent); protected: mitk::OpenCVVideoSource::Pointer m_VideoSource; QmitkVideoBackground* m_VideoBackground; QmitkOpenCVVideoControls* m_OpenCVVideoControls; }; #endif // !defined(QmitkVideoPlayer_h) diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp index a410fd0719..de167d7df5 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp @@ -1,30 +1,29 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtActionBarAdvisor.h" QmitkExtActionBarAdvisor::QmitkExtActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer) : berry::ActionBarAdvisor(configurer) { } void QmitkExtActionBarAdvisor::FillMenuBar(void* ) { } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h index 986d7d987c..b4345b7cbe 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h @@ -1,36 +1,35 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEXTACTIONBARADVISOR_H_ #define QMITKEXTACTIONBARADVISOR_H_ #include #include class MITK_QT_COMMON_EXT_EXPORT QmitkExtActionBarAdvisor : public berry::ActionBarAdvisor { public: QmitkExtActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer); protected: void FillMenuBar(void* menuBar); }; #endif /*QMITKEXTACTIONBARADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp index f14f1ddb46..dcdd2274d1 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp @@ -1,165 +1,164 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-10-07 16:14:59 +0200 (Mi, 07 Okt 2009) $ -Version: $Revision: 19343 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtFileSaveProjectAction.h" #include "internal/QmitkCommonExtPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow::Pointer window) : QAction(0) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&Save Project..."); this->setToolTip("Save content of Data Manager as a .mitk project file"); m_Window = window; this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkExtFileSaveProjectAction::Run() { try { /** * @brief stores the last path of last saved file */ static QString m_LastPath; mitk::IDataStorageReference::Pointer dsRef; { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsServiceRef = context->getServiceReference(); if (dsServiceRef) { dss = context->getService(dsServiceRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dsRef = dss->GetDataStorage(); context->ungetService(dsServiceRef); } mitk::DataStorage::Pointer storage = dsRef->GetDataStorage(); QString dialogTitle = "Save MITK Scene (%1)"; QString fileName = QFileDialog::getSaveFileName(NULL, dialogTitle.arg(dsRef->GetLabel()), m_LastPath, "MITK scene files (*.mitk)", NULL ); if (fileName.isEmpty() ) return; // remember the location m_LastPath = fileName; if ( fileName.right(5) != ".mitk" ) fileName += ".mitk"; mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); /* Build list of nodes that should be saved */ mitk::NodePredicateNot::Pointer isNotHelperObject = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true))); mitk::DataStorage::SetOfObjects::ConstPointer nodesToBeSaved = storage->GetSubset(isNotHelperObject); if ( !sceneIO->SaveScene( nodesToBeSaved, storage, fileName.toStdString() ) ) { QMessageBox::information(NULL, "Scene saving", "Scene could not be written completely. Please check the log.", QMessageBox::Ok); } mitk::ProgressBar::GetInstance()->Progress(2); mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes(); if (!failedNodes->empty()) { std::stringstream ss; ss << "The following nodes could not be serialized:" << std::endl; for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { ss << " - "; if ( mitk::BaseData* data =(*iter)->GetData() ) { ss << data->GetNameOfClass(); } else { ss << "(NULL)"; } ss << " contained in node '" << (*iter)->GetName() << "'" << std::endl; } MITK_WARN << ss.str(); } mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties(); if (!failedProperties->GetMap()->empty()) { std::stringstream ss; ss << "The following properties could not be serialized:" << std::endl; const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { ss << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'" << std::endl; } MITK_WARN << ss.str(); } } catch (std::exception& e) { MITK_ERROR << "Exception caught during scene saving: " << e.what(); } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h index 7b00d8361c..e340a2a9ec 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h @@ -1,52 +1,51 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-10-09 16:36:23 +0200 (Fr, 09 Okt 2009) $ -Version: $Revision: 19414 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkExtFileSaveProjectAction_H_ #define QmitkExtFileSaveProjectAction_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include class MITK_QT_COMMON_EXT_EXPORT QmitkExtFileSaveProjectAction : public QAction { Q_OBJECT public: QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow::Pointer window); protected slots: void Run(); private: berry::IWorkbenchWindow::Pointer m_Window; }; #endif /*QmitkExtFileSaveProjectAction_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index f1c849dc34..b13dc5569f 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1148 +1,1147 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtWorkbenchWindowAdvisor.h" #include "QmitkExtActionBarAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include QmitkExtWorkbenchWindowAdvisorHack * QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(berry::IWorkbenchPartReference::Pointer ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(berry::IWorkbenchPartReference::Pointer ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(berry::IWorkbenchPartReference::Pointer /*ref*/) { windowAdvisor->UpdateTitle(false); } void PartHidden(berry::IWorkbenchPartReference::Pointer ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(true); } } void PartVisible(berry::IWorkbenchPartReference::Pointer ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(berry::IWorkbenchPartReference::Pointer ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa), perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED; } void PerspectiveActivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*oldPerspective*/, berry::IPerspectiveDescriptor::Pointer /*newPerspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { if (perspectivesClosed) { QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->closeProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(true); } } perspectivesClosed = false; } void PerspectiveClosed(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer /*perspective*/) { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { std::vector perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->closeProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(false); } } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(berry::IWorkbenchPage::Pointer /*page*/, berry::IPerspectiveDescriptor::Pointer perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer), lastInput(0), wbAdvisor(wbAdvisor), showViewToolbar(true), showPerspectiveToolbar(false), showVersionInfo(true), showMitkVersionInfo(true), showViewMenuItem(true), showNewWindowMenuItem(false), showClosePerspectiveMenuItem(true), dropTargetListener(new QmitkDefaultDropTargetListener) { productName = berry::Platform::GetConfiguration().getString("application.baseName"); } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { berry::ActionBarAdvisor::Pointer actionBarAdvisor( new QmitkExtActionBarAdvisor(configurer)); return actionBarAdvisor; } void* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(void* parent) { QWidget* parentWidget = static_cast(parent); QLabel* label = new QLabel(parentWidget); label->setText("No perspectives are open. Open a perspective in the Window->Open Perspective menu."); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show) { showClosePerspectiveMenuItem = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem() { return showClosePerspectiveMenuItem; } void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show) { showNewWindowMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show) { showViewMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show) { showPerspectiveToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::SetProductName(const std::string& product) { productName = product; } void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const std::string& wndIcon) { windowIcon = wndIcon; } void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); if (!windowIcon.empty()) { mainWindow->setWindowIcon(QIcon(QString::fromStdString(windowIcon))); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); /*mainWindow->setStyleSheet("color: white;" "background-color: #808080;" "selection-color: #659EC7;" "selection-background-color: #808080;" " QMenuBar {" "background-color: #808080; }");*/ // ==== Application menu ============================ QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); QAction* fileOpenAction = new QmitkFileOpenAction(QIcon(":/org.mitk.gui.qt.ext/Load_48.png"), window); fileMenu->addAction(fileOpenAction); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(QIcon(":/org.mitk.gui.qt.ext/Save_48.png")); fileMenu->addAction(fileSaveProjectAction); closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(QIcon(":/org.mitk.gui.qt.ext/Remove_48.png")); fileMenu->addAction(closeProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const std::vector& viewDescriptors = viewRegistry->GetViews(); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(QIcon(":/org.mitk.gui.qt.ext/Undo_48.png"), "&Undo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), QKeySequence("CTRL+Z")); undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(QIcon(":/org.mitk.gui.qt.ext/Redo_48.png") , "&Redo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), QKeySequence("CTRL+Y")); redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); imageNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/Slider.png"), "&Image Navigator", NULL); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (imageNavigatorViewFound) { QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); imageNavigatorAction->setCheckable(true); // add part listener for image navigator imageNavigatorPartListener = new PartListenerForImageNavigator(imageNavigatorAction); window->GetPartService()->AddPartListener(imageNavigatorPartListener); berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); imageNavigatorAction->setChecked(false); if (imageNavigatorView) { bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) imageNavigatorAction->setChecked(true); } imageNavigatorAction->setToolTip("Open image navigator for navigating through image"); } // toolbar for showing file open, undo, redo and other main actions QToolBar* mainActionsToolBar = new QToolBar; mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif mainActionsToolBar->addAction(fileOpenAction); mainActionsToolBar->addAction(fileSaveProjectAction); mainActionsToolBar->addAction(closeProjectAction); mainActionsToolBar->addAction(undoAction); mainActionsToolBar->addAction(redoAction); if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } mainWindow->addToolBar(mainActionsToolBar); #ifdef __APPLE__ mainWindow->setUnifiedTitleAndToolBarOnMac(true); #endif // ==== Window Menu ========================== QMenu* windowMenu = menuBar->addMenu("Window"); if (showNewWindowMenuItem) { windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); windowMenu->addSeparator(); } QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); QMenu* viewMenu; if (showViewMenuItem) { viewMenu = windowMenu->addMenu("Show &View"); viewMenu->setObjectName("Show View"); } windowMenu->addSeparator(); resetPerspAction = windowMenu->addAction("&Reset Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); if(showClosePerspectiveMenuItem) closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); windowMenu->addSeparator(); windowMenu->addAction("&Preferences...", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), QKeySequence("CTRL+P")); // fill perspective menu berry::IPerspectiveRegistry* perspRegistry = window->GetWorkbench()->GetPerspectiveRegistry(); QActionGroup* perspGroup = new QActionGroup(menuBar); std::vector perspectives( perspRegistry->GetPerspectives()); bool skip = false; for (std::vector::iterator perspIt = perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (unsigned int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup); mapPerspIdToAction.insert(std::make_pair((*perspIt)->GetId(), perspAction)); } perspMenu->addActions(perspGroup->actions()); // sort elements (converting vector to map...) std::vector::const_iterator iter; std::map VDMap; skip = false; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { // if viewExcludeList is set, it contains the id-strings of view, which // should not appear as an menu-entry in the menu if (viewExcludeList.size() > 0) { for (unsigned int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; if ((*iter)->GetId() == "org.mitk.views.imagenavigator") continue; std::pair p( (*iter)->GetLabel(), (*iter)); VDMap.insert(p); } // ================================================== // ==== Perspective Toolbar ================================== QToolBar* qPerspectiveToolbar = new QToolBar; if (showPerspectiveToolbar) { qPerspectiveToolbar->addActions(perspGroup->actions()); mainWindow->addToolBar(qPerspectiveToolbar); } else delete qPerspectiveToolbar; // ==== View Toolbar ================================== QToolBar* qToolbar = new QToolBar; std::map::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); viewActions.push_back(viewAction); if(showViewMenuItem) viewMenu->addAction(viewAction); if (showViewToolbar) { qToolbar->addAction(viewAction); } } if (showViewToolbar) { mainWindow->addToolBar(qToolbar); } else delete qToolbar; QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); // ==================================================== // ===== Help menu ==================================== QMenu* helpMenu = menuBar->addMenu("Help"); helpMenu->addAction("&Welcome",this, SLOT(onIntro())); helpMenu->addAction("&Contents", this, SLOT(onHelpContents())); helpMenu->addAction("Context &Help",this, SLOT(onHelp()), QKeySequence("F1")); helpMenu->addAction("&About",this, SLOT(onAbout())); // ===================================================== QStatusBar* qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); QmitkProgressBar *progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); // progBar->AddStepsToDo(2); // progBar->Progress(1); mainWindow->setStatusBar(qStatusBar); QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); // show the shortcut bar and progress indicator, which are hidden by // default //configurer->SetShowPerspectiveBar(true); //configurer->SetShowFastViewBars(true); //configurer->SetShowProgressIndicator(true); // // add the drag and drop support for the editor area // configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance()); // configurer.addEditorAreaTransfer(ResourceTransfer.getInstance()); // configurer.addEditorAreaTransfer(FileTransfer.getInstance()); // configurer.addEditorAreaTransfer(MarkerTransfer.getInstance()); // configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter( // configurer.getWindow())); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener = new PerspectiveListenerForMenu(this); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener); } void QmitkExtWorkbenchWindowAdvisor::onIntro() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkExtWorkbenchWindowAdvisor::onHelp() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkExtWorkbenchWindowAdvisor::onHelpContents() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpContents(); } void QmitkExtWorkbenchWindowAdvisor::onAbout() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack() : QObject() { } QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack() { } void QmitkExtWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // get ImageNavigatorView berry::IViewPart::Pointer imageNavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); if (imageNavigatorView) { bool isImageNavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(imageNavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagenavigator"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkExtWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow() { berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(0); } void QmitkExtWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); file.open(QIODevice::ReadOnly | QIODevice::Text); // Als Text-Datei nur zum Lesen öffnen QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(NULL, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == 0) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = 0; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == 0) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelpContents() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkExtWorkbenchWindowAdvisorHack::onAbout() { QmitkAboutDialog* aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),NULL); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener = new PartListenerForTitle(this); titlePerspectiveListener = new PerspectiveListenerForTitle(this); editorPropertyListener = new berry::PropertyChangeIntAdapter< QmitkExtWorkbenchWindowAdvisor>(this, &QmitkExtWorkbenchWindowAdvisor::PropertyChange); // configurer.getWindow().addPageListener(new IPageListener() { // public void pageActivated(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageClosed(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageOpened(IWorkbenchPage page) { // // do nothing // } // }); configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener); } std::string QmitkExtWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } std::string title; //TODO Product // IProduct product = Platform.getProduct(); // if (product != null) { // title = product.getName(); // } // instead of the product name, we use a custom variable for now title = productName; if(showMitkVersionInfo) { title += std::string(" ") + MITK_VERSION_STRING; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 VTK %4.%5.%6 Qt %7 MITK %8)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR) .arg(MITK_VERSION_STRING); title += versions.toStdString(); } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.empty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); std::string label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.empty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); std::string oldTitle = configurer->GetTitle(); std::string newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = 0; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = 0; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } if (!lastActiveEditor.Expired()) { lastActiveEditor.Lock()->RemovePropertyListener(editorPropertyListener); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener); } RecomputeTitle(); } void QmitkExtWorkbenchWindowAdvisor::PropertyChange(berry::Object::Pointer /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { if (!lastActiveEditor.Expired()) { std::string newTitle = lastActiveEditor.Lock()->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(std::vector v) { this->perspectiveExcludeList = v; } std::vector QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(std::vector v) { this->viewExcludeList = v; } std::vector QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkExtWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h index 49a0f6c775..9ffa9ad3a8 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h @@ -1,166 +1,165 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEXTWORKBENCHWINDOWADVISOR_H_ #define QMITKEXTWORKBENCHWINDOWADVISOR_H_ #include #include #include #include #include #include #include #include class QAction; class QMenu; class MITK_QT_COMMON_EXT_EXPORT QmitkExtWorkbenchWindowAdvisor : public QObject, public berry::WorkbenchWindowAdvisor { Q_OBJECT public: QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer); berry::ActionBarAdvisor::Pointer CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer); void* CreateEmptyWindowContents(void* parent); void PostWindowCreate(); void PreWindowOpen(); void PostWindowClose(); void ShowViewToolbar(bool show); void ShowPerspectiveToolbar(bool show); void ShowVersionInfo(bool show); void ShowMitkVersionInfo(bool show); void ShowViewMenuItem(bool show); void ShowNewWindowMenuItem(bool show); void ShowClosePerspectiveMenuItem(bool show); bool GetShowClosePerspectiveMenuItem(); //TODO should be removed when product support is here void SetProductName(const std::string& product); void SetWindowIcon(const std::string& wndIcon); void SetPerspectiveExcludeList(std::vector v); std::vector GetPerspectiveExcludeList(); void SetViewExcludeList(std::vector v); std::vector GetViewExcludeList(); protected slots: virtual void onIntro(); virtual void onHelp(); virtual void onHelpContents(); virtual void onAbout(); private: /** * Hooks the listeners needed on the window * * @param configurer */ void HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer); std::string ComputeTitle(); void RecomputeTitle(); QString GetQSettingsFile() const; /** * Updates the window title. Format will be: [pageInput -] * [currentPerspective -] [editorInput -] [workspaceLocation -] productName * @param editorHidden TODO */ void UpdateTitle(bool editorHidden); void PropertyChange(berry::Object::Pointer /*source*/, int propId); static QString QT_SETTINGS_FILENAME; berry::IPartListener::Pointer titlePartListener; berry::IPerspectiveListener::Pointer titlePerspectiveListener; berry::IPerspectiveListener::Pointer menuPerspectiveListener; berry::IPartListener::Pointer imageNavigatorPartListener; berry::IPropertyChangeListener::Pointer editorPropertyListener; friend struct berry::PropertyChangeIntAdapter; friend class PartListenerForTitle; friend class PerspectiveListenerForTitle; friend class PerspectiveListenerForMenu; friend class PartListenerForImageNavigator; berry::IEditorPart::WeakPtr lastActiveEditor; berry::IPerspectiveDescriptor::WeakPtr lastPerspective; berry::IWorkbenchPage::WeakPtr lastActivePage; std::string lastEditorTitle; berry::IAdaptable* lastInput; berry::WorkbenchAdvisor* wbAdvisor; bool showViewToolbar; bool showPerspectiveToolbar; bool showVersionInfo; bool showMitkVersionInfo; bool showViewMenuItem; bool showNewWindowMenuItem; bool showClosePerspectiveMenuItem; std::string productName; std::string windowIcon; // enables DnD on the editor area berry::IDropTargetListener::Pointer dropTargetListener; // stringlist for excluding perspectives from the perspective menu entry (e.g. Welcome Perspective) std::vector perspectiveExcludeList; // stringlist for excluding views from the menu entry std::vector viewExcludeList; // maps perspective ids to QAction objects std::map mapPerspIdToAction; // actions which will be enabled/disabled depending on the application state QList viewActions; QAction* fileSaveProjectAction; QAction* closeProjectAction; QAction* undoAction; QAction* redoAction; QAction* imageNavigatorAction; QAction* resetPerspAction; QAction* closePerspAction; }; #endif /*QMITKEXTWORKBENCHWINDOWADVISOR_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 9d1c520208..b73550e174 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp @@ -1,71 +1,70 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkAppInstancesPreferencePage.h" #include #include QmitkAppInstancesPreferencePage::QmitkAppInstancesPreferencePage() { } void QmitkAppInstancesPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkAppInstancesPreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); prefs = prefService->GetSystemPreferences()->Node("/General"); Update(); } QWidget* QmitkAppInstancesPreferencePage::GetQtControl() const { return mainWidget; } bool QmitkAppInstancesPreferencePage::PerformOk() { prefs->PutBool("newInstance.always", controls.newInstanceAlways->isChecked()); prefs->PutBool("newInstance.scene", controls.newInstanceScene->isChecked()); return true; } void QmitkAppInstancesPreferencePage::PerformCancel() { } void QmitkAppInstancesPreferencePage::Update() { bool always = prefs->GetBool("newInstance.always", false); bool scene = prefs->GetBool("newInstance.scene", true); controls.newInstanceAlways->setChecked(always); controls.newInstanceScene->setChecked(scene); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h index d3937ac996..b4c76c2c86 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h @@ -1,57 +1,56 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKAPPINSTANCESPREFERENCEPAGE_H_ #define QMITKAPPINSTANCESPREFERENCEPAGE_H_ #include #include #include 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); void CreateQtControl(QWidget* parent); QWidget* GetQtControl() const; bool PerformOk(); void PerformCancel(); void Update(); private: Ui::QmitkAppInstancesPreferencePage controls; berry::IPreferences::Pointer prefs; QWidget* mainWidget; }; #endif /* QMITKAPPINSTANCESPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp index 1109246ed4..17e97e54e0 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp @@ -1,253 +1,252 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkCommonExtPlugin.h" #include #include "QmitkAppInstancesPreferencePage.h" #include "QmitkInputDevicesPrefPage.h" #include "QmitkModuleView.h" #include #include #include #include #include #include #include #include #include #include #include ctkPluginContext* QmitkCommonExtPlugin::_context = 0; void QmitkCommonExtPlugin::start(ctkPluginContext* context) { this->_context = context; QmitkExtRegisterClasses(); BERRY_REGISTER_EXTENSION_CLASS(QmitkAppInstancesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkInputDevicesPrefPage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context) if (qApp->metaObject()->indexOfSignal("messageReceived(QByteArray)") > -1) { connect(qApp, SIGNAL(messageReceived(QByteArray)), this, SLOT(handleIPCMessage(QByteArray))); } std::vector args = berry::Platform::GetApplicationArgs(); QStringList qargs; for (std::vector::const_iterator it = args.begin(); it != args.end(); ++it) { qargs << QString::fromStdString(*it); } // This is a potentially long running operation. loadDataFromDisk(qargs, true); } void QmitkCommonExtPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = 0; } ctkPluginContext* QmitkCommonExtPlugin::getContext() { return _context; } void QmitkCommonExtPlugin::loadDataFromDisk(const QStringList &arguments, bool globalReinit) { if (!arguments.empty()) { ctkServiceReference serviceRef = _context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService* dataStorageService = _context->getService(serviceRef); mitk::DataStorage::Pointer dataStorage = dataStorageService->GetDefaultDataStorage()->GetDataStorage(); int argumentsAdded = 0; for (int i = 0; i < arguments.size(); ++i) { if (arguments[i].right(5) == ".mitk") { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); mitk::ProgressBar::GetInstance()->Progress(2); argumentsAdded++; } else { mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); try { nodeReader->SetFileName(arguments[i].toStdString()); nodeReader->Update(); for (unsigned int j = 0 ; j < nodeReader->GetNumberOfOutputs( ); ++j) { mitk::DataNode::Pointer node = nodeReader->GetOutput(j); if (node->GetData() != 0) { dataStorage->Add(node); argumentsAdded++; } } } catch(...) { MITK_WARN << "Failed to load command line argument: " << arguments[i].toStdString(); } } } // end for each command line argument if (argumentsAdded > 0 && globalReinit) { // calculate bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(dataStorage->ComputeBoundingGeometry3D()); } } else { MITK_ERROR << "A service reference for mitk::IDataStorageService does not exist"; } } } void QmitkCommonExtPlugin::startNewInstance(const QStringList &args, const QStringList& files) { QStringList newArgs(args); #ifdef Q_OS_UNIX newArgs << QString("--") + QString::fromStdString(berry::Platform::ARG_NEWINSTANCE); #else newArgs << QString("/") + QString::fromStdString(berry::Platform::ARG_NEWINSTANCE); #endif newArgs << files; QProcess::startDetached(qApp->applicationFilePath(), newArgs); } void QmitkCommonExtPlugin::handleIPCMessage(const QByteArray& msg) { QDataStream ds(msg); QString msgType; ds >> msgType; // we only handle messages containing command line arguments if (msgType != "$cmdLineArgs") return; // activate the current workbench window berry::IWorkbenchWindow::Pointer window = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); mainWindow->setWindowState(mainWindow->windowState() & ~Qt::WindowMinimized); mainWindow->raise(); mainWindow->activateWindow(); // Get the preferences for the instantiation behavior berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); berry::IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node("/General"); bool newInstanceAlways = prefs->GetBool("newInstance.always", false); bool newInstanceScene = prefs->GetBool("newInstance.scene", true); QStringList args; ds >> args; QStringList fileArgs; QStringList sceneArgs; Poco::Util::OptionSet os; berry::Platform::GetOptionSet(os); Poco::Util::OptionProcessor processor(os); #if !defined(POCO_OS_FAMILY_UNIX) processor.setUnixStyle(false); #endif args.pop_front(); QStringList::Iterator it = args.begin(); while (it != args.end()) { std::string name; std::string value; if (processor.process(it->toStdString(), name, value)) { ++it; } else { if (it->endsWith(".mitk")) { sceneArgs << *it; } else { fileArgs << *it; } it = args.erase(it); } } if (newInstanceAlways) { if (newInstanceScene) { startNewInstance(args, fileArgs); foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { fileArgs.append(sceneArgs); startNewInstance(args, fileArgs); } } else { loadDataFromDisk(fileArgs, false); if (newInstanceScene) { foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { loadDataFromDisk(sceneArgs, false); } } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_ext, QmitkCommonExtPlugin) diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.h index 8e10046865..5c0513a900 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.h @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKCOMMONEXTPLUGIN_H_ #define QMITKCOMMONEXTPLUGIN_H_ #include class QmitkCommonExtPlugin : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static ctkPluginContext* getContext(); private: void loadDataFromDisk(const QStringList& args, bool globalReinit); void startNewInstance(const QStringList& args, const QStringList &files); private Q_SLOTS: void handleIPCMessage(const QByteArray &msg); private: static ctkPluginContext* _context; }; #endif /* QMITKCOMMONEXTPLUGIN_H_ */ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExtWorkbenchWindowAdvisorHack.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExtWorkbenchWindowAdvisorHack.h index 59412c1fb5..c594cc84bd 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExtWorkbenchWindowAdvisorHack.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExtWorkbenchWindowAdvisorHack.h @@ -1,59 +1,58 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include class ctkPluginContext; class QmitkPreferencesDialog; class QmitkExtWorkbenchWindowAdvisorHack : public QObject { Q_OBJECT public slots: void onUndo(); void onRedo(); void onImageNavigator(); void onEditPreferences(); void onQuit(); void onResetPerspective(); void onClosePerspective(); void onNewWindow(); void onIntro(); /** * @brief This slot is called if the user klicks the menu item "help->context help" or presses F1. * The help page is shown in a workbench editor. */ void onHelp(); void onHelpContents(); /** * @brief This slot is called if the user clicks in help menu the about button */ void onAbout(); public: QmitkExtWorkbenchWindowAdvisorHack(); ~QmitkExtWorkbenchWindowAdvisorHack(); static QmitkExtWorkbenchWindowAdvisorHack* undohack; }; 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 5c33dcd749..70f6a00ed1 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.cpp @@ -1,189 +1,188 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-07 16:57:15 +0200 (Di, 07 Jul 2009) $ -Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkInputDevicesPrefPage.h" #include #include #include #include #include #include #include #include #include #include #include QmitkInputDevicesPrefPage::QmitkInputDevicesPrefPage() : m_MainControl(0) { // gets the old setting of the preferences and loads them into the preference node berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); this->m_InputDevicesPrefNode = prefService->GetSystemPreferences()->Node(mitk::CoreExtConstants::INPUTDEVICE_PREFERENCES); } void QmitkInputDevicesPrefPage::Init(berry::IWorkbench::Pointer ) { } void QmitkInputDevicesPrefPage::CreateQtControl(QWidget* parent) { m_MainControl = new QWidget(parent); QVBoxLayout *layout = new QVBoxLayout; mitk::IInputDeviceRegistry::Pointer inputDeviceRegistry = berry::Platform::GetServiceRegistry().GetServiceById(mitk::CoreExtConstants::INPUTDEVICE_SERVICE); std::vector temp(inputDeviceRegistry->GetInputDevices()); for(std::vector::const_iterator it = temp.begin(); it != temp.end();++it) { QString inputDeviceName(QString::fromStdString((*it)->GetName())); QCheckBox* 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 (QString::fromStdString(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING)); m_WiiMoteSurfaceInteraction = new QRadioButton (QString::fromStdString(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION)); m_WiiMoteHeadTracking->setChecked(true); QVBoxLayout* vBoxLayout = new QVBoxLayout; vBoxLayout->addWidget(m_WiiMoteHeadTracking); vBoxLayout->addWidget(m_WiiMoteSurfaceInteraction); m_WiiMoteModes->setLayout(vBoxLayout); layout->addWidget(m_WiiMoteModes); } } layout->addStretch(); m_MainControl->setLayout(layout); this->Update(); } QWidget* QmitkInputDevicesPrefPage::GetQtControl() const { return m_MainControl; } bool QmitkInputDevicesPrefPage::PerformOk() { bool result = true; mitk::IInputDeviceRegistry::Pointer inputDeviceRegistry = berry::Platform::GetServiceRegistry(). GetServiceById(mitk::CoreExtConstants::INPUTDEVICE_SERVICE); QHashIterator it(m_InputDevices); while (it.hasNext()) { it.next(); mitk::IInputDeviceDescriptor::Pointer inputdevice(inputDeviceRegistry->Find(it.value())); if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { QString headTracking(m_WiiMoteHeadTracking->text()); QString surfaceInteraction(m_WiiMoteSurfaceInteraction->text()); this->m_InputDevicesPrefNode->PutBool (headTracking.toStdString(),m_WiiMoteHeadTracking->isChecked()); this->m_InputDevicesPrefNode->PutBool (surfaceInteraction.toStdString(),m_WiiMoteSurfaceInteraction->isChecked()); // forced flush of the preferences is needed // because otherwise the mitk::WiiMoteActivator class // cannot distinguish the two different modes without // changing the interface for all input devices berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry(). GetServiceById(berry::IPreferencesService::ID); if (prefService) { prefService->GetSystemPreferences()->Flush(); } } if(it.key()->isChecked()) { result &= inputdevice->CreateInputDevice()->RegisterInputDevice(); } else { result &= inputdevice->CreateInputDevice()->UnRegisterInputDevice(); // temporary fix, unclean solution: // e.g. user activates SpaceNavigator and leaves the // the wiimote deactivated, the user will get the warning // despite the fact that it has never been activated if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { // until now 2010-09-06 there were some unfixed problems // with reconnecting the wiimote after disconnecting it. // It was suggested that it might have something to do // with the type of stack, that is used for the pairing. // MS-Stack for example does not work properly. QMessageBox::information(NULL,"WiiMote supportproblem", "A reconnect of the WiiMote is not yet supported! " "Please restart the application, if you want to " "activate the Wii remote/s again."); } } if(result) { this->m_InputDevicesPrefNode->PutBool(it.value(),it.key()->isChecked()); } } return result; } void QmitkInputDevicesPrefPage::PerformCancel() { } void QmitkInputDevicesPrefPage::Update() { QHashIterator it(m_InputDevices); while (it.hasNext()) { it.next(); it.key()->setChecked(this->m_InputDevicesPrefNode->GetBool(it.value(), false)); if(it.value() == mitk::CoreExtConstants::WIIMOTE_XMLATTRIBUTE_NAME) { m_WiiMoteHeadTracking->setChecked( this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_HEADTRACKING,false)); m_WiiMoteSurfaceInteraction->setChecked (this->m_InputDevicesPrefNode->GetBool(mitk::CoreExtConstants::WIIMOTE_SURFACEINTERACTION,false)); } } } 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 d645157014..8654bc335b 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkInputDevicesPrefPage.h @@ -1,89 +1,88 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ -Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITK_INPUTDEVICESPREFPAGE_H_ #define QMITK_INPUTDEVICESPREFPAGE_H_ #include "berryIQtPreferencePage.h" #include #include #include #include class QWidget; class QCheckBox; 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); /** * @see berry::IPreferencePage::CreateQtControl(void* parent) */ void CreateQtControl(QWidget* widget); /** * @see berry::IPreferencePage::CreateQtControl() */ QWidget* GetQtControl() const; /** * @see berry::IPreferencePage::PerformOk() */ virtual bool PerformOk(); /** * @see berry::IPreferencePage::PerformCancel() */ virtual void PerformCancel(); /** * @see berry::IPreferencePage::Update() */ virtual void Update(); protected: QWidget* m_MainControl; QHash m_InputDevices; // specific for Wiimote QGroupBox* m_WiiMoteModes; QRadioButton* m_WiiMoteHeadTracking; QRadioButton* m_WiiMoteSurfaceInteraction; berry::IPreferences::Pointer m_InputDevicesPrefNode; }; #endif // QMITK_INPUTDEVICESPREFPAGE_H_ diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp index bf3613cb65..b003c2953a 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp @@ -1,100 +1,99 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkModuleView.h" #include #include #include #include #include #include QmitkModuleView::QmitkModuleView() : tableView(0) { } void QmitkModuleView::SetFocus() { //tableView->setFocus(); } void QmitkModuleView::CreateQtPartControl(QWidget *parent) { QHBoxLayout* layout = new QHBoxLayout(); layout->setMargin(0); parent->setLayout(layout); tableView = new QTableView(parent); QmitkModuleTableModel* tableModel = new QmitkModuleTableModel(tableView); QSortFilterProxyModel* sortProxyModel = new QSortFilterProxyModel(tableView); sortProxyModel->setSourceModel(tableModel); sortProxyModel->setDynamicSortFilter(true); tableView->setModel(sortProxyModel); tableView->verticalHeader()->hide(); tableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::ExtendedSelection); tableView->setTextElideMode(Qt::ElideMiddle); tableView->setSortingEnabled(true); tableView->sortByColumn(0, Qt::AscendingOrder); tableView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); tableView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); tableView->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents); tableView->horizontalHeader()->setStretchLastSection(true); tableView->horizontalHeader()->setCascadingSectionResizes(true); layout->addWidget(tableView); if (viewState) { berry::IMemento::Pointer tableHeaderState = viewState->GetChild("tableHeader"); if (tableHeaderState) { std::string key; tableHeaderState->GetString("qsettings-key", key); if (!key.empty()) { QSettings settings; QByteArray ba = settings.value(QString::fromStdString(key)).toByteArray(); tableView->horizontalHeader()->restoreState(ba); } } } } void QmitkModuleView::Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento) { berry::QtViewPart::Init(site, memento); viewState = memento; } void QmitkModuleView::SaveState(berry::IMemento::Pointer memento) { QString key = "QmitkModuleView_tableHeader"; QByteArray ba = tableView->horizontalHeader()->saveState(); QSettings settings; settings.setValue(key, ba); berry::IMemento::Pointer tableHeaderState = memento->CreateChild("tableHeader"); tableHeaderState->PutString("qsettings-key", key.toStdString()); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h index 633601a808..5b559c8129 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h @@ -1,47 +1,46 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKMODULEVIEW_H #define QMITKMODULEVIEW_H #include class QTableView; class QmitkModuleView : public berry::QtViewPart { Q_OBJECT public: QmitkModuleView(); protected: void SetFocus(); void CreateQtPartControl(QWidget *parent); void Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento); void SaveState(berry::IMemento::Pointer memento); private: QTableView* tableView; berry::IMemento::Pointer viewState; }; #endif // QMITKMODULEVIEW_H diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp index 8d3a3982d1..4a53411042 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp @@ -1,56 +1,55 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtAppWorkbenchAdvisor.h" #include "internal/QmitkExtApplicationPlugin.h" #include const std::string QmitkExtAppWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.extapp.defaultperspective"; void QmitkExtAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkExtAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); // Exclude the help perspective from org.blueberry.ui.qt.help from // the normal perspective list. // The perspective gets a dedicated menu entry in the help menu std::vector excludePerspectives; excludePerspectives.push_back("org.blueberry.perspectives.help"); advisor->SetPerspectiveExcludeList(excludePerspectives); advisor->SetWindowIcon(":/QmitkExtApplication/icon_research.xpm"); return advisor; //return new QmitkExtWorkbenchWindowAdvisor(this, configurer); } std::string QmitkExtAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.h index 6e470bbb54..5673dcec78 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.h @@ -1,45 +1,44 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEXTAPPWORKBENCHADVISOR_H_ #define QMITKEXTAPPWORKBENCHADVISOR_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include class QmitkExtAppWorkbenchAdvisor: public berry::QtWorkbenchAdvisor { public: static const std::string DEFAULT_PERSPECTIVE_ID; // = "org.mitk.extapp.defaultperspective" void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); std::string GetInitialWindowPerspectiveId(); }; #endif /*QMITKEXTAPPWORKBENCHADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.cpp index 29dc6d4baf..bbbc789c61 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.cpp @@ -1,43 +1,42 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtApplication.h" #include #include "QmitkExtAppWorkbenchAdvisor.h" QmitkExtApplication::QmitkExtApplication() { } int QmitkExtApplication::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); int code = berry::PlatformUI::CreateAndRunWorkbench(display, new QmitkExtAppWorkbenchAdvisor()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void QmitkExtApplication::Stop() { } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.h b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.h index 3eddeaa7a4..2e167a53a1 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.h +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplication.h @@ -1,37 +1,36 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEXTAPPLICATION_H_ #define QMITKEXTAPPLICATION_H_ #include class QmitkExtApplication : public QObject, public berry::IApplication { Q_OBJECT Q_INTERFACES(berry::IApplication) public: QmitkExtApplication(); int Start(); void Stop(); }; #endif /*QMITKEXTAPPLICATION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.cpp index 77b26ee77c..47786d687d 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.cpp @@ -1,85 +1,84 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtApplicationPlugin.h" #include "QmitkExtDefaultPerspective.h" #include "QmitkExtApplication.h" #include #include #include #include #include #include #include QmitkExtApplicationPlugin* QmitkExtApplicationPlugin::inst = 0; QmitkExtApplicationPlugin::QmitkExtApplicationPlugin() { inst = this; } QmitkExtApplicationPlugin::~QmitkExtApplicationPlugin() { } QmitkExtApplicationPlugin* QmitkExtApplicationPlugin::GetDefault() { return inst; } void QmitkExtApplicationPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkExtDefaultPerspective, context); BERRY_REGISTER_EXTENSION_CLASS(QmitkExtApplication, context); ctkServiceReference cmRef = context->getServiceReference(); ctkConfigurationAdmin* configAdmin = 0; if (cmRef) { configAdmin = context->getService(cmRef); } // Use the CTK Configuration Admin service to configure the BlueBerry help system if (configAdmin) { ctkConfigurationPtr conf = configAdmin->getConfiguration("org.blueberry.services.help", QString()); ctkDictionary helpProps; helpProps.insert("homePage", "qthelp://org.mitk.gui.qt.extapplication/bundle/index.html"); conf->update(helpProps); context->ungetService(cmRef); } else { MITK_WARN << "Configuration Admin service unavailable, cannot set home page url."; } } ctkPluginContext* QmitkExtApplicationPlugin::GetPluginContext() const { return context; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_extapplication, QmitkExtApplicationPlugin) diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.h b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.h index bf9076659c..fa8e0f8384 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.h +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtApplicationPlugin.h @@ -1,53 +1,52 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEXTAPPLICATIONPLUGIN_H_ #define QMITKEXTAPPLICATIONPLUGIN_H_ #include #include #include class QmitkExtApplicationPlugin : public QObject, public berry::AbstractUICTKPlugin { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: QmitkExtApplicationPlugin(); ~QmitkExtApplicationPlugin(); static QmitkExtApplicationPlugin* GetDefault(); ctkPluginContext* GetPluginContext() const; void start(ctkPluginContext*); QString GetQtHelpCollectionFile() const; private: static QmitkExtApplicationPlugin* inst; ctkPluginContext* context; }; #endif /* QMITKEXTAPPLICATIONPLUGIN_H_ */ diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.cpp index ca63bf447d..bf8dff433e 100755 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.cpp @@ -1,41 +1,40 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkExtDefaultPerspective.h" #include "berryIViewLayout.h" QmitkExtDefaultPerspective::QmitkExtDefaultPerspective() { } void QmitkExtDefaultPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { std::string editorArea = layout->GetEditorArea(); layout->AddView("org.mitk.views.datamanager", berry::IPageLayout::LEFT, 0.3f, editorArea); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.datamanager"); lo->SetCloseable(false); layout->AddView("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, 0.5f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer bottomFolder = layout->CreateFolder("bottom", berry::IPageLayout::BOTTOM, 0.7f, editorArea); bottomFolder->AddView("org.mitk.views.propertylistview"); bottomFolder->AddView("org.blueberry.views.logview"); } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.h b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.h index 6f0d1a0c0e..48e98aae9f 100755 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.h +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtDefaultPerspective.h @@ -1,37 +1,36 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKEXTDEFAULTPERSPECTIVE_H_ #define QMITKEXTDEFAULTPERSPECTIVE_H_ #include class QmitkExtDefaultPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) public: QmitkExtDefaultPerspective(); void CreateInitialLayout(berry::IPageLayout::Pointer layout); }; #endif /* QMITKEXTDEFAULTPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.cpp b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.cpp index 238ea87293..c81d252302 100644 --- a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.cpp +++ b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.cpp @@ -1,1043 +1,1042 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkIGTTrackingLabView.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include // Qt #include #include const std::string QmitkIGTTrackingLabView::VIEW_ID = "org.mitk.views.igttrackinglab"; QmitkIGTTrackingLabView::QmitkIGTTrackingLabView() : QmitkFunctionality() ,m_Source(NULL) ,m_FiducialRegistrationFilter(NULL) ,m_PermanentRegistrationFilter(NULL) ,m_Visualizer(NULL) ,m_VirtualView(NULL) ,m_PSRecordingPointSet(NULL) ,m_RegistrationTrackingFiducialsName("Tracking Fiducials") ,m_RegistrationImageFiducialsName("Image Fiducials") ,m_PointSetRecordingDataNodeName("Recorded Points") ,m_PointSetRecording(false) ,m_ImageFiducialsDataNode(NULL) ,m_TrackerFiducialsDataNode(NULL) ,m_PermanentRegistrationSourcePoints(NULL) { //[-1;0;0] for WOLF_6D bronchoscope m_DirectionOfProjectionVector[0]=0; m_DirectionOfProjectionVector[1]=0; m_DirectionOfProjectionVector[2]=-1;} QmitkIGTTrackingLabView::~QmitkIGTTrackingLabView() { } void QmitkIGTTrackingLabView::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); m_ToolBox = new QToolBox(parent); m_Controls.m_VBoxLayout->addWidget(m_ToolBox); this->CreateBundleWidgets( parent ); this->CreateConnections(); } void QmitkIGTTrackingLabView::CreateBundleWidgets( QWidget* parent ) { // configuration widget m_NDIConfigWidget = new QmitkNDIConfigurationWidget(parent); m_NDIConfigWidget->SetToolTypes(QStringList () << "Instrument" << "Fiducial" << "Skinmarker" << "Unknown" ); m_ToolBox->addItem(m_NDIConfigWidget, "Configuration"); // registration widget m_RegistrationWidget = new QmitkFiducialRegistrationWidget(parent); m_RegistrationWidget->HideStaticRegistrationRadioButton(true); m_RegistrationWidget->HideContinousRegistrationRadioButton(true); m_RegistrationWidget->HideUseICPRegistrationCheckbox(true); m_ToolBox->addItem(m_RegistrationWidget, "Initial Registration"); // permanent registration widget m_PermanentRegistrationToolSelectionWidget = new QmitkToolSelectionWidget(parent); m_PermanentRegistrationToolSelectionWidget->SetCheckboxtText("Use this tool for permanent registration"); m_ToolBox->addItem(m_PermanentRegistrationToolSelectionWidget, "Permanent Registration"); // pointset recording m_ToolBox->addItem(this->CreatePointSetRecordingWidget(parent), "PointSet Recording"); // virtual view m_VirtualViewToolSelectionWidget = new QmitkToolSelectionWidget(parent); m_VirtualViewToolSelectionWidget->SetCheckboxtText("Enable Virtual Camera"); m_ToolBox->addItem(m_VirtualViewToolSelectionWidget, "Virtual Camera"); // tracking status m_ToolStatusWidget = new QmitkToolTrackingStatusWidget( parent ); m_Controls.m_VBoxLayout->addWidget(m_ToolStatusWidget); // update timer m_RenderingTimerWidget = new QmitkUpdateTimerWidget( parent ); m_RenderingTimerWidget->SetPurposeLabelText(QString("Navigation")); m_RenderingTimerWidget->SetTimerInterval( 50 ); // set rendering timer at 20Hz (updating every 50msec) m_Controls.m_VBoxLayout->addWidget(m_RenderingTimerWidget); } void QmitkIGTTrackingLabView::CreateConnections() { connect( m_ToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnToolBoxCurrentChanged(int)) ); //connect( m_NDIConfigWidget, SIGNAL(Connected()), m_RenderingTimerWidget, SLOT(EnableWidget()) ); connect( m_NDIConfigWidget, SIGNAL(Disconnected()), this, SLOT(OnTrackerDisconnected()) ); connect( m_NDIConfigWidget, SIGNAL(Connected()), this, SLOT(OnSetupNavigation()) ); connect( m_NDIConfigWidget, SIGNAL(SignalToolNameChanged(int, QString)), this, SLOT(OnChangeToolName(int, QString)) ); connect( m_NDIConfigWidget, SIGNAL(SignalLoadTool(int, mitk::DataNode::Pointer)), this, SLOT(OnToolLoaded(int, mitk::DataNode::Pointer)) ); connect( m_NDIConfigWidget, SIGNAL(ToolsAdded(QStringList)), this, SLOT(OnToolsAdded(QStringList)) ); connect( m_NDIConfigWidget, SIGNAL(RepresentationChanged( int ,mitk::Surface::Pointer )), this, SLOT(ChangeToolRepresentation( int, mitk::Surface::Pointer ))); connect( m_RegistrationWidget, SIGNAL(AddedTrackingFiducial()), this, SLOT(OnAddRegistrationTrackingFiducial()) ); connect( m_RegistrationWidget, SIGNAL(PerformFiducialRegistration()), this, SLOT(OnRegisterFiducials()) ); connect( m_RenderingTimerWidget, SIGNAL(Started()), this, SLOT(OnStartNavigation()) ); connect( m_RenderingTimerWidget, SIGNAL(Stopped()), this, SLOT(OnStopNavigation()) ); connect( m_VirtualViewToolSelectionWidget, SIGNAL(SignalUseTool(int, bool)), this, SLOT(OnVirtualCamera(int, bool))); connect( m_PermanentRegistrationToolSelectionWidget, SIGNAL(SignalUseTool(int, bool)), this, SLOT(OnPermanentRegistration(int, bool)) ); } void QmitkIGTTrackingLabView::OnAddRegistrationTrackingFiducial() { mitk::DataStorage* ds = this->GetDefaultDataStorage(); // check if DataStorage available if(ds == NULL) throw std::invalid_argument("DataStorage is not available"); if (m_FiducialRegistrationFilter.IsNull()) { std::string message( "IGT Pipeline is not ready. Please 'Start Navigation' before adding points"); QMessageBox::warning(NULL, "Adding Fiducials not possible", message.c_str()); return; } if (m_FiducialRegistrationFilter->GetNumberOfOutputs() < 1 || m_FiducialRegistrationFilter->GetNumberOfInputs() < 1) { std::string message("There are no tracking instruments! Please add an instrument first!"); QMessageBox::warning(NULL, "Adding Fiducials not possible", message.c_str()); return; } if (m_FiducialRegistrationFilter->GetInput()->IsDataValid() == false) { std::string message("instrument can currently not be tracked. Please make sure that the instrument is visible to the tracker"); QMessageBox::warning(NULL, "Adding Fiducials not possible", message.c_str()); return; } mitk::NavigationData::Pointer nd = m_Source->GetOutput(0); if( nd.IsNull() || !nd->IsDataValid()) QMessageBox::warning( 0, "Invalid tracking data", "Navigation data is not available or invalid!", QMessageBox::Ok ); // in case the tracker fiducials datanode has been renamed or removed //if(trackerFiducialsPS.IsNull()) //{ // mitk::DataNode::Pointer trackerFiducialsDN = mitk::DataNode::New(); // trackerFiducialsDN->SetName(m_RegistrationTrackingFiducialsName); // trackerFiducialsPS = mitk::PointSet::New(); // trackerFiducialsDN->SetData(trackerFiducialsPS); // m_RegistrationWidget->SetTrackerFiducialsNode(trackerFiducialsDN); //} if(m_TrackerFiducialsDataNode.IsNotNull() && m_TrackerFiducialsDataNode->GetData() != NULL) { mitk::PointSet::Pointer ps = dynamic_cast(m_TrackerFiducialsDataNode->GetData()); ps->InsertPoint(ps->GetSize(), nd->GetPosition()); } else QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "Can not access Tracker Fiducials. Adding fiducial not possible!"); } void QmitkIGTTrackingLabView::OnSetupNavigation() { if(m_Source.IsNotNull()) if(m_Source->IsTracking()) return; mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "can not access DataStorage. Navigation not possible"); return; } // Building up the filter pipeline try { this->SetupIGTPipeline(); } catch(std::exception& e) { QMessageBox::warning(NULL, QString("IGTSurfaceTracker: Error"), QString("Error while building the IGT-Pipeline: %1").arg(e.what())); this->DestroyIGTPipeline(); // destroy the pipeline if building is incomplete return; } catch(...) { QMessageBox::warning(NULL, QString("IGTSurfaceTracker: Error"), QString("Error while building the IGT-Pipeline")); this->DestroyIGTPipeline(); return; } } void QmitkIGTTrackingLabView::SetupIGTPipeline() { mitk::DataStorage* ds = this->GetDefaultDataStorage(); // check if DataStorage is available if(ds == NULL) throw std::invalid_argument("DataStorage is not available"); mitk::TrackingDevice::Pointer tracker = m_NDIConfigWidget->GetTracker(); // get current tracker from configuration widget if(tracker.IsNull()) // check if tracker is valid throw std::invalid_argument("tracking device is NULL!"); m_Source = mitk::TrackingDeviceSource::New(); // create new source for the IGT-Pipeline m_Source->SetTrackingDevice(tracker); // set the found tracker from the configuration widget to the source this->InitializeFilters(); // initialize all needed filters if(m_NDIConfigWidget->GetTracker()->GetType() == mitk::NDIAurora) { for (unsigned int i=0; i < m_Source->GetNumberOfOutputs(); ++i) { m_FiducialRegistrationFilter->SetInput(i, m_Source->GetOutput(i)); // set input for registration filter m_Visualizer->SetInput(i, m_FiducialRegistrationFilter->GetOutput(i)); // set input for visualization filter } for(unsigned int i= 0; i < m_Visualizer->GetNumberOfOutputs(); ++i) { const char* toolName = tracker->GetTool(i)->GetToolName(); mitk::DataNode::Pointer representation = this->CreateInstrumentVisualization(this->GetDefaultDataStorage(), toolName); m_PSRecToolSelectionComboBox->addItem(QString(toolName)); m_PermanentRegistrationToolSelectionWidget->AddToolName(QString(toolName)); m_VirtualViewToolSelectionWidget->AddToolName(QString(toolName)); m_Visualizer->SetRepresentationObject(i, representation->GetData()); } if(m_Source->GetTrackingDevice()->GetToolCount() > 0) m_RenderingTimerWidget->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); this->GlobalReinit(); } // this->CreateInstrumentVisualization(ds, tracker);//create for each single connected ND a corresponding 3D representation } void QmitkIGTTrackingLabView::InitializeFilters() { //1. Fiducial Registration Filters m_FiducialRegistrationFilter = mitk::NavigationDataLandmarkTransformFilter::New(); // filter used for initial fiducial registration //2. Visualization Filter m_Visualizer = mitk::NavigationDataObjectVisualizationFilter::New(); // filter to display NavigationData m_PermanentRegistrationFilter = mitk::NavigationDataLandmarkTransformFilter::New(); //3. Virtual Camera m_VirtualView = mitk::CameraVisualization::New(); // filter to update the vtk camera according to the reference navigation data m_VirtualView->SetRenderer(mitk::BaseRenderer::GetInstance(this->GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow())); mitk::Vector3D viewUpInToolCoordinatesVector; viewUpInToolCoordinatesVector[0]=1; viewUpInToolCoordinatesVector[1]=0; viewUpInToolCoordinatesVector[2]=0; m_VirtualView->SetDirectionOfProjectionInToolCoordinates(m_DirectionOfProjectionVector); m_VirtualView->SetFocalLength(5000.0); m_VirtualView->SetViewUpInToolCoordinates(viewUpInToolCoordinatesVector); } void QmitkIGTTrackingLabView::OnRegisterFiducials( ) { /* filter pipeline can only be build, if source and visualization filters exist */ if (m_Source.IsNull() || m_Visualizer.IsNull() || m_FiducialRegistrationFilter.IsNull()) { QMessageBox::warning(NULL, "Registration not possible", "Navigation pipeline is not ready. Please (re)start the navigation"); return; } if (m_Source->IsTracking() == false) { QMessageBox::warning(NULL, "Registration not possible", "Registration only possible if navigation is running"); return; } /* retrieve fiducials from data storage */ mitk::DataStorage* ds = this->GetDefaultDataStorage(); mitk::PointSet::Pointer imageFiducials = dynamic_cast(m_ImageFiducialsDataNode->GetData()); mitk::PointSet::Pointer trackerFiducials = dynamic_cast(m_TrackerFiducialsDataNode->GetData()); //mitk::PointSet::Pointer imageFiducials = ds->GetNamedObject(m_RegistrationImageFiducialsName.c_str()); //mitk::PointSet::Pointer trackerFiducials = ds->GetNamedObject(m_RegistrationTrackingFiducialsName.c_str()); if (imageFiducials.IsNull() || trackerFiducials.IsNull()) { QMessageBox::warning(NULL, "Registration not possible", "Fiducial data objects not found. \n" "Please set 3 or more fiducials in the image and with the tracking system.\n\n" "Registration is not possible"); return; } unsigned int minFiducialCount = 3; // \Todo: move to view option if ((imageFiducials->GetSize() < minFiducialCount) || (trackerFiducials->GetSize() < minFiducialCount) || (imageFiducials->GetSize() != trackerFiducials->GetSize())) { QMessageBox::warning(NULL, "Registration not possible", QString("Not enough fiducial pairs found. At least %1 fiducial must " "exist for the image and the tracking system respectively.\n" "Currently, %2 fiducials exist for the image, %3 fiducials exist for the tracking system").arg(minFiducialCount).arg(imageFiducials->GetSize()).arg(trackerFiducials->GetSize())); return; } /* now we have two PointSets with enough points to perform a landmark based transform */ if ( m_RegistrationWidget->UseICPIsChecked() ) m_FiducialRegistrationFilter->UseICPInitializationOn(); else m_FiducialRegistrationFilter->UseICPInitializationOff(); m_FiducialRegistrationFilter->SetSourceLandmarks(trackerFiducials); m_FiducialRegistrationFilter->SetTargetLandmarks(imageFiducials); if (m_FiducialRegistrationFilter.IsNotNull() && m_FiducialRegistrationFilter->IsInitialized()) // update registration quality display { QString registrationQuality = QString("%0: FRE is %1mm (Std.Dev. %2), \n" "RMS error is %3mm,\n" "Minimum registration error (best fitting landmark) is %4mm,\n" "Maximum registration error (worst fitting landmark) is %5mm.") .arg("Fiducial Registration") .arg(m_FiducialRegistrationFilter->GetFRE(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetFREStdDev(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetRMSError(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetMinError(), 3, 'f', 3) .arg(m_FiducialRegistrationFilter->GetMaxError(), 3, 'f', 3); m_RegistrationWidget->SetQualityDisplayText(registrationQuality); } //trackerFiducials->Clear(); //this->GlobalReinit(); } void QmitkIGTTrackingLabView::OnTrackerDisconnected() { m_RenderingTimerWidget->DisableWidget(); this->DestroyInstrumentVisualization(this->GetDefaultDataStorage(), m_NDIConfigWidget->GetTracker()); } mitk::DataNode::Pointer QmitkIGTTrackingLabView::CreateInstrumentVisualization(mitk::DataStorage* ds, const char* toolName) { //const char* toolName = tracker->GetTool(i)->GetToolName(); mitk::DataNode::Pointer toolRepresentationNode; toolRepresentationNode = ds->GetNamedNode(toolName); // check if node with same name already exists if(toolRepresentationNode.IsNotNull()) ds->Remove(toolRepresentationNode); // remove old node with same name toolRepresentationNode = this->CreateConeRepresentation( toolName ); // m_Visualizer->SetRepresentationObject(i, toolRepresentationNode->GetData()); ds->Add(toolRepresentationNode); // adds node to data storage return toolRepresentationNode; } mitk::DataNode::Pointer QmitkIGTTrackingLabView::CreateConeRepresentation( const char* label ) { //new data mitk::Cone::Pointer activeToolData = mitk::Cone::New(); vtkConeSource* vtkData = vtkConeSource::New(); vtkData->SetRadius(7.5); vtkData->SetHeight(15.0); vtkData->SetDirection(m_DirectionOfProjectionVector[0],m_DirectionOfProjectionVector[1],m_DirectionOfProjectionVector[2]); vtkData->SetCenter(0.0, 0.0, 7.5); vtkData->SetResolution(20); vtkData->CappingOn(); vtkData->Update(); activeToolData->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); //new node mitk::DataNode::Pointer coneNode = mitk::DataNode::New(); coneNode->SetData(activeToolData); coneNode->GetPropertyList()->SetProperty("name", mitk::StringProperty::New( label )); coneNode->GetPropertyList()->SetProperty("layer", mitk::IntProperty::New(0)); coneNode->GetPropertyList()->SetProperty("visible", mitk::BoolProperty::New(true)); coneNode->SetColor(1.0,0.0,0.0); coneNode->SetOpacity(0.85); coneNode->Modified(); return coneNode; } void QmitkIGTTrackingLabView::DestroyIGTPipeline() { if(m_Source.IsNotNull()) { m_Source->StopTracking(); m_Source->Disconnect(); m_Source = NULL; } m_FiducialRegistrationFilter = NULL; m_PermanentRegistrationFilter = NULL; m_Visualizer = NULL; m_VirtualView = NULL; } void QmitkIGTTrackingLabView::OnChangeToolName(int index, QString name) { if(m_Source.IsNull()) return; mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL,"DataStorage Access Error", "Could not access DataStorage. Tool Name can not be changed!"); return; } mitk::NavigationData::Pointer tempND = m_Source->GetOutput(index); if(tempND.IsNull()) return; const char* oldName = tempND->GetName(); mitk::DataNode::Pointer tempNode = ds->GetNamedNode(oldName); if(tempNode.IsNotNull()) { tempNode->SetName(name.toStdString().c_str()); tempND->SetName(name.toStdString().c_str()); } else QMessageBox::warning(NULL, "Rename Tool Error", "Couldn't find the corresponding tool for changing it's name!"); } void QmitkIGTTrackingLabView::OnToolLoaded(int index, mitk::DataNode::Pointer toolNode) { if(m_Source.IsNull() || m_Visualizer.IsNull()) return; mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL,"DataStorage Access Error", "Could not access DataStorage. Loaded tool representation can not be shown!"); return; } mitk::NavigationData::Pointer tempND = m_Source->GetOutput(index); if(tempND.IsNull()) return; // try to find DataNode for tool in DataStorage const char* toolName = tempND->GetName(); mitk::DataNode::Pointer tempNode = ds->GetNamedNode(toolName); if(tempNode.IsNull()) { tempNode = mitk::DataNode::New(); // create new node, if none was found ds->Add(tempNode); } tempNode->SetData(toolNode->GetData()); tempNode->SetName(toolNode->GetName()); m_PSRecToolSelectionComboBox->setItemText(index,toolNode->GetName().c_str()); m_VirtualViewToolSelectionWidget->ChangeToolName(index, QString(toolNode->GetName().c_str())); m_PermanentRegistrationToolSelectionWidget->ChangeToolName(index, QString(toolNode->GetName().c_str())); m_Visualizer->SetRepresentationObject(index, tempNode->GetData()); m_Visualizer->Update(); tempNode->Modified(); this->GlobalReinit(); } void QmitkIGTTrackingLabView::OnStartNavigation() { if(m_Source.IsNull()) { QMessageBox::warning(NULL, "IGTTrackingLab: Error", "can not access tracking source. Navigation not possible"); return; } if(!m_Source->IsTracking()) { m_Source->StartTracking(); try { m_RenderingTimerWidget->GetTimerInterval(); this->StartContinuousUpdate(); // start tracker with set interval for(unsigned int i = 0; i < m_Source->GetNumberOfOutputs(); i++) // add navigation data to bundle widgets { m_ToolStatusWidget->AddNavigationData(dynamic_cast(m_Source->GetOutputs().at(i).GetPointer())); } m_ToolStatusWidget->ShowStatusLabels(); // show status for every tool if ND is valid or not //m_IGTPlayerWidget->setEnabled(true); } catch(...) { //m_IGTPlayerWidget->setDisabled(true); this->StopContinuousUpdate(); this->DestroyIGTPipeline(); return; } m_NDIConfigWidget->EnableAddToolsButton(false); } } void QmitkIGTTrackingLabView::StopContinuousUpdate() { if (this->m_RenderingTimerWidget->GetUpdateTimer() != NULL) { m_RenderingTimerWidget->StopTimer(); disconnect( (QTimer*) m_RenderingTimerWidget->GetUpdateTimer(), SIGNAL(timeout()), this, SLOT(RenderScene()) ); // disconnect timer from RenderScene() method } if(m_PointSetRecordPushButton) m_PointSetRecordPushButton->setDisabled(true); } void QmitkIGTTrackingLabView::RenderScene( ) { try { if (m_Visualizer.IsNull() || this->GetActiveStdMultiWidget() == NULL) return; try { if(m_Source.IsNotNull() && m_Source->IsTracking()) m_ToolStatusWidget->Refresh(); if(m_VirtualViewToolSelectionWidget->IsSelectedToolActivated()) { m_VirtualView->Update(); mitk::Point3D p = m_Visualizer->GetOutput(m_VirtualViewToolSelectionWidget->GetCurrentSelectedIndex())->GetPosition(); this->GetActiveStdMultiWidget()->MoveCrossToPosition(p); } if(m_PermanentRegistrationToolSelectionWidget->IsSelectedToolActivated() && m_PermanentRegistrationToolSelectionWidget->GetCurrentSelectedIndex() >= 0 ) { mitk::NavigationData::Pointer permRegTool = m_Source->GetOutput((unsigned int) m_PermanentRegistrationToolSelectionWidget->GetCurrentSelectedIndex()); m_PermanentRegistrationFilter->SetSourceLandmarks(this->GetVirtualPointSetFromPosition(permRegTool)); } if(m_PointSetRecording && m_PSRecordingPointSet.IsNotNull()) { int size = m_PSRecordingPointSet->GetSize(); mitk::NavigationData::Pointer nd= m_Visualizer->GetOutput(m_PSRecToolSelectionComboBox->currentIndex()); if(size > 0) { mitk::Point3D p = m_PSRecordingPointSet->GetPoint(size-1); if(p.EuclideanDistanceTo(nd->GetPosition()) > (double) m_PSRecordingSpinBox->value()) m_PSRecordingPointSet->InsertPoint(size, nd->GetPosition()); } else m_PSRecordingPointSet->InsertPoint(size, nd->GetPosition()); } } catch(std::exception& e) { MITK_WARN << "Exception during QmitkIGTTrackingLab::RenderScene():" << e.what() << "\n"; } //if(m_VirtualViewCheckBox->isChecked()) // mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); ////update all Widgets //else m_Visualizer->Update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); } catch (std::exception& e) { MITK_WARN << "RenderAll exception: " << e.what() << "\n"; } catch (...) { MITK_WARN << "RenderAll unknown exception\n"; } } void QmitkIGTTrackingLabView::StartContinuousUpdate( ) { if (m_Source.IsNull() || m_Visualizer.IsNull() ) throw std::invalid_argument("Pipeline is not set up correctly"); if (m_RenderingTimerWidget->GetUpdateTimer() == NULL) return; else { connect( (QTimer*) m_RenderingTimerWidget->GetUpdateTimer(), SIGNAL(timeout()), this, SLOT(RenderScene()) ); // connect update timer to RenderScene() method } if(m_PointSetRecordPushButton) m_PointSetRecordPushButton->setEnabled(true); } void QmitkIGTTrackingLabView::OnStopNavigation() { if(m_Source.IsNull()) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "can not access tracking source. Navigation not possible"); return; } if(m_Source->IsTracking()) { m_Source->StopTracking(); this->StopContinuousUpdate(); m_ToolStatusWidget->RemoveStatusLabels(); m_NDIConfigWidget->EnableAddToolsButton(true); } } void QmitkIGTTrackingLabView::OnToolsAdded(QStringList toolsList) { if(m_Source.IsNull() || m_FiducialRegistrationFilter.IsNull() || m_Visualizer.IsNull()) return; m_Source->UpdateOutputInformation(); unsigned int nrOfOldOutputs = m_Visualizer->GetNumberOfOutputs(); for(unsigned int i = nrOfOldOutputs; i < m_Source->GetNumberOfOutputs(); ++i) { m_FiducialRegistrationFilter->SetInput(i, m_Source->GetOutput(i)); m_Visualizer->SetInput(i, m_FiducialRegistrationFilter->GetOutput(i)); } for(unsigned int j = nrOfOldOutputs; j < m_Visualizer->GetNumberOfOutputs(); ++j) { mitk::DataNode::Pointer representation = this->CreateInstrumentVisualization(this->GetDefaultDataStorage(), m_Source->GetTrackingDevice()->GetTool(j)->GetToolName()); m_PSRecToolSelectionComboBox->addItem(QString(m_Source->GetTrackingDevice()->GetTool(j)->GetToolName())); m_PermanentRegistrationToolSelectionWidget->AddToolName(QString(m_Source->GetTrackingDevice()->GetTool(j)->GetToolName())); m_VirtualViewToolSelectionWidget->AddToolName(QString(m_Source->GetTrackingDevice()->GetTool(j)->GetToolName())); m_Visualizer->SetRepresentationObject(j, representation->GetData()); } if(m_Source->GetTrackingDevice()->GetToolCount() > 0) m_RenderingTimerWidget->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); this->GlobalReinit(); //mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_ALL); } void QmitkIGTTrackingLabView::InitializeRegistration() { mitk::DataStorage* ds = this->GetDefaultDataStorage(); if( ds == NULL ) return; m_RegistrationWidget->SetMultiWidget(this->GetActiveStdMultiWidget()); // passing multiwidget to pointsetwidget if(m_ImageFiducialsDataNode.IsNull()) { m_ImageFiducialsDataNode = mitk::DataNode::New(); mitk::PointSet::Pointer ifPS = mitk::PointSet::New(); m_ImageFiducialsDataNode->SetData(ifPS); mitk::Color color; color.Set(1.0f, 0.0f, 0.0f); m_ImageFiducialsDataNode->SetName(m_RegistrationImageFiducialsName); m_ImageFiducialsDataNode->SetColor(color); m_ImageFiducialsDataNode->SetBoolProperty( "updateDataOnRender", false ); ds->Add(m_ImageFiducialsDataNode); } m_RegistrationWidget->SetMultiWidget(this->GetActiveStdMultiWidget()); m_RegistrationWidget->SetImageFiducialsNode(m_ImageFiducialsDataNode); if(m_TrackerFiducialsDataNode.IsNull()) { m_TrackerFiducialsDataNode = mitk::DataNode::New(); mitk::PointSet::Pointer tfPS = mitk::PointSet::New(); m_TrackerFiducialsDataNode->SetData(tfPS); mitk::Color color; color.Set(0.0f, 1.0f, 0.0f); m_TrackerFiducialsDataNode->SetName(m_RegistrationTrackingFiducialsName); m_TrackerFiducialsDataNode->SetColor(color); m_TrackerFiducialsDataNode->SetBoolProperty( "updateDataOnRender", false ); ds->Add(m_TrackerFiducialsDataNode); } m_RegistrationWidget->SetTrackerFiducialsNode(m_TrackerFiducialsDataNode); } void QmitkIGTTrackingLabView::OnToolBoxCurrentChanged(const int index) { switch (index) { case RegistrationWidget: this->InitializeRegistration(); break; default: break; } } mitk::DataNode::Pointer QmitkIGTTrackingLabView::CreateRegistrationFiducialsNode( const std::string& label, const mitk::Color& color) { mitk::DataNode::Pointer fiducialsNode = mitk::DataNode::New(); mitk::PointSet::Pointer fiducialsPointSet = mitk::PointSet::New(); fiducialsNode->SetData(fiducialsPointSet); fiducialsNode->SetName( label ); fiducialsNode->SetColor( color ); fiducialsNode->SetBoolProperty( "updateDataOnRender", false ); return fiducialsNode; } void QmitkIGTTrackingLabView::ChangeToolRepresentation( int toolID , mitk::Surface::Pointer surface ) { mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "Can not access DataStorage. Changing tool representation not possible!"); return; } mitk::TrackingDevice::Pointer tracker = m_NDIConfigWidget->GetTracker(); if(tracker.IsNull()) { QMessageBox::warning(NULL, "IGTSurfaceTracker: Error", "Can not access Tracker. Changing tool representation not possible!"); return; } try { const char* name = tracker->GetTool(toolID)->GetToolName(); // get tool name by id mitk::DataNode::Pointer toolNode = ds->GetNamedNode(name); if(toolNode.IsNull()) return; toolNode->SetData(surface); // change surface representation of node toolNode->SetColor(0.45,0.70,0.85); //light blue like old 5D sensors toolNode->Modified(); m_Visualizer->SetRepresentationObject( toolID, toolNode->GetData()); // updating node with changed surface back in visualizer mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } catch(std::exception& e) { QMessageBox::warning(NULL, QString("IGTSurfaceTracker: Error"), QString("Can not change tool representation!").arg(e.what())); return; } } QWidget* QmitkIGTTrackingLabView::CreatePointSetRecordingWidget(QWidget* parent) { QWidget* pointSetRecordingWidget = new QWidget(parent); m_PSRecToolSelectionComboBox = new QComboBox(pointSetRecordingWidget); m_PSRecordingSpinBox = new QSpinBox(pointSetRecordingWidget); QLabel* psRecordingEpsilonDistance = new QLabel("mm (point distance)", pointSetRecordingWidget); // the recording button m_PointSetRecordPushButton = new QPushButton("Start PointSet Recording", pointSetRecordingWidget); m_PointSetRecordPushButton->setDisabled(true); m_PointSetRecordPushButton->setIcon(QIcon(":/QmitkQmitkIGTTrackingLabView/start_rec.png")); m_PointSetRecordPushButton->setCheckable(true); connect( m_PointSetRecordPushButton, SIGNAL(toggled(bool)), this, SLOT(OnPointSetRecording(bool)) ); // distances spin m_PSRecordingSpinBox->setValue(1); m_PSRecordingSpinBox->setMinimum(1); m_PSRecordingSpinBox->setMaximum(20); QLabel* toolSelectLabel = new QLabel("Select tool for recording:", pointSetRecordingWidget); QGridLayout* layout = new QGridLayout(pointSetRecordingWidget); int row = 0; int col = 0; layout->addWidget(toolSelectLabel,row,col++,1,1,Qt::AlignRight); layout->addWidget(m_PSRecToolSelectionComboBox,row,col++,1,3,Qt::AlignLeft); col +=2; layout->addWidget(m_PSRecordingSpinBox,row,col++,1,1,Qt::AlignRight); layout->addWidget(psRecordingEpsilonDistance, row, col++,1,1,Qt::AlignLeft); row++; col=4; layout->addWidget(m_PointSetRecordPushButton,row,col++,1,2,Qt::AlignRight); return pointSetRecordingWidget; } void QmitkIGTTrackingLabView::OnPointSetRecording(bool record) { mitk::DataStorage* ds = this->GetDefaultDataStorage(); if(ds == NULL) return; if(record) { mitk::DataNode::Pointer psRecND = ds->GetNamedNode(m_PointSetRecordingDataNodeName); if(m_PSRecordingPointSet.IsNull() || psRecND.IsNull()) { m_PSRecordingPointSet = NULL; m_PSRecordingPointSet = mitk::PointSet::New(); mitk::DataNode::Pointer dn = mitk::DataNode::New(); dn->SetName(m_PointSetRecordingDataNodeName); dn->SetColor(0.,1.,0.); dn->SetData(m_PSRecordingPointSet); ds->Add(dn); } else m_PSRecordingPointSet->Clear(); m_PointSetRecording = true; m_PointSetRecordPushButton->setText("Stop PointSet Recording"); m_PSRecToolSelectionComboBox->setDisabled(true); } else { m_PointSetRecording = false; m_PointSetRecordPushButton->setText("Start PointSet Recording"); m_PSRecToolSelectionComboBox->setEnabled(true); } } void QmitkIGTTrackingLabView::DestroyInstrumentVisualization(mitk::DataStorage* ds, mitk::TrackingDevice::Pointer tracker) { if(ds == NULL || tracker.IsNull()) return; for(int i=0; i < tracker->GetToolCount(); ++i) { mitk::DataNode::Pointer dn = ds->GetNamedNode(tracker->GetTool(i)->GetToolName()); if(dn.IsNotNull()) ds->Remove(dn); } } void QmitkIGTTrackingLabView::GlobalReinit() { // request global reiinit mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); //global reinit end } void QmitkIGTTrackingLabView::OnVirtualCamera(int toolNr, bool on) { if(m_VirtualView.IsNull() || m_FiducialRegistrationFilter.IsNull()) return; if(on) { m_VirtualView->SetInput(m_FiducialRegistrationFilter->GetOutput(toolNr)); this->GetActiveStdMultiWidget()->SetWidgetPlaneModeToRotation(true); } else this->GetActiveStdMultiWidget()->SetWidgetPlaneModeToSlicing(true); } void QmitkIGTTrackingLabView::OnPermanentRegistration(int toolID, bool on) { if (m_PermanentRegistrationFilter.IsNull() || m_FiducialRegistrationFilter.IsNull()) return; if(on) { if(m_PermanentRegistrationSourcePoints.IsNull()) m_PermanentRegistrationSourcePoints = mitk::PointSet::New(); // interconnectiong permanent registration filter between tracking source and fiducial registration filter for(unsigned int i=0; i < m_Source->GetNumberOfOutputs(); ++i) { m_PermanentRegistrationFilter->SetInput(i,m_Source->GetOutput(i)); m_FiducialRegistrationFilter->SetInput(i,m_PermanentRegistrationFilter->GetOutput(i)); } mitk::NavigationData::Pointer nd = m_Source->GetOutput((unsigned int) toolID); m_PermanentRegistrationFilter->SetTargetLandmarks(this->GetVirtualPointSetFromPosition(nd)); } else { for(unsigned int i=0; i < m_FiducialRegistrationFilter->GetNumberOfOutputs(); ++i) m_FiducialRegistrationFilter->SetInput(i,m_Source->GetOutput()); } } mitk::PointSet::Pointer QmitkIGTTrackingLabView::GetVirtualPointSetFromPosition(mitk::NavigationData::Pointer navigationData) { typedef itk::QuaternionRigidTransform QuaternionTransformType; mitk::NavigationData::PositionType pointA; mitk::NavigationData::PositionType pointB; mitk::NavigationData::PositionType pointC; //initializing three points with position(0|0|0) pointA.Fill(0); pointB.Fill(0); pointC.Fill(0); // changing position off all points in order to make them orthogonal pointA[0] = 1; pointB[1] = 1; pointC[2] = 1; QuaternionTransformType::Pointer quatTransform = QuaternionTransformType::New(); // orientation of NavigationData from parameter mitk::NavigationData::OrientationType quatIn = navigationData->GetOrientation(); // set orientation to quaternion transform vnl_quaternion const vnlQuatIn(quatIn.x(), quatIn.y(), quatIn.z(), quatIn.r()); quatTransform->SetRotation(vnlQuatIn); // transform each point pointA = quatTransform->TransformPoint(pointA); pointB = quatTransform->TransformPoint(pointB); pointC = quatTransform->TransformPoint(pointC); // add position data from NavigationData parameter to each point pointA[0] += navigationData->GetPosition()[0]; pointA[1] += navigationData->GetPosition()[1]; pointA[2] += navigationData->GetPosition()[2]; pointB[0] += navigationData->GetPosition()[0]; pointB[1] += navigationData->GetPosition()[1]; pointB[2] += navigationData->GetPosition()[2]; pointC[0] += navigationData->GetPosition()[0]; pointC[1] += navigationData->GetPosition()[1]; pointC[2] += navigationData->GetPosition()[2]; // insert points in source points pointset for the permanent registration landmark transform m_PermanentRegistrationSourcePoints->InsertPoint(0,pointA); m_PermanentRegistrationSourcePoints->InsertPoint(1,pointB); m_PermanentRegistrationSourcePoints->InsertPoint(2,pointC); return m_PermanentRegistrationSourcePoints; } diff --git a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.h b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.h index 33392fe823..db4c0f6fdd 100644 --- a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.h +++ b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTrackingLabView.h @@ -1,268 +1,267 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkIGTTrackingLabView_h #define QmitkIGTTrackingLabView_h #include #include #include "ui_QmitkIGTTrackingLabViewControls.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include class QmitkNDIConfigurationWidget; class QmitkFiducialRegistrationWidget; class QmitkUpdateTimerWidget; class QmitkToolSelectionWidget; class QmitkToolTrackingStatusWidget; /*! \brief QmitkIGTTrackingLabView \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup ${plugin_target}_internal */ class QmitkIGTTrackingLabView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; /** \brief default constructor */ QmitkIGTTrackingLabView(); /** \brief default destructor */ virtual ~QmitkIGTTrackingLabView(); virtual void CreateQtPartControl(QWidget *parent); protected slots: /** \brief This method adds a new fiducial to the tracker fiducials PointSet. */ void OnAddRegistrationTrackingFiducial(); /** \brief This method calls the fiducial registration. */ void OnRegisterFiducials(); /** \brief This method should be called if deconnecting the tracker. */ void OnTrackerDisconnected(); /** \brief This method sets up the navigation pipeline before tracking is started. */ void OnSetupNavigation(); /** \brief This method changes the name of a specific tool. */ void OnChangeToolName(int index, QString name); /** \brief This method creates the surface representation for a tool loaded from file. */ void OnToolLoaded(int index, mitk::DataNode::Pointer toolNode); /** \brief This method starts the navigation. */ void OnStartNavigation(); /** \brief This method stops the navigation. */ void OnStopNavigation(); /** \brief This method performs the visualisation of all NavigationDatas and performs the PointSet recording if activated. */ void RenderScene(); /** \brief This method should be called if new tools have been added to the tracking device. */ void OnToolsAdded(QStringList toolsList); /** \brief This method reacts on toolbox item changes. */ void OnToolBoxCurrentChanged(int index); /** \brief This method initializes the registration for the FiducialRegistrationWidget. */ void InitializeRegistration(); /** \brief This method reacts on tool surface changes. */ void ChangeToolRepresentation( int toolID , mitk::Surface::Pointer surface ); /** \brief This method starts the PointSet recording. */ void OnPointSetRecording(bool record); /** \brief This method activates the virtual camera. */ void OnVirtualCamera(int toolNr, bool on); /** \brief This method activates the permanent registration based on one tool's position. */ void OnPermanentRegistration(int toolID, bool on); protected: enum ToolBoxElement // enums for the different ToolBox item tabs. { NDIConfigurationWidget = 0, RegistrationWidget = 1, PermanentRecording = 2, PointSetRecording = 3, VirtualCamera = 4 }; Ui::QmitkIGTTrackingLabViewControls m_Controls; /** \brief This method creates all widgets this bundle needs. */ void CreateBundleWidgets( QWidget* parent ); /** \brief This method creates the SIGNAL SLOT connections. */ void CreateConnections(); /** \brief This method sets up the filter pipeline. */ void SetupIGTPipeline(); /** \brief This method initializes all needed filters. */ void InitializeFilters(); /** \brief This method destroys the filter pipeline. */ void DestroyIGTPipeline(); /** \brief This method starts the continuos update of the tracking device and the rendering. */ void StartContinuousUpdate(); /** \brief This method stops the continuos update of the tracking device and the rendering. */ void StopContinuousUpdate(); /** \brief This method creates a DataNode for fiducial PointSets. */ mitk::DataNode::Pointer CreateRegistrationFiducialsNode( const std::string& label, const mitk::Color& color); /** \brief This method creates the visualization for all connected instruments. */ mitk::DataNode::Pointer CreateInstrumentVisualization(mitk::DataStorage* ds, const char* toolName); // create 3D models for all connected tools /** \brief This method creates a DataNode of a 3D cone object. */ mitk::DataNode::Pointer CreateConeRepresentation(const char* label = ""); // create a 3D cone as representation for a tool /** \brief This method destroys the instrument visualization. */ void DestroyInstrumentVisualization(mitk::DataStorage* ds, mitk::TrackingDevice::Pointer tracker); /** \brief This method creates a widget with all input objects needed for the PointSet recording. */ QWidget* CreatePointSetRecordingWidget(QWidget* parent); /** \brief This method returns a PointSet with three vritual points transformed from the position and orientation of the given NavigationData. This method is needed to calculate the source points for permanent registration from one tool's position. */ mitk::PointSet::Pointer GetVirtualPointSetFromPosition(mitk::NavigationData::Pointer navigationData); mitk::TrackingDeviceSource::Pointer m_Source; ///< source that connects to the tracking device mitk::NavigationDataLandmarkTransformFilter::Pointer m_FiducialRegistrationFilter; ///< this filter transforms from tracking coordinates into mitk world coordinates mitk::NavigationDataLandmarkTransformFilter::Pointer m_PermanentRegistrationFilter; ///< this filter transforms from tracking coordinates into mitk world coordinates if needed it is interconnected before the FiducialEegistrationFilter mitk::NavigationDataObjectVisualizationFilter::Pointer m_Visualizer; ///< visualization filter mitk::CameraVisualization::Pointer m_VirtualView; ///< filter to update the vtk camera according to the reference navigation data mitk::Vector3D m_DirectionOfProjectionVector;///< vector for direction of projection of instruments private: QToolBox* m_ToolBox; QComboBox* m_PSRecToolSelectionComboBox; QSpinBox* m_PSRecordingSpinBox; QPushButton* m_PointSetRecordPushButton; mitk::PointSet::Pointer m_PSRecordingPointSet; QmitkNDIConfigurationWidget* m_NDIConfigWidget; // tracking device configuration widget QmitkFiducialRegistrationWidget* m_RegistrationWidget; // landmark registration widget QmitkUpdateTimerWidget* m_RenderingTimerWidget; // update timer widget for rendering and updating QmitkToolTrackingStatusWidget* m_ToolStatusWidget; // tracking status visualizer widget std::string m_RegistrationTrackingFiducialsName; std::string m_RegistrationImageFiducialsName; std::string m_PointSetRecordingDataNodeName; bool m_PointSetRecording; mitk::DataNode::Pointer m_ImageFiducialsDataNode; mitk::DataNode::Pointer m_TrackerFiducialsDataNode; QmitkToolSelectionWidget* m_PermanentRegistrationToolSelectionWidget; QmitkToolSelectionWidget* m_VirtualViewToolSelectionWidget; mitk::NavigationData::PositionType m_TargetPosition; mitk::NavigationData::OrientationType m_PermanentRegistrationInitialOrientation; mitk::PointSet::Pointer m_PermanentRegistrationSourcePoints; /** \brief This method performs GlobalReinit() for the rendering widgets. */ void GlobalReinit(); }; #endif // QmitkIGTTrackingLabView_h diff --git a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.cpp b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.cpp index 76bb3189a1..ad9710713b 100644 --- a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.cpp +++ b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.cpp @@ -1,241 +1,240 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ -Version: $Revision: 16719 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkIGTTutorialView.h" #include "QmitkStdMultiWidget.h" #include "QmitkStdMultiWidgetEditor.h" #include "mitkNDIPassiveTool.h" #include "mitkNDITrackingDevice.h" #include "mitkVirtualTrackingDevice.h" #include "mitkStandardFileLocations.h" #include "mitkSerialCommunication.h" #include "mitkCone.h" #include #include const std::string QmitkIGTTutorialView::VIEW_ID = "org.mitk.views.igttutorial"; QmitkIGTTutorialView::QmitkIGTTutorialView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_Source(NULL), m_Visualizer(NULL), m_Timer(NULL) { } QmitkIGTTutorialView::~QmitkIGTTutorialView() { } void QmitkIGTTutorialView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widget m_Controls = new Ui::QmitkIGTTutorialViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkIGTTutorialView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkIGTTutorialView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkIGTTutorialView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_StartButton), SIGNAL(clicked()),(QObject*) this, SLOT(OnStartIGT())); connect( (QObject*)(m_Controls->m_StopButton), SIGNAL(clicked()),(QObject*) this, SLOT(OnStopIGT())); } } void QmitkIGTTutorialView::Activated() { QmitkFunctionality::Activated(); } void QmitkIGTTutorialView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkIGTTutorialView::OnStartIGT() { //This method is called when the Do IGT button is pressed. Any kind of navigation application will //start with the connection to a tracking system and as we do image guided procedures we want to show //something on the screen. In this tutorial we connect to the NDI Polaris tracking system and we will //show the movement of a tool as cone in MITK. //Check if we have a widget for visualization. Makes no sense to start otherwise. //If there is no multiwidget, create one. //if (m_MultiWidget == NULL) //{ //} if (m_MultiWidget == NULL) // if creating the multiwidget failed, stop here. { QMessageBox::warning ( NULL, "Error", "Starting the tutorial is not possible without an initialized " "rendering widget. Please load a dataset first."); return; } try { /**************** Variant 1: Use a NDI Polaris Tracking Device ****************/ ////Here we want to use the NDI Polaris tracking device. Therefore we instantiate a object of the class ////NDITrackingDevice and make some settings which are necessary for a proper connection to the device. //mitk::NDITrackingDevice::Pointer tracker = mitk::NDITrackingDevice::New(); //instantiate //tracker->SetPortNumber(mitk::SerialCommunication::COM4); //set the comport //tracker->SetBaudRate(mitk::SerialCommunication::BaudRate115200); //set the baud rate //tracker->SetType(mitk::NDIPolaris); //set the type there you can choose between Polaris and Aurora ////The tools represent the sensors of the tracking device. In this case we have one pointer tool. ////The TrackingDevice object it self fills the tool with data. So we have to add the tool to the ////TrackingDevice object. //mitk::NDIPassiveTool::Pointer tool = mitk::NDIPassiveTool::New(); //tool->SetToolName("MyInstrument"); //Every tool should have a name. //tool->LoadSROMFile("c:\\myinstrument.rom"); //The Polaris system needs a ".rom" file which describes ////the geometry of the markers related to the tool tip. ////NDI provides an own software (NDI architect) to ////generate those files. ////tool->LoadSROMFile(mitk::StandardFileLocations::GetInstance()->FindFile("myToolDefinitionFile.srom").c_str()); //tracker->Add6DTool(tool); //Add the tool to the TrackingDevice object. /**************** End of Variant 1 ****************/ /**************** Variant 2: Emulate a Tracking Device with mitk::VirtualTrackingDevice ****************/ // For tests, it is useful to simulate a tracking device in software. This is what mitk::VirtualTrackingDevice does. // It will produce random position, orientation and error values for each tool that is added. mitk::VirtualTrackingDevice::Pointer tracker = mitk::VirtualTrackingDevice::New(); // create virtual tracker mitk::ScalarType bounds[] = {0.0, 200.0, 0.0, 200.0, 0.0, 200.0}; tracker->SetBounds(bounds); tracker->AddTool("MyInstrument"); // add a tool to tracker /**************** End of Variant 2 ****************/ //The tracking device object is used for the physical connection to the device. To use the //data inside of our tracking pipeline we need a source. This source encapsulate the tracking device //and provides objects of the type mitk::NavigationData as output. The NavigationData objects stores //position, orientation, if the data is valid or not and special error informations in a covariance //matrix. // //Typically the start of a pipeline is a TrackingDeviceSource. To work correct we have to set a //TrackingDevice object. Attention you have to set the tools before you set the whole TrackingDevice //object to the TrackingDeviceSource because the source need to know how many outputs should be //generated. m_Source = mitk::TrackingDeviceSource::New(); //We need the filter objects to stay alive, //therefore they must be members. m_Source->SetTrackingDevice(tracker); //Here we set the tracking device to the source of the pipeline. m_Source->Connect(); //Now we connect to the tracking system. //Note we do not call this on the TrackingDevice object //As we wish to visualize our tool we need to have a PolyData which shows us the movement of our tool. //Here we take a cone shaped PolyData. In MITK you have to add the PolyData as a node into the DataStorage //to show it inside of the rendering windows. After that you can change the properties of the cone //to manipulate rendering, e.g. the position and orientation as in our case. mitk::Cone::Pointer cone = mitk::Cone::New(); //instantiate a new cone float scale[] = {10.0, 10.0, 10.0}; cone->GetGeometry()->SetSpacing(scale); //scale it a little that so we can see something mitk::DataNode::Pointer node = mitk::DataNode::New(); //generate a new node to store the cone into //the DataStorage. node->SetData(cone); //The data of that node is our cone. node->SetName("My tracked object"); //The node has additional properties like a name node->SetColor(1.0, 0.0, 0.0); //or the color. Here we make it red. this->GetDefaultDataStorage()->Add(node); //After adding the Node with the cone in it to the //DataStorage, MITK will show the cone in the //render windows. //For updating the render windows we use another filter of the MITK-IGT pipeline concept. The //NavigationDataObjectVisualizationFilter needs as input a NavigationData and a //PolyData. In our case the input is the source and the PolyData our cone. //First we create a new filter for the visualization update. m_Visualizer = mitk::NavigationDataObjectVisualizationFilter::New(); m_Visualizer->SetInput(0, m_Source->GetOutput(0)); //Then we connect to the pipeline. m_Visualizer->SetRepresentationObject(0, cone); //After that we have to assign the cone to the input //Now this simple pipeline is ready, so we can start the tracking. Here again: We do not call the //StartTracking method from the tracker object itself. Instead we call this method from our source. m_Source->StartTracking(); //Now every call of m_Visualizer->Update() will show us the cone at the position and orientation //given from the tracking device. //We use a QTimer object to call this Update() method in a fixed interval. if (m_Timer == NULL) { m_Timer = new QTimer(this); //create a new timer } connect(m_Timer, SIGNAL(timeout()), this, SLOT(OnTimer())); //connect the timer to the method OnTimer() m_Timer->start(100); //Every 100ms the method OnTimer() is called. -> 10fps //Now have look at the OnTimer() method. } catch (std::exception& e) { // add cleanup std::cout << "Error in QmitkIGTTutorial::OnDoIGT():" << e.what() << std::endl; } } void QmitkIGTTutorialView::OnTimer() { //Here we call the Update() method from the Visualization Filter. Internally the filter checks if //new NavigationData is available. If we have a new NavigationData the cone position and orientation //will be adapted. m_Visualizer->Update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //update the render windows } void QmitkIGTTutorialView::OnStopIGT() { //This method is called when the Stop button is pressed. Here we disconnect the pipeline. if (m_Timer == NULL) { std::cout << "No Timer was set yet!" << std::endl; return; } //To disconnect the pipeline in a save way we first stop the timer than we disconnect the tracking device. //After that we destroy all filters with changing them to NULL. m_Timer->stop(); disconnect(m_Timer, SIGNAL(timeout()), this, SLOT(OnTimer())); m_Timer = NULL; m_Source->StopTracking(); m_Source->Disconnect(); m_Source = NULL; m_Visualizer = NULL; m_Source = NULL; this->GetDefaultDataStorage()->Remove(this->GetDefaultDataStorage()->GetNamedNode("My tracked object")); } diff --git a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.h b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.h index 1f254e1c70..49d85861d7 100644 --- a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.h +++ b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/QmitkIGTTutorialView.h @@ -1,106 +1,105 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ -Version: $Revision: 16719 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKIGTTUTORIALVIEW_H_INCLUDED #define _QMITKIGTTUTORIALVIEW_H_INCLUDED #include #include #include "ui_QmitkIGTTutorialViewControls.h" //#include "../IgttutorialDll.h" #include "mitkTrackingDeviceSource.h" #include "mitkNavigationDataObjectVisualizationFilter.h" /** * \brief QmitkIGTTutorial shows a small typically navigation MITK functionality. * * Any kind of navigation application will start with the connection to a tracking system * and as we do image guided procedures we want to show something on the screen. In this * tutorial we connect to the NDI Polaris tracking system (or alternatively use a virtual tracking device) * and we will show the movement of a tool as cone in the StdMultiWidget editor. * * \sa also take a look at the CMakeLists.txt of this functionality to see how to * link to the mitkIGT library. * \sa QmitkFunctionality * \ingroup Functionalities */ class QmitkIGTTutorialView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkIGTTutorialView(); QmitkIGTTutorialView(const QmitkIGTTutorialView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkIGTTutorialView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /** * \brief Execute MITK-IGT Tutorial */ void OnStartIGT(); /** * \brief stop IGT scene and clean up */ void OnStopIGT(); /** * \brief timer based update of IGT scene */ void OnTimer(); protected: Ui::QmitkIGTTutorialViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; ///< our display widget mitk::TrackingDeviceSource::Pointer m_Source; ///< source filer that connects to the tracking device mitk::NavigationDataObjectVisualizationFilter::Pointer m_Visualizer; ///< visualization filter uses output from m_Source QTimer* m_Timer; ///< timer for continuous tracking update }; #endif // _QMITKIGTTUTORIALVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.cpp b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.cpp index 093d1f1b97..66fe554047 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.cpp +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.cpp @@ -1,70 +1,69 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkMITKIGTNavigationToolManagerView.h" #include "QmitkStdMultiWidget.h" // Qt #include const std::string QmitkMITKIGTNavigationToolManagerView::VIEW_ID = "org.mitk.views.mitkigtnavigationtoolmanager"; QmitkMITKIGTNavigationToolManagerView::QmitkMITKIGTNavigationToolManagerView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkMITKIGTNavigationToolManagerView::~QmitkMITKIGTNavigationToolManagerView() { } void QmitkMITKIGTNavigationToolManagerView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkMITKIGTNavigationToolManagerViewControls; m_Controls->setupUi( parent ); } m_Controls->m_toolManagerWidget->Initialize(this->GetDataStorage()); } void QmitkMITKIGTNavigationToolManagerView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkMITKIGTNavigationToolManagerView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.h b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.h index a4519122ca..12e70670de 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.h +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTNavigationToolManagerView.h @@ -1,71 +1,70 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkMITKIGTNavigationToolManagerView_h #define QmitkMITKIGTNavigationToolManagerView_h #include #include #include "ui_QmitkMITKIGTNavigationToolManagerViewControls.h" /*! \brief QmitkMITKIGTNavigationToolManagerView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkMITKIGTNavigationToolManagerView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkMITKIGTNavigationToolManagerView(); QmitkMITKIGTNavigationToolManagerView(const QmitkMITKIGTNavigationToolManagerView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkMITKIGTNavigationToolManagerView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: protected: Ui::QmitkMITKIGTNavigationToolManagerViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; }; #endif // _QMITKMITKIGTNAVIGATIONTOOLMANAGERVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp index 08a7cbe78c..53a3a06517 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp @@ -1,567 +1,566 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkMITKIGTTrackingToolboxView.h" #include "QmitkStdMultiWidget.h" // Qt #include #include // MITK #include #include #include #include #include #include #include // vtk #include const std::string QmitkMITKIGTTrackingToolboxView::VIEW_ID = "org.mitk.views.mitkigttrackingtoolbox"; QmitkMITKIGTTrackingToolboxView::QmitkMITKIGTTrackingToolboxView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { m_TrackingTimer = new QTimer(this); m_tracking = false; m_logging = false; m_loggedFrames = 0; } QmitkMITKIGTTrackingToolboxView::~QmitkMITKIGTTrackingToolboxView() { //remove the tracking volume this->GetDataStorage()->Remove(m_TrackingVolumeNode); } void QmitkMITKIGTTrackingToolboxView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkMITKIGTTrackingToolboxViewControls; m_Controls->setupUi( parent ); //create connections connect( m_Controls->m_LoadTools, SIGNAL(clicked()), this, SLOT(OnLoadTools()) ); connect( m_Controls->m_StartTracking, SIGNAL(clicked()), this, SLOT(OnStartTracking()) ); connect( m_Controls->m_StopTracking, SIGNAL(clicked()), this, SLOT(OnStopTracking()) ); connect( m_TrackingTimer, SIGNAL(timeout()), this, SLOT(UpdateTrackingTimer())); connect( m_Controls->m_ChooseFile, SIGNAL(clicked()), this, SLOT(OnChooseFileClicked())); connect( m_Controls->m_StartLogging, SIGNAL(clicked()), this, SLOT(StartLogging())); connect( m_Controls->m_StopLogging, SIGNAL(clicked()), this, SLOT(StopLogging())); connect( m_Controls->m_configurationWidget, SIGNAL(TrackingDeviceSelectionChanged()), this, SLOT(OnTrackingDeviceChanged())); connect( m_Controls->m_VolumeSelectionBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(OnTrackingVolumeChanged(QString))); connect( m_Controls->m_ShowTrackingVolume, SIGNAL(clicked()), this, SLOT(OnShowTrackingVolumeChanged())); connect( m_Controls->m_AutoDetectTools, SIGNAL(clicked()), this, SLOT(OnAutoDetectTools())); connect( m_Controls->m_ResetTools, SIGNAL(clicked()), this, SLOT(OnResetTools())); connect( m_Controls->m_AddSingleTool, SIGNAL(clicked()), this, SLOT(OnAddSingleTool())); connect( m_Controls->m_NavigationToolCreationWidget, SIGNAL(NavigationToolFinished()), this, SLOT(OnAddSingleToolFinished())); connect( m_Controls->m_NavigationToolCreationWidget, SIGNAL(Canceled()), this, SLOT(OnAddSingleToolCanceled())); //initialize widgets m_Controls->m_configurationWidget->EnableAdvancedUserControl(false); m_Controls->m_TrackingToolsStatusWidget->SetShowPositions(true); m_Controls->m_TrackingToolsStatusWidget->SetTextAlignment(Qt::AlignLeft); //initialize tracking volume node m_TrackingVolumeNode = mitk::DataNode::New(); m_TrackingVolumeNode->SetName("TrackingVolume"); m_TrackingVolumeNode->SetOpacity(0.25); m_TrackingVolumeNode->SetBoolProperty("Backface Culling",true); mitk::Color red; red.SetRed(1); m_TrackingVolumeNode->SetColor(red); GetDataStorage()->Add(m_TrackingVolumeNode); //initialize buttons m_Controls->m_StopTracking->setEnabled(false); m_Controls->m_StopLogging->setEnabled(false); m_Controls->m_AutoDetectTools->setVisible(false); //only visible if tracking device is Aurora //Update List of available models for selected tool. std::vector Compatibles = mitk::GetDeviceDataForLine( m_Controls->m_configurationWidget->GetTrackingDevice()->GetType()); m_Controls->m_VolumeSelectionBox->clear(); for(int i = 0; i < Compatibles.size(); i++) { m_Controls->m_VolumeSelectionBox->addItem(Compatibles[i].Model.c_str()); } } } void QmitkMITKIGTTrackingToolboxView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkMITKIGTTrackingToolboxView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkMITKIGTTrackingToolboxView::OnLoadTools() { //read in filename QString filename = QFileDialog::getOpenFileName(NULL,tr("Open Toolfile"), "/", tr("All Files (*.*)")); //later perhaps: tr("Toolfile (*.tfl)" if (filename.isNull()) return; //read tool storage from disk std::string errorMessage = ""; mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(GetDataStorage()); m_toolStorage = myDeserializer->Deserialize(filename.toStdString()); if(m_toolStorage->isEmpty()) { errorMessage = myDeserializer->GetErrorMessage(); MessageBox(errorMessage); return; } //update label Poco::Path myPath = Poco::Path(filename.toStdString()); //use this to seperate filename from path QString toolLabel = QString("Loaded Tools: ") + QString::number(m_toolStorage->GetToolCount()) + " Tools from " + myPath.getFileName().c_str(); m_Controls->m_toolLabel->setText(toolLabel); //update tool preview m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); } void QmitkMITKIGTTrackingToolboxView::OnResetTools() { m_toolStorage = NULL; m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); QString toolLabel = QString("Loaded Tools: "); m_Controls->m_toolLabel->setText(toolLabel); } void QmitkMITKIGTTrackingToolboxView::OnStartTracking() { //check if everything is ready to start tracking if (this->m_toolStorage.IsNull()) { MessageBox("Error: No Tools Loaded Yet!"); return; } else if (this->m_toolStorage->GetToolCount() == 0) { MessageBox("Error: No Way To Track Without Tools!"); return; } //build the IGT pipeline mitk::TrackingDevice::Pointer trackingDevice = this->m_Controls->m_configurationWidget->GetTrackingDevice(); //Get Tracking Volume Data mitk::TrackingDeviceData data = mitk::DeviceDataUnspecified; QString qstr = m_Controls->m_VolumeSelectionBox->currentText(); if ( (! qstr.isNull()) || (! qstr.isEmpty()) ) { std::string str = qstr.toStdString(); data = mitk::GetDeviceDataByName(str); //Data will be set later, after device generation } mitk::TrackingDeviceSourceConfigurator::Pointer myTrackingDeviceSourceFactory = mitk::TrackingDeviceSourceConfigurator::New(this->m_toolStorage,trackingDevice); m_TrackingDeviceSource = myTrackingDeviceSourceFactory->CreateTrackingDeviceSource(this->m_ToolVisualizationFilter); if (m_TrackingDeviceSource.IsNull()) { MessageBox(myTrackingDeviceSourceFactory->GetErrorMessage()); return; } //disable Buttons m_Controls->m_StopTracking->setEnabled(true); m_Controls->m_StartTracking->setEnabled(false); DisableOptionsButtons(); DisableTrackingConfigurationButtons(); //initialize tracking try { m_TrackingDeviceSource->Connect(); m_TrackingDeviceSource->StartTracking(); } catch (...) { MessageBox("Error while starting the tracking device!"); //enable Buttons m_Controls->m_StopTracking->setEnabled(false); m_Controls->m_StartTracking->setEnabled(true); EnableOptionsButtons(); EnableTrackingConfigurationButtons(); return; } m_TrackingTimer->start(1000/(m_Controls->m_UpdateRate->value())); m_Controls->m_TrackingControlLabel->setText("Status: tracking"); //connect the tool visualization widget for(int i=0; iGetNumberOfOutputs(); i++) { m_Controls->m_TrackingToolsStatusWidget->AddNavigationData(m_TrackingDeviceSource->GetOutput(i)); } m_Controls->m_TrackingToolsStatusWidget->ShowStatusLabels(); if (m_Controls->m_ShowToolQuaternions->isChecked()) {m_Controls->m_TrackingToolsStatusWidget->SetShowQuaternions(true);} else {m_Controls->m_TrackingToolsStatusWidget->SetShowQuaternions(false);} //set configuration finished this->m_Controls->m_configurationWidget->ConfigurationFinished(); //show tracking volume this->OnTrackingVolumeChanged(m_Controls->m_VolumeSelectionBox->currentText()); m_tracking = true; this->GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnStopTracking() { if (!m_tracking) return; m_TrackingTimer->stop(); m_TrackingDeviceSource->StopTracking(); m_TrackingDeviceSource->Disconnect(); this->m_Controls->m_configurationWidget->Reset(); m_Controls->m_TrackingControlLabel->setText("Status: stopped"); if (m_logging) StopLogging(); m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); m_tracking = false; //enable Buttons m_Controls->m_StopTracking->setEnabled(false); m_Controls->m_StartTracking->setEnabled(true); EnableOptionsButtons(); EnableTrackingConfigurationButtons(); this->GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnTrackingDeviceChanged() { mitk::TrackingDeviceType Type = m_Controls->m_configurationWidget->GetTrackingDevice()->GetType(); // Code to enable/disable device specific buttons if (Type == mitk::NDIAurora) //Aurora { m_Controls->m_AutoDetectTools->setVisible(true); m_Controls->m_AddSingleTool->setEnabled(false); } else //Polaris or Microntracker { m_Controls->m_AutoDetectTools->setVisible(false); m_Controls->m_AddSingleTool->setEnabled(true); } // Code to select appropriate tracking volume for current type std::vector Compatibles = mitk::GetDeviceDataForLine(Type); m_Controls->m_VolumeSelectionBox->clear(); for(int i = 0; i < Compatibles.size(); i++) { m_Controls->m_VolumeSelectionBox->addItem(Compatibles[i].Model.c_str()); } } void QmitkMITKIGTTrackingToolboxView::OnTrackingVolumeChanged(QString qstr) { if (qstr.isNull()) return; if (qstr.isEmpty()) return; if (m_Controls->m_ShowTrackingVolume->isChecked()) { mitk::TrackingVolumeGenerator::Pointer volumeGenerator = mitk::TrackingVolumeGenerator::New(); std::string str = qstr.toStdString(); mitk::TrackingDeviceData data = mitk::GetDeviceDataByName(str); volumeGenerator->SetTrackingDeviceData(data); volumeGenerator->Update(); mitk::Surface::Pointer volumeSurface = volumeGenerator->GetOutput(); m_TrackingVolumeNode->SetData(volumeSurface); GlobalReinit(); } } void QmitkMITKIGTTrackingToolboxView::OnShowTrackingVolumeChanged() { if (m_Controls->m_ShowTrackingVolume->isChecked()) { OnTrackingVolumeChanged(m_Controls->m_VolumeSelectionBox->currentText()); GetDataStorage()->Add(m_TrackingVolumeNode); } else { GetDataStorage()->Remove(m_TrackingVolumeNode); GlobalReinit(); } } void QmitkMITKIGTTrackingToolboxView::OnAutoDetectTools() { if (m_Controls->m_configurationWidget->GetTrackingDevice()->GetType() == mitk::NDIAurora) { DisableTrackingConfigurationButtons(); mitk::NDITrackingDevice::Pointer currentDevice = dynamic_cast(m_Controls->m_configurationWidget->GetTrackingDevice().GetPointer()); currentDevice->OpenConnection(); currentDevice->StartTracking(); mitk::NavigationToolStorage::Pointer autoDetectedStorage = mitk::NavigationToolStorage::New(this->GetDataStorage()); for (int i=0; iGetToolCount(); i++) { //create a navigation tool with sphere as surface std::stringstream toolname; toolname << "AutoDetectedTool" << i; mitk::NavigationTool::Pointer newTool = mitk::NavigationTool::New(); newTool->SetSerialNumber(dynamic_cast(currentDevice->GetTool(i))->GetSerialNumber()); newTool->SetIdentifier(toolname.str()); newTool->SetTrackingDeviceType(mitk::NDIAurora); mitk::DataNode::Pointer newNode = mitk::DataNode::New(); mitk::Surface::Pointer mySphere = mitk::Surface::New(); vtkSphereSource *vtkData = vtkSphereSource::New(); vtkData->SetRadius(3.0f); vtkData->SetCenter(0.0, 0.0, 0.0); vtkData->Update(); mySphere->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); newNode->SetData(mySphere); newNode->SetName(toolname.str()); newTool->SetDataNode(newNode); autoDetectedStorage->AddTool(newTool); } //save detected tools m_toolStorage = autoDetectedStorage; //update label QString toolLabel = QString("Loaded Tools: ") + QString::number(m_toolStorage->GetToolCount()) + " Tools (Auto Detected)"; m_Controls->m_toolLabel->setText(toolLabel); //update tool preview m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); currentDevice->StopTracking(); currentDevice->CloseConnection(); EnableTrackingConfigurationButtons(); if (m_toolStorage->GetToolCount()>0) { //ask the user if he wants to save the detected tools QMessageBox msgBox; msgBox.setText("Found " + QString::number(m_toolStorage->GetToolCount()) + " tools!"); msgBox.setInformativeText("Do you want to save this tools as tool storage, so you can load them again?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); if (ret == 16384) //yes { //ask the user for a filename QString fileName = QFileDialog::getSaveFileName(NULL, tr("Save File"),"",tr("*.*")); mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New(); if (!mySerializer->Serialize(fileName.toStdString(),m_toolStorage)) MessageBox(mySerializer->GetErrorMessage()); return; } else if (ret == 65536) //no { return; } } } } void QmitkMITKIGTTrackingToolboxView::MessageBox(std::string s) { QMessageBox msgBox; msgBox.setText(s.c_str()); msgBox.exec(); } void QmitkMITKIGTTrackingToolboxView::UpdateTrackingTimer() { m_ToolVisualizationFilter->Update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if (m_logging) { this->m_loggingFilter->Update(); m_loggedFrames = this->m_loggingFilter->GetRecordCounter(); this->m_Controls->m_LoggedFramesLabel->setText("Logged Frames: "+QString::number(m_loggedFrames)); //check if logging stopped automatically if((m_loggedFrames>1)&&(!m_loggingFilter->GetRecording())){StopLogging();} } m_Controls->m_TrackingToolsStatusWidget->Refresh(); } void QmitkMITKIGTTrackingToolboxView::OnChooseFileClicked() { QString filename = QFileDialog::getSaveFileName(NULL,tr("Choose Logging File"), "/", "*.*"); if (filename == "") return; this->m_Controls->m_LoggingFileName->setText(filename); } void QmitkMITKIGTTrackingToolboxView::StartLogging() { if (!m_logging) { //initialize logging filter m_loggingFilter = mitk::NavigationDataRecorder::New(); m_loggingFilter->SetRecordingMode(mitk::NavigationDataRecorder::NormalFile); if (m_Controls->m_xmlFormat->isChecked()) m_loggingFilter->SetOutputFormat(mitk::NavigationDataRecorder::xml); else if (m_Controls->m_csvFormat->isChecked()) m_loggingFilter->SetOutputFormat(mitk::NavigationDataRecorder::csv); m_loggingFilter->SetFileName(m_Controls->m_LoggingFileName->text().toStdString().c_str()); if (m_Controls->m_LoggingLimit->isChecked()){m_loggingFilter->SetRecordCountLimit(m_Controls->m_LoggedFramesLimit->value());} //connect filter for(int i=0; iGetNumberOfOutputs(); i++){m_loggingFilter->AddNavigationData(m_ToolVisualizationFilter->GetOutput(i));} //start filter m_loggingFilter->StartRecording(); //update labels / logging variables this->m_Controls->m_LoggingLabel->setText("Logging ON"); this->m_Controls->m_LoggedFramesLabel->setText("Logged Frames: 0"); m_loggedFrames = 0; m_logging = true; DisableLoggingButtons(); } } void QmitkMITKIGTTrackingToolboxView::StopLogging() { if (m_logging) { //update label this->m_Controls->m_LoggingLabel->setText("Logging OFF"); m_loggingFilter->StopRecording(); m_logging = false; EnableLoggingButtons(); } } void QmitkMITKIGTTrackingToolboxView::OnAddSingleTool() { QString Identifier = "Tool#"; if (m_toolStorage.IsNotNull()) Identifier += QString::number(m_toolStorage->GetToolCount()); else Identifier += "0"; m_Controls->m_NavigationToolCreationWidget->Initialize(GetDataStorage(),Identifier.toStdString()); m_Controls->m_NavigationToolCreationWidget->SetTrackingDeviceType(m_Controls->m_configurationWidget->GetTrackingDevice()->GetType(),false); m_Controls->m_TrackingToolsWidget->setCurrentIndex(1); } void QmitkMITKIGTTrackingToolboxView::OnAddSingleToolFinished() { m_Controls->m_TrackingToolsWidget->setCurrentIndex(0); if (this->m_toolStorage.IsNull()) m_toolStorage = mitk::NavigationToolStorage::New(GetDataStorage()); m_toolStorage->AddTool(m_Controls->m_NavigationToolCreationWidget->GetCreatedTool()); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); QString toolLabel = QString("Loaded Tools: "); } void QmitkMITKIGTTrackingToolboxView::OnAddSingleToolCanceled() { m_Controls->m_TrackingToolsWidget->setCurrentIndex(0); } void QmitkMITKIGTTrackingToolboxView::GlobalReinit() { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } void QmitkMITKIGTTrackingToolboxView::DisableLoggingButtons() { m_Controls->m_StartLogging->setEnabled(false); m_Controls->m_LoggingFileName->setEnabled(false); m_Controls->m_ChooseFile->setEnabled(false); m_Controls->m_LoggingLimit->setEnabled(false); m_Controls->m_LoggedFramesLimit->setEnabled(false); m_Controls->m_csvFormat->setEnabled(false); m_Controls->m_xmlFormat->setEnabled(false); m_Controls->m_StopLogging->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::EnableLoggingButtons() { m_Controls->m_StartLogging->setEnabled(true); m_Controls->m_LoggingFileName->setEnabled(true); m_Controls->m_ChooseFile->setEnabled(true); m_Controls->m_LoggingLimit->setEnabled(true); m_Controls->m_LoggedFramesLimit->setEnabled(true); m_Controls->m_csvFormat->setEnabled(true); m_Controls->m_xmlFormat->setEnabled(true); m_Controls->m_StopLogging->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::DisableOptionsButtons() { m_Controls->m_ShowTrackingVolume->setEnabled(false); m_Controls->m_UpdateRate->setEnabled(false); m_Controls->m_ShowToolQuaternions->setEnabled(false); m_Controls->m_OptionsUpdateRateLabel->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::EnableOptionsButtons() { m_Controls->m_ShowTrackingVolume->setEnabled(true); m_Controls->m_UpdateRate->setEnabled(true); m_Controls->m_ShowToolQuaternions->setEnabled(true); m_Controls->m_OptionsUpdateRateLabel->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::EnableTrackingConfigurationButtons() { m_Controls->m_AutoDetectTools->setEnabled(true); if (m_Controls->m_configurationWidget->GetTrackingDevice()->GetType() != mitk::NDIAurora) m_Controls->m_AddSingleTool->setEnabled(true); m_Controls->m_LoadTools->setEnabled(true); m_Controls->m_ResetTools->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::DisableTrackingConfigurationButtons() { m_Controls->m_AutoDetectTools->setEnabled(false); if (m_Controls->m_configurationWidget->GetTrackingDevice()->GetType() != mitk::NDIAurora) m_Controls->m_AddSingleTool->setEnabled(false); m_Controls->m_LoadTools->setEnabled(false); m_Controls->m_ResetTools->setEnabled(false); } diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h index 378fd25e80..1468052c2a 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h @@ -1,162 +1,161 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkMITKIGTTrackingToolboxView_h #define QmitkMITKIGTTrackingToolboxView_h #include #include #include "ui_QmitkMITKIGTTrackingToolboxViewControls.h" //mitk headers #include #include #include #include //QT headers #include /*! \brief QmitkMITKIGTTrackingToolboxView This is the view of the bundle IGT Tracking Toolbox. The IGT Tracking Toolbox can be used to access tracking devices with MITK-IGT. The Tracking Toolbox can be used to log tracking data in XML or CSV format for measurement purposes. The Tracking Toolbox further allows for visualization of tools with given surfaces in combination with the NaviagtionToolManager. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkMITKIGTTrackingToolboxView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkMITKIGTTrackingToolboxView(); QmitkMITKIGTTrackingToolboxView(const QmitkMITKIGTTrackingToolboxView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkMITKIGTTrackingToolboxView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /** @brief This slot is called if the user wants to load a new tool file. A new window opens where the user can choose a file. If the chosen file is corrupt or not valid the user gets an error message. If the file was loaded successfully the tools are show in the tool status widget. */ void OnLoadTools(); /** @brief This slot tries to start tracking with the current device. If start tracking fails the user gets an error message and tracking stays off.*/ void OnStartTracking(); /** @brief This slot stops tracking. If tracking is not strated it does nothing.*/ void OnStopTracking(); /** @brief This slot is called if the user want's to choose a file name for logging. A new windows to navigate through the file system and choose a file opens.*/ void OnChooseFileClicked(); /** @brief This slot starts logging. Logging is only possible if a device is tracking. If not the logging mechanism start when the start tracking is called.*/ void StartLogging(); /** @brief This slot stops logging. If logging is not running it does nothing.*/ void StopLogging(); /** @brief This slot enables / disables UI elements depending on the tracking device after a device is changed.*/ void OnTrackingDeviceChanged(); /** @brief This slot selects the Tracking Volume appropriate for a given model */ void OnTrackingVolumeChanged(QString qstr); /** @brief Shows or hides the tracking volume according to the checkboxe's state */ void OnShowTrackingVolumeChanged(); /** @brief This slot auto detects tools of a NDI Aurora tracking device. If tools where found they will be stored internally as a tool storage. The user is also asked if he wants to save this tool storage to load it later. Only call it if a Aurora device was configured because other devices don't support auto detection.*/ void OnAutoDetectTools(); /** @brief Slot for tracking timer. The timer updates the IGT pipline and also the logging filter if logging is activated.*/ void UpdateTrackingTimer(); /** @brief Resets the Tracking Tools: this means all tools are removed. */ void OnResetTools(); /** @brief Opens a dialog where a new navigation tool can be created. */ void OnAddSingleTool(); /** @brief This slot is called if the user finishes the creation of a new tool. */ void OnAddSingleToolFinished(); /** @brief This slot is called if the user cancels the creation of a new tool. */ void OnAddSingleToolCanceled(); protected: Ui::QmitkMITKIGTTrackingToolboxViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; bool m_tracking; ///> bool which is true if tracking is running, false if not bool m_logging; ///> bool which is true if logging is running, false if not int m_loggedFrames; ///> stores the current number of logged frames if logging is on mitk::NavigationToolStorage::Pointer m_toolStorage; ///>stores the loaded tools mitk::DataNode::Pointer m_TrackingVolumeNode; ///>holds the data node of the tracking volume if volume is visualized /** @brief Shows a message box with the text given as parameter. */ void MessageBox(std::string s); /** @brief reinits the view globally. */ void GlobalReinit(); //members for the filter pipeline mitk::TrackingDeviceSource::Pointer m_TrackingDeviceSource; ///> member for the source of the IGT pipeline mitk::NavigationDataObjectVisualizationFilter::Pointer m_ToolVisualizationFilter; ///> holds the tool visualization filter (second filter of the IGT pipeline) mitk::NavigationDataRecorder::Pointer m_loggingFilter; ///> holds the logging filter if logging is on (third filter of the IGT pipeline) /** @brief This timer updates the IGT pipline and also the logging filter if logging is activated.*/ QTimer* m_TrackingTimer; //help methods for enable/disable buttons void DisableLoggingButtons(); void EnableLoggingButtons(); void DisableOptionsButtons(); void EnableOptionsButtons(); void EnableTrackingConfigurationButtons(); void DisableTrackingConfigurationButtons(); }; #endif // _QMITKMITKIGTTRACKINGTOOLBOXVIEW_H_INCLUDED \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.cpp b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.cpp index 88a9f2fb54..3a32884f7c 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.cpp +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.cpp @@ -1,477 +1,476 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkNavigationDataPlayerView.h" #include "QmitkStdMultiWidget.h" //mitk #include #include #include // Qt #include // vtk #include const std::string QmitkNavigationDataPlayerView::VIEW_ID = "org.mitk.views.navigationdataplayer"; QmitkNavigationDataPlayerView::QmitkNavigationDataPlayerView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_Trajectory( NULL ) , m_TrajectoryIndex( -1 ) , m_ReloadData( true ) , m_ShowTrajectory( false ) , m_SplineMapper( NULL ) , m_PointSetMapper( NULL ) { m_TrajectoryPointSet = mitk::PointSet::New(); // PointSet for trajectory points } QmitkNavigationDataPlayerView::~QmitkNavigationDataPlayerView() { delete m_PlayerWidget; } void QmitkNavigationDataPlayerView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkNavigationDataPlayerViewControls; m_Controls->setupUi( parent ); this->CreateBundleWidgets( parent ); this->CreateConnections(); } } void QmitkNavigationDataPlayerView::CreateBundleWidgets(QWidget* parent) { m_PlayerWidget = new QmitkIGTPlayerWidget( parent ); // this bundle's ND player widget } void QmitkNavigationDataPlayerView::CreateConnections() { connect( m_PlayerWidget, SIGNAL(SignalPlayingStarted()), this, SLOT(OnCreatePlaybackVisualization()) ); connect( m_PlayerWidget, SIGNAL(SignalPlayerUpdated()), this, SLOT(OnPerformPlaybackVisualization()) ); connect( m_PlayerWidget, SIGNAL(SignalInputFileChanged()), this, SLOT(OnReinit()) ); connect( m_PlayerWidget, SIGNAL(SignalCurrentTrajectoryChanged(int)), this, SLOT (OnShowTrajectory(int)) ); connect( m_PlayerWidget, SIGNAL(SignalPlayingStarted()), this, SLOT(OnPlayingStarted()) ); connect( m_PlayerWidget, SIGNAL(SignalSplineModeToggled(bool)), this, SLOT(OnEnableSplineTrajectoryMapper(bool)) ); } void QmitkNavigationDataPlayerView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkNavigationDataPlayerView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkNavigationDataPlayerView::OnPlayingStarted() { m_TrajectoryPointSet->Clear(); // clear trajectory data before every replay } void QmitkNavigationDataPlayerView::OnCreatePlaybackVisualization() { if(m_ReloadData) // only if input file changed { m_Visualizer = mitk::NavigationDataObjectVisualizationFilter::New(); mitk::DataStorage* ds = this->GetDefaultDataStorage(); unsigned int nrTools = m_PlayerWidget->GetNumberOfTools(); // obtain number of tools from replay file QStringList toolNames; toolNames << "No trajectory selected ..."; // info statement at beginning of trajectories list for(int i=0; iGetColorCircleColor(i); // color for replay object mitk::DataNode::Pointer playbackRepresentation = this->CreateRepresentationObject( nodeName.toStdString(), color ); // create replay DataNode object m_Visualizer->SetRepresentationObject(i, playbackRepresentation->GetData()); // add replay object to visualizer // add new representation object to DataStorage this->AddRepresentationObject(this->GetDefaultDataStorage(), playbackRepresentation); } this->m_PlayerWidget->SetTrajectoryNames(toolNames); // set names in player widget trajectory selection combobox m_ReloadData = false; /// request global reiinit mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); /// global reinit end } } mitk::DataNode::Pointer QmitkNavigationDataPlayerView::CreateTrajectory( mitk::PointSet::Pointer points, const std::string& name, const mitk::Color color ) { mitk::DataNode::Pointer result = mitk::DataNode::New(); // instantiate return DataNode result->SetData(points); result->SetName(name); result->SetColor(color); mitk::PointSetVtkMapper3D::Pointer mapper; // create mapper for trajectory visualization if(m_PlayerWidget->IsTrajectoryInSplineMode()) mapper = this->GetTrajectoryMapper(Splines); else mapper = this->GetTrajectoryMapper(Points); result->SetMapper(mitk::BaseRenderer::Standard3D, mapper); // trajectory properties result->SetProperty("contourcolor", mitk::ColorProperty::New(color)); result->SetBoolProperty("show contour", true); result->SetBoolProperty("updateDataOnRender", false); return result; } mitk::DataNode::Pointer QmitkNavigationDataPlayerView::CreateRepresentationObject(const std::string& name, const mitk::Color color) { mitk::DataNode::Pointer representationNode = mitk::DataNode::New(); // creating cone DataNode for tool visualization mitk::Cone::Pointer cone = mitk::Cone::New(); vtkConeSource* vtkData = vtkConeSource::New(); vtkData->SetRadius(7.5); vtkData->SetHeight(15.0); vtkData->SetDirection(0.0, 0.0, 1.0); vtkData->SetCenter(0.0, 0.0, 0.0); vtkData->SetResolution(20); vtkData->CappingOn(); vtkData->Update(); cone->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); representationNode->SetData(cone); representationNode->GetPropertyList()->SetProperty("name", mitk::StringProperty::New( name.c_str() )); representationNode->GetPropertyList()->SetProperty("layer", mitk::IntProperty::New(0)); representationNode->GetPropertyList()->SetProperty("visible", mitk::BoolProperty::New(true)); representationNode->SetColor(color); representationNode->SetOpacity(1.0); representationNode->Modified(); return representationNode; } void QmitkNavigationDataPlayerView::OnPerformPlaybackVisualization() { if(m_PlayerWidget == NULL || m_Visualizer.IsNull()) return; static int update = 0; static int counter = -1; for(unsigned int i = 0 ; i < m_PlayerWidget->GetNavigationDatas().size(); ++i) { m_Visualizer->SetInput(i, m_PlayerWidget->GetNavigationDatas().at(i)); // pass updated tool NDs to visualizer // show trajectory for selected tool with user given resolution if(m_ShowTrajectory && (i == m_TrajectoryIndex) && (update++ % m_PlayerWidget->GetResolution() == 0) ) { mitk::PointSet::PointType currentPoint = m_PlayerWidget->GetNavigationDataPoint(i); // current ND point for tool trajectory // if realtime mode is selected, trajectory points that are equal in position to their antecessor // will not be inserted in the trajectory pointset to avoid "vtk can't create normals" warning if(m_PlayerWidget->GetCurrentPlaybackMode() == QmitkIGTPlayerWidget::RealTimeMode) { mitk::PointSet::PointType lastPoint; if(counter == -1) { lastPoint[0] = -1; lastPoint[1] = -1; lastPoint[2] = -1; } else lastPoint = m_TrajectoryPointSet->GetPoint(counter); // antecessor point is last point from PointSet mitk::PointSet::PointType currentPoint = m_PlayerWidget->GetNavigationDataPoint(i); // check for position differences between last and current point bool diff0 = lastPoint[0] != currentPoint[0]; bool diff1 = lastPoint[1] != currentPoint[1]; bool diff2 = lastPoint[2] != currentPoint[2]; if(diff0 || diff1 || diff2) m_TrajectoryPointSet->InsertPoint(++counter, currentPoint); // insert only if there are differences } else { m_TrajectoryPointSet->InsertPoint(++counter, currentPoint); // insert point in trajectory PointSet } } } this->RenderScene(); } void QmitkNavigationDataPlayerView::RenderScene() { try { if (m_Visualizer.IsNull() || this->GetActiveStdMultiWidget() == NULL) return; try { m_Visualizer->Update(); } catch(std::exception& e) { std::cout << "Exception during QmitkNavigationDataPlayerView::RenderScene():" << e.what() << "\n"; } //update all Widgets // mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS); // update only Widget4 mitk::BaseRenderer::GetInstance(m_MultiWidget->mitkWidget4->GetRenderWindow())->RequestUpdate(); // update 3D render window } catch (std::exception& e) { std::cout << "RenderAll exception: " << e.what() << "\n"; } catch (...) { std::cout << "RenderAll unknown exception\n"; } } void QmitkNavigationDataPlayerView::OnReinit() { std::vector::iterator it; mitk::DataStorage* ds = this->GetDefaultDataStorage(); // clear tool representation objects from DataStorage for ( it = m_RepresentationObjects.begin() ; it != m_RepresentationObjects.end(); it++ ) { //ds->Remove(*it); mitk::DataNode::Pointer dn = ds->GetNamedNode((*it)->GetName()); if(dn.IsNotNull()) ds->Remove(dn); } m_RepresentationObjects.clear(); // clear tool representation objects vector if(m_Trajectory.IsNotNull()) this->GetDefaultDataStorage()->Remove(m_Trajectory); // remove trajectory DataNode from DataStorage m_TrajectoryPointSet->Clear(); // clear trajectory PointSet this->m_PlayerWidget->ClearTrajectorySelectCombobox(); // clear trajectory selection combobox in player widget m_ReloadData = true; // set flag to true so representation data will be reload if play is triggered again } void QmitkNavigationDataPlayerView::AddTrajectory(mitk::DataStorage* ds, mitk::DataNode::Pointer trajectoryNode) { if(ds == NULL) return; if(m_Trajectory.IsNotNull()) ds->Remove(m_Trajectory); // remove trajectory from DataStorage if already exists // add trajectory to DataStorage if(ds != NULL && trajectoryNode.IsNotNull()) { m_Trajectory = trajectoryNode; ds->Add(m_Trajectory); } } void QmitkNavigationDataPlayerView::AddRepresentationObject(mitk::DataStorage* ds, mitk::DataNode::Pointer reprObject) { m_RepresentationObjects.push_back(reprObject); ds->Add(reprObject); } void QmitkNavigationDataPlayerView::RemoveRepresentationObject(mitk::DataStorage* ds, mitk::DataNode::Pointer reprObject) { std::vector::iterator it; for ( it = m_RepresentationObjects.begin() ; it != m_RepresentationObjects.end(); it++ ) { if(*it == reprObject) { m_RepresentationObjects.erase(it); ds->Remove(reprObject); } } } void QmitkNavigationDataPlayerView::OnShowTrajectory(int index) { mitk::DataStorage* ds = this->GetDefaultDataStorage(); // no trajectory selected if(index == 0) { m_ShowTrajectory = false; m_TrajectoryIndex = -1; if(m_Trajectory.IsNotNull()) ds->Remove(m_Trajectory); } else { m_ShowTrajectory = true; // index-1 because combobox is filled with infovalue at index = 0 mitk::DataNode::Pointer replayObject = m_RepresentationObjects.at(index-1); std::string prefix("Trajectory of "); std::string name = replayObject->GetName(); mitk::Color color = this->GetColorCircleColor(index-1); if(m_TrajectoryPointSet.IsNotNull()) m_TrajectoryPointSet->Clear(); m_TrajectoryIndex = index-1; mitk::DataNode::Pointer trajectory = this->CreateTrajectory( m_TrajectoryPointSet, prefix.append(name), color ); this->AddTrajectory(this->GetDefaultDataStorage(), trajectory); } } void QmitkNavigationDataPlayerView::OnEnableSplineTrajectoryMapper(bool enable) { if(m_Trajectory.IsNull()) return; // if enabled set spline mapper if(enable) m_Trajectory->SetMapper(mitk::BaseRenderer::Standard3D, this->GetTrajectoryMapper(Splines)); // if disabled set pointset mapper else m_Trajectory->SetMapper(mitk::BaseRenderer::Standard3D, this->GetTrajectoryMapper(Points)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // request update after mapper change } mitk::Color QmitkNavigationDataPlayerView::GetColorCircleColor(int index) { mitk::Color result; mitk::ColorSequenceCycleH colorCycle; for(int i=0; i <= index; ++i) { result = colorCycle.GetNextColor(); } return result; } mitk::PointSetVtkMapper3D::Pointer QmitkNavigationDataPlayerView::GetTrajectoryMapper(TrajectoryStyle style) { if(style == Points) { if(m_PointSetMapper.IsNull()) m_PointSetMapper = mitk::PointSetVtkMapper3D::New(); return m_PointSetMapper; } else if(style == Splines) { if(m_SplineMapper.IsNull()) m_SplineMapper = mitk::SplineVtkMapper3D::New(); return m_SplineMapper.GetPointer(); } else return NULL; } diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.h b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.h index 1920f42db8..457eefceae 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.h +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkNavigationDataPlayerView.h @@ -1,184 +1,183 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkNavigationDataPlayerView_h #define QmitkNavigationDataPlayerView_h #include //Qmitk #include #include #include #include // ui #include "ui_QmitkNavigationDataPlayerViewControls.h" //mitk #include #include /*! \brief QmitkNavigationDataPlayerView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkNavigationDataPlayerView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkNavigationDataPlayerView(); QmitkNavigationDataPlayerView(const QmitkNavigationDataPlayerView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkNavigationDataPlayerView(); virtual void CreateQtPartControl(QWidget *parent); /** \brief This method creates this bundle's SIGNAL and SLOT connections */ virtual void CreateConnections(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /*! \brief Creates DataNodes for all available playback objects */ void OnCreatePlaybackVisualization(); /*! \brief Assigns position changings from the player widget to the visualization objects */ void OnPerformPlaybackVisualization(); /*! \brief Reinits this player. Cleans all timers and trajectory data */ void OnReinit(); /*! \brief Shows trajectory of tool with index */ void OnShowTrajectory(int index); /*! \brief Cleans trajectory data before playing is started */ void OnPlayingStarted(); /*! \brief Enables or disables trajectory visualization with splines */ void OnEnableSplineTrajectoryMapper(bool enable); protected: enum TrajectoryStyle { Points = 1, Splines = 2 }; void CreateBundleWidgets(QWidget* parent); /** \brief Refreshes the visualization of the playback object DataNodes. */ void RenderScene(); /** \brief Creates representation DataNode with given name and color */ mitk::DataNode::Pointer CreateRepresentationObject( const std::string& name , const mitk::Color color ); /** \brief Adds representation DataNode to the DataStorage */ void AddRepresentationObject(mitk::DataStorage* ds, mitk::DataNode::Pointer reprObject); /** \brief Removes representation DataNode from the DataStorage */ void RemoveRepresentationObject(mitk::DataStorage* ds, mitk::DataNode::Pointer reprObject); /** \brief Adds trajectory DataNode to the DataStorage */ void AddTrajectory(mitk::DataStorage* ds, mitk::DataNode::Pointer trajectoryNode); /** \brief Creates a trajectory DataNode from given PointSet with given name and color */ mitk::DataNode::Pointer CreateTrajectory( mitk::PointSet::Pointer points, const std::string& name, const mitk::Color color ); Ui::QmitkNavigationDataPlayerViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; QmitkIGTPlayerWidget* m_PlayerWidget; ///< this bundle's playback widget mitk::NavigationDataObjectVisualizationFilter::Pointer m_Visualizer; ///< this filter visualizes the navigation data std::vector m_RepresentationObjects; ///< vector for current visualization objects mitk::DataNode::Pointer m_Trajectory; ///< main trajectory visualization DataNode mitk::PointSet::Pointer m_TrajectoryPointSet; ///< PointSet with all points for trajectory int m_TrajectoryIndex; ///< trajectory tool index bool m_ReloadData; ///< flag needed for refresh of visualization if needed bool m_ShowTrajectory; ///< flag needed for trajectory visualization mitk::SplineVtkMapper3D::Pointer m_SplineMapper; ///< spline trajectory mapper mitk::PointSetVtkMapper3D::Pointer m_PointSetMapper; ///< standard trajectroy mapper private: /** \brief Returns color from colorcycle with given index */ mitk::Color GetColorCircleColor(int index); /** \brief Returns the trajectory mapper for the given style if stýle is not Points or Splines NULL will be returned. */ mitk::PointSetVtkMapper3D::Pointer GetTrajectoryMapper(TrajectoryStyle style); }; #endif // _QMITKNAVIGATIONDATAPLAYERVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp index 4322ade9f0..3d1226ca47 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp @@ -1,43 +1,42 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkPluginActivator.h" #include #include "QmitkMITKIGTNavigationToolManagerView.h" #include "QmitkMITKIGTTrackingToolboxView.h" #include "QmitkNavigationDataPlayerView.h" namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkMITKIGTNavigationToolManagerView, context) BERRY_REGISTER_EXTENSION_CLASS( QmitkMITKIGTTrackingToolboxView , context) BERRY_REGISTER_EXTENSION_CLASS( QmitkNavigationDataPlayerView , context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_igttracking, mitk::PluginActivator) \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.h index 7592169885..6810284ebf 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.h @@ -1,41 +1,40 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include namespace mitk { class PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } #endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.cpp b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.cpp index 432e4606fe..11a2e143a3 100644 --- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.cpp +++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.cpp @@ -1,433 +1,432 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 14134 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include "QmitkImageCropper.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkUndoController.h" #include "mitkBoundingObjectCutter.h" #include "mitkImageAccessByItk.h" #include "mitkITKImageImport.h" #include "mitkIDataStorageService.h" #include "mitkNodePredicateDataType.h" #include //to be moved to mitkInteractionConst.h by StateMachineEditor const mitk::OperationType QmitkImageCropper::OP_EXCHANGE = 717; // constructors for operation classes QmitkImageCropper::opExchangeNodes::opExchangeNodes( mitk::OperationType type, mitk::DataNode* node, mitk::BaseData* oldData, mitk::BaseData* newData ) :mitk::Operation(type),m_Node(node),m_OldData(oldData),m_NewData(newData), m_NodeDeletedObserverTag(0), m_OldDataDeletedObserverTag(0), m_NewDataDeletedObserverTag(0) { // listen to the node the image is hold itk::MemberCommand::Pointer nodeDeletedCommand = itk::MemberCommand::New(); nodeDeletedCommand->SetCallbackFunction(this, &opExchangeNodes::NodeDeleted); m_NodeDeletedObserverTag = m_Node->AddObserver(itk::DeleteEvent(), nodeDeletedCommand); m_OldDataDeletedObserverTag = m_OldData->AddObserver(itk::DeleteEvent(), nodeDeletedCommand); m_NewDataDeletedObserverTag = m_NewData->AddObserver(itk::DeleteEvent(), nodeDeletedCommand); } // destructor for operation class QmitkImageCropper::opExchangeNodes::~opExchangeNodes() { if (m_Node != NULL) { m_Node->RemoveObserver(m_NodeDeletedObserverTag); m_Node=NULL; } if (m_OldData.IsNotNull()) { m_OldData->RemoveObserver(m_OldDataDeletedObserverTag); m_OldData=NULL; } if (m_NewData.IsNotNull()) { m_NewData->RemoveObserver(m_NewDataDeletedObserverTag); m_NewData=NULL; } } void QmitkImageCropper::opExchangeNodes::NodeDeleted(const itk::Object * /*caller*/, const itk::EventObject &/*event*/) { m_Node = NULL; m_OldData = NULL; m_NewData = NULL; } QmitkImageCropper::QmitkImageCropper(QObject *parent) : m_Controls(NULL), m_ParentWidget(0) { m_Interface = new mitk::ImageCropperEventInterface; m_Interface->SetImageCropper( this ); } QmitkImageCropper::~QmitkImageCropper() { //delete smart pointer objects m_CroppingObjectNode = NULL; m_CroppingObject = NULL; m_Interface->Delete(); } void QmitkImageCropper::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { m_ParentWidget = parent; // build ui elements m_Controls = new Ui::QmitkImageCropperControls; m_Controls->setupUi(parent); // setup ui elements m_Controls->groupInfo->hide(); m_Controls->m_SurroundingSlider->hide(); m_Controls->m_SurroundingSpin->hide(); m_Controls->m_NewBoxButton->setEnabled(true); // create ui element connections this->CreateConnections(); } } void QmitkImageCropper::CreateConnections() { if ( m_Controls ) { connect( m_Controls->btnCrop, SIGNAL(clicked()), this, SLOT(CropImage())); // click on the crop button connect( m_Controls->m_NewBoxButton, SIGNAL(clicked()), this, SLOT(CreateNewBoundingObject()) ); connect( m_Controls->m_EnableSurroundingCheckBox, SIGNAL(toggled(bool)), this, SLOT(SurroundingCheck(bool)) ); connect( m_Controls->chkInformation, SIGNAL(toggled(bool)), this, SLOT(ChkInformationToggled(bool)) ); } } void QmitkImageCropper::Activated() { QmitkFunctionality::Activated(); // just call the inherited function } void QmitkImageCropper::Deactivated() { RemoveBoundingObjectFromNode(); QmitkFunctionality::Deactivated(); // just call the inherited function mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } /*! When called with an opExchangeNodes, it changes the content of a node from one data set to another */ void QmitkImageCropper::ExecuteOperation (mitk::Operation *operation) { if (!operation) return; switch (operation->GetOperationType()) { case OP_EXCHANGE: { //RemoveBoundingObjectFromNode(); opExchangeNodes* op = static_cast(operation); op->GetNode()->SetData(op->GetNewData()); mitk::RenderingManager::GetInstance()->InitializeViews(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); break; } default:; } } void QmitkImageCropper::CreateNewBoundingObject() { // attach the cuboid to the image and update the views if (this->IsVisible()) { if (m_ImageNode.IsNotNull()) { m_ImageToCrop = dynamic_cast(m_ImageNode->GetData()); if(m_ImageToCrop.IsNotNull()) { if (this->GetDefaultDataStorage()->GetNamedDerivedNode("CroppingObject", m_ImageNode)) { // We are in "Reset bounding box!" mode m_CroppingObject->FitGeometry(m_ImageToCrop->GetTimeSlicedGeometry()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return; } bool fitCroppingObject = false; if(m_CroppingObject.IsNull()) { CreateBoundingObject(); fitCroppingObject = true; } if (m_CroppingObject.IsNull()) return; AddBoundingObjectToNode( m_ImageNode, fitCroppingObject ); m_ImageNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->InitializeViews(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_Controls->m_NewBoxButton->setText("Reset bounding box!"); m_Controls->btnCrop->setEnabled(true); } } else QMessageBox::information(NULL, "Image cropping functionality", "Load an image first!"); } } void QmitkImageCropper::SurroundingCheck(bool value) { if(value) { if(m_ImageNode.IsNotNull()) { mitk::DataNode *imageNode = m_ImageNode.GetPointer(); if (imageNode) { mitk::BaseData* data = imageNode->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image* image = dynamic_cast( data ); if (image) { float min = 10000.0; float max = -10000.0; min = image->GetScalarValueMin(); max = image->GetScalarValueMax(); m_Controls->m_SurroundingSlider->setRange((int)min,(int)max); m_Controls->m_SurroundingSpin->setRange((int)min,(int)max); } } } m_Controls->m_SurroundingSlider->show(); m_Controls->m_SurroundingSpin->show(); } else m_Controls->m_EnableSurroundingCheckBox->setChecked(false); } else { m_Controls->m_SurroundingSlider->hide(); m_Controls->m_SurroundingSpin->hide(); } } void QmitkImageCropper::CropImage() { // test, if image is selected if (m_ImageToCrop.IsNull()) return; // test, if bounding box is visible if (m_CroppingObjectNode.IsNull()) { QMessageBox::information(NULL, "Image cropping functionality", "Generate a new bounding object first!"); return; } // image and bounding object ok mitk::BoundingObjectCutter::Pointer cutter = mitk::BoundingObjectCutter::New(); cutter->SetBoundingObject( m_CroppingObject ); cutter->SetInput( m_ImageToCrop ); cutter->AutoOutsideValueOff(); if (m_Controls->m_EnableSurroundingCheckBox->isChecked()) { cutter->SetOutsideValue(m_Controls->m_SurroundingSpin->value()); } // do the actual cutting try { cutter->Update(); //cutter->UpdateLargestPossibleRegion(); } catch(itk::ExceptionObject&) { QMessageBox::warning ( NULL, tr("Cropping not possible"), tr("Sorry, the bounding box has to be completely inside the image.\n\n" "The possibility to drag it larger than the image is a bug and has to be fixed."), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton ); return; } // cutting successful mitk::Image::Pointer resultImage = cutter->GetOutput(); resultImage->DisconnectPipeline(); RemoveBoundingObjectFromNode(); { opExchangeNodes* doOp = new opExchangeNodes(OP_EXCHANGE, m_ImageNode.GetPointer(), m_ImageNode->GetData(), resultImage); opExchangeNodes* undoOp = new opExchangeNodes(OP_EXCHANGE, m_ImageNode.GetPointer(), resultImage, m_ImageNode->GetData()); // TODO: MITK doesn't recognize that a new event happens in the next line, // because nothing happens in the render window. // As a result the undo action will happen together with the last action // recognized by MITK. mitk::OperationEvent* operationEvent = new mitk::OperationEvent( m_Interface, doOp, undoOp, "Crop image"); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent( operationEvent ); // tell the undo controller about the action ExecuteOperation(doOp); // execute action } m_Controls->m_NewBoxButton->setEnabled(true); m_Controls->btnCrop->setEnabled(false); } void QmitkImageCropper::CreateBoundingObject() { QStringList items; items << tr("Cuboid") << tr("Ellipsoid") << tr("Cylinder") << tr("Cone"); bool ok; QString item = QInputDialog::getItem(m_Parent, tr("Select Bounding Object"), tr("Type of Bounding Object:"), items, 0, false, &ok); if (!ok) return; if (item == "Ellipsoid") m_CroppingObject = mitk::Ellipsoid::New(); else if(item == "Cylinder") m_CroppingObject = mitk::Cylinder::New(); else if (item == "Cone") m_CroppingObject = mitk::Cone::New(); else if (item == "Cuboid") m_CroppingObject = mitk::Cuboid::New(); else return; m_CroppingObjectNode = mitk::DataNode::New(); m_CroppingObjectNode->SetData( m_CroppingObject ); m_CroppingObjectNode->SetProperty( "name", mitk::StringProperty::New( "CroppingObject" ) ); m_CroppingObjectNode->SetProperty( "color", mitk::ColorProperty::New(1.0, 1.0, 0.0) ); m_CroppingObjectNode->SetProperty( "opacity", mitk::FloatProperty::New(0.4) ); m_CroppingObjectNode->SetProperty( "layer", mitk::IntProperty::New(99) ); // arbitrary, copied from segmentation functionality m_CroppingObjectNode->SetProperty( "helper object", mitk::BoolProperty::New(true) ); m_AffineInteractor = mitk::AffineInteractor::New("AffineInteractions ctrl-drag", m_CroppingObjectNode); } void QmitkImageCropper::OnSelectionChanged(std::vector nodes) { this->RemoveBoundingObjectFromNode(); if (nodes.size() != 1 || dynamic_cast(nodes[0]->GetData()) == 0) { m_ParentWidget->setEnabled(false); return; } m_ImageNode = nodes[0]; m_ParentWidget->setEnabled(true); } void QmitkImageCropper::AddBoundingObjectToNode(mitk::DataNode* node, bool fit) { m_ImageToCrop = dynamic_cast(node->GetData()); if(!this->GetDefaultDataStorage()->Exists(m_CroppingObjectNode)) { this->GetDefaultDataStorage()->Add(m_CroppingObjectNode, node); if (fit) { m_CroppingObject->FitGeometry(m_ImageToCrop->GetTimeSlicedGeometry()); } mitk::GlobalInteraction::GetInstance()->AddInteractor( m_AffineInteractor ); } m_CroppingObjectNode->SetVisibility(true); } void QmitkImageCropper::RemoveBoundingObjectFromNode() { if (m_CroppingObjectNode.IsNotNull()) { if(this->GetDefaultDataStorage()->Exists(m_CroppingObjectNode)) { this->GetDefaultDataStorage()->Remove(m_CroppingObjectNode); mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_AffineInteractor); } m_Controls->m_NewBoxButton->setText("New bounding box!"); } } void QmitkImageCropper::ChkInformationToggled( bool on ) { if (on) m_Controls->groupInfo->show(); else m_Controls->groupInfo->hide(); } void QmitkImageCropper::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { m_MultiWidget = &stdMultiWidget; } void QmitkImageCropper::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkImageCropper::NodeRemoved(const mitk::DataNode *node) { std::string name = node->GetName(); if (strcmp(name.c_str(), "CroppingObject")==0) { m_Controls->btnCrop->setEnabled(false); m_Controls->m_NewBoxButton->setEnabled(true); } } diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.h b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.h index 89b2fdd1d1..ad93e8db27 100644 --- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.h +++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropper.h @@ -1,213 +1,212 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 13136 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QMITK_IMAGECROPPER_H__INCLUDED) #define QMITK_IMAGECROPPER_H__INCLUDED #ifdef WIN32 #pragma warning( disable : 4250 ) #endif #include "QmitkFunctionality.h" #include #include #include #include #include "mitkWeakPointer.h" #include #include #include "mitkImageCropperEventInterface.h" #include "ui_QmitkImageCropperControls.h" /*! \ingroup org_mitk_gui_qt_imagecropper_internal \brief Functionality for cropping images with a cuboid This functionality lets the user select an image from the data tree, select an area of interest by placing a cuboid object, and then crop the image, so that pixels from outside the cuboid will remove. The image size is automatically reduced, if the cuboid is not rotated but parallel to the image axes. \b Implementation The functionality owns a cuboid (m_CroppingObject) and the associated interactor (m_AffineInteractor), which implements moving and scaling the cuboid. */ class QmitkImageCropper : public QmitkFunctionality, public mitk::OperationActor { /// Operation base class, which holds pointers to a node of the data tree (mitk::DataNode) /// and to two data sets (mitk::BaseData) instances class opExchangeNodes: public mitk::Operation { public: opExchangeNodes( mitk::OperationType type, mitk::DataNode* node, mitk::BaseData* oldData, mitk::BaseData* newData ); ~opExchangeNodes(); mitk::DataNode* GetNode() { return m_Node; } mitk::BaseData* GetOldData() { return m_OldData; } mitk::BaseData* GetNewData() { return m_NewData; } protected: void NodeDeleted(const itk::Object * /*caller*/, const itk::EventObject & /*event*/); private: mitk::DataNode* m_Node; mitk::BaseData::Pointer m_OldData; mitk::BaseData::Pointer m_NewData; long m_NodeDeletedObserverTag; long m_OldDataDeletedObserverTag; long m_NewDataDeletedObserverTag; }; private: Q_OBJECT public: /*! \brief Constructor. Called by SampleApp (or other apps that use functionalities) */ QmitkImageCropper(QObject *parent=0); /*! \brief Destructor */ virtual ~QmitkImageCropper(); /*! \brief Creates the Qt widget containing the functionality controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget* parent); /*! \brief Creates the Qt connections needed */ virtual void CreateConnections(); /*! \brief Invoked when this functionality is selected by the application */ virtual void Activated(); /*! \brief Invoked when the user leaves this functionality */ virtual void Deactivated(); /// /// Called when a StdMultiWidget is available. /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available. /// virtual void StdMultiWidgetNotAvailable(); /* \brief Interface of a mitk::StateMachine (for undo/redo) */ virtual void ExecuteOperation (mitk::Operation*); QWidget* GetControls(); public slots: virtual void CropImage(); virtual void SurroundingCheck(bool value); virtual void CreateNewBoundingObject(); virtual void ChkInformationToggled( bool on ); protected: /*! * Default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget* m_MultiWidget; /*! * Controls containing an image selection drop down, some usage information and a "crop" button */ Ui::QmitkImageCropperControls * m_Controls; /*! * The parent QWidget */ QWidget* m_ParentWidget; /*! * \brief A pointer to the node of the image to be croped. */ mitk::WeakPointer m_ImageNode; /*! * \brief A pointer to the image to be cropped. */ mitk::WeakPointer m_ImageToCrop; /*! * \brief The cuboid used for cropping. */ mitk::BoundingObject::Pointer m_CroppingObject; /*! * \brief Tree node of the cuboid used for cropping. */ mitk::DataNode::Pointer m_CroppingObjectNode; /*! * \brief Interactor for moving and scaling the cuboid */ mitk::AffineInteractor::Pointer m_AffineInteractor; /*! * \brief Creates the cuboid and its data tree node. */ virtual void CreateBoundingObject(); /*! * \brief Called from superclass, handles selection changes. */ virtual void OnSelectionChanged(std::vector nodes); /*! * \brief Finds the given node in the data tree and optionally fits the cuboid to it */ virtual void AddBoundingObjectToNode(mitk::DataNode* node, bool fit); /*! * \brief Removes the cuboid from any node and hides it from the user. */ virtual void RemoveBoundingObjectFromNode(); virtual void NodeRemoved(const mitk::DataNode* node); private: // operation constant static const mitk::OperationType OP_EXCHANGE; //Interface class for undo redo mitk::ImageCropperEventInterface* m_Interface; }; #endif // !defined(QMITK_IMAGECROPPER_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.cpp b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.cpp index f329cd07a8..b52661c7bb 100644 --- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.cpp +++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.cpp @@ -1,33 +1,32 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-02-26 12:27:39 +0100 (Fr, 26 Feb 2010) $ -Version: $Revision: 21501 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkImageCropper.h" #include "mitkImageCropperEventInterface.h" mitk::ImageCropperEventInterface::ImageCropperEventInterface() { } mitk::ImageCropperEventInterface::~ImageCropperEventInterface() { } void mitk::ImageCropperEventInterface::ExecuteOperation(mitk::Operation* op) { m_ImageCropper->ExecuteOperation( op ); } diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.h b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.h index 3a6847ed14..5dd29cf8ec 100644 --- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.h +++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperEventInterface.h @@ -1,52 +1,51 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-02-26 12:27:39 +0100 (Fr, 26 Feb 2010) $ -Version: $Revision: 21501 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKIMAGECROPPEREVENTINTERFACE_H #define MITKIMAGECROPPEREVENTINTERFACE_H #include "itkObject.h" #include "mitkOperation.h" #include "mitkOperationActor.h" class QmitkImageCropper; namespace mitk { class ImageCropperEventInterface : public itk::Object, public OperationActor { public: ImageCropperEventInterface(); ~ImageCropperEventInterface(); void SetImageCropper( QmitkImageCropper* imageCropper ) { m_ImageCropper = imageCropper; } virtual void ExecuteOperation(mitk::Operation* op); private: QmitkImageCropper* m_ImageCropper; }; } #endif // MITKIMAGECROPPEREVENTINTERFACE_H diff --git a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.cpp b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.cpp index 36bbf94d3b..8572e6c006 100644 --- a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.cpp +++ b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.cpp @@ -1,393 +1,398 @@ -/*========================================================================= -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkImageNavigatorView.h" #include #include #include const std::string QmitkImageNavigatorView::VIEW_ID = "org.mitk.views.imagenavigator"; QmitkImageNavigatorView::QmitkImageNavigatorView() : m_TransversalStepper(0) , m_SagittalStepper(0) , m_FrontalStepper(0) , m_TimeStepper(0) , m_Parent(0) , m_IRenderWindowPart(0) { } QmitkImageNavigatorView::~QmitkImageNavigatorView() { } void QmitkImageNavigatorView::CreateQtPartControl(QWidget *parent) { // create GUI widgets m_Parent = parent; m_Controls.setupUi(parent); m_Controls.m_SliceNavigatorTransversal->SetInverseDirection(true); connect(m_Controls.m_XWorldCoordinateSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnMillimetreCoordinateValueChanged())); connect(m_Controls.m_YWorldCoordinateSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnMillimetreCoordinateValueChanged())); connect(m_Controls.m_ZWorldCoordinateSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnMillimetreCoordinateValueChanged())); m_Parent->setEnabled(false); mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); this->RenderWindowPartActivated(renderPart); } void QmitkImageNavigatorView::SetFocus () { m_Controls.m_XWorldCoordinateSpinBox->setFocus(); } void QmitkImageNavigatorView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (this->m_IRenderWindowPart != renderWindowPart) { this->m_IRenderWindowPart = renderWindowPart; this->m_Parent->setEnabled(true); QmitkRenderWindow* renderWindow = renderWindowPart->GetRenderWindow("transversal"); if (renderWindow) { if (m_TransversalStepper) m_TransversalStepper->deleteLater(); m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, renderWindow->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample"); m_Controls.m_SliceNavigatorTransversal->setEnabled(true); m_Controls.m_TransversalLabel->setEnabled(true); m_Controls.m_ZWorldCoordinateSpinBox->setEnabled(true); connect(m_TransversalStepper, SIGNAL(Refetch()), this, SLOT(OnRefetch())); } else { m_Controls.m_SliceNavigatorTransversal->setEnabled(false); m_Controls.m_TransversalLabel->setEnabled(false); m_Controls.m_ZWorldCoordinateSpinBox->setEnabled(false); } renderWindow = renderWindowPart->GetRenderWindow("sagittal"); if (renderWindow) { if (m_SagittalStepper) m_SagittalStepper->deleteLater(); m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, renderWindow->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); m_Controls.m_SliceNavigatorSagittal->setEnabled(true); m_Controls.m_SagittalLabel->setEnabled(true); m_Controls.m_YWorldCoordinateSpinBox->setEnabled(true); connect(m_SagittalStepper, SIGNAL(Refetch()), this, SLOT(OnRefetch())); } else { m_Controls.m_SliceNavigatorSagittal->setEnabled(false); m_Controls.m_SagittalLabel->setEnabled(false); m_Controls.m_YWorldCoordinateSpinBox->setEnabled(false); } renderWindow = renderWindowPart->GetRenderWindow("coronal"); if (renderWindow) { if (m_FrontalStepper) m_FrontalStepper->deleteLater(); m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, renderWindow->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); m_Controls.m_SliceNavigatorFrontal->setEnabled(true); m_Controls.m_CoronalLabel->setEnabled(true); m_Controls.m_XWorldCoordinateSpinBox->setEnabled(true); connect(m_FrontalStepper, SIGNAL(Refetch()), this, SLOT(OnRefetch())); } else { m_Controls.m_SliceNavigatorFrontal->setEnabled(false); m_Controls.m_CoronalLabel->setEnabled(false); m_Controls.m_XWorldCoordinateSpinBox->setEnabled(false); } mitk::SliceNavigationController* timeController = renderWindowPart->GetTimeNavigationController(); if (timeController) { if (m_TimeStepper) m_TimeStepper->deleteLater(); m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, timeController->GetTime(), "sliceNavigatorTimeFromSimpleExample"); m_Controls.m_SliceNavigatorTime->setEnabled(true); m_Controls.m_TimeLabel->setEnabled(true); } else { m_Controls.m_SliceNavigatorTime->setEnabled(false); m_Controls.m_TimeLabel->setEnabled(false); } } } void QmitkImageNavigatorView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* /*renderWindowPart*/) { m_IRenderWindowPart = 0; m_Parent->setEnabled(false); } int QmitkImageNavigatorView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkImageNavigatorView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return 200; } else { return preferredResult; } } int QmitkImageNavigatorView::GetClosestAxisIndex(mitk::Vector3D normal) { // cos(theta) = normal . axis // cos(theta) = (a, b, c) . (d, e, f) // cos(theta) = (a, b, c) . (1, 0, 0) = a // cos(theta) = (a, b, c) . (0, 1, 0) = b // cos(theta) = (a, b, c) . (0, 0, 1) = c double absCosThetaWithAxis[3]; for (int i = 0; i < 3; i++) { absCosThetaWithAxis[i] = fabs(normal[i]); } int largestIndex = 0; double largestValue = absCosThetaWithAxis[0]; for (int i = 1; i < 3; i++) { if (absCosThetaWithAxis[i] > largestValue) { largestValue = absCosThetaWithAxis[i]; largestIndex = i; } } return largestIndex; } void QmitkImageNavigatorView::SetBorderColors() { if (m_IRenderWindowPart) { QmitkRenderWindow* renderWindow = m_IRenderWindowPart->GetRenderWindow("transversal"); if (renderWindow) { mitk::PlaneGeometry::ConstPointer geometry = renderWindow->GetSliceNavigationController()->GetCurrentPlaneGeometry(); if (geometry.IsNotNull()) { mitk::Vector3D normal = geometry->GetNormal(); int axis = this->GetClosestAxisIndex(normal); this->SetBorderColor(axis, QString("red")); } } renderWindow = m_IRenderWindowPart->GetRenderWindow("sagittal"); if (renderWindow) { mitk::PlaneGeometry::ConstPointer geometry = renderWindow->GetSliceNavigationController()->GetCurrentPlaneGeometry(); if (geometry.IsNotNull()) { mitk::Vector3D normal = geometry->GetNormal(); int axis = this->GetClosestAxisIndex(normal); this->SetBorderColor(axis, QString("green")); } } renderWindow = m_IRenderWindowPart->GetRenderWindow("coronal"); if (renderWindow) { mitk::PlaneGeometry::ConstPointer geometry = renderWindow->GetSliceNavigationController()->GetCurrentPlaneGeometry(); if (geometry.IsNotNull()) { mitk::Vector3D normal = geometry->GetNormal(); int axis = this->GetClosestAxisIndex(normal); this->SetBorderColor(axis, QString("blue")); } } } } void QmitkImageNavigatorView::SetBorderColor(int axis, QString colorAsStyleSheetString) { if (axis == 0) { this->SetBorderColor(m_Controls.m_XWorldCoordinateSpinBox, colorAsStyleSheetString); } else if (axis == 1) { this->SetBorderColor(m_Controls.m_YWorldCoordinateSpinBox, colorAsStyleSheetString); } else if (axis == 2) { this->SetBorderColor(m_Controls.m_ZWorldCoordinateSpinBox, colorAsStyleSheetString); } } void QmitkImageNavigatorView::SetBorderColor(QDoubleSpinBox *spinBox, QString colorAsStyleSheetString) { assert(spinBox); spinBox->setStyleSheet(QString("border: 2px solid ") + colorAsStyleSheetString + ";"); } void QmitkImageNavigatorView::SetStepSizes() { this->SetStepSize(0); this->SetStepSize(1); this->SetStepSize(2); } void QmitkImageNavigatorView::SetStepSize(int axis) { if (m_IRenderWindowPart) { mitk::Geometry3D::ConstPointer geometry = m_IRenderWindowPart->GetActiveRenderWindow()->GetSliceNavigationController()->GetInputWorldGeometry(); if (geometry.IsNotNull()) { mitk::Point3D crossPositionInIndexCoordinates; mitk::Point3D crossPositionInIndexCoordinatesPlus1; mitk::Point3D crossPositionInMillimetresPlus1; mitk::Vector3D transformedAxisDirection; mitk::Point3D crossPositionInMillimetres = m_IRenderWindowPart->GetSelectedPosition(); geometry->WorldToIndex(crossPositionInMillimetres, crossPositionInIndexCoordinates); crossPositionInIndexCoordinatesPlus1 = crossPositionInIndexCoordinates; crossPositionInIndexCoordinatesPlus1[axis] += 1; geometry->IndexToWorld(crossPositionInIndexCoordinatesPlus1, crossPositionInMillimetresPlus1); transformedAxisDirection = crossPositionInMillimetresPlus1 - crossPositionInMillimetres; int closestAxisInMillimetreSpace = this->GetClosestAxisIndex(transformedAxisDirection); double stepSize = transformedAxisDirection.GetNorm(); this->SetStepSize(closestAxisInMillimetreSpace, stepSize); } } } void QmitkImageNavigatorView::SetStepSize(int axis, double stepSize) { if (axis == 0) { m_Controls.m_XWorldCoordinateSpinBox->setSingleStep(stepSize); } else if (axis == 1) { m_Controls.m_YWorldCoordinateSpinBox->setSingleStep(stepSize); } else if (axis == 2) { m_Controls.m_ZWorldCoordinateSpinBox->setSingleStep(stepSize); } } void QmitkImageNavigatorView::OnMillimetreCoordinateValueChanged() { if (m_IRenderWindowPart) { mitk::Geometry3D::ConstPointer geometry = m_IRenderWindowPart->GetActiveRenderWindow()->GetSliceNavigationController()->GetInputWorldGeometry(); if (geometry.IsNotNull()) { mitk::Point3D positionInWorldCoordinates; positionInWorldCoordinates[0] = m_Controls.m_XWorldCoordinateSpinBox->value(); positionInWorldCoordinates[1] = m_Controls.m_YWorldCoordinateSpinBox->value(); positionInWorldCoordinates[2] = m_Controls.m_ZWorldCoordinateSpinBox->value(); m_IRenderWindowPart->SetSelectedPosition(positionInWorldCoordinates); } } } void QmitkImageNavigatorView::OnRefetch() { if (m_IRenderWindowPart) { mitk::Geometry3D::ConstPointer geometry = m_IRenderWindowPart->GetActiveRenderWindow()->GetSliceNavigationController()->GetInputWorldGeometry(); if (geometry.IsNotNull()) { mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); mitk::Point3D cornerPoint1InIndexCoordinates; cornerPoint1InIndexCoordinates[0] = bounds[0]; cornerPoint1InIndexCoordinates[1] = bounds[2]; cornerPoint1InIndexCoordinates[2] = bounds[4]; mitk::Point3D cornerPoint2InIndexCoordinates; cornerPoint2InIndexCoordinates[0] = bounds[1]; cornerPoint2InIndexCoordinates[1] = bounds[3]; cornerPoint2InIndexCoordinates[2] = bounds[5]; if (!geometry->GetImageGeometry()) { cornerPoint1InIndexCoordinates[0] += 0.5; cornerPoint1InIndexCoordinates[1] += 0.5; cornerPoint1InIndexCoordinates[2] += 0.5; cornerPoint2InIndexCoordinates[0] -= 0.5; cornerPoint2InIndexCoordinates[1] -= 0.5; cornerPoint2InIndexCoordinates[2] -= 0.5; } mitk::Point3D crossPositionInWorldCoordinates = m_IRenderWindowPart->GetSelectedPosition(); mitk::Point3D cornerPoint1InWorldCoordinates; mitk::Point3D cornerPoint2InWorldCoordinates; geometry->IndexToWorld(cornerPoint1InIndexCoordinates, cornerPoint1InWorldCoordinates); geometry->IndexToWorld(cornerPoint2InIndexCoordinates, cornerPoint2InWorldCoordinates); m_Controls.m_XWorldCoordinateSpinBox->blockSignals(true); m_Controls.m_YWorldCoordinateSpinBox->blockSignals(true); m_Controls.m_ZWorldCoordinateSpinBox->blockSignals(true); m_Controls.m_XWorldCoordinateSpinBox->setMinimum(std::min(cornerPoint1InWorldCoordinates[0], cornerPoint2InWorldCoordinates[0])); m_Controls.m_YWorldCoordinateSpinBox->setMinimum(std::min(cornerPoint1InWorldCoordinates[1], cornerPoint2InWorldCoordinates[1])); m_Controls.m_ZWorldCoordinateSpinBox->setMinimum(std::min(cornerPoint1InWorldCoordinates[2], cornerPoint2InWorldCoordinates[2])); m_Controls.m_XWorldCoordinateSpinBox->setMaximum(std::max(cornerPoint1InWorldCoordinates[0], cornerPoint2InWorldCoordinates[0])); m_Controls.m_YWorldCoordinateSpinBox->setMaximum(std::max(cornerPoint1InWorldCoordinates[1], cornerPoint2InWorldCoordinates[1])); m_Controls.m_ZWorldCoordinateSpinBox->setMaximum(std::max(cornerPoint1InWorldCoordinates[2], cornerPoint2InWorldCoordinates[2])); m_Controls.m_XWorldCoordinateSpinBox->setValue(crossPositionInWorldCoordinates[0]); m_Controls.m_YWorldCoordinateSpinBox->setValue(crossPositionInWorldCoordinates[1]); m_Controls.m_ZWorldCoordinateSpinBox->setValue(crossPositionInWorldCoordinates[2]); m_Controls.m_XWorldCoordinateSpinBox->blockSignals(false); m_Controls.m_YWorldCoordinateSpinBox->blockSignals(false); m_Controls.m_ZWorldCoordinateSpinBox->blockSignals(false); } this->SetBorderColors(); } } diff --git a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.h b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.h index d6a0fef2b8..d81cad83a1 100644 --- a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.h +++ b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/QmitkImageNavigatorView.h @@ -1,97 +1,96 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 17495 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKIMAGENAVIGATORVIEW_H_INCLUDED #define _QMITKIMAGENAVIGATORVIEW_H_INCLUDED #include #include #include #include "ui_QmitkImageNavigatorViewControls.h" class QmitkStepperAdapter; /*! * \ingroup org_mitk_gui_qt_imagenavigator_internal * * \class QmitkImageNavigatorView * * \brief Provides a means to scan quickly through a dataset via Transversal, * Coronal and Sagittal sliders, displaying millimetre location and stepper position. * * For images, the stepper position corresponds to a voxel index. For other datasets * such as a surface, it corresponds to a sub-division of the bounding box. * * \sa QmitkAbstractView */ class QmitkImageNavigatorView : public QmitkAbstractView, public mitk::IRenderWindowPartListener, public berry::ISizeProvider { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkImageNavigatorView(); virtual ~QmitkImageNavigatorView(); virtual void CreateQtPartControl(QWidget *parent); virtual int GetSizeFlags(bool width); virtual int ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult); protected slots: void OnMillimetreCoordinateValueChanged(); void OnRefetch(); protected: void SetFocus(); void RenderWindowPartActivated(mitk::IRenderWindowPart *renderWindowPart); void RenderWindowPartDeactivated(mitk::IRenderWindowPart *renderWindowPart); void SetBorderColors(); void SetBorderColor(QDoubleSpinBox *spinBox, QString colorAsStyleSheetString); void SetBorderColor(int axis, QString colorAsStyleSheetString); void SetStepSizes(); void SetStepSize(int axis); void SetStepSize(int axis, double stepSize); int GetClosestAxisIndex(mitk::Vector3D normal); Ui::QmitkImageNavigatorViewControls m_Controls; QmitkStepperAdapter* m_TransversalStepper; QmitkStepperAdapter* m_SagittalStepper; QmitkStepperAdapter* m_FrontalStepper; QmitkStepperAdapter* m_TimeStepper; QWidget* m_Parent; mitk::IRenderWindowPart* m_IRenderWindowPart; }; #endif // _QMITKIMAGENAVIGATORVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp index 46162ce248..839aec247d 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp @@ -1,320 +1,319 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ -Version: $Revision: 16719 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ #include "QmitkMITKSurfaceMaterialEditorView.h" #include "mitkBaseRenderer.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkIDataStorageService.h" #include "mitkDataNodeObject.h" #include "berryIEditorPart.h" #include "berryIWorkbenchPage.h" #include "mitkShaderProperty.h" #include "mitkShaderRepository.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkStandaloneDataStorage.h" const std::string QmitkMITKSurfaceMaterialEditorView::VIEW_ID = "org.mitk.views.mitksurfacematerialeditor"; QmitkMITKSurfaceMaterialEditorView::QmitkMITKSurfaceMaterialEditorView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { fixedProperties.push_back( "shader" ); fixedProperties.push_back( "material.representation" ); fixedProperties.push_back( "color" ); fixedProperties.push_back( "opacity" ); fixedProperties.push_back( "material.wireframeLineWidth" ); fixedProperties.push_back( "material.ambientCoefficient" ); fixedProperties.push_back( "material.diffuseCoefficient" ); fixedProperties.push_back( "material.ambientColor" ); fixedProperties.push_back( "material.diffuseColor" ); fixedProperties.push_back( "material.specularColor" ); fixedProperties.push_back( "material.specularCoefficient" ); fixedProperties.push_back( "material.specularPower" ); fixedProperties.push_back( "material.interpolation" ); shaderProperties.push_back( "shader" ); shaderProperties.push_back( "material.representation" ); shaderProperties.push_back( "color" ); shaderProperties.push_back( "opacity" ); shaderProperties.push_back( "material.wireframeLineWidth" ); observerAllocated = false; mitk::ShaderRepository::GetGlobalShaderRepository(); } QmitkMITKSurfaceMaterialEditorView::~QmitkMITKSurfaceMaterialEditorView() { } void QmitkMITKSurfaceMaterialEditorView::InitPreviewWindow() { usedTimer=0; vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetThetaResolution(25); sphereSource->SetPhiResolution(25); sphereSource->Update(); vtkPolyData* sphere = sphereSource->GetOutput(); m_Surface = mitk::Surface::New(); m_Surface->SetVtkPolyData( sphere ); m_DataNode = mitk::DataNode::New(); m_DataNode->SetData( m_Surface ); m_DataTree = mitk::StandaloneDataStorage::New(); m_DataTree->Add( m_DataNode , (mitk::DataNode *)0 ); m_Controls->m_PreviewRenderWindow->GetRenderer()->SetDataStorage( m_DataTree ); m_Controls->m_PreviewRenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); sphereSource->Delete(); } void QmitkMITKSurfaceMaterialEditorView::RefreshPropertiesList() { mitk::DataNode* SrcND = m_SelectedDataNode; mitk::DataNode* DstND = m_DataNode; mitk::PropertyList* DstPL = DstND->GetPropertyList(); m_Controls->m_ShaderPropertyList->SetPropertyList( 0 ); DstPL->Clear(); if(observerAllocated) { observedProperty->RemoveObserver( observerIndex ); observerAllocated=false; } if(SrcND) { mitk::PropertyList* SrcPL = SrcND->GetPropertyList(); mitk::ShaderProperty::Pointer shaderEnum = dynamic_cast(SrcPL->GetProperty("shader")); std::string shaderState = "fixed"; if(shaderEnum.IsNotNull()) { shaderState = shaderEnum->GetValueAsString(); itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange); observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); observedProperty = shaderEnum; observerAllocated=true; } MITK_INFO << "PROPERTIES SCAN BEGIN"; for(mitk::PropertyList::PropertyMap::const_iterator it=SrcPL->GetMap()->begin(); it!=SrcPL->GetMap()->end(); it++) { std::string name=it->first; mitk::BaseProperty *p=it->second; // MITK_INFO << "property '" << name << "' found"; if(shaderState.compare("fixed")==0) { if(std::find(fixedProperties.begin(), fixedProperties.end(), name) != fixedProperties.end()) { DstPL->SetProperty(name,p); } } else { //if(std::find(shaderProperties.begin(), shaderProperties.end(), name) != shaderProperties.end()) { DstPL->SetProperty(name,p); } } } MITK_INFO << "PROPERTIES SCAN END"; } m_Controls->m_ShaderPropertyList->SetPropertyList( DstPL ); //m_Controls->m_PreviewRenderWindow->GetRenderer()->GetVtkRenderer()->ResetCameraClippingRange(); } /* // subscribe for property change events itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified); m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkDataStorageTableModel::PropertyModified); mitk::BaseProperty* visibilityProperty = (*it)->GetProperty("visible"); if(visibilityProperty) m_PropertyModifiedObserverTags[visibilityProperty] = visibilityProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); mitk::BaseProperty* nameProperty = (*it)->GetProperty("name"); if(nameProperty) m_PropertyModifiedObserverTags[nameProperty] = nameProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); for(mitk::PropertyList::PropertyMap::const_iterator it=m_PropertyList->GetMap()->begin() ; it!=m_PropertyList->GetMap()->end() ; it++) { // add relevant property column values m_PropertyListElements.push_back((*it)); // subscribe for property change events itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified); m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);*/ void QmitkMITKSurfaceMaterialEditorView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkMITKSurfaceMaterialEditorViewControls; m_Controls->setupUi(parent); this->CreateConnections(); InitPreviewWindow(); RefreshPropertiesList(); } } void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkMITKSurfaceMaterialEditorView::CreateConnections() { } void QmitkMITKSurfaceMaterialEditorView::Activated() { QmitkFunctionality::Activated(); } void QmitkMITKSurfaceMaterialEditorView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkMITKSurfaceMaterialEditorView::OnSelectionChanged(std::vector nodes) { if(!nodes.empty()) { m_SelectedDataNode = nodes.at(0); MITK_INFO << "Node '" << m_SelectedDataNode->GetName() << "' selected"; SurfaceSelected(); } } void QmitkMITKSurfaceMaterialEditorView::SurfaceSelected() { postRefresh(); } void QmitkMITKSurfaceMaterialEditorView::shaderEnumChange(const itk::Object * /*caller*/, const itk::EventObject & /*event*/) { postRefresh(); } void QmitkMITKSurfaceMaterialEditorView::postRefresh() { if(usedTimer) return; usedTimer=startTimer(0); } void QmitkMITKSurfaceMaterialEditorView::timerEvent( QTimerEvent *e ) { if(usedTimer!=e->timerId()) { MITK_ERROR << "INTERNAL ERROR: usedTimer[" << usedTimer << "] != timerId[" << e->timerId() << "]"; } if(usedTimer) { killTimer(usedTimer); usedTimer=0; } RefreshPropertiesList(); } \ No newline at end of file diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h index 07f5f6dc6a..030b437e96 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h @@ -1,131 +1,130 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ -Version: $Revision: 16719 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED #define _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED #include #include #include #include #include "ui_QmitkMITKSurfaceMaterialEditorViewControls.h" /* #include #include #include #include #include #include #include "QtGui/QMenubarUpdatedEvent" */ #include "QmitkRenderWindow.h" #include "mitkCommon.h" #include "mitkDataStorage.h" #include "mitkDataNode.h" #include "mitkShaderProperty.h" #include "mitkSurface.h" #include "vtkRenderer.h" #include "vtkTextActor.h" /*! \brief QmitkMITKSurfaceMaterialEditorView \sa QmitkFunctionality \ingroup Functionalities */ class QmitkMITKSurfaceMaterialEditorView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkMITKSurfaceMaterialEditorView(); QmitkMITKSurfaceMaterialEditorView(const QmitkMITKSurfaceMaterialEditorView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkMITKSurfaceMaterialEditorView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void OnSelectionChanged(std::vector nodes); protected slots: void SurfaceSelected(); protected: Ui::QmitkMITKSurfaceMaterialEditorViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; private: mitk::Surface::Pointer m_Surface; mitk::DataStorage::Pointer m_DataTree; mitk::DataNode::Pointer m_DataNode; mitk::DataNode::Pointer m_SelectedDataNode; std::list fixedProperties; std::list shaderProperties; unsigned long observerIndex; bool observerAllocated; mitk::ShaderProperty::Pointer observedProperty; void InitPreviewWindow(); int usedTimer; void timerEvent( QTimerEvent *e ); void RefreshPropertiesList(); void postRefresh(); void shaderEnumChange(const itk::Object *caller, const itk::EventObject &event); berry::IStructuredSelection::ConstPointer m_CurrentSelection; berry::ISelectionListener::Pointer m_SelectionListener; }; #endif // _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp index 0e068a49da..5bd8ecd3f1 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp @@ -1,795 +1,794 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-22 11:00:35 +0200 (Fr, 22 Mai 2009) $ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkImageStatisticsView.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkStdMultiWidget.h" #include "QmitkSliderNavigatorWidget.h" #include "mitkNodePredicateDataType.h" #include "mitkImageTimeSelector.h" #include "mitkProperties.h" #include "mitkProgressBar.h" // Includes for image processing #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkDataNodeObject.h" #include "mitkNodePredicateData.h" #include "mitkPlanarFigureInteractor.h" #include const std::string QmitkImageStatisticsView::VIEW_ID = "org.mitk.views.imagestatistics"; class QmitkRequestStatisticsUpdateEvent : public QEvent { public: enum Type { StatisticsUpdateRequest = QEvent::MaxUser - 1025 }; QmitkRequestStatisticsUpdateEvent() : QEvent( (QEvent::Type) StatisticsUpdateRequest ) {}; }; typedef itk::Image ImageType; typedef itk::Image FloatImageType; typedef itk::Image, 3> VectorImageType; inline bool my_isnan(float x) { volatile float d = x; if(d!=d) return true; if(d==d) return false; return d != d; } QmitkImageStatisticsView::QmitkImageStatisticsView(QObject* /*parent*/, const char* /*name*/) : m_Controls( NULL ), m_TimeStepperAdapter( NULL ), m_SelectedImageNode( NULL ), m_SelectedImage( NULL ), m_SelectedMaskNode( NULL ), m_SelectedImageMask( NULL ), m_SelectedPlanarFigure( NULL ), m_ImageObserverTag( -1 ), m_ImageMaskObserverTag( -1 ), m_PlanarFigureObserverTag( -1 ), m_CurrentStatisticsValid( false ), m_StatisticsUpdatePending( false ), m_Visible(false) { } QmitkImageStatisticsView::~QmitkImageStatisticsView() { if ( m_SelectedImage != NULL ) m_SelectedImage->RemoveObserver( m_ImageObserverTag ); if ( m_SelectedImageMask != NULL ) m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); if ( m_SelectedPlanarFigure != NULL ) m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); } void QmitkImageStatisticsView::CreateQtPartControl(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new Ui::QmitkImageStatisticsViewControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_Controls->m_LineProfileWidget->SetPathModeToPlanarFigure(); } } void QmitkImageStatisticsView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ButtonCopyHistogramToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(ClipboardHistogramButtonClicked())); connect( (QObject*)(m_Controls->m_ButtonCopyStatisticsToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(ClipboardStatisticsButtonClicked())); connect( (QObject*)(m_Controls->m_IgnoreZerosCheckbox), SIGNAL(clicked()),(QObject*) this, SLOT(IgnoreZerosCheckboxClicked())); } } void QmitkImageStatisticsView::IgnoreZerosCheckboxClicked( ) { UpdateStatistics(); } void QmitkImageStatisticsView::ClipboardHistogramButtonClicked() { if ( m_CurrentStatisticsValid && (m_CurrentStatisticsCalculator.IsNotNull()) ) { typedef mitk::ImageStatisticsCalculator::HistogramType HistogramType; const HistogramType *histogram = m_CurrentStatisticsCalculator->GetHistogram(); QString clipboard( "Measurement \t Frequency\n" ); for ( HistogramType::ConstIterator it = histogram->Begin(); it != histogram->End(); ++it ) { clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( it.GetMeasurementVector()[0], 0, 'f', 2 ) .arg( it.GetFrequency() ); } QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); } else { QApplication::clipboard()->clear(); } } void QmitkImageStatisticsView::ClipboardStatisticsButtonClicked() { if ( m_CurrentStatisticsValid && (m_CurrentStatisticsCalculator.IsNotNull()) ) { const mitk::ImageStatisticsCalculator::Statistics &statistics = m_CurrentStatisticsCalculator->GetStatistics(); // Copy statistics to clipboard ("%Ln" will use the default locale for // number formatting) QString clipboard( "Mean \t StdDev \t RMS \t Max \t Min \t N \t V (mm³)\n" ); clipboard = clipboard.append( "%L1 \t %L2 \t %L3 \t %L4 \t %L5 \t %L6 \t %L7" ) .arg( statistics.Mean, 0, 'f', 10 ) .arg( statistics.Sigma, 0, 'f', 10 ) .arg( statistics.RMS, 0, 'f', 10 ) .arg( statistics.Max, 0, 'f', 10 ) .arg( statistics.Min, 0, 'f', 10 ) .arg( statistics.N ) .arg( m_Controls->m_StatisticsTable->item( 0, 6 )->text() ); QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); } else { QApplication::clipboard()->clear(); } } void QmitkImageStatisticsView::FillStatisticsTableView( const mitk::ImageStatisticsCalculator::Statistics &s, const mitk::Image *image ) { m_Controls->m_StatisticsTable->setItem( 0, 0, new QTableWidgetItem( QString("%1").arg(s.Mean, 0, 'f', 2) ) ); m_Controls->m_StatisticsTable->setItem( 0, 1, new QTableWidgetItem( QString("%1").arg(s.Sigma, 0, 'f', 2) ) ); m_Controls->m_StatisticsTable->setItem( 0, 2, new QTableWidgetItem( QString("%1").arg(s.RMS, 0, 'f', 2) ) ); m_Controls->m_StatisticsTable->setItem( 0, 3, new QTableWidgetItem( QString("%1").arg(s.Max, 0, 'f', 2) ) ); m_Controls->m_StatisticsTable->setItem( 0, 4, new QTableWidgetItem( QString("%1").arg(s.Min, 0, 'f', 2) ) ); m_Controls->m_StatisticsTable->setItem( 0, 5, new QTableWidgetItem( QString("%1").arg(s.N) ) ); const mitk::Geometry3D *geometry = image->GetGeometry(); if ( geometry != NULL ) { const mitk::Vector3D &spacing = image->GetGeometry()->GetSpacing(); double volume = spacing[0] * spacing[1] * spacing[2] * (double) s.N; m_Controls->m_StatisticsTable->setItem( 0, 6, new QTableWidgetItem( QString("%1").arg(volume, 0, 'f', 2) ) ); } else { m_Controls->m_StatisticsTable->setItem( 0, 6, new QTableWidgetItem( "NA" ) ); } } void QmitkImageStatisticsView::InvalidateStatisticsTableView() { for ( unsigned int i = 0; i < 7; ++i ) { m_Controls->m_StatisticsTable->setItem( 0, i, new QTableWidgetItem( "NA" ) ); } } void QmitkImageStatisticsView::OnSelectionChanged( berry::IWorkbenchPart::Pointer /*part*/, const QList &selectedNodes ) { // Clear any unreferenced images this->RemoveOrphanImages(); if ( !m_Visible ) { return; } // Check if selection makeup consists only of valid nodes: // One image, segmentation or planarFigure // One image and one of the other two bool tooManyNodes( true ); bool invalidNodes( true ); if ( selectedNodes.size() < 3 ) { tooManyNodes = false; } QList nodes(selectedNodes); if( !tooManyNodes ) { unsigned int numberImages = 0; unsigned int numberSegmentations = 0; unsigned int numberPlanarFigures = 0; for ( int index = 0; index < nodes.size(); index++ ) { m_SelectedImageMask = dynamic_cast< mitk::Image * >( nodes[ index ]->GetData() ); m_SelectedPlanarFigure = dynamic_cast< mitk::PlanarFigure * >( nodes[ index ]->GetData() ); if ( m_SelectedImageMask != NULL ) { bool isMask( false ); nodes[ index ]->GetPropertyValue("binary", isMask); if ( !isMask ) { numberImages++; } else { numberSegmentations++; if ( numberImages != 0 ) // image should be last element { std::swap( nodes[ index ], nodes[ index - 1 ] ); } } } else if ( m_SelectedPlanarFigure != NULL ) { numberPlanarFigures++; if ( numberImages != 0 ) // image should be last element { std::swap( nodes[ index ], nodes[ index - 1 ] ); } } } if ( ( numberPlanarFigures + numberSegmentations + numberImages ) == nodes.size() && //No invalid nodes ( numberPlanarFigures + numberSegmentations ) < 2 && numberImages < 2 // maximum of one image and/or one of either planar figure or segmentation ) { invalidNodes = false; } } if ( nodes.empty() || tooManyNodes || invalidNodes ) { // Nothing to do: invalidate image, clear statistics, histogram, and GUI m_SelectedImage = NULL; this->InvalidateStatisticsTableView() ; m_Controls->m_HistogramWidget->ClearItemModel(); m_Controls->m_LineProfileWidget->ClearItemModel(); m_CurrentStatisticsValid = false; m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_SelectedMaskLabel->setText( "None" ); return; } // Get selected element mitk::DataNode *selectedNode = nodes.front(); mitk::Image *selectedImage = dynamic_cast< mitk::Image * >( selectedNode->GetData() ); // Find the next parent/grand-parent node containing an image, if any mitk::DataStorage::SetOfObjects::ConstPointer parentObjects; mitk::DataNode *parentNode = NULL; mitk::Image *parentImage = NULL; // Possibly previous change listeners if ( (m_SelectedPlanarFigure != NULL) && (m_PlanarFigureObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_PlanarFigureObserverTag = -1; } if ( (m_SelectedImage != NULL) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } if ( (m_SelectedImageMask != NULL) && (m_ImageMaskObserverTag >= 0) ) { m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); m_ImageMaskObserverTag = -1; } // Deselect all images and masks by default m_SelectedImageNode = NULL; m_SelectedImage = NULL; m_SelectedMaskNode = NULL; m_SelectedImageMask = NULL; m_SelectedPlanarFigure = NULL; { unsigned int parentObjectIndex = 0; parentObjects = this->GetDataStorage()->GetSources( selectedNode ); while( parentObjectIndex < parentObjects->Size() ) { // Use first parent object (if multiple parents are present) parentNode = parentObjects->ElementAt( parentObjectIndex ); parentImage = dynamic_cast< mitk::Image * >( parentNode->GetData() ); if( parentImage != NULL ) { break; } parentObjectIndex++; } } if ( nodes.size() == 2 ) { parentNode = nodes.back(); parentImage = dynamic_cast< mitk::Image * >( parentNode->GetData() ); } if ( parentImage != NULL ) { m_SelectedImageNode = parentNode; m_SelectedImage = parentImage; // Check if a valid mask has been selected (Image or PlanarFigure) m_SelectedImageMask = dynamic_cast< mitk::Image * >( selectedNode->GetData() ); m_SelectedPlanarFigure = dynamic_cast< mitk::PlanarFigure * >( selectedNode->GetData() ); // Check whether ImageMask is a binary segmentation if ( (m_SelectedImageMask != NULL) ) { bool isMask( false ); selectedNode->GetPropertyValue("binary", isMask); if ( !isMask ) { m_SelectedImageNode = selectedNode; m_SelectedImage = selectedImage; m_SelectedImageMask = NULL; } else { m_SelectedMaskNode = selectedNode; } } else if ( (m_SelectedPlanarFigure != NULL) ) { m_SelectedMaskNode = selectedNode; } } else if ( selectedImage != NULL ) { m_SelectedImageNode = selectedNode; m_SelectedImage = selectedImage; } typedef itk::SimpleMemberCommand< QmitkImageStatisticsView > ITKCommandType; ITKCommandType::Pointer changeListener; changeListener = ITKCommandType::New(); changeListener->SetCallbackFunction( this, &QmitkImageStatisticsView::RequestStatisticsUpdate ); // Add change listeners to selected objects if ( m_SelectedImage != NULL ) { m_ImageObserverTag = m_SelectedImage->AddObserver( itk::ModifiedEvent(), changeListener ); } if ( m_SelectedImageMask != NULL ) { m_ImageMaskObserverTag = m_SelectedImageMask->AddObserver( itk::ModifiedEvent(), changeListener ); } if ( m_SelectedPlanarFigure != NULL ) { m_PlanarFigureObserverTag = m_SelectedPlanarFigure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), changeListener ); } // Clear statistics / histogram GUI if nothing is selected if ( m_SelectedImage == NULL ) { // Clear statistics, histogram, and GUI this->InvalidateStatisticsTableView(); m_Controls->m_HistogramWidget->ClearItemModel(); m_Controls->m_LineProfileWidget->ClearItemModel(); m_CurrentStatisticsValid = false; m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_SelectedMaskLabel->setText( "None" ); } else { // Else, request statistics and GUI update this->RequestStatisticsUpdate(); } } void QmitkImageStatisticsView::UpdateStatistics() { // Remove any cached images that are no longer referenced elsewhere this->RemoveOrphanImages(); mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if ( renderPart == NULL ) { return; } unsigned int timeStep = renderPart->GetTimeNavigationController()->GetTime()->GetPos(); if ( m_SelectedImage != NULL ) { // Check if a the selected image is a multi-channel image. If yes, statistics // cannot be calculated currently. if ( m_SelectedImage->GetPixelType().GetNumberOfComponents() > 1 ) { std::stringstream message; message << "Multi-component images not supported."; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; return; } // Retrieve ImageStatisticsCalculator from has map (or create a new one // for this image if non-existant) ImageStatisticsMapType::iterator it = m_ImageStatisticsMap.find( m_SelectedImage ); if ( it != m_ImageStatisticsMap.end() ) { m_CurrentStatisticsCalculator = it->second; MITK_INFO << "Retrieving StatisticsCalculator"; } else { m_CurrentStatisticsCalculator = mitk::ImageStatisticsCalculator::New(); m_CurrentStatisticsCalculator->SetImage( m_SelectedImage ); m_ImageStatisticsMap[m_SelectedImage] = m_CurrentStatisticsCalculator; MITK_INFO << "Creating StatisticsCalculator"; } std::string maskName; std::string maskType; unsigned int maskDimension; if ( m_SelectedImageMask != NULL ) { m_CurrentStatisticsCalculator->SetImageMask( m_SelectedImageMask ); m_CurrentStatisticsCalculator->SetMaskingModeToImage(); maskName = m_SelectedMaskNode->GetName(); maskType = m_SelectedImageMask->GetNameOfClass(); maskDimension = 3; } else if ( m_SelectedPlanarFigure != NULL ) { m_CurrentStatisticsCalculator->SetPlanarFigure( m_SelectedPlanarFigure ); m_CurrentStatisticsCalculator->SetMaskingModeToPlanarFigure(); maskName = m_SelectedMaskNode->GetName(); maskType = m_SelectedPlanarFigure->GetNameOfClass(); maskDimension = 2; } else { m_CurrentStatisticsCalculator->SetMaskingModeToNone(); maskName = "None"; maskType = ""; maskDimension = 0; } if(m_Controls->m_IgnoreZerosCheckbox->isChecked()) { m_CurrentStatisticsCalculator->SetIgnorePixelValue(0); m_CurrentStatisticsCalculator->SetDoIgnorePixelValue(true); } else { m_CurrentStatisticsCalculator->SetDoIgnorePixelValue(false); } std::stringstream maskLabel; maskLabel << maskName; if ( maskDimension > 0 ) { maskLabel << " [" << maskDimension << "D " << maskType << "]"; } m_Controls->m_SelectedMaskLabel->setText( maskLabel.str().c_str() ); bool statisticsChanged = false; bool statisticsCalculationSuccessful = false; // Initialize progress bar mitk::ProgressBar::GetInstance()->AddStepsToDo( 100 ); // Install listener for progress events and initialize progress bar typedef itk::SimpleMemberCommand< QmitkImageStatisticsView > ITKCommandType; ITKCommandType::Pointer progressListener; progressListener = ITKCommandType::New(); progressListener->SetCallbackFunction( this, &QmitkImageStatisticsView::UpdateProgressBar ); unsigned long progressObserverTag = m_CurrentStatisticsCalculator ->AddObserver( itk::ProgressEvent(), progressListener ); // show wait cursor this->WaitCursorOn(); try { // Compute statistics statisticsChanged = m_CurrentStatisticsCalculator->ComputeStatistics( timeStep ); statisticsCalculationSuccessful = true; } catch ( const std::runtime_error &e ) { // In case of exception, print error message on GUI std::stringstream message; message << "" << e.what() << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); } catch ( const std::exception &e ) { MITK_ERROR << "Caught exception: " << e.what(); // In case of exception, print error message on GUI std::stringstream message; message << "Error! Unequal Dimensions of Image and Segmentation. No recompute possible "; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); } m_CurrentStatisticsCalculator->RemoveObserver( progressObserverTag ); // Make sure that progress bar closes mitk::ProgressBar::GetInstance()->Progress( 100 ); // remove wait cursor this->WaitCursorOff(); if ( statisticsCalculationSuccessful ) { if ( statisticsChanged ) { // Do not show any error messages m_Controls->m_ErrorMessageLabel->hide(); m_CurrentStatisticsValid = true; } m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_Controls->m_HistogramWidget->SetHistogramModeToDirectHistogram(); m_Controls->m_HistogramWidget->SetHistogram( m_CurrentStatisticsCalculator->GetHistogram( timeStep ) ); m_Controls->m_HistogramWidget->UpdateItemModelFromHistogram(); MITK_INFO << "UpdateItemModelFromHistogram()"; this->FillStatisticsTableView( m_CurrentStatisticsCalculator->GetStatistics( timeStep ), m_SelectedImage ); } else { m_Controls->m_SelectedMaskLabel->setText( "None" ); // Clear statistics and histogram this->InvalidateStatisticsTableView(); m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; // If a (non-closed) PlanarFigure is selected, display a line profile widget if ( m_SelectedPlanarFigure != NULL ) { // check whether PlanarFigure is initialized const mitk::Geometry2D *planarFigureGeometry2D = m_SelectedPlanarFigure->GetGeometry2D(); if ( planarFigureGeometry2D == NULL ) { // Clear statistics, histogram, and GUI this->InvalidateStatisticsTableView(); m_Controls->m_HistogramWidget->ClearItemModel(); m_Controls->m_LineProfileWidget->ClearItemModel(); m_CurrentStatisticsValid = false; m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_SelectedMaskLabel->setText( "None" ); return; } // TODO: enable line profile widget m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 1 ); m_Controls->m_LineProfileWidget->SetImage( m_SelectedImage ); m_Controls->m_LineProfileWidget->SetPlanarFigure( m_SelectedPlanarFigure ); m_Controls->m_LineProfileWidget->UpdateItemModelFromPath(); } } } } void QmitkImageStatisticsView::UpdateProgressBar() { mitk::ProgressBar::GetInstance()->Progress(); } void QmitkImageStatisticsView::RequestStatisticsUpdate() { if ( !m_StatisticsUpdatePending ) { QApplication::postEvent( this, new QmitkRequestStatisticsUpdateEvent ); m_StatisticsUpdatePending = true; } } void QmitkImageStatisticsView::RemoveOrphanImages() { ImageStatisticsMapType::iterator it = m_ImageStatisticsMap.begin(); while ( it != m_ImageStatisticsMap.end() ) { mitk::Image *image = it->first; mitk::ImageStatisticsCalculator *calculator = it->second; ++it; mitk::NodePredicateData::Pointer hasImage = mitk::NodePredicateData::New( image ); if ( this->GetDataStorage()->GetNode( hasImage ) == NULL ) { if ( m_SelectedImage == image ) { m_SelectedImage = NULL; m_SelectedImageNode = NULL; } if ( m_CurrentStatisticsCalculator == calculator ) { m_CurrentStatisticsCalculator = NULL; } m_ImageStatisticsMap.erase( image ); it = m_ImageStatisticsMap.begin(); } } } bool QmitkImageStatisticsView::event( QEvent *event ) { if ( event->type() == (QEvent::Type) QmitkRequestStatisticsUpdateEvent::StatisticsUpdateRequest ) { // Update statistics m_StatisticsUpdatePending = false; this->UpdateStatistics(); return true; } return false; } void QmitkImageStatisticsView::ComputeIntensityProfile( mitk::PlanarLine* line ) { double sampling = 300; QmitkVtkHistogramWidget::HistogramType::Pointer histogram = QmitkVtkHistogramWidget::HistogramType::New(); itk::Size<1> siz; siz[0] = sampling; itk::FixedArray lower, higher; lower.Fill(0); mitk::Point3D begin = line->GetWorldControlPoint(0); mitk::Point3D end = line->GetWorldControlPoint(1); itk::Vector direction = (end - begin); higher.Fill(direction.GetNorm()); histogram->Initialize(siz, lower, higher); for(int i = 0; i < sampling; i++) { //mitk::Point3D location = begin + double(i)/sampling * direction; double d = m_SelectedImage->GetPixelValueByWorldCoordinate(begin + double(i)/sampling * direction); histogram->SetFrequency(i,d); } m_Controls->m_HistogramWidget->SetHistogramModeToDirectHistogram(); m_Controls->m_HistogramWidget->SetHistogram( histogram ); m_Controls->m_HistogramWidget->UpdateItemModelFromHistogram(); } void QmitkImageStatisticsView::Activated() { } void QmitkImageStatisticsView::Deactivated() { } void QmitkImageStatisticsView::Visible() { m_Visible = true; this->OnSelectionChanged(this->GetSite()->GetPage()->FindView("org.mitk.views.datamanager"), this->GetDataManagerSelection()); } void QmitkImageStatisticsView::Hidden() { m_Visible = false; } void QmitkImageStatisticsView::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h index b68efa3921..b6b8f81b42 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h @@ -1,167 +1,166 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-28 20:08:26 +0200 (Do, 28 Mai 2009) $ -Version: $Revision: 10185 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkImageStatisticsView_H__INCLUDED #define QmitkImageStatisticsView_H__INCLUDED #include "ui_QmitkImageStatisticsViewControls.h" #include #include #include "QmitkStepperAdapter.h" #include "mitkImageStatisticsCalculator.h" #include #include "mitkPlanarLine.h" /*! \brief QmitkImageStatisticsView \sa QmitkFunctionality \ingroup Functionalities */ class QmitkImageStatisticsView : public QmitkAbstractView, public mitk::ILifecycleAwarePart { Q_OBJECT public: /*! \ Convenient typedefs */ typedef mitk::DataStorage::SetOfObjects ConstVector; typedef ConstVector::ConstPointer ConstVectorPointer; typedef ConstVector::ConstIterator ConstVectorIterator; /*! \brief default constructor */ QmitkImageStatisticsView(QObject *parent=0, const char *name=0); /*! \brief default destructor */ virtual ~QmitkImageStatisticsView(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); bool IsExclusiveFunctionality() const; virtual bool event( QEvent *event ); void OnSelectionChanged( berry::IWorkbenchPart::Pointer part, const QList &nodes ); static const std::string VIEW_ID; protected slots: void ClipboardHistogramButtonClicked(); void ClipboardStatisticsButtonClicked(); void IgnoreZerosCheckboxClicked( ); protected: void FillStatisticsTableView( const mitk::ImageStatisticsCalculator::Statistics &s, const mitk::Image *image ); void InvalidateStatisticsTableView(); /** \brief Issues a request to update statistics by sending an event to the * Qt event processing queue. * * Statistics update should only be executed after program execution returns * to the Qt main loop. This mechanism also prevents multiple execution of * updates where only one is required.*/ void RequestStatisticsUpdate(); /** \brief Recalculate statistics for currently selected image and mask and * update the GUI. */ void UpdateStatistics(); /** \brief Listener for progress events to update progress bar. */ void UpdateProgressBar(); /** \brief Removes any cached images which are no longer referenced elsewhere. */ void RemoveOrphanImages(); /** \brief Computes an Intensity Profile along line and updates the histogram widget with it. */ void ComputeIntensityProfile( mitk::PlanarLine* line ); void Activated(); void Deactivated(); void Visible(); void Hidden(); void SetFocus(); typedef std::map< mitk::Image *, mitk::ImageStatisticsCalculator::Pointer > ImageStatisticsMapType; /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkImageStatisticsViewControls *m_Controls; QmitkStepperAdapter* m_TimeStepperAdapter; unsigned int m_CurrentTime; QString m_Clipboard; // Image and mask data mitk::DataNode *m_SelectedImageNode; mitk::Image *m_SelectedImage; mitk::DataNode *m_SelectedMaskNode; mitk::Image *m_SelectedImageMask; mitk::PlanarFigure *m_SelectedPlanarFigure; long m_ImageObserverTag; long m_ImageMaskObserverTag; long m_PlanarFigureObserverTag; // Hash map for associating one image statistics calculator with each iamge // (so that previously calculated histograms / statistics can be recovered // if a recalculation is not required) ImageStatisticsMapType m_ImageStatisticsMap; mitk::ImageStatisticsCalculator::Pointer m_CurrentStatisticsCalculator; bool m_CurrentStatisticsValid; bool m_StatisticsUpdatePending; bool m_Visible; }; #endif // QmitkImageStatisticsView_H__INCLUDED diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp index 959abb469a..d72a14b1c1 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp @@ -1,1100 +1,1099 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 15412 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include #include "mitkGlobalInteraction.h" #include "mitkPointSet.h" #include "mitkProperties.h" #include "mitkStringProperty.h" #include "mitkIDataStorageService.h" #include "mitkDataNodeObject.h" #include #include #include #include #include #include #include #include "mitkPlanarCircle.h" #include "mitkPlanarPolygon.h" #include "mitkPlanarAngle.h" #include "mitkPlanarRectangle.h" #include "mitkPlanarLine.h" #include "mitkPlanarCross.h" #include "mitkPlanarFourPointAngle.h" #include "mitkPlanarFigureInteractor.h" #include "mitkPlaneGeometry.h" #include "QmitkPlanarFiguresTableModel.h" #include "QmitkMeasurementView.h" #include #include #include #include #include #include #include #include #include #include #include "mitkNodePredicateDataType.h" #include "mitkPlanarFigure.h" #include #include #include #include const std::string QmitkMeasurementView::VIEW_ID = "org.mitk.views.measurement"; QmitkMeasurementView::QmitkMeasurementView() : m_Parent(0), m_Layout(0), m_DrawActionsToolBar(0), m_DrawActionsGroup(0), m_MeasurementInfoRenderer(0), m_MeasurementInfoAnnotation(0), m_SelectedPlanarFigures(0), m_SelectedImageNode(), m_LineCounter(0), m_PathCounter(0), m_AngleCounter(0), m_FourPointAngleCounter(0), m_EllipseCounter(0), m_RectangleCounter(0), m_PolygonCounter(0), m_Visible(false), m_CurrentFigureNodeInitialized(false), m_Activated(false), m_LastRenderWindow(0) { } QmitkMeasurementView::~QmitkMeasurementView() { this->GetDataStorage()->AddNodeEvent -= mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeAddedInDataStorage ); m_SelectedPlanarFigures->NodeChanged.RemoveListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeChanged ) ); m_SelectedPlanarFigures->NodeRemoved.RemoveListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeRemoved ) ); m_SelectedPlanarFigures->PropertyChanged.RemoveListener( mitk::MessageDelegate2( this, &QmitkMeasurementView::PropertyChanged ) ); m_SelectedImageNode->NodeChanged.RemoveListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeChanged ) ); m_SelectedImageNode->NodeRemoved.RemoveListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeRemoved ) ); m_SelectedImageNode->PropertyChanged.RemoveListener( mitk::MessageDelegate2( this, &QmitkMeasurementView::PropertyChanged ) ); if(this->m_LastRenderWindow != NULL) { this->SetMeasurementInfoToRenderWindow("",m_LastRenderWindow); mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->RemoveRenderer( m_MeasurementInfoRenderer); } this->m_MeasurementInfoRenderer->Delete(); } void QmitkMeasurementView::CreateQtPartControl(QWidget* parent) { m_Parent = parent; m_MeasurementInfoRenderer = vtkRenderer::New(); m_MeasurementInfoAnnotation = vtkCornerAnnotation::New(); vtkTextProperty *textProp = vtkTextProperty::New(); m_MeasurementInfoAnnotation->SetMaximumFontSize(12); textProp->SetColor(1.0, 1.0, 1.0); m_MeasurementInfoAnnotation->SetTextProperty(textProp); m_MeasurementInfoRenderer->AddActor(m_MeasurementInfoAnnotation); m_DrawActionsToolBar = new QToolBar; m_DrawActionsGroup = new QActionGroup(this); m_DrawActionsGroup->setExclusive(true); //# add actions QAction* currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/line.png"), "Draw Line"); m_DrawLine = currentAction; m_DrawLine->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawLineTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/path.png"), "Draw Path"); m_DrawPath = currentAction; m_DrawPath->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawPathTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/angle.png"), "Draw Angle"); m_DrawAngle = currentAction; m_DrawAngle->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawAngleTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/four-point-angle.png"), "Draw Four Point Angle"); m_DrawFourPointAngle = currentAction; m_DrawFourPointAngle->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawFourPointAngleTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/circle.png"), "Draw Circle"); m_DrawEllipse = currentAction; m_DrawEllipse->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawEllipseTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/rectangle.png"), "Draw Rectangle"); m_DrawRectangle = currentAction; m_DrawRectangle->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawRectangleTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/measurement/polygon.png"), "Draw Polygon"); m_DrawPolygon = currentAction; m_DrawPolygon->setCheckable(true); m_DrawActionsToolBar->addAction(currentAction); m_DrawActionsGroup->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawPolygonTriggered(bool) ) ); currentAction = m_DrawActionsToolBar->addAction(QIcon( ":/Qmitk/Images_48.png"), "Reproduce potential bug"); m_DrawActionsToolBar->addAction(currentAction); QObject::connect( currentAction, SIGNAL( triggered(bool) ) , this, SLOT( ReproducePotentialBug(bool) ) ); QLabel* selectedImageLabel = new QLabel("Selected Image: "); m_SelectedImage = new QLabel; m_SelectedImage->setStyleSheet("font-weight: bold;"); m_SelectedPlanarFiguresText = new QTextBrowser; m_CopyToClipboard = new QPushButton("Copy to Clipboard"); QObject::connect( m_CopyToClipboard, SIGNAL( clicked(bool) ) , this, SLOT( CopyToClipboard(bool) ) ); m_Layout = new QGridLayout; m_Layout->addWidget(selectedImageLabel, 0, 0, 1, 1); m_Layout->addWidget(m_SelectedImage, 0, 1, 1, 1); m_Layout->addWidget(m_DrawActionsToolBar, 1, 0, 1, 2); m_Layout->addWidget(m_SelectedPlanarFiguresText, 2, 0, 1, 2); m_Layout->addWidget(m_CopyToClipboard, 3, 0, 1, 2); m_Layout->setRowStretch(0, 1); m_Layout->setRowStretch(1, 1); m_Layout->setRowStretch(2, 10); m_Layout->setRowStretch(3, 1); m_Layout->setContentsMargins(2, 2, 2, 2); parent->setLayout(m_Layout); m_SelectedPlanarFigures = mitk::DataStorageSelection::New(this->GetDataStorage(), false); m_SelectedPlanarFigures->NodeChanged.AddListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeChanged ) ); m_SelectedPlanarFigures->NodeRemoved.AddListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeRemoved ) ); m_SelectedPlanarFigures->PropertyChanged.AddListener( mitk::MessageDelegate2( this, &QmitkMeasurementView::PropertyChanged ) ); m_SelectedImageNode = mitk::DataStorageSelection::New(this->GetDataStorage(), false); m_SelectedImageNode->PropertyChanged.AddListener( mitk::MessageDelegate2( this, &QmitkMeasurementView::PropertyChanged ) ); m_SelectedImageNode->NodeChanged.AddListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeChanged ) ); m_SelectedImageNode->NodeRemoved.AddListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeRemoved ) ); this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1( this, &QmitkMeasurementView::NodeAddedInDataStorage ) ); } void QmitkMeasurementView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList &nodes) { if ( nodes.isEmpty() ) return; m_SelectedImageNode->RemoveAllNodes(); mitk::BaseData* _BaseData; mitk::PlanarFigure* _PlanarFigure; mitk::Image* selectedImage; m_SelectedPlanarFigures->RemoveAllNodes(); foreach (mitk::DataNode::Pointer _DataNode, nodes) { _PlanarFigure = 0; if (!_DataNode) continue; _BaseData = _DataNode->GetData(); if (!_BaseData) continue; // planar figure selected if ((_PlanarFigure = dynamic_cast (_BaseData))) { // add to the selected planar figures m_SelectedPlanarFigures->AddNode(_DataNode); // take parent image as the selected image mitk::DataStorage::SetOfObjects::ConstPointer parents = this->GetDataStorage()->GetSources(_DataNode); if (parents->size() > 0) { mitk::DataNode::Pointer parent = parents->front(); if ((selectedImage = dynamic_cast (parent->GetData()))) { *m_SelectedImageNode = parent; } } } else if ((selectedImage = dynamic_cast (_BaseData))) { *m_SelectedImageNode = _DataNode; /*mitk::RenderingManager::GetInstance()->InitializeViews( selectedImage->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );*/ } } // end for this->PlanarFigureSelectionChanged(); } void QmitkMeasurementView::PlanarFigureSelectionChanged() { if ( !this->m_Activated ) return; if (m_SelectedImageNode->GetNode().IsNotNull()) { mitk::Image* selectedImage = dynamic_cast(m_SelectedImageNode->GetNode()->GetData()); if(selectedImage && selectedImage->GetDimension() > 3) { m_SelectedImageNode->RemoveAllNodes(); m_SelectedImage->setText( "4D images are not supported." ); m_DrawActionsToolBar->setEnabled(false); } else { m_SelectedImage->setText(QString::fromStdString( m_SelectedImageNode->GetNode()->GetName())); m_DrawActionsToolBar->setEnabled(true); } } else { m_SelectedImage->setText( "None. Please select an image."); m_DrawActionsToolBar->setEnabled(false); } if (m_SelectedPlanarFigures->GetSize() == 0 && this->GetRenderWindowPart() != 0) { foreach (QmitkRenderWindow* renderWindow, this->GetRenderWindowPart()->GetRenderWindows().values()) { this->SetMeasurementInfoToRenderWindow("", renderWindow); } } unsigned int j = 1; mitk::PlanarFigure* _PlanarFigure = 0; mitk::PlanarAngle* planarAngle = 0; mitk::PlanarFourPointAngle* planarFourPointAngle = 0; mitk::DataNode::Pointer node = 0; m_SelectedPlanarFiguresText->clear(); QString infoText; QString plainInfoText; std::vector nodes = m_SelectedPlanarFigures->GetNodes(); for (std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it, ++j) { plainInfoText.clear(); node = *it; if(j>1) infoText.append("
"); infoText.append(QString("%1
").arg(QString::fromStdString( node->GetName()))); plainInfoText.append(QString("%1").arg(QString::fromStdString( node->GetName()))); _PlanarFigure = dynamic_cast (node->GetData()); planarAngle = dynamic_cast (_PlanarFigure); if(!planarAngle) { planarFourPointAngle = dynamic_cast (_PlanarFigure); } if(!_PlanarFigure) continue; double featureQuantity = 0.0; for (unsigned int i = 0; i < _PlanarFigure->GetNumberOfFeatures(); ++i) { if ( !_PlanarFigure->IsFeatureActive( i ) ) continue; featureQuantity = _PlanarFigure->GetQuantity(i); if ((planarAngle && i == planarAngle->FEATURE_ID_ANGLE) || (planarFourPointAngle && i == planarFourPointAngle->FEATURE_ID_ANGLE)) featureQuantity = featureQuantity * 180 / vnl_math::pi; infoText.append( QString("%1: %2 %3") .arg(QString( _PlanarFigure->GetFeatureName(i))) .arg(featureQuantity, 0, 'f', 2) .arg(QString(_PlanarFigure->GetFeatureUnit(i)))); plainInfoText.append( QString("\n%1: %2 %3") .arg(QString(_PlanarFigure->GetFeatureName(i))) .arg( featureQuantity, 0, 'f', 2) .arg(QString( _PlanarFigure->GetFeatureUnit(i)))); if(i+1 != _PlanarFigure->GetNumberOfFeatures()) infoText.append("
"); } if (j != nodes.size()) infoText.append("
"); } m_SelectedPlanarFiguresText->setHtml(infoText); // for the last selected planar figure ... if (_PlanarFigure) { const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if (renderPart) { foreach(QmitkRenderWindow* renderWindow, renderPart->GetRenderWindows().values()) { if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, renderWindow->GetRenderer())) { selectedRenderWindow = renderWindow; break; } } } // make node visible if (selectedRenderWindow) { mitk::Point3D centerP = _PlaneGeometry->GetOrigin(); //selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( //centerP, _PlaneGeometry->GetNormal()); selectedRenderWindow->GetSliceNavigationController()->SelectSliceByPoint( centerP); // now paint infos also on renderwindow this->SetMeasurementInfoToRenderWindow(plainInfoText, selectedRenderWindow); } } // no last planarfigure else this->SetMeasurementInfoToRenderWindow("", 0); this->RequestRenderWindowUpdate(); } void QmitkMeasurementView::NodeAddedInDataStorage(const mitk::DataNode* node) { if(!m_Visible) return; mitk::DataNode* nonConstNode = const_cast(node); mitk::PlanarFigure* figure = dynamic_cast(nonConstNode->GetData()); if(figure) { mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", nonConstNode); // remove old interactor if present if( m_CurrentFigureNode.IsNotNull() && m_CurrentFigureNodeInitialized == false ) { mitk::Interactor::Pointer oldInteractor = m_CurrentFigureNode->GetInteractor(); if(oldInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(oldInteractor); this->GetDataStorage()->Remove(m_CurrentFigureNode); } mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } void QmitkMeasurementView::PlanarFigureInitialized() { if(m_CurrentFigureNode.IsNull()) return; m_CurrentFigureNodeInitialized = true; this->PlanarFigureSelectionChanged(); m_DrawLine->setChecked(false); m_DrawPath->setChecked(false); m_DrawAngle->setChecked(false); m_DrawFourPointAngle->setChecked(false); m_DrawEllipse->setChecked(false); m_DrawRectangle->setChecked(false); m_DrawPolygon->setChecked(false); // enable the crosshair navigation this->EnableCrosshairNavigation(); } void QmitkMeasurementView::PlanarFigureSelected( itk::Object* object, const itk::EventObject& /*event*/ ) { // Mark to-be-edited PlanarFigure as selected mitk::PlanarFigure* figure = dynamic_cast< mitk::PlanarFigure* >( object ); if ( figure != NULL ) { // Get node corresponding to PlanarFigure mitk::DataNode::Pointer figureNode = this->GetDataStorage()->GetNode( mitk::NodePredicateData::New( figure ) ); // Select this node (and deselect all others) QList< mitk::DataNode::Pointer > selectedNodes = this->GetDataManagerSelection(); for ( int i = 0; i < selectedNodes.size(); i++ ) { selectedNodes[i]->SetSelected( false ); } std::vector< mitk::DataNode* > selectedNodes2 = m_SelectedPlanarFigures->GetNodes(); for ( unsigned int i = 0; i < selectedNodes2.size(); i++ ) { selectedNodes2[i]->SetSelected( false ); } figureNode->SetSelected( true ); m_CurrentFigureNode = figureNode; *m_SelectedPlanarFigures = figureNode; // Re-initialize after selecting new PlanarFigure this->PlanarFigureSelectionChanged(); } } mitk::DataNode::Pointer QmitkMeasurementView::DetectTopMostVisibleImage() { // get all images from the data storage mitk::DataStorage::SetOfObjects::ConstPointer Images = this->GetDataStorage()->GetSubset( mitk::NodePredicateDataType::New("Image") ); mitk::DataNode::Pointer currentNode( m_SelectedImageNode->GetNode() ); int maxLayer = itk::NumericTraits::min(); // iterate over selection for (mitk::DataStorage::SetOfObjects::ConstIterator sofIt = Images->Begin(); sofIt != Images->End(); ++sofIt) { mitk::DataNode::Pointer node = sofIt->Value(); if ( node.IsNull() ) continue; if (node->IsVisible(NULL) == false) continue; int layer = 0; node->GetIntProperty("layer", layer); if ( layer < maxLayer ) continue; currentNode = node; } return currentNode; } void QmitkMeasurementView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey, mitk::BaseProperty *property ) { if ( m_CurrentFigureNode.IsNotNull() ) { m_CurrentFigureNode->GetData()->RemoveObserver( m_EndPlacementObserverTag ); } mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); // Add custom property, if available if ( (propertyKey != NULL) && (property != NULL) ) { newNode->AddProperty( propertyKey, property ); } // add observer for event when figure has been placed typedef itk::SimpleMemberCommand< QmitkMeasurementView > SimpleCommandType; SimpleCommandType::Pointer initializationCommand = SimpleCommandType::New(); initializationCommand->SetCallbackFunction( this, &QmitkMeasurementView::PlanarFigureInitialized ); m_EndPlacementObserverTag = figure->AddObserver( mitk::EndPlacementPlanarFigureEvent(), initializationCommand ); // add observer for event when figure is picked (selected) typedef itk::MemberCommand< QmitkMeasurementView > MemberCommandType; MemberCommandType::Pointer selectCommand = MemberCommandType::New(); selectCommand->SetCallbackFunction( this, &QmitkMeasurementView::PlanarFigureSelected ); m_SelectObserverTag = figure->AddObserver( mitk::SelectPlanarFigureEvent(), selectCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer startInteractionCommand = SimpleCommandType::New(); startInteractionCommand->SetCallbackFunction( this, &QmitkMeasurementView::DisableCrosshairNavigation); m_StartInteractionObserverTag = figure->AddObserver( mitk::StartInteractionPlanarFigureEvent(), startInteractionCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer endInteractionCommand = SimpleCommandType::New(); endInteractionCommand->SetCallbackFunction( this, &QmitkMeasurementView::EnableCrosshairNavigation); m_EndInteractionObserverTag = figure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), endInteractionCommand ); // figure drawn on the topmost layer / image this->GetDataStorage()->Add(newNode, this->DetectTopMostVisibleImage() ); QList selectedNodes = GetDataManagerSelection(); for(int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } std::vector selectedNodes2 = m_SelectedPlanarFigures->GetNodes(); for(unsigned int i = 0; i < selectedNodes2.size(); i++) { selectedNodes2[i]->SetSelected(false); } newNode->SetSelected(true); m_CurrentFigureNodeInitialized = false; m_CurrentFigureNode = newNode; *m_SelectedPlanarFigures = newNode; this->RequestRenderWindowUpdate(); } bool QmitkMeasurementView::AssertDrawingIsPossible(bool checked) { if (m_SelectedImageNode->GetNode().IsNull()) { checked = false; this->HandleException("Please select an image!", this->m_Parent, true); m_DrawLine->setChecked(false); return false; } mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart()); if (linkedRenderWindow) { linkedRenderWindow->EnableSlicingPlanes(false); } // disable the crosshair navigation during the drawing this->DisableCrosshairNavigation(); return checked; } void QmitkMeasurementView::ActionDrawLineTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarLine::Pointer figure = mitk::PlanarLine::New(); QString qString; if(m_CurrentFigureNode.IsNull() || m_LineCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Line%1").arg(++m_LineCounter); } else{ qString = QString("Line%1").arg(m_LineCounter); } this->AddFigureToDataStorage(figure, qString); MITK_INFO << "PlanarLine initialized..."; } void QmitkMeasurementView::ActionDrawPathTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOff(); mitk::BoolProperty::Pointer closedProperty = mitk::BoolProperty::New( false ); QString qString; if(m_CurrentFigureNode.IsNull() || m_PathCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Path%1").arg(++m_PathCounter); } else{ qString = QString("Path%1").arg(m_PathCounter); } this->AddFigureToDataStorage(figure, qString, "ClosedPlanarPolygon", closedProperty); MITK_INFO << "PlanarPath initialized..."; } void QmitkMeasurementView::ActionDrawAngleTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarAngle::Pointer figure = mitk::PlanarAngle::New(); QString qString; if(m_CurrentFigureNode.IsNull() || m_AngleCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Angle%1").arg(++m_AngleCounter); } else{ qString = QString("Angle%1").arg(m_AngleCounter); } this->AddFigureToDataStorage(figure, qString); MITK_INFO << "PlanarAngle initialized..."; } void QmitkMeasurementView::ActionDrawFourPointAngleTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarFourPointAngle::Pointer figure = mitk::PlanarFourPointAngle::New(); QString qString; if(m_CurrentFigureNode.IsNull() || m_FourPointAngleCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Four Point Angle%1").arg(++m_FourPointAngleCounter); } else{ qString = QString("Four Point Angle%1").arg(m_FourPointAngleCounter); } this->AddFigureToDataStorage(figure, qString); MITK_INFO << "PlanarFourPointAngle initialized..."; } void QmitkMeasurementView::ActionDrawEllipseTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); QString qString; if(m_CurrentFigureNode.IsNull() || m_EllipseCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Circle%1").arg(++m_EllipseCounter); } else{ qString = QString("Circle%1").arg(m_EllipseCounter); } this->AddFigureToDataStorage(figure, qString); MITK_INFO << "PlanarCircle initialized..."; } void QmitkMeasurementView::ActionDrawRectangleTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarRectangle::Pointer figure = mitk::PlanarRectangle::New(); QString qString; if(m_CurrentFigureNode.IsNull() || m_RectangleCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Rectangle%1").arg(++m_RectangleCounter); } else{ qString = QString("Rectangle%1").arg(m_RectangleCounter); } this->AddFigureToDataStorage(figure, qString); MITK_INFO << "PlanarRectangle initialized..."; } void QmitkMeasurementView::ActionDrawPolygonTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); QString qString; if(m_CurrentFigureNode.IsNull() || m_PolygonCounter == 0 || m_CurrentFigureNodeInitialized){ qString = QString("Polygon%1").arg(++m_PolygonCounter); } else{ qString = QString("Polygon%1").arg(m_PolygonCounter); } this->AddFigureToDataStorage(figure, qString); MITK_INFO << "PlanarPolygon initialized..."; } void QmitkMeasurementView::ActionDrawArrowTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; MITK_WARN << "Draw Arrow not implemented yet."; } void QmitkMeasurementView::ActionDrawTextTriggered(bool checked) { if(!this->AssertDrawingIsPossible(checked)) return; MITK_WARN << "Draw Text not implemented yet."; } void QmitkMeasurementView::Activated() { m_Activated = true; MITK_INFO << "QmitkMeasurementView::Activated"; if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { linkedRenderWindow->EnableSlicingPlanes(false); } mitk::TNodePredicateDataType::Pointer isPlanarFigure = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigure* figure = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; // finally add all nodes to the model for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } m_Visible = true; } void QmitkMeasurementView::Deactivated() { MITK_INFO << "QmitkMeasurementView::Deactivated"; } void QmitkMeasurementView::ActivatedZombieView(berry::IWorkbenchPartReference::Pointer /*newZombiePart*/) { if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { linkedRenderWindow->EnableSlicingPlanes(true); } this->SetMeasurementInfoToRenderWindow("", m_LastRenderWindow); this->EnableCrosshairNavigation(); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigure* figure = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; // finally add all nodes to the model for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figure->RemoveAllObservers(); figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(figureInteractor); } } m_Activated = false; } void QmitkMeasurementView::Visible() { m_Visible = true; MITK_INFO << "QmitkMeasurementView::Visible"; } void QmitkMeasurementView::Hidden() { m_Visible = false; MITK_INFO << "QmitkMeasurementView::Hidden"; } void QmitkMeasurementView::PropertyChanged(const mitk::DataNode* /*node*/, const mitk::BaseProperty* /*prop*/) { this->PlanarFigureSelectionChanged(); } void QmitkMeasurementView::NodeChanged(const mitk::DataNode* /*node*/) { this->PlanarFigureSelectionChanged(); } void QmitkMeasurementView::NodeRemoved(const mitk::DataNode* /*node*/) { this->PlanarFigureSelectionChanged(); } void QmitkMeasurementView::CopyToClipboard(bool) { std::vector headerRow; std::vector > rows; QString featureName; QString featureQuantity; std::vector newRow; headerRow.push_back("Name"); std::vector nodes = m_SelectedPlanarFigures->GetNodes(); for (std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it) { mitk::PlanarFigure* planarFigure = dynamic_cast ((*it)->GetData()); if (!planarFigure) continue; newRow.clear(); newRow.push_back(QString::fromStdString((*it)->GetName())); newRow.resize(headerRow.size()); for (unsigned int i = 0; i < planarFigure->GetNumberOfFeatures(); ++i) { if ( !planarFigure->IsFeatureActive( i ) ) continue; featureName = planarFigure->GetFeatureName(i); featureName.append(QString(" [%1]").arg(planarFigure->GetFeatureUnit(i))); std::vector::iterator itColumn = std::find(headerRow.begin(), headerRow.end(), featureName); featureQuantity = QString("%1").arg(planarFigure->GetQuantity(i)).replace(QChar('.'), ","); if (itColumn == headerRow.end()) { headerRow.push_back(featureName); newRow.push_back(featureQuantity); } else { newRow[std::distance(headerRow.begin(), itColumn)] = featureQuantity; } } rows.push_back(newRow); } QString clipboardText; for (std::vector::iterator it = headerRow.begin(); it != headerRow.end(); ++it) clipboardText.append(QString("%1 \t").arg(*it)); for (std::vector >::iterator it = rows.begin(); it != rows.end(); ++it) { clipboardText.append("\n"); for (std::vector::iterator it2 = (*it).begin(); it2 != (*it).end(); ++it2) { clipboardText.append(QString("%1 \t").arg(*it2)); } } QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); } void QmitkMeasurementView::SetMeasurementInfoToRenderWindow(const QString& text, QmitkRenderWindow* _RenderWindow) { if(m_LastRenderWindow != _RenderWindow) { if(m_LastRenderWindow) { QObject::disconnect( m_LastRenderWindow, SIGNAL( destroyed(QObject*) ) , this, SLOT( OnRenderWindowDelete(QObject*) ) ); } m_LastRenderWindow = _RenderWindow; if(m_LastRenderWindow) { QObject::connect( m_LastRenderWindow, SIGNAL( destroyed(QObject*) ) , this, SLOT( OnRenderWindowDelete(QObject*) ) ); } } if(m_LastRenderWindow) { if (!text.isEmpty() && m_SelectedPlanarFigures->GetNode()->IsSelected()) { m_MeasurementInfoAnnotation->SetText(1, text.toLatin1().data()); mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->InsertForegroundRenderer( m_MeasurementInfoRenderer, true); } else { if (mitk::VtkLayerController::GetInstance( m_LastRenderWindow->GetRenderWindow()) ->IsRendererInserted( m_MeasurementInfoRenderer)) mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->RemoveRenderer( m_MeasurementInfoRenderer); } } } void QmitkMeasurementView::EnableCrosshairNavigation() { // enable the crosshair navigation if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { linkedRenderWindow->EnableLinkedNavigation(true); } } void QmitkMeasurementView::DisableCrosshairNavigation() { // disable the crosshair navigation during the drawing if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { linkedRenderWindow->EnableLinkedNavigation(false); } } void QmitkMeasurementView::SetFocus() { } void QmitkMeasurementView::OnRenderWindowDelete(QObject * obj) { if(obj == m_LastRenderWindow) m_LastRenderWindow = 0; } void QmitkMeasurementView::ReproducePotentialBug(bool) { std::vector nodes = m_SelectedPlanarFigures->GetNodes(); QString output; for (std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it) { mitk::DataNode* node = *it; if (!node) continue; mitk::PlanarFigure* pf = dynamic_cast( node->GetData() ); if (!pf) continue; output.append("huhu"); output.append( QString::fromStdString( node->GetName() ) ); /** Bug reproduction: 1. get geometry of planar figure from object 2. use this geometry to initialize rendering manager via InitializeViews 3. see what is produced. the DisplayGeometry of the render window will NOT contain the planar figure nicely. */ mitk::PlaneGeometry::Pointer planarFigureGeometry = dynamic_cast( pf->GetGeometry() ); if (planarFigureGeometry.IsNull()) continue; // not expected mitk::PlaneGeometry::Pointer geometryForRendering = dynamic_cast( planarFigureGeometry->Clone().GetPointer() ); bool applyWorkaround(true); geometryForRendering->SetImageGeometry( applyWorkaround ); std::cout << "==== with" << (applyWorkaround?"":"OUT") << " workaround ====================================" << std::endl; std::cout << "--- PlanarFigure geometry --------------" << std::endl; planarFigureGeometry->Print(std::cout); std::cout << "----------------------------------------" << std::endl; mitk::RenderingManager::GetInstance()->InitializeViews( geometryForRendering, mitk::RenderingManager::REQUEST_UPDATE_ALL, false ); QmitkRenderWindow* renderWindow = this->GetRenderWindowPart()->GetRenderWindows().values().front(); if (renderWindow == 0) { std::cout << "** No QmitkkRenderWindow available **" << std::endl; return; } std::cout << "--- Renderer->GetDisplayGeometry() ------------" << std::endl; renderWindow->GetRenderer()->GetDisplayGeometry()->Print(std::cout); std::cout << "--- Renderer->GetCurrentWorldGeometry2D() -----" << std::endl; renderWindow->GetRenderer()->GetCurrentWorldGeometry2D()->Print(std::cout); std::cout << "--- Renderer->GetWorldGeometry() --------------" << std::endl; renderWindow->GetRenderer()->GetWorldGeometry()->Print(std::cout); } m_SelectedPlanarFiguresText->setText(output); } diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.h b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.h index e321d8d3d5..048bec3f80 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.h +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.h @@ -1,222 +1,221 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 15412 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITK_MEASUREMENT_H__INCLUDED #define QMITK_MEASUREMENT_H__INCLUDED #include #include #include #include #include #include #include #include #include #include #include #include class QmitkPlanarFiguresTableModel; class QGridLayout; class QMainWindow; class QToolBar; class QLabel; class QTableView; class QTextBrowser; class QActionGroup; class QPushButton; class vtkRenderer; class vtkCornerAnnotation; /// /// A view for doing measurements in digital images by means of /// mitk::Planarfigures which can represent drawing primitives (Lines, circles, ...). /// The view consists of only three main elements: /// 1. A toolbar for activating PlanarFigure drawing /// 2. A textbrowser which shows details for the selected PlanarFigures /// 3. A button for copying all details to the clipboard /// class QmitkMeasurementView : public QmitkAbstractView, public mitk::IZombieViewPart { Q_OBJECT public: /// /// Just a shortcut /// typedef std::vector DataNodes; /// /// Initialize pointers to 0. The rest is done in CreateQtPartControl() /// QmitkMeasurementView(); /// /// Remove all event listener from DataStorage, DataStorageSelection, Selection Service /// virtual ~QmitkMeasurementView(); static const std::string VIEW_ID; public: /// /// Initializes all variables. /// Builds up GUI. /// void CreateQtPartControl(QWidget* parent); /// /// Set widget planes visibility to false. /// Show only transversal view. /// Add an interactor to all PlanarFigures in the DataStorage (if they dont have one yet). /// Add their interactor to the global interaction. /// virtual void Activated(); virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); /// /// Show widget planes and all renderwindows again. /// Remove all planar figure interactors from the global interaction. /// virtual void ActivatedZombieView(berry::IWorkbenchPartReference::Pointer zombieView); /// /// Invoked from a DataStorage selection /// virtual void NodeChanged(const mitk::DataNode* node); virtual void PropertyChanged(const mitk::DataNode* node, const mitk::BaseProperty* prop); virtual void NodeRemoved(const mitk::DataNode* node); virtual void NodeAddedInDataStorage(const mitk::DataNode* node); virtual void PlanarFigureInitialized(); virtual void PlanarFigureSelected( itk::Object* object, const itk::EventObject& event ); virtual void AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey = NULL, mitk::BaseProperty *property = NULL ); /// /// Invoked when the DataManager selection changed. /// If an image is in the selection it will be set as the selected one for measurement, /// If a planarfigure is in the selection its parent image will be set as the selected one for measurement. /// All selected planarfigures will be added to m_SelectedPlanarFigures. /// Then PlanarFigureSelectionChanged is called /// virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes); public slots: /// /// Called when the renderwindow gets deleted /// void OnRenderWindowDelete(QObject * obj = 0); protected: /// /// Prints all features of the selected PlanarFigures into the TextBrowser. /// For the last figure in the selection list: /// - Go to the corresponding slice and show figure /// - Draw info text on the bottom right side of the corresponding renderwindow /// void PlanarFigureSelectionChanged(); /// Draws a string on the bottom left side of the render window /// void SetMeasurementInfoToRenderWindow(const QString& text, QmitkRenderWindow* _RenderWindow); bool AssertDrawingIsPossible(bool checked); void EnableCrosshairNavigation(); void DisableCrosshairNavigation(); void SetFocus(); protected slots: ///# draw actions void ActionDrawLineTriggered( bool checked = false ); void ActionDrawPathTriggered( bool checked = false ); void ActionDrawAngleTriggered( bool checked = false ); void ActionDrawFourPointAngleTriggered( bool checked = false ); void ActionDrawEllipseTriggered( bool checked = false ); void ActionDrawRectangleTriggered( bool checked = false ); void ActionDrawPolygonTriggered( bool checked = false ); void ActionDrawArrowTriggered( bool checked = false ); void ActionDrawTextTriggered( bool checked = false ); void CopyToClipboard( bool checked = false ); void ReproducePotentialBug(bool); // fields // widgets protected: QWidget* m_Parent; QGridLayout* m_Layout; QLabel* m_SelectedImage; QAction* m_DrawLine; QAction* m_DrawPath; QAction* m_DrawAngle; QAction* m_DrawFourPointAngle; QAction* m_DrawEllipse; QAction* m_DrawRectangle; QAction* m_DrawPolygon; QToolBar* m_DrawActionsToolBar; QActionGroup* m_DrawActionsGroup; QTextBrowser* m_SelectedPlanarFiguresText; QPushButton* m_CopyToClipboard; vtkRenderer * m_MeasurementInfoRenderer; vtkCornerAnnotation *m_MeasurementInfoAnnotation; // Selection service /// berry::SelectionChangedAdapter must be a friend to call friend struct berry::SelectionChangedAdapter; berry::ISelectionListener::Pointer m_SelectionListener; mitk::DataStorageSelection::Pointer m_SelectedPlanarFigures; /// Selected image on which measurements will be performed /// mitk::DataStorageSelection::Pointer m_SelectedImageNode; mitk::DataNode::Pointer m_CurrentFigureNode; /// Counter variables to give a newly created Figure a unique name. /// unsigned int m_LineCounter; unsigned int m_PathCounter; unsigned int m_AngleCounter; unsigned int m_FourPointAngleCounter; unsigned int m_EllipseCounter; unsigned int m_RectangleCounter; unsigned int m_PolygonCounter; unsigned int m_EndPlacementObserverTag; unsigned int m_SelectObserverTag; unsigned int m_StartInteractionObserverTag; unsigned int m_EndInteractionObserverTag; bool m_Visible; bool m_CurrentFigureNodeInitialized; bool m_Activated; /// /// Saves the last renderwindow any info data was inserted /// QmitkRenderWindow* m_LastRenderWindow; private: mitk::DataNode::Pointer DetectTopMostVisibleImage(); }; #endif // QMITK_MEASUREMENT_H__INCLUDED diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.cpp index 77c03c0626..47eb191575 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.cpp @@ -1,125 +1,124 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPlanarFiguresTableModel.h" #include #include #include QmitkPlanarFiguresTableModel::QmitkPlanarFiguresTableModel( mitk::DataStorage::Pointer _DataStorage, mitk::NodePredicateBase* _Predicate, QObject* parent ) : QmitkDataStorageTableModel(_DataStorage, _Predicate, parent) { } QmitkPlanarFiguresTableModel::~QmitkPlanarFiguresTableModel() { } QVariant QmitkPlanarFiguresTableModel::headerData( int section, Qt::Orientation orientation, int role ) const { QVariant headerData; // show only horizontal header if ( role == Qt::DisplayRole ) { if( orientation == Qt::Horizontal ) { // first column: "Name" if(section == 0) headerData = "Name"; else if(section == 1) headerData = "Info"; } else if( orientation == Qt::Vertical ) { // show numbers for rows headerData = section+1; } } return headerData; } Qt::ItemFlags QmitkPlanarFiguresTableModel::flags( const QModelIndex &index ) const { // name & visibility is editable if (index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable; else return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } int QmitkPlanarFiguresTableModel::columnCount( const QModelIndex & ) const { return 2; } QVariant QmitkPlanarFiguresTableModel::data( const QModelIndex &index, int role ) const { QVariant data; if(!index.isValid()) return data; mitk::DataNode::Pointer node = this->m_NodeSet.at(index.row()); if(!node) return data; if(index.column() == 0 && role == Qt::DecorationRole) { if(node) { QmitkNodeDescriptor* nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(node); data = nodeDescriptor->GetIcon(); } } else if(index.column() == 1) { if(role == Qt::DisplayRole || role == Qt::ToolTipRole) { QString info; mitk::PlanarFigure* planarFigure = dynamic_cast(node->GetData()); if(!planarFigure) return data; mitk::PlanarAngle* planarAngle = dynamic_cast(planarFigure); double featureQuantity; for(unsigned int i=0; iGetNumberOfFeatures(); ++i) { featureQuantity = planarFigure->GetQuantity(i); if(planarAngle && i == planarAngle->FEATURE_ID_ANGLE) featureQuantity = featureQuantity * 180 / vnl_math::pi; //std::ostringstream s; s.precision(2); s << featureQuantity; info.append(QString("%1: %2 %3") .arg(QString(planarFigure->GetFeatureName(i))) .arg(featureQuantity, 0, 'f', 2) .arg(QString(planarFigure->GetFeatureUnit(i)))); if((i+1) != planarFigure->GetNumberOfFeatures()) info.append(", "); data = info; } } } else return QmitkDataStorageTableModel::data(index, role); return data; } diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.h b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.h index 5cf2315a08..a901f4751a 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.h +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkPlanarFiguresTableModel.h @@ -1,76 +1,75 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkPlanarFiguresTableModel_h #define QmitkPlanarFiguresTableModel_h /// Toolkit includes. #include /// Forward declarations. /// /// \class QmitkPlanarFiguresTableModel /// /// \brief A table model for a set of DataNodes defined by a predicate. /// \TODO make columns interchangeable, select which properties to show as columns /// class QmitkPlanarFiguresTableModel : public QmitkDataStorageTableModel { Q_OBJECT //#Ctors/Dtor public: /// /// Constructs a new QmitkPlanarFiguresTableModel and sets a predicate that defines /// this list. /// \see setPredicate() /// QmitkPlanarFiguresTableModel(mitk::DataStorage::Pointer _DataStorage, mitk::NodePredicateBase* _Predicate = 0 , QObject* parent = 0 ); /// /// Standard dtor. Delete predicate, disconnect from DataStorage. /// virtual ~QmitkPlanarFiguresTableModel(); //# Public GETTER public: /// /// Overridden from QAbstractTableModel. Returns the header data at section /// for given orientation and role. /// QVariant headerData(int section, Qt::Orientation orientation, int role) const; /// /// Overridden from QAbstractTableModel. Returns what can be done /// with an item. /// Qt::ItemFlags flags(const QModelIndex &index) const; /// /// Overridden from QAbstractTableModel. Returns the number of features (columns) to display. /// int columnCount(const QModelIndex &parent) const; /// /// Overridden from QAbstractTableModel. Returns the data at index for given role. /// QVariant data(const QModelIndex &index, int role) const; }; #endif diff --git a/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.cpp b/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.cpp index 44d8642dac..422457e262 100644 --- a/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.cpp +++ b/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.cpp @@ -1,232 +1,231 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkMeshDecimationView.h" #include "QmitkStdMultiWidget.h" // Qt #include #include #include // mitk #include #include #include // VTK #include #include #include const std::string QmitkMeshDecimationView::VIEW_ID = "org.mitk.views.meshdecimation"; QmitkMeshDecimationView::QmitkMeshDecimationView() : QmitkAbstractView() , m_Controls( 0 ) , m_MessageBox( 0 ) , m_MessageBoxDisplayTime( 5 ) , m_MessageBoxTimer( new QTimer(this) ) { m_MessageBoxTimer->setInterval(1000); connect(m_MessageBoxTimer, SIGNAL(timeout()), this, SLOT(MessageBoxTimer())); } QmitkMeshDecimationView::~QmitkMeshDecimationView() { } void QmitkMeshDecimationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkMeshDecimationView; m_Controls->setupUi( parent ); connect((QObject*)(m_Controls->Decimate), SIGNAL(clicked()), this, SLOT(Decimate())); } } void QmitkMeshDecimationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes) { this->m_Node = 0; this->DisableGui(); for( int i=0; iGetData(); if( dynamic_cast( baseData ) != 0 ) { this->m_Node = nodes.at(i); this->m_Controls->NodeLabel->setEnabled( true ); this->m_Controls->TargetReduction->setEnabled( true ); this->m_Controls->Decimate->setEnabled( true ); this->m_Controls->DecimationType->setEnabled( true ); break; } } this->UpdateNodeLabel(); } void QmitkMeshDecimationView::SetFocus() { m_Controls->NodeLabel->setFocus(); } void QmitkMeshDecimationView::DisableGui() { this->m_Controls->NodeLabel->setEnabled( false ); this->m_Controls->TargetReduction->setEnabled( false ); this->m_Controls->Decimate->setEnabled( false ); this->m_Controls->DecimationType->setEnabled( false ); } void QmitkMeshDecimationView::UpdateNodeLabel() { QString nodeLabel = "none selected"; if (this->m_Node.IsNotNull()) { vtkPolyData* polyData = static_cast(this->m_Node->GetData())->GetVtkPolyData(); nodeLabel = QString::fromStdString( this->m_Node->GetName() ); nodeLabel.append(" ("); nodeLabel.append( QString("%1").arg( polyData->GetNumberOfCells() ) ); nodeLabel.append(" cells)"); } this->m_Controls->NodeLabel->setText( nodeLabel ); } void QmitkMeshDecimationView::Decimate() { if (this->m_Node.IsNotNull()) { this->WaitCursorOn(); QString error; try { vtkPolyData* polyData = static_cast(this->m_Node->GetData())->GetVtkPolyData(); int startingNumberOfCells = polyData->GetNumberOfCells(); if( startingNumberOfCells == 0 ) throw std::logic_error("Could not reduce Mesh since it is already empty."); double targetReduction = static_cast(this->m_Controls->TargetReduction->value()) / 100.0; vtkPolyData* newPolyData = 0; if( this->m_Controls->DecimationType->currentText() == "DecimatePro" ) { vtkSmartPointer decimator = vtkDecimatePro::New(); decimator->SetInput( polyData ); decimator->SetTargetReduction( targetReduction ); decimator->SetPreserveTopology( 1 ); decimator->Update(); newPolyData = decimator->GetOutput(); } else { vtkSmartPointer decimator = vtkQuadricDecimation::New(); decimator->SetInput( polyData ); decimator->SetTargetReduction( targetReduction ); decimator->Update(); newPolyData = decimator->GetOutput(); } if( newPolyData != 0 ) { static_cast(this->m_Node->GetData())->SetVtkPolyData(newPolyData); this->m_Node->Update(); this->UpdateNodeLabel(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } int endingNumberOfCells = newPolyData->GetNumberOfCells(); int reducedCells = startingNumberOfCells - endingNumberOfCells; QString message; if( reducedCells == 0 ) message = "Decimation was not able to reduce any more cells from Mesh."; else message = QString("Decimation successful. %1 cells removed").arg(reducedCells); this->WaitCursorOff(); this->ShowAutoCloseMessageDialog(message); } catch(std::exception& e) { this->WaitCursorOff(); error = QString::fromStdString(e.what()); } catch(...) { this->WaitCursorOff(); error = "An unknown error occured. Please report error at bugs.mitk.org."; } if( !error.isEmpty() ) this->ShowAutoCloseErrorDialog(error); } else this->DisableGui(); } void QmitkMeshDecimationView::MessageBoxTimer() { m_MessageBoxDisplayTime--; QString text = m_MessageBoxText; text.append( QString(" (Will close in %1 seconds)").arg(m_MessageBoxDisplayTime) ); m_MessageBox->setText( text ); if( m_MessageBoxDisplayTime == 0 ) { m_MessageBox->accept(); } } void QmitkMeshDecimationView::ShowAutoCloseErrorDialog( const QString& error ) { m_MessageBox = new QMessageBox(QMessageBox::Warning, "Warning", error, QMessageBox::Ok ); m_MessageBoxDisplayTime = 5; m_MessageBoxText = error; this->MessageBoxTimer(); m_MessageBoxTimer->start(); m_MessageBox->exec(); m_MessageBoxTimer->stop(); delete m_MessageBox; m_MessageBox = 0; } void QmitkMeshDecimationView::ShowAutoCloseMessageDialog( const QString& message ) { m_MessageBox = new QMessageBox(QMessageBox::Information, "Information", message, QMessageBox::Ok ); m_MessageBoxDisplayTime = 5; m_MessageBoxText = message; this->MessageBoxTimer(); m_MessageBoxTimer->start(); m_MessageBox->exec(); m_MessageBoxTimer->stop(); delete m_MessageBox; m_MessageBox = 0; } diff --git a/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.h b/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.h index e333577be4..ac916a1c22 100644 --- a/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.h +++ b/Plugins/org.mitk.gui.qt.meshdecimation/src/internal/QmitkMeshDecimationView.h @@ -1,72 +1,71 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkMeshDecimationView_h #define QmitkMeshDecimationView_h #include #include #include #include #include #include "ui_QmitkMeshDecimationView.h" /*! \brief QmitkMeshDecimationView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkMeshDecimationView : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkMeshDecimationView(); virtual ~QmitkMeshDecimationView(); virtual void CreateQtPartControl(QWidget *parent); virtual void SetFocus(); virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList&); protected slots: void Decimate(); void MessageBoxTimer(); protected: void DisableGui(); void UpdateNodeLabel(); void ShowAutoCloseErrorDialog( const QString& error ); void ShowAutoCloseMessageDialog( const QString& message ); Ui::QmitkMeshDecimationView* m_Controls; mitk::WeakPointer m_Node; QWidget* m_Parent; QMessageBox* m_MessageBox; int m_MessageBoxDisplayTime; QString m_MessageBoxText; QTimer *m_MessageBoxTimer; }; #endif // _QMITKMESHSMOOTHINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.cpp index 907f0221fd..51f34fc47c 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.cpp +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.cpp @@ -1,772 +1,771 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision: 16947 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkMovieMaker.h" //#include "QmitkMovieMakerControls.h" #include "QmitkStepperAdapter.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "QmitkMovieMaker.h" //#include "QmitkMovieMakerControls.h" #include "QmitkStepperAdapter.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "mitkVtkPropRenderer.h" #include "mitkGlobalInteraction.h" #include #include #include #include #include #include #include #include #include #include "qapplication.h" #include "vtkImageWriter.h" #include "vtkJPEGWriter.h" #include "vtkPNGWriter.h" #include "vtkRenderLargeImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTestUtilities.h" #include #include "vtkMitkRenderProp.h" #include #include #include "vtkRenderWindowInteractor.h" #include QmitkMovieMaker::QmitkMovieMaker(QObject *parent, const char * /*name*/) : QmitkFunctionality(), m_Controls(NULL), m_StepperAdapter(NULL), m_FocusManagerCallback(0), m_Looping(true), m_Direction(0), m_Aspect(0) { parentWidget = parent; m_Timer = new QTimer(this); m_Time = new QTime(); m_FocusManagerCallback = MemberCommand::New(); m_FocusManagerCallback->SetCallbackFunction(this, &QmitkMovieMaker::FocusChange); m_movieGenerator = mitk::MovieGenerator::New(); if (m_movieGenerator.IsNull()) { MITK_ERROR << "Either mitk::MovieGenerator is not implemented for your"; MITK_ERROR << " platform or an error occurred during"; MITK_ERROR << " mitk::MovieGenerator::New()" ; } } QmitkMovieMaker::~QmitkMovieMaker() { delete m_StepperAdapter; delete m_Timer; delete m_Time; //delete m_RecordingRenderer; } mitk::BaseController* QmitkMovieMaker::GetSpatialController() { mitk::BaseRenderer* focusedRenderer = mitk::GlobalInteraction::GetInstance()->GetFocus(); if (mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget1->GetRenderWindow()) == focusedRenderer) { return GetActiveStdMultiWidget()->mitkWidget1->GetController(); } else if (mitk::BaseRenderer::GetInstance( GetActiveStdMultiWidget()->mitkWidget2->GetRenderWindow()) == focusedRenderer) { return GetActiveStdMultiWidget()->mitkWidget2->GetController(); } else if (mitk::BaseRenderer::GetInstance( GetActiveStdMultiWidget()->mitkWidget3->GetRenderWindow()) == focusedRenderer) { return GetActiveStdMultiWidget()->mitkWidget3->GetController(); } else if (mitk::BaseRenderer::GetInstance( GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow()) == focusedRenderer) { return GetActiveStdMultiWidget()->mitkWidget4->GetController(); } return GetActiveStdMultiWidget()->mitkWidget4->GetController(); } mitk::BaseController* QmitkMovieMaker::GetTemporalController() { return GetActiveStdMultiWidget()->GetTimeNavigationController(); } void QmitkMovieMaker::CreateConnections() { if (m_Controls) { // start / pause / stop playing connect((QObject*) m_Controls->btnPlay, SIGNAL(clicked()), (QObject*) this, SLOT(StartPlaying())); connect((QObject*) m_Controls->btnPause, SIGNAL(clicked()), this, SLOT(PausePlaying())); connect((QObject*) m_Controls->btnStop, SIGNAL(clicked()), this, SLOT(StopPlaying())); connect((QObject*) m_Controls->rbtnForward, SIGNAL(clicked()), this, SLOT(RBTNForward())); connect((QObject*) m_Controls->rbtnBackward, SIGNAL(clicked()), this, SLOT(RBTNBackward())); connect((QObject*) m_Controls->rbtnPingPong, SIGNAL(clicked()), this, SLOT(RBTNPingPong())); // radio button group: forward, backward, ping-pong connect( this, SIGNAL(SwitchDirection(int)), this, SLOT(SetDirection(int)) ); // radio button group: spatial, temporal connect((QObject*) m_Controls->rbtnSpatial, SIGNAL(clicked()), this, SLOT(RBTNSpatial())); connect((QObject*) m_Controls->rbtnTemporal, SIGNAL(clicked()), this, SLOT(RBTNTemporal())); connect((QObject*) m_Controls->rbtnCombined, SIGNAL(clicked()), this, SLOT(RBTNCombined())); connect( this, SIGNAL(SwitchAspect(int)), this, SLOT(SetAspect(int)) ); // stepper window selection connect((QObject*) (m_Controls->cmbSelectedStepperWindow), SIGNAL ( activated ( int) ), (QObject*) this, SLOT ( SetStepperWindow (int) ) ); // recording window selection connect((QObject*) (m_Controls->cmbSelectedRecordingWindow), SIGNAL ( activated ( int) ), (QObject*) this, SLOT ( SetRecordingWindow (int) ) ); // advance the animation // every timer tick connect((QObject*) m_Timer, SIGNAL(timeout()), this, SLOT(AdvanceAnimation())); // movie generation // when the movie button is clicked connect((QObject*) m_Controls->btnMovie, SIGNAL(clicked()), this, SLOT(GenerateMovie())); connect((QObject*) m_Controls->btnScreenshot, SIGNAL(clicked()), this, SLOT( GenerateScreenshot())); connect((QObject*) m_Controls->m_HRScreenshot, SIGNAL(clicked()), this, SLOT( GenerateHR3DScreenshot())); // blocking of ui elements during movie generation connect((QObject*) this, SIGNAL(StartBlockControls()), (QObject*) this, SLOT(BlockControls())); connect((QObject*) this, SIGNAL(EndBlockControls()), (QObject*) this, SLOT(UnBlockControls())); connect((QObject*) this, SIGNAL(EndBlockControlsMovieDeactive()), (QObject*) this, SLOT( UnBlockControlsMovieDeactive())); // allow for change of spatialtime relation connect((QObject*) m_Controls->spatialTimeRelation, SIGNAL(valueChanged ( int ) ), this, SLOT( DeleteMStepper() ) ); m_Controls->btnScreenshot->setVisible(false); m_Controls->m_HRScreenshot->setVisible(false); } } void QmitkMovieMaker::Activated() { QmitkFunctionality::Activated(); // create a member command that will be executed from the observer itk::SimpleMemberCommand::Pointer stepperChangedCommand; stepperChangedCommand = itk::SimpleMemberCommand::New(); // set the callback function of the member command stepperChangedCommand->SetCallbackFunction(this, &QmitkMovieMaker::UpdateGUI); // add an observer to the data tree node pointer connected to the above member command MITK_INFO << "Add observer on insertion point node in NavigationPathController::AddObservers"; m_StepperObserverTag = this->GetTemporalController()->GetTime()->AddObserver( itk::ModifiedEvent(), stepperChangedCommand); m_FocusManagerObserverTag = mitk::GlobalInteraction::GetInstance()->GetFocusManager()->AddObserver(mitk::FocusEvent(), m_FocusManagerCallback); this->UpdateGUI(); // Initialize steppers etc. this->FocusChange(); } void QmitkMovieMaker::Deactivated() { QmitkFunctionality::Deactivated(); this->GetTemporalController()->GetTime()->RemoveObserver(m_StepperObserverTag); mitk::GlobalInteraction::GetInstance()->GetFocusManager()->RemoveObserver( m_FocusManagerObserverTag); // remove (if tag is invalid, nothing is removed) } void QmitkMovieMaker::FocusChange() { mitk::Stepper *stepper = this->GetAspectStepper(); m_StepperAdapter->SetStepper(stepper); // Make the stepper movement non-inverted stepper->InverseDirectionOff(); // Set stepping direction and aspect (spatial / temporal) for new stepper this->UpdateLooping(); this->UpdateDirection(); // Set newly focused window as active in "Selected Window" combo box const mitk::RenderingManager::RenderWindowVector rwv = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); int i; mitk::RenderingManager::RenderWindowVector::const_iterator iter; for (iter = rwv.begin(), i = 0; iter != rwv.end(); ++iter, ++i) { mitk::BaseRenderer* focusedRenderer = mitk::GlobalInteraction::GetInstance()->GetFocusManager()->GetFocused(); if (focusedRenderer == mitk::BaseRenderer::GetInstance((*iter))) { m_Controls->cmbSelectedStepperWindow->setCurrentIndex(i); // this->cmbSelectedStepperWindow_activated(i); this->SetStepperWindow(i); m_Controls->cmbSelectedRecordingWindow->setCurrentIndex(i); // this->cmbSelectedRecordWindow_activated(i); this->SetRecordingWindow(i); break; } } } void QmitkMovieMaker::AdvanceAnimation() { // This method is called when a timer timeout occurs. It increases the // stepper value according to the elapsed time and the stepper interval. // Note that a screen refresh is not forced, but merely requested, and may // occur only after more calls to AdvanceAnimation(). mitk::Stepper* stepper = this->GetAspectStepper(); m_StepperAdapter->SetStepper(stepper); int elapsedTime = m_Time->elapsed(); m_Time->restart(); static double increment = 0.0; increment = increment - static_cast (increment); increment += elapsedTime * stepper->GetSteps() / (m_Controls->spnDuration->value() * 1000.0); int i, n = static_cast (increment); for (i = 0; i < n; ++i) { stepper->Next(); } } void QmitkMovieMaker::RenderSlot() { int *i = widget->GetRenderWindow()->GetSize(); m_PropRenderer->Resize(i[0], i[1]); widget->GetRenderWindow()->Render(); } void QmitkMovieMaker::PausePlaying() { m_Controls->slidAngle->setDisabled(false); m_Controls->btnMovie->setEnabled(true); m_Controls->btnPlay->setEnabled(true); m_Controls->btnScreenshot->setEnabled(true); m_Timer->stop(); m_Controls->btnPlay->setHidden(false); m_Controls->btnPause->setHidden(true); if (m_movieGenerator.IsNull()) m_Controls->btnMovie->setEnabled(false); } void QmitkMovieMaker::StopPlaying() { m_Controls->slidAngle->setDisabled(false); m_Controls->btnMovie->setEnabled(true); m_Controls->btnPlay->setEnabled(true); m_Controls->btnScreenshot->setEnabled(true); m_Controls->btnPlay->setHidden(false); m_Controls->btnPause->setHidden(true); m_Timer->stop(); switch (m_Direction) { case 0: case 2: this->GetAspectStepper()->First(); break; case 1: this->GetAspectStepper()->Last(); break; } // Reposition slider GUI element m_StepperAdapter->SetStepper(this->GetAspectStepper()); if (m_movieGenerator.IsNull()) m_Controls->btnMovie->setEnabled(false); } void QmitkMovieMaker::SetLooping(bool looping) { m_Looping = looping; this->UpdateLooping(); } void QmitkMovieMaker::SetDirection(int direction) { m_Direction = direction; this->UpdateDirection(); } void QmitkMovieMaker::SetAspect(int aspect) { m_Aspect = aspect; m_StepperAdapter->SetStepper(this->GetAspectStepper()); this->UpdateLooping(); this->UpdateDirection(); } void QmitkMovieMaker::SetStepperWindow(int window) { // Set newly selected window / renderer as focused const mitk::RenderingManager::RenderWindowVector rwv = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); //Delete MultiStepper DeleteMStepper(); int i; mitk::RenderingManager::RenderWindowVector::const_iterator iter; for (iter = rwv.begin(), i = 0; iter != rwv.end(); ++iter, ++i) { if (i == window) { mitk::GlobalInteraction::GetInstance()->GetFocusManager() ->SetFocused( mitk::BaseRenderer::GetInstance((*iter))); break; } } } void QmitkMovieMaker::SetRecordingWindow(int window) { // Set newly selected window for recording const mitk::RenderingManager::RenderWindowVector rwv = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); //Delete MultiStepper DeleteMStepper(); int i; mitk::RenderingManager::RenderWindowVector::const_iterator iter; for (iter = rwv.begin(), i = 0; iter != rwv.end(); ++iter, ++i) { if (i == window) { m_RecordingRenderer = mitk::BaseRenderer::GetInstance((*iter)); break; } } } void QmitkMovieMaker::UpdateLooping() { this->GetAspectStepper()->SetAutoRepeat(m_Looping); } void QmitkMovieMaker::UpdateDirection() { mitk::Stepper* stepper = this->GetAspectStepper(); switch (m_Direction) { case 0: stepper->InverseDirectionOff(); stepper->PingPongOff(); break; case 1: stepper->InverseDirectionOn(); stepper->PingPongOff(); break; case 2: stepper->PingPongOn(); break; } } mitk::Stepper* QmitkMovieMaker::GetAspectStepper() { if (m_Aspect == 0) { m_Stepper = NULL; return this->GetSpatialController()->GetSlice(); } else if (m_Aspect == 1) { m_Stepper = NULL; return this->GetTemporalController()->GetTime(); } else if (m_Aspect == 2) { if (m_Stepper.IsNull()) { int rel = m_Controls->spatialTimeRelation->value(); int timeRepeat = 1; int sliceRepeat = 1; if (rel < 0) { sliceRepeat = -rel; } else if (rel > 0) { timeRepeat = rel; } m_Stepper = mitk::MultiStepper::New(); m_Stepper->AddStepper(this->GetSpatialController()->GetSlice(), sliceRepeat); m_Stepper->AddStepper(this->GetTemporalController()->GetTime(), timeRepeat); } return m_Stepper.GetPointer(); } else { // should never get here return 0; } } void QmitkMovieMaker::GenerateMovie() { emit StartBlockControls(); // provide the movie generator with the stepper and rotate the camera each step if (m_movieGenerator.IsNotNull()) { m_movieGenerator->SetStepper(this->GetAspectStepper()); m_movieGenerator->SetRenderer(m_RecordingRenderer); m_movieGenerator->SetFrameRate(static_cast (360 / (m_Controls->spnDuration->value()))); // QString movieFileName = QFileDialog::getSaveFileName( QString::null, "Movie (*.avi)", 0, "movie file dialog", "Choose a file name" ); QString movieFileName = QFileDialog::getSaveFileName(0, "Choose a file name", QString::null, "Movie (*.avi)", 0, 0); if (movieFileName.isEmpty() == false) { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_movieGenerator->SetFileName(movieFileName.toAscii()); m_movieGenerator->WriteMovie(); } emit EndBlockControls(); } else { MITK_ERROR << "Either mitk::MovieGenerator is not implemented for your"; MITK_ERROR << " platform or an error occurred during"; MITK_ERROR << " mitk::MovieGenerator::New()"; emit EndBlockControlsMovieDeactive(); } } void QmitkMovieMaker::GenerateScreenshot() { emit StartBlockControls(); QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)"); vtkRenderer* renderer = mitk::GlobalInteraction::GetInstance()->GetFocus()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, 1, fileName); if (m_movieGenerator.IsNotNull()) emit EndBlockControls(); else emit EndBlockControlsMovieDeactive(); } void QmitkMovieMaker::GenerateHR3DScreenshot() { emit StartBlockControls(); QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)"); // only works correctly for 3D RenderWindow vtkRenderer* renderer = m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, 4, fileName); if (m_movieGenerator.IsNotNull()) emit EndBlockControls(); else emit EndBlockControlsMovieDeactive(); } void QmitkMovieMaker::UpdateGUI() { int bla = this->GetTemporalController()->GetTime()->GetSteps(); if (bla < 2) { m_Controls->rbtnTemporal->setEnabled(false); m_Controls->rbtnCombined->setEnabled(false); m_Controls->spatialTimeRelation->setEnabled(false); } else { m_Controls->rbtnTemporal->setEnabled(true); m_Controls->rbtnCombined->setEnabled(true); m_Controls->spatialTimeRelation->setEnabled(true); } } void QmitkMovieMaker::DataStorageChanged() { // UpdateGUI(); } void QmitkMovieMaker::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkMovieMakerControls; m_Controls->setupUi(parent); m_StepperAdapter = new QmitkStepperAdapter((QObject*) m_Controls->slidAngle, this->GetSpatialController()->GetSlice(), "AngleStepperToMovieMakerFunctionality"); // Initialize "Selected Window" combo box const mitk::RenderingManager::RenderWindowVector rwv = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); mitk::RenderingManager::RenderWindowVector::const_iterator iter; unsigned int i = 0; for (iter = rwv.begin(); iter != rwv.end(); ++iter) { QString name(mitk::BaseRenderer::GetInstance((*iter))->GetName()); if (name=="stdmulti.widget1") { m_Controls->cmbSelectedStepperWindow->insertItem(i, "Transversal"); m_Controls->cmbSelectedRecordingWindow->insertItem(i++, "Transversal"); } else if (name=="stdmulti.widget2") { m_Controls->cmbSelectedStepperWindow->insertItem(i, "Sagittal"); m_Controls->cmbSelectedRecordingWindow->insertItem(i++, "Sagittal"); } else if (name=="stdmulti.widget3") { m_Controls->cmbSelectedStepperWindow->insertItem(i, "Coronal"); m_Controls->cmbSelectedRecordingWindow->insertItem(i++, "Coronal"); } else if (name=="stdmulti.widget4") { m_Controls->cmbSelectedStepperWindow->insertItem(i, "3D Window"); m_Controls->cmbSelectedRecordingWindow->insertItem(i++, "3D Window"); } else { m_Controls->cmbSelectedStepperWindow->insertItem(i, name); m_Controls->cmbSelectedRecordingWindow->insertItem(i++, name); } } m_Controls->btnPause->setHidden(true); if (m_movieGenerator.IsNull()) m_Controls->btnMovie->setEnabled(false); } this->CreateConnections(); } void QmitkMovieMaker::StartPlaying() { m_Controls->slidAngle->setDisabled(true); m_Controls->btnMovie->setEnabled(false); m_Controls->btnPlay->setEnabled(false); m_Controls->btnScreenshot->setEnabled(false); // Restart timer with 5 msec interval - this should be fine-grained enough // even for high display refresh frequencies m_Timer->start(5); m_Time->restart(); m_Controls->btnPlay->setHidden(true); m_Controls->btnPause->setHidden(false); if (m_movieGenerator.IsNull()) m_Controls->btnMovie->setEnabled(false); } void QmitkMovieMaker::RBTNForward() { emit SwitchDirection(0); } void QmitkMovieMaker::RBTNBackward() { emit SwitchDirection(1); } void QmitkMovieMaker::RBTNPingPong() { emit SwitchDirection(2); } void QmitkMovieMaker::RBTNSpatial() { emit SwitchAspect(0); } void QmitkMovieMaker::RBTNTemporal() { emit SwitchAspect(1); } void QmitkMovieMaker::RBTNCombined() { emit SwitchAspect(2); } void QmitkMovieMaker::BlockControls() { BlockControls(true); } void QmitkMovieMaker::UnBlockControls() { BlockControls(false); } void QmitkMovieMaker::UnBlockControlsMovieDeactive() { BlockControls(false); m_Controls->btnMovie->setEnabled(false); } void QmitkMovieMaker::BlockControls(bool blocked) { m_Controls->slidAngle->setDisabled(blocked); m_Controls->spnDuration->setEnabled(!blocked); m_Controls->btnPlay->setEnabled(!blocked); m_Controls->btnMovie->setEnabled(!blocked); m_Controls->btnScreenshot->setEnabled(!blocked); } void QmitkMovieMaker::StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget) { m_MultiWidget = &stdMultiWidget; m_Parent->setEnabled(true); } void QmitkMovieMaker::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; m_Parent->setEnabled(false); } void QmitkMovieMaker::TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName) { if ((renderer == NULL) ||(magnificationFactor < 1) || fileName.isEmpty()) return; bool doubleBuffering( renderer->GetRenderWindow()->GetDoubleBuffer() ); renderer->GetRenderWindow()->DoubleBufferOff(); vtkImageWriter* fileWriter; QFileInfo fi(fileName); QString suffix = fi.suffix(); if (suffix.compare("png", Qt::CaseInsensitive) == 0) { fileWriter = vtkPNGWriter::New(); } else // default is jpeg { vtkJPEGWriter* w = vtkJPEGWriter::New(); w->SetQuality(100); w->ProgressiveOff(); fileWriter = w; } vtkRenderLargeImage* magnifier = vtkRenderLargeImage::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(magnificationFactor); //magnifier->Update(); fileWriter->SetInput(magnifier->GetOutput()); fileWriter->SetFileName(fileName.toLatin1()); // vtkRenderLargeImage has problems with different layers, therefore we have to // temporarily deactivate all other layers. // we set the background to white, because it is nicer than black... double oldBackground[3]; renderer->GetBackground(oldBackground); double white[] = {1.0, 1.0, 1.0}; renderer->SetBackground(white); m_MultiWidget->DisableColoredRectangles(); m_MultiWidget->DisableDepartmentLogo(); m_MultiWidget->DisableGradientBackground(); m_MultiWidget->mitkWidget1->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget2->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget3->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget4->ActivateMenuWidget( false ); fileWriter->Write(); fileWriter->Delete(); m_MultiWidget->mitkWidget1->ActivateMenuWidget( true ); m_MultiWidget->mitkWidget2->ActivateMenuWidget( true ); m_MultiWidget->mitkWidget3->ActivateMenuWidget( true ); m_MultiWidget->mitkWidget4->ActivateMenuWidget( true ); m_MultiWidget->EnableColoredRectangles(); m_MultiWidget->EnableDepartmentLogo(); m_MultiWidget->EnableGradientBackground(); renderer->SetBackground(oldBackground); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void QmitkMovieMaker::DeleteMStepper() { m_Stepper = NULL; UpdateLooping(); } diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.h b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.h index b35e065b1d..734435875d 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.h +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMaker.h @@ -1,307 +1,306 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision: 15436 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QMITK_MOVIEMAKER_H__INCLUDED) #define QMITK_MOVIEMAKER_H__INCLUDED #include "QmitkFunctionality.h" #include "mitkCameraRotationController.h" #include "mitkStepper.h" #include "mitkMultiStepper.h" #include "mitkMovieGenerator.h" #include "itkCommand.h" #include "QVTKWidget.h" #include "vtkEventQtSlotConnect.h" #include "vtkRenderWindow.h" #include "mitkVtkPropRenderer.h" #include "ui_QmitkMovieMakerControls.h" //#include "../MovieMakerDll.h" //class QmitkStdMultiWidget; //class QmitkMovieMakerControls; class QmitkStepperAdapter; class vtkCamera; class QTimer; class QTime; /** * \brief Functionality for creating movies (AVIs) * \ingroup Functionalities * * * - \ref QmitkMovieMakerOverview * - \ref QmitkMovieMakerImplementation * - \ref QmitkMovieMakerTodo * * \section QmitkMovieMakerOverview Overview * * The MovieMaker functionality extends existing modes of data visualization * with animation capabilities. The animation aspect determines which * aspect of a visualization gets animated. This aspect can be spatial * (i.e. the camera position and orientation in a 3D view, or the selected * slice in a 2D view), temporal (the time step in a time-based dataset), or * something more sophisticated (for example, volume rendering transfer * functions might be changed dynamically as part of an animation to produce * interesting effects). Currently, the following animation modes are * supported: * * - Rotation of the camera around the dataset (3D views) * - Stepping through the dataset slice by slice (2D views) * - Stepping through a time-based dataset (2D and 3D views) * * As can be seen in the screenshot below, the functionality provides cine * controls to start, pause and stop the animation. The direction of the * animation can be selected (forward, backward or ping-pong). The animation * can be set to either the spatial or the temporal aspect, or to both * aspects combined. The cycle time determines the duration of one animation * loop. * * In a multi-view scenario, the animation is applied to the currently * focussed view. Other views which display the same data may be affected as * well. * * Animations can be written on disk; the corresponding button creates an * animation consisting of one single loop and writes every animation frame * into an AVI file. * * \image html QmitkMovieMakerGUI.png * * \section QmitkMovieMakerImplementation Implementation * * The following diagram provides an overview over the classes collaborating * with QmitkMovieMaker. * * \image html QmitkMovieMakerClasses.png * * The respective roles of these classes are: * - QmitkMovieMaker * - Provides a class interface for configuring and controlling the * animation * - Is associated with the user interface * - As a Functionality, controls initialization and maintainance of the * involved components * - mitk::BaseController * - Controls an animation aspect (slice selection, camera angle, ...) * - Subclass mitk::SliceNavigationController: Transfers the animation * requests to the associated Renderer for selecting a slice in a 3D * dataset * - Subclass mitk::CameraRotationController: Modifies the camera angle * - mitk::Stepper * - Link between MovieMaker and Controller * - Holds the current step position of the associated animation aspect * (e.g. the camera rotation angle, or the slice number) * - mitk::FocusManager * - Determines which of the available RenderWindows (and thereby which * Renderers) the animation shall be applied to * - mitk::BaseRenderer * - Controls the rendering of a dataset * - Target class of the animation * - mitk::MovieGenerator * - Writes an AVI file * * * \section QmitkMovieMakerTodo Future plans * * The basic animation capabilities of this functionality could be extended * to allow the creation of more sophisticated animations. Potentially useful * features include: * * - Camera paths: Allow the definition of complex camera paths along * which the camera can then be moved during an animation. This might be * done by defining camera keyframes between which camera movements are * interpolated (as in standard 3D animation applications). Paths derived * from anatomical features (e.g. vessel graphs) could also serve as a * basis for camera movements. * - Color / transfer function animation: Choosing suitable color * and transfer functions is critical to the quality and benefit of volume * rendering. Dynamically changing transfer functions could visually enrich * an animation. One way of achieving this could be to define transfer * function keyframes between which an animation interpolates. * */ class QmitkMovieMaker: public QmitkFunctionality { Q_OBJECT public: /** \brief Constructor. */ QmitkMovieMaker(QObject *parent=0, const char *name=0); QmitkMovieMaker(const QmitkMovieMaker& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } /** \brief Destructor. */ virtual ~QmitkMovieMaker(); /** \brief Method for creating the widget containing the application * controls, like sliders, buttons etc. */ void CreateQtPartControl(QWidget *parent); // virtual QWidget * CreateControlWidget(QWidget *parent); /** \brief Method for creating the connections of main and control widget. */ virtual void CreateConnections(); /** \brief Method for creating an QAction object, i.e. button & menu entry. * @param parent the parent QWidget */ // virtual QAction * CreateAction(QActionGroup *parent); virtual void Activated(); virtual void Deactivated(); /** \brief Called when another window receives the focus. */ void FocusChange(); virtual void DataStorageChanged(); /// /// Called when a StdMultiWidget is available. /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available. /// virtual void StdMultiWidgetNotAvailable(); signals: void StartBlockControls(); void EndBlockControls(); void EndBlockControlsMovieDeactive(); public slots: /** \brief Start playing the animation by restarting the timer. */ void StartPlaying(); /** \brief Pauses playing the animation by stopping the timer. */ void PausePlaying(); /** \brief Stops playing the animation and resets the stepper. */ void StopPlaying(); /** \brief Sets animation looping ON/OFF. */ void SetLooping(bool looping); /** \brief Sets the direction: 0 = forward, 1 = backward, 2 = pingpong. */ void SetDirection(int direction); /** \brief Sets the animation aspect: * 0 = spatial, 1 = temporal, 2 = combined. */ void SetAspect(int aspect); /** \brief Sets a specified stepper window, which is moving. */ void SetStepperWindow(int window); /** \brief Sets a specified recording window, from which the movie is generated. */ void SetRecordingWindow(int window); /** \brief Advances the animation by one frame. * Exactly how much the stepper advances depends on the time elapsed since * the last call to this function. */ void AdvanceAnimation(); protected slots: void RenderSlot(); void GenerateMovie(); void GenerateScreenshot(); void GenerateHR3DScreenshot(); void RBTNForward(); void RBTNBackward(); void RBTNPingPong(); void RBTNSpatial(); void RBTNTemporal(); void RBTNCombined(); void BlockControls(); void UnBlockControls(); void UnBlockControlsMovieDeactive(); void BlockControls(bool blocked); void DeleteMStepper(); signals: void SwitchDirection(int); void SwitchAspect(int); void SwitchSelectedStepperWindow(int); void SwitchSelectedRecordingWindow(int); protected: QObject *parentWidget; QVTKWidget * widget; QmitkStdMultiWidget* m_MultiWidget; vtkEventQtSlotConnect * connections; vtkRenderWindow * renderWindow; mitk::VtkPropRenderer::Pointer m_PropRenderer; Ui::QmitkMovieMakerControls* m_Controls; private: mitk::BaseController* GetSpatialController(); mitk::BaseController* GetTemporalController(); void UpdateLooping(); void UpdateDirection(); void UpdateGUI(); mitk::Stepper* GetAspectStepper(); /*! \brief taking a screenshot "from" the specified renderer \param magnificationFactor specifying the quality of the screenshot (the magnification of the actual RenderWindow size) \param fileName file location and name where the screenshot should be saved */ void TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName); QmitkStepperAdapter* m_StepperAdapter; typedef itk::SimpleMemberCommand MemberCommand; MemberCommand::Pointer m_FocusManagerCallback; QTimer* m_Timer; QTime* m_Time; bool m_Looping; int m_Direction; int m_Aspect; mitk::MultiStepper::Pointer m_Stepper; mitk::BaseRenderer * m_RecordingRenderer; mitk::MovieGenerator::Pointer m_movieGenerator; unsigned long m_FocusManagerObserverTag; unsigned long m_StepperObserverTag; }; #endif // !defined(QMITK_MOVIEMAKER_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp index a16a783436..61028bad02 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp @@ -1,381 +1,380 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision: 16947 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkScreenshotMaker.h" //#include "QmitkMovieMakerControls.h" #include "QmitkStepperAdapter.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "mitkVtkPropRenderer.h" #include "mitkGlobalInteraction.h" #include #include #include #include #include #include #include #include #include #include #include #include "qapplication.h" #include "vtkImageWriter.h" #include "vtkJPEGWriter.h" #include "vtkPNGWriter.h" #include "vtkRenderLargeImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTestUtilities.h" #include #include "vtkMitkRenderProp.h" #include #include #include "vtkRenderWindowInteractor.h" #include #include "mitkSliceNavigationController.h" #include "mitkPlanarFigure.h" QmitkScreenshotMaker::QmitkScreenshotMaker(QObject *parent, const char * /*name*/) : QmitkFunctionality(), m_Controls(NULL), m_SelectedNode(0), m_BackgroundColor(QColor(0,0,0)) { parentWidget = parent; } QmitkScreenshotMaker::~QmitkScreenshotMaker() { } void QmitkScreenshotMaker::CreateConnections() { if (m_Controls) { connect((QObject*) m_Controls->m_AllViews, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateMultiplanar3DHighresScreenshot())); connect((QObject*) m_Controls->m_View1, SIGNAL(clicked()), (QObject*) this, SLOT(View1())); connect((QObject*) m_Controls->m_View2, SIGNAL(clicked()), (QObject*) this, SLOT(View2())); connect((QObject*) m_Controls->m_View3, SIGNAL(clicked()), (QObject*) this, SLOT(View3())); connect((QObject*) m_Controls->m_Shot, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateMultiplanarScreenshots())); connect((QObject*) m_Controls->m_BackgroundColor, SIGNAL(clicked()), (QObject*) this, SLOT(SelectBackgroundColor())); connect((QObject*) m_Controls->btnScreenshot, SIGNAL(clicked()), this, SLOT(GenerateScreenshot())); connect((QObject*) m_Controls->m_HRScreenshot, SIGNAL(clicked()), this, SLOT(Generate3DHighresScreenshot())); QString styleSheet = "background-color:rgb(0,0,0)"; m_Controls->m_BackgroundColor->setStyleSheet(styleSheet); } } void QmitkScreenshotMaker::Activated() { QmitkFunctionality::Activated(); } void QmitkScreenshotMaker::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkScreenshotMaker::GenerateScreenshot() { QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath()+"/screenshot.jpg", "JPEG file (*.jpg);;PNG file (*.png)"); vtkRenderer* renderer = mitk::GlobalInteraction::GetInstance()->GetFocus()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, 1, fileName); } void QmitkScreenshotMaker::GenerateMultiplanarScreenshots() { QString fileName = QFileDialog::getExistingDirectory(NULL, "Save screenshots to...", QDir::currentPath()); if( fileName.isEmpty() ) { return; } //emit StartBlockControls(); mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 1,1,1 ) ); // n->SetProperty("helper object", mitk::BoolProperty::New(false)); } n = this->m_MultiWidget->GetWidgetPlane2(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 1,1,1 ) ); // n->SetProperty("helper object", mitk::BoolProperty::New(false)); } n = this->m_MultiWidget->GetWidgetPlane3(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 1,1,1 ) ); // n->SetProperty("helper object", mitk::BoolProperty::New(false)); } // only works correctly for 3D RenderWindow vtkRenderer* renderer = m_MultiWidget->mitkWidget1->GetRenderer()->GetVtkRenderer(); if (renderer != NULL) this->TakeScreenshot(renderer, 1, fileName+"/transversal.png"); renderer = m_MultiWidget->mitkWidget2->GetRenderer()->GetVtkRenderer(); if (renderer != NULL) this->TakeScreenshot(renderer, 1, fileName+"/sagittal.png"); renderer = m_MultiWidget->mitkWidget3->GetRenderer()->GetVtkRenderer(); if (renderer != NULL) this->TakeScreenshot(renderer, 1, fileName+"/coronal.png"); n = this->m_MultiWidget->GetWidgetPlane1(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 1,0,0 ) ); // n->SetProperty("helper object", mitk::BoolProperty::New(false)); } n = this->m_MultiWidget->GetWidgetPlane2(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 0,1,0 ) ); // n->SetProperty("helper object", mitk::BoolProperty::New(false)); } n = this->m_MultiWidget->GetWidgetPlane3(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 0,0,1 ) ); // n->SetProperty("helper object", mitk::BoolProperty::New(false)); } } void QmitkScreenshotMaker::Generate3DHighresScreenshot() { QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath()+"/3D_screenshot.jpg", "JPEG file (*.jpg);;PNG file (*.png)"); GenerateHR3DAtlasScreenshots(fileName); } void QmitkScreenshotMaker::GenerateMultiplanar3DHighresScreenshot() { QString fileName = QFileDialog::getExistingDirectory( NULL, "Save screenshots to...", QDir::currentPath()); if( fileName.isEmpty() ) { return; } GetCam()->Azimuth( -7.5 ); GetCam()->Roll(-4); GenerateHR3DAtlasScreenshots(fileName+"/3D_1.png"); GetCam()->Roll(4); GetCam()->Azimuth( 90 ); GetCam()->Elevation( 4 ); GenerateHR3DAtlasScreenshots(fileName+"/3D_2.png"); GetCam()->Elevation( 90 ); GetCam()->Roll( -2.5 ); GenerateHR3DAtlasScreenshots(fileName+"/3D_3.png"); } void QmitkScreenshotMaker::GenerateHR3DAtlasScreenshots(QString fileName) { // only works correctly for 3D RenderWindow vtkRenderer* renderer = m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, this->m_Controls->m_MagFactor->text().toFloat(), fileName); } vtkCamera* QmitkScreenshotMaker::GetCam() { mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow()); vtkCamera* cam = 0; const mitk::VtkPropRenderer *propRenderer = dynamic_cast( renderer ); if (propRenderer) { // get vtk renderer vtkRenderer* vtkrenderer = propRenderer->GetVtkRenderer(); if (vtkrenderer) { // get vtk camera vtkCamera* vtkcam = vtkrenderer->GetActiveCamera(); if (vtkcam) { // vtk smart pointer handling cam = vtkcam; cam->Register( NULL ); } } } return cam; } void QmitkScreenshotMaker::View1() { GetCam()->Elevation( 45 ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::View2() { GetCam()->Azimuth(45); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::View3() { GetCam()->Roll(45); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::OnSelectionChanged( std::vector nodes ) { if(nodes.size()) m_SelectedNode = nodes[0]; } void QmitkScreenshotMaker::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkScreenshotMakerControls; m_Controls->setupUi(parent); // Initialize "Selected Window" combo box const mitk::RenderingManager::RenderWindowVector rwv = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); } this->CreateConnections(); } void QmitkScreenshotMaker::StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget) { m_MultiWidget = &stdMultiWidget; m_Parent->setEnabled(true); } void QmitkScreenshotMaker::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; m_Parent->setEnabled(false); } void QmitkScreenshotMaker::TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName) { if ((renderer == NULL) ||(magnificationFactor < 1) || fileName.isEmpty()) return; bool doubleBuffering( renderer->GetRenderWindow()->GetDoubleBuffer() ); renderer->GetRenderWindow()->DoubleBufferOff(); vtkImageWriter* fileWriter; QFileInfo fi(fileName); QString suffix = fi.suffix(); if (suffix.compare("png", Qt::CaseInsensitive) == 0) { fileWriter = vtkPNGWriter::New(); } else // default is jpeg { vtkJPEGWriter* w = vtkJPEGWriter::New(); w->SetQuality(100); w->ProgressiveOff(); fileWriter = w; } vtkRenderLargeImage* magnifier = vtkRenderLargeImage::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(magnificationFactor); //magnifier->Update(); fileWriter->SetInput(magnifier->GetOutput()); fileWriter->SetFileName(fileName.toLatin1()); // vtkRenderLargeImage has problems with different layers, therefore we have to // temporarily deactivate all other layers. // we set the background to white, because it is nicer than black... double oldBackground[3]; renderer->GetBackground(oldBackground); // QColor color = QColorDialog::getColor(); double bgcolor[] = {m_BackgroundColor.red()/255.0, m_BackgroundColor.green()/255.0, m_BackgroundColor.blue()/255.0}; renderer->SetBackground(bgcolor); m_MultiWidget->DisableColoredRectangles(); m_MultiWidget->DisableDepartmentLogo(); m_MultiWidget->DisableGradientBackground(); m_MultiWidget->mitkWidget1->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget2->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget3->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget4->ActivateMenuWidget( false ); fileWriter->Write(); fileWriter->Delete(); m_MultiWidget->mitkWidget1->ActivateMenuWidget( true ); m_MultiWidget->mitkWidget2->ActivateMenuWidget( true ); m_MultiWidget->mitkWidget3->ActivateMenuWidget( true ); m_MultiWidget->mitkWidget4->ActivateMenuWidget( true ); m_MultiWidget->EnableColoredRectangles(); m_MultiWidget->EnableDepartmentLogo(); m_MultiWidget->EnableGradientBackground(); renderer->SetBackground(oldBackground); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void QmitkScreenshotMaker::SelectBackgroundColor() { m_BackgroundColor = QColorDialog::getColor(); m_Controls->m_BackgroundColor->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(m_BackgroundColor.red())); styleSheet.append(","); styleSheet.append(QString::number(m_BackgroundColor.green())); styleSheet.append(","); styleSheet.append(QString::number(m_BackgroundColor.blue())); styleSheet.append(")"); m_Controls->m_BackgroundColor->setStyleSheet(styleSheet); } diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.h b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.h index 5367a5c4d6..d243fcbc85 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.h +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.h @@ -1,130 +1,129 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision: 15436 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QMITK_ScreenshotMaker_H__INCLUDED) #define QMITK_ScreenshotMaker_H__INCLUDED #include "QmitkFunctionality.h" #include "mitkCameraRotationController.h" #include "mitkStepper.h" #include "mitkMultiStepper.h" #include "mitkMovieGenerator.h" #include "itkCommand.h" #include "QVTKWidget.h" #include "vtkEventQtSlotConnect.h" #include "vtkRenderWindow.h" #include "mitkVtkPropRenderer.h" #include "ui_QmitkScreenshotMakerControls.h" //#include "../MovieMakerDll.h" //class QmitkStdMultiWidget; //class QmitkMovieMakerControls; class QmitkStepperAdapter; class vtkCamera; class QTimer; class QTime; /** * \brief Functionality for creating movies (AVIs) * \ingroup Functionalities */ class QmitkScreenshotMaker: public QmitkFunctionality { Q_OBJECT public: /** \brief Constructor. */ QmitkScreenshotMaker(QObject *parent=0, const char *name=0); /** \brief Destructor. */ virtual ~QmitkScreenshotMaker(); /** \brief Method for creating the widget containing the application * controls, like sliders, buttons etc. */ void CreateQtPartControl(QWidget *parent); // virtual QWidget * CreateControlWidget(QWidget *parent); /** \brief Method for creating the connections of main and control widget. */ virtual void CreateConnections(); /** \brief Method for creating an QAction object, i.e. button & menu entry. * @param parent the parent QWidget */ // virtual QAction * CreateAction(QActionGroup *parent); virtual void Activated(); virtual void Deactivated(); /// /// Called when a StdMultiWidget is available. /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available. /// virtual void StdMultiWidgetNotAvailable(); signals: protected slots: void GenerateScreenshot(); void GenerateMultiplanarScreenshots(); void Generate3DHighresScreenshot(); void GenerateMultiplanar3DHighresScreenshot(); void View1(); void View2(); void View3(); void SelectBackgroundColor(); protected: QObject *parentWidget; QVTKWidget * widget; QmitkStdMultiWidget* m_MultiWidget; vtkEventQtSlotConnect * connections; vtkRenderWindow * renderWindow; mitk::VtkPropRenderer::Pointer m_PropRenderer; Ui::QmitkScreenshotMakerControls* m_Controls; private: void OnSelectionChanged( std::vector nodes ); vtkCamera* GetCam(); void GenerateHR3DAtlasScreenshots(QString fileName); void GenerateMultiplanarScreenshots(QString fileName); /*! \brief taking a screenshot "from" the specified renderer \param magnificationFactor specifying the quality of the screenshot (the magnification of the actual RenderWindow size) \param fileName file location and name where the screenshot should be saved */ void TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName); QColor m_BackgroundColor; mitk::DataNode* m_SelectedNode; }; #endif // !defined(QMITK_ScreenshotMaker_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.cpp b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.cpp index a94a160831..882edfca14 100755 --- a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.cpp +++ b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.cpp @@ -1,159 +1,158 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Qmitk related includes #include "QmitkPointSetInteractionView.h" #include "ui_QmitkPointSetInteractionViewControls.h" #include #include #include #include #include #include #include #include #include #include QmitkPointSetInteractionView::QmitkPointSetInteractionView( QObject* /*parent*/ ) : m_Controls(0) { } QmitkPointSetInteractionView::~QmitkPointSetInteractionView() { } void QmitkPointSetInteractionView::CreateQtPartControl( QWidget *parent ) { m_Controls = new Ui::QmitkPointSetInteractionControls; m_Controls->setupUi(parent); m_Controls->m_PbAddPointSet->connect( m_Controls->m_PbAddPointSet, SIGNAL( clicked() ) , this, SLOT( OnAddPointSetClicked() ) ); } void QmitkPointSetInteractionView::Activated() { // emulate datamanager selection std::vector selection = this->GetDataManagerSelection(); this->OnSelectionChanged( selection ); } void QmitkPointSetInteractionView::Deactivated() { // emulate empty selection std::vector selection; this->OnSelectionChanged( selection ); m_Controls->m_PointListWidget->DeactivateInteractor(true); } void QmitkPointSetInteractionView::OnAddPointSetClicked() { //Ask for the name of the point set bool ok = false; QString name = QInputDialog::getText( QApplication::activeWindow() , "Add point set...", "Enter name for the new point set", QLineEdit::Normal, "PointSet", &ok ); if ( ! ok || name.isEmpty() ) return; // //Create a new empty pointset // mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); // // Create a new data tree node // mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New(); // // fill the data tree node with the appropriate information // pointSetNode->SetData( pointSet ); pointSetNode->SetProperty( "name", mitk::StringProperty::New( name.toStdString() ) ); pointSetNode->SetProperty( "opacity", mitk::FloatProperty::New( 1 ) ); pointSetNode->SetColor( 1.0, 1.0, 0.0 ); // // add the node to the ds // this->GetDefaultDataStorage()->Add(pointSetNode); // make new selection and emulate selection for this std::vector selection; selection.push_back( pointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkPointSetInteractionView::OnSelectionChanged(std::vector nodes) { mitk::DataNode* selectedNode = 0; if(nodes.size() > 0) selectedNode = nodes.front(); mitk::PointSet* pointSet = 0; if(selectedNode) pointSet = dynamic_cast ( selectedNode->GetData() ); //if( m_SelectedPointSetInteractor.IsNotNull() ) //{ // mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_SelectedPointSetInteractor ); // m_SelectedPointSetInteractor = NULL; //} if (pointSet /*&& this->IsActivated()*/) { m_SelectedPointSetNode = selectedNode; m_Controls->m_CurrentPointSetLabel->setText(QString::fromStdString(selectedNode->GetName())); m_Controls->m_PointListWidget->SetPointSetNode(selectedNode); // add interactor //mitk::PointSetInteractor::Pointer _Interactor = mitk::PointSetInteractor::New("pointsetinteractor", selectedNode); //mitk::GlobalInteraction::GetInstance()->AddInteractor( _Interactor ); //m_SelectedPointSetInteractor = _Interactor; } else { m_Controls->m_CurrentPointSetLabel->setText("None"); m_Controls->m_PointListWidget->SetPointSetNode(0); } } bool QmitkPointSetInteractionView::IsExclusiveFunctionality() const { return true; } void QmitkPointSetInteractionView::NodeChanged( const mitk::DataNode* node ) { if(node == m_SelectedPointSetNode && m_Controls->m_CurrentPointSetLabel->text().toStdString() != node->GetName()) { m_Controls->m_CurrentPointSetLabel->setText(QString::fromStdString(node->GetName())); } } void QmitkPointSetInteractionView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { if(m_Controls) m_Controls->m_PointListWidget->SetMultiWidget( &stdMultiWidget ); } void QmitkPointSetInteractionView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { if(m_Controls) m_Controls->m_PointListWidget->SetMultiWidget( 0 ); } diff --git a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.h b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.h index f7dd04f989..6609d8d658 100755 --- a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.h +++ b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/QmitkPointSetInteractionView.h @@ -1,65 +1,64 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QmitkPointSetInteraction_H__INCLUDED) #define QmitkPointSetInteraction_H__INCLUDED #include #include #include #include #include namespace Ui { class QmitkPointSetInteractionControls; }; /*! \brief QmitkPointSetInteractionView */ class QmitkPointSetInteractionView : public QmitkFunctionality { Q_OBJECT public: QmitkPointSetInteractionView(QObject *parent=0); QmitkPointSetInteractionView(const QmitkPointSetInteractionView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkPointSetInteractionView(); virtual void CreateQtPartControl(QWidget *parent); void OnSelectionChanged(std::vector nodes); void Activated(); void Deactivated(); void NodeChanged(const mitk::DataNode* node); bool IsExclusiveFunctionality() const; virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); virtual void StdMultiWidgetClosed(QmitkStdMultiWidget& stdMultiWidget); protected slots: void OnAddPointSetClicked(); protected: Ui::QmitkPointSetInteractionControls * m_Controls; mitk::WeakPointer m_SelectedPointSetNode; mitk::WeakPointer m_SelectedPointSetInteractor; }; #endif // !defined(QmitkPointSetInteraction_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.cpp index 1c00a6c4bf..8e2b981284 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.cpp @@ -1,81 +1,80 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkCTKPythonShell.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkDataStorageEditorInput.h" // berry Includes #include #include #include #include #include #include #include #include QmitkCTKPythonShell::QmitkCTKPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent) { this->initialize( pythonManager ); m_PythonManager = pythonManager; QmitkPythonMediator::getInstance()->registerPasteCommandClient( this ); } QmitkCTKPythonShell::~QmitkCTKPythonShell() { QmitkPythonMediator::getInstance()->unregisterPasteCommandClient( this ); } void QmitkCTKPythonShell::dragEnterEvent(QDragEnterEvent *event) { event->accept(); } void QmitkCTKPythonShell::paste(const QString& command) { m_PythonManager->executeString( command ); } void QmitkCTKPythonShell::dropEvent(QDropEvent *event) { QList urls = event->mimeData()->urls(); for(int i = 0; i < urls.size(); i++) { m_PythonManager->executeString(urls[i].toString()); } } bool QmitkCTKPythonShell::canInsertFromMimeData( const QMimeData *source ) const { return true; } void QmitkCTKPythonShell::executeCommand(const QString& command) { emit this->executeCommandSignal(command); ctkPythonConsole::executeCommand(command); QmitkPythonMediator::getInstance()->update(); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.h index 3c1b87a9a6..081cfd0922 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkCTKPythonShell.h @@ -1,65 +1,64 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKCTKPYTHONSHELL_H #define _QMITKCTKPYTHONSHELL_H #include #include #include "QmitkPythonMediator.h" #include #include #include /*! * \ingroup org_mitk_gui_qt_imagenavigator_internal * * \brief QmitkPythonVariableStack * * Document your class here. * * \sa QmitkFunctionality */ class QmitkCTKPythonShell : public ctkPythonConsole, public QmitkPythonPasteClient { Q_OBJECT public: QmitkCTKPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent = 0); ~QmitkCTKPythonShell(); virtual void paste(const QString& command); protected: virtual void dragEnterEvent(QDragEnterEvent *event); virtual void dropEvent(QDropEvent *event); virtual bool canInsertFromMimeData( const QMimeData *source ) const; virtual void executeCommand(const QString& command); signals: void executeCommandSignal(const QString&); private: ctkAbstractPythonManager* m_PythonManager; }; #endif // _QmitkPythonVariableStack_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.cpp index 46a8031c42..f1d29a0520 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.cpp @@ -1,125 +1,124 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include #include // Qmitk #include "QmitkPythonCommandHistory.h" #include "QmitkPythonConsoleView.h" #include "QmitkStdMultiWidget.h" // Qt #include #include "mitkCoreObjectFactory.h" #include #include #include #include #include #include "berryFileEditorInput.h" #include const std::string QmitkPythonCommandHistory::VIEW_ID = "org.mitk.views.pythoncommandhistory"; QmitkPythonCommandHistory::QmitkPythonCommandHistory() : QmitkFunctionality() //, m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkPythonCommandHistory::~QmitkPythonCommandHistory() { QmitkPythonMediator::getInstance()->unregisterClient(this); } void QmitkPythonCommandHistory::CreateQtPartControl( QWidget *parent ) { QGridLayout *gridLayout; if (parent->objectName().isEmpty()) parent->setObjectName(QString::fromUtf8("parent")); parent->resize(790, 773); parent->setMinimumSize(QSize(0, 0)); gridLayout = new QGridLayout(parent); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); m_treeWidget = new QmitkPythonCommandHistoryTreeWidget(parent); QTreeWidgetItem *treeWidgetItem = new QTreeWidgetItem(); treeWidgetItem->setText(0, QString::fromUtf8("Command")); treeWidgetItem->setFlags(Qt::ItemIsEditable); m_treeWidget->setHeaderItem(treeWidgetItem); m_treeWidget->setObjectName(QString::fromUtf8("treeWidget")); m_treeWidget->setColumnCount(1); m_treeWidget->setDragEnabled(true); m_treeWidget->setDragDropMode(QAbstractItemView::DragOnly); m_treeWidget->setAcceptDrops(false); m_treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); gridLayout->addWidget(m_treeWidget, 0, 0, 1, 1); parent->setWindowTitle(QApplication::translate("QmitkPythonConsoleViewControls", "QmitkTemplate", 0, QApplication::UnicodeUTF8)); QMetaObject::connectSlotsByName(parent); QmitkPythonMediator::getInstance()->setClient(this); } void QmitkPythonCommandHistory::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkPythonCommandHistory::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkPythonCommandHistory::AddCommand(const QString& command) { m_commandHistory.push_back(QStringList() << command); m_treeWidget->clear(); for(int i = 0; i < m_commandHistory.size(); i++) { if( m_commandHistory[i].value(0).compare("") != 0 ) m_treeWidget->addTopLevelItem(new QTreeWidgetItem(m_commandHistory[i])); } } void QmitkPythonCommandHistory::SetCommandHistory(std::vector history) { m_commandHistory = history; m_treeWidget->clear(); for(int i = 0; i < m_commandHistory.size(); i++) { if( m_commandHistory[i].value(0).compare("") != 0 ) m_treeWidget->addTopLevelItem(new QTreeWidgetItem(m_commandHistory[i])); } } void QmitkPythonCommandHistory::update() { SetCommandHistory(QmitkPythonMediator::getInstance()->GetCommandHistory()); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.h index 4f4148eedf..2044a11cbd 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistory.h @@ -1,80 +1,79 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkPythonCommandHistory_h #define QmitkPythonCommandHistory_h #include #include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkPythonCommandHistoryTreeWidget.h" #include "QmitkPythonMediator.h" class QmitkPythonCommandHistory : public QmitkFunctionality, public QmitkPythonClient { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkPythonCommandHistory(); QmitkPythonCommandHistory(const QmitkPythonCommandHistory& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkPythonCommandHistory(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); void SetCommandHistory(std::vector); virtual void update(); public slots: void AddCommand(const QString&); protected slots: private: QmitkStdMultiWidget* m_MultiWidget; std::vector m_commandHistory; QmitkPythonCommandHistoryTreeWidget *m_treeWidget; QmitkPythonMediator *m_PythonMediator; }; #endif // _QMITKPYTHONCONSOLEVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.cpp index 1e615a1b9a..aeef885199 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.cpp @@ -1,60 +1,59 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonCommandHistoryTreeWidget.h" #include #include #include #include #include QmitkPythonCommandHistoryTreeWidget::QmitkPythonCommandHistoryTreeWidget(QWidget *parent) :QTreeWidget(parent) { } QmitkPythonCommandHistoryTreeWidget::~QmitkPythonCommandHistoryTreeWidget() { } void QmitkPythonCommandHistoryTreeWidget::mouseMoveEvent(QMouseEvent *event) { // if not left button - return if (!(event->buttons() & Qt::LeftButton)) return; // if no item selected, return (else it would crash) if (selectedItems().isEmpty()) return; QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; //QList list; QList listItems = selectedItems(); for(int i = 0; i < listItems.size(); i++) { //list.append(QUrl(listItems[i]->text(0))); mimeData->setText(listItems[i]->text(0)); } //mimeData->setUrls(list); drag->setMimeData(mimeData); // start drag drag->start(Qt::CopyAction | Qt::MoveAction); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.h index 5935f4b211..a4f2f54c48 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonCommandHistoryTreeWidget.h @@ -1,43 +1,42 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONCOMMANDHISTORYTREEWIDGET_H_ #define QMITKPYTHONCOMMANDHISTORYTREEWIDGET_H_ #include class QmitkPythonCommandHistoryTreeWidget : public QTreeWidget { // 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: QmitkPythonCommandHistoryTreeWidget(QWidget *parent = 0); virtual ~QmitkPythonCommandHistoryTreeWidget(); signals: protected slots: protected: virtual void mouseMoveEvent(QMouseEvent *event); private: }; #endif diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.cpp index a77015a19d..0d3407349c 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.cpp @@ -1,178 +1,177 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include #include // Qmitk #include "QmitkPythonConsoleView.h" #include "QmitkStdMultiWidget.h" // Qt #include #include #include "mitkCoreObjectFactory.h" #include #include #include #include #include #include //#include #include "berryFileEditorInput.h" #include #include "QmitkPythonVariableStack.h" #include "QmitkPythonCommandHistory.h" #include "mitkPythonPath.h" const std::string QmitkPythonConsoleView::VIEW_ID = "org.mitk.views.pythonconsole"; QmitkPythonConsoleView::QmitkPythonConsoleView() : QmitkFunctionality() //, m_Controls( 0 ) , m_MultiWidget( NULL ) ,m_ctkPythonManager( NULL ) ,m_ctkPythonShell( NULL ) { // TODO: take it to the activator // std::cout << "running PYTHON PATH COMMANDS" << std::endl; QmitkPythonMediator::getInstance()->runSimpleString("import sys"); std::string cmd ( "sys.path.append('" MITK_PYTHONPATH_MITK_LIBRARY_DIRS "');" ); QmitkPythonMediator::getInstance()->runSimpleString(cmd.c_str()); cmd = "sys.path.append('" MITK_PYTHONPATH_ITK_LIBRARY_DIRS "');"; QmitkPythonMediator::getInstance()->runSimpleString(cmd.c_str()); cmd = "sys.path.append('" MITK_PYTHONPATH_WRAP_ITK_DIR "');"; QmitkPythonMediator::getInstance()->runSimpleString(cmd.c_str()); cmd = "sys.path.append('" MITK_PYTHONPATH_VTK_LIBRARY_DIRS "');"; QmitkPythonMediator::getInstance()->runSimpleString(cmd.c_str()); cmd = "sys.path.append('" MITK_PYTHONPATH_VTK_PYTHON_WRAPPING_DIR "');"; QmitkPythonMediator::getInstance()->runSimpleString(cmd.c_str()); if( strcmp("", MITK_PYTHONPATH_OPEN_CV_LIBRARY_DIRS) != 0 ) { // std::cout << "setting opencv PYTHON PATH" << std::endl; cmd = "sys.path.append('" MITK_PYTHONPATH_OPEN_CV_LIBRARY_DIRS "');"; QmitkPythonMediator::getInstance()->runSimpleString(cmd.c_str()); } } QmitkPythonConsoleView::~QmitkPythonConsoleView() { QmitkPythonMediator::getInstance()->unregisterClient(this); } void QmitkPythonConsoleView::CreateQtPartControl( QWidget *parent ) { QGridLayout *gridLayout; if (parent->objectName().isEmpty()) parent->setObjectName(QString::fromUtf8("parent")); parent->resize(790, 774); parent->setMinimumSize(QSize(0, 0)); gridLayout = new QGridLayout(parent); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); m_ctkPythonManager = new ctkAbstractPythonManager(parent); m_ctkPythonShell = new QmitkCTKPythonShell(m_ctkPythonManager, parent); m_ctkPythonShell->setObjectName(QString::fromUtf8("m_ctkPythonShell")); m_ctkPythonShell->setMinimumSize(QSize(120, 100)); m_ctkPythonShell->setMaximumSize(QSize(2000, 2000)); gridLayout->addWidget(m_ctkPythonShell, 0, 0, 1, 1); m_ButtonOpenEditor = new QPushButton(parent); m_ButtonOpenEditor->setObjectName(QString::fromUtf8("m_ButtonOpenEditor")); gridLayout->addWidget(m_ButtonOpenEditor, 1, 0, 1, 1); parent->setWindowTitle(QApplication::translate("parent", "QmitkTemplate", 0, QApplication::UnicodeUTF8)); m_ButtonOpenEditor->setText(QApplication::translate("parent", "Open Editor", 0, QApplication::UnicodeUTF8)); QMetaObject::connectSlotsByName(parent); mitk::DataStorage::Pointer dataStorage = this->GetDefaultDataStorage(); m_ctkPythonManager->executeString("import mitk"); QmitkPythonMediator::getInstance()->setClient(this); QmitkPythonMediator::getInstance()->update(); connect( m_ctkPythonShell, SIGNAL(executeCommandSignal(const QString&)), this, SLOT(SetCommandHistory(const QString&))); connect( m_ButtonOpenEditor, SIGNAL(clicked()), this, SLOT(OpenEditor()) ); } void QmitkPythonConsoleView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkPythonConsoleView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkPythonConsoleView::OnSelectionChanged( std::vector nodes ) { for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { return; } } } void QmitkPythonConsoleView::NodeAdded(const mitk::DataNode* node) { } void QmitkPythonConsoleView::OpenEditor() { berry::FileEditorInput::Pointer editorInput; editorInput = new berry::FileEditorInput(""); m_PythonEditor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkPythonEditor::EDITOR_ID, true, berry::IWorkbenchPage::MATCH_NONE).Cast(); } void QmitkPythonConsoleView::SetCommandHistory(const QString& command) { QmitkPythonMediator::getInstance()->SetCommandHistory(command); // QmitkPythonMediator::getInstance()->update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPythonConsoleView::update() { //QmitkPythonMediator::runSimpleString("\r\n"); } QmitkPythonMediator *QmitkPythonConsoleView::getPythonMediator() { return m_PythonMediator; } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.h index 8a99ec9a30..1558c8b223 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonConsoleView.h @@ -1,98 +1,97 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkPythonConsoleView_h #define QmitkPythonConsoleView_h #include #include #include "QmitkPythonEditor.h" #include #include #include #include #include #include #include #include #include #include #include //#include "ctkPythonShell.h" #include "QmitkCTKPythonShell.h" #include "ctkAbstractPythonManager.h" #include "QmitkPythonMediator.h" /*! \brief QmitkPythonConsoleView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkPythonConsoleView : public QmitkFunctionality, public QmitkPythonClient { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkPythonConsoleView(); QmitkPythonConsoleView(const QmitkPythonConsoleView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkPythonConsoleView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void NodeAdded(const mitk::DataNode* node); virtual void update(); QmitkPythonMediator *getPythonMediator(); protected slots: void OpenEditor(); void SetCommandHistory(const QString&); protected: virtual void OnSelectionChanged( std::vector nodes ); QmitkStdMultiWidget* m_MultiWidget; berry::SmartPointer m_PythonEditor; private: FILE * m_scriptFile; QmitkCTKPythonShell *m_ctkPythonShell; ctkAbstractPythonManager *m_ctkPythonManager; QPushButton *m_ButtonOpenEditor; QmitkPythonMediator *m_PythonMediator; }; #endif // _QMITKPYTHONCONSOLEVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.cpp index 00691b042a..819b30535e 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.cpp @@ -1,84 +1,83 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "berryFileEditorInput.h" const std::string QmitkPythonEditor::EDITOR_ID = "org.mitk.editors.pythoneditor"; QmitkPythonEditor::QmitkPythonEditor() { } QmitkPythonEditor::~QmitkPythonEditor() { } void QmitkPythonEditor::CreateQtPartControl(QWidget* parent) { m_PythonScriptEditor = new QmitkPythonScriptEditor(parent); if (parent->objectName().isEmpty()) parent->setObjectName(QString::fromUtf8("parent")); parent->resize(790, 773); parent->setMinimumSize(QSize(0, 0)); QGridLayout *gridLayout = new QGridLayout(parent); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); gridLayout->addWidget(m_PythonScriptEditor, 0, 0, 1, 3); QMetaObject::connectSlotsByName(parent); } void QmitkPythonEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { if (input.Cast().IsNull()) throw berry::PartInitException("Invalid Input: Must be FileEditorInput"); this->SetSite(site); this->SetInput(input); } void QmitkPythonEditor::SetFocus() { } berry::IPartListener::Events::Types QmitkPythonEditor::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.h index 05802064f0..290457d307 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonEditor.h @@ -1,70 +1,69 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONEDITOR_H_ #define QMITKPYTHONEDITOR_H_ #include #include #include #include "mitkQtCommonDll.h" #include #include #include #include "QmitkPythonScriptEditor.h" class QmitkPythonEditor : public berry::QtEditorPart, virtual public berry::IPartListener { Q_OBJECT public: berryObjectMacro(QmitkPythonEditor); static const std::string EDITOR_ID; QmitkPythonEditor(); QmitkPythonEditor(const QmitkPythonEditor& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } ~QmitkPythonEditor(); void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input); void SetFocus(); void DoSave() {} void DoSaveAs() {} bool IsDirty() const { return false; } bool IsSaveAsAllowed() const { return false; } protected: void CreateQtPartControl(QWidget* parent); Events::Types GetPartEventTypes() const; private: QmitkPythonScriptEditor *m_PythonScriptEditor; }; #endif diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.cpp index d7f5a73f12..0d17970214 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.cpp @@ -1,151 +1,150 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonMediator.h" #include QmitkPythonMediator::QmitkPythonMediator() { } QmitkPythonMediator::~QmitkPythonMediator() { } void QmitkPythonMediator::Initialize() { if(!Py_IsInitialized()) Py_Initialize(); } void QmitkPythonMediator::Finalize() { if(m_clients.size() == 0) Py_Finalize(); } QmitkPythonMediator *QmitkPythonMediator::getInstance() { static QmitkPythonMediator m_mediatorInstance; return &m_mediatorInstance; } void QmitkPythonMediator::paste(const QString& pasteCommand) { std::set::iterator it = m_PasteClients.begin(); while( it!= m_PasteClients.end()) { (*it)->paste( pasteCommand ); ++it; } } void QmitkPythonMediator::runSimpleString(const char* str) { if(!Py_IsInitialized()){ Py_Initialize(); } PyRun_SimpleString(str); } std::vector QmitkPythonMediator::getAttributeList() { PyObject* dict = PyImport_GetModuleDict(); PyObject* object = PyDict_GetItemString(dict, "__main__"); PyObject* dirMain = PyObject_Dir(object); PyObject* tempObject; std::vector variableStack; if(dirMain){ QString attr, attrValue, attrType; variableStack.clear(); for(int i = 0; iob_type->tp_name; if(PyUnicode_Check(tempObject) || PyString_Check(tempObject)) attrValue = PyString_AsString(tempObject); else attrValue = ""; variableStack.push_back(QStringList() << attr << attrValue << attrType); } } return variableStack; } PyObject * QmitkPythonMediator::getPyObject(PyObject * object) { PyObject* dict = PyImport_GetModuleDict(); PyObject* main = PyDict_GetItemString(dict, "__main__"); return PyObject_GetAttr(main, object); } PyObject * QmitkPythonMediator::getPyObjectString(QString * objectName) { PyObject* dict = PyImport_GetModuleDict(); PyObject* main = PyDict_GetItemString(dict, "__main__"); return PyObject_GetAttrString(main, objectName->toLocal8Bit().data()); } void QmitkPythonMediator::registerPasteCommandClient(QmitkPythonPasteClient * client ) { m_PasteClients.insert( client ); } void QmitkPythonMediator::unregisterPasteCommandClient(QmitkPythonPasteClient * client) { m_PasteClients.erase( client ); } void QmitkPythonMediator::setClient(QmitkPythonClient * client) { m_clients.insert(client); } void QmitkPythonMediator::unregisterClient(QmitkPythonClient * client) { m_clients.erase( client ); } void QmitkPythonMediator::update() { if(Py_IsInitialized) { std::set::iterator it = m_clients.begin(); while( it!= m_clients.end()) { (*it)->update(); ++it; } } } void QmitkPythonMediator::SetCommandHistory(const QString& command) { m_commandHistory.push_back(QStringList() << command); } std::vector QmitkPythonMediator::GetCommandHistory() { return m_commandHistory; } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.h index 6cad83f4d3..8947c6e26c 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonMediator.h @@ -1,75 +1,74 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -=========================================================================*/ +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkPythonMediator_h #define QmitkPythonMediator_h #include #include #include #include #include #include "mitkCommon.h" class QmitkPythonClient { public: virtual ~QmitkPythonClient(){}; virtual void update() = 0; }; class QmitkPythonPasteClient { public: virtual ~QmitkPythonPasteClient(){}; virtual void paste(const QString&) = 0; }; class QmitkPythonMediator { public: void update(); static void runSimpleString(const char*); static std::vector getAttributeList(); static PyObject * getPyObject(PyObject * object); static PyObject * getPyObjectString(QString * objectName); static QmitkPythonMediator *getInstance(); void setClient(QmitkPythonClient *); void unregisterClient(QmitkPythonClient *); void registerPasteCommandClient(QmitkPythonPasteClient *); void unregisterPasteCommandClient(QmitkPythonPasteClient *); void paste(const QString& pasteCommand); std::vector GetCommandHistory(); void SetCommandHistory(const QString&); void Initialize(); void Finalize(); protected: QmitkPythonMediator(); virtual ~QmitkPythonMediator(); private: std::set m_clients; std::set m_PasteClients; std::vector m_commandHistory; std::vector m_variableStack; }; #endif // _QMITKPYTHONCONSOLEVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.cpp index 7f5ff69a67..4eabd34aa3 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.cpp @@ -1,43 +1,42 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonPerspective.h" #include "berryIViewLayout.h" void QmitkPythonPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { std::string editorArea = layout->GetEditorArea(); layout->AddView("org.mitk.views.datamanager", berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddView("org.mitk.views.pythoncommandhistory", berry::IPageLayout::TOP, 0.3f, "org.mitk.views.datamanager"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.datamanager"); lo->SetCloseable(false); berry::IFolderLayout::Pointer leftbottomFolder = layout->CreateFolder("leftbottom", berry::IPageLayout::BOTTOM, 0.7f, "org.mitk.views.datamanager"); leftbottomFolder->AddView("org.mitk.views.pythonvariablestack"); leftbottomFolder->AddView("org.mitk.views.pythonsnippets"); leftbottomFolder->AddView("org.mitk.views.imagenavigator"); berry::IFolderLayout::Pointer bottomFolder = layout->CreateFolder("bottom", berry::IPageLayout::BOTTOM, 0.7f, editorArea); bottomFolder->AddView("org.mitk.views.pythonconsole"); bottomFolder->AddView("org.mitk.views.propertylistview"); bottomFolder->AddView("org.blueberry.views.logview"); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.h index 61d9094f28..6915746330 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonPerspective.h @@ -1,40 +1,39 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONPERSPECTIVE_H_ #define QMITKPYTHONPERSPECTIVE_H_ #include #include struct QmitkPythonPerspective : public QObject, public berry::IPerspectiveFactory { Q_OBJECT void CreateInitialLayout(berry::IPageLayout::Pointer layout); QmitkPythonPerspective(const QmitkPythonPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } }; #endif /* QMITKEXTDEFAULTPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.cpp index d3fb8ef591..5617e8544c 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.cpp @@ -1,157 +1,156 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonScriptEditor.h" //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "berryFileEditorInput.h" #include #include #include "QmitkPythonConsoleView.h" #include "QmitkPythonVariableStack.h" #include "QmitkPythonScriptEditorHighlighter.h" #include "QmitkPythonMediator.h" const std::string QmitkPythonScriptEditor::EDITOR_ID = "org.mitk.editors.pythonscripteditor"; QmitkPythonScriptEditor::QmitkPythonScriptEditor(QWidget *parent) :QWidget(parent) { QGridLayout *gridLayout; QPushButton *buttonLoadScript; QPushButton *buttonSaveScript; QPushButton *buttonRunScript; if (parent->objectName().isEmpty()) parent->setObjectName(QString::fromUtf8("parent")); parent->resize(790, 773); parent->setMinimumSize(QSize(0, 0)); gridLayout = new QGridLayout(parent); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); m_TextEditor = new QTextEdit(parent); m_TextEditor->setObjectName(QString::fromUtf8("m_TextEditor")); m_TextEditor->viewport()->setAcceptDrops(true); QmitkPythonScriptEditorHighlighter *highlighter = new QmitkPythonScriptEditorHighlighter(m_TextEditor->document()); gridLayout->addWidget(m_TextEditor, 0, 0, 1, 3); buttonLoadScript = new QPushButton(parent); buttonLoadScript->setObjectName(QString::fromUtf8("buttonLoadScript")); gridLayout->addWidget(buttonLoadScript, 1, 0, 1, 1); buttonSaveScript = new QPushButton(parent); buttonSaveScript->setObjectName(QString::fromUtf8("buttonSaveScript")); gridLayout->addWidget(buttonSaveScript, 1, 1, 1, 1); buttonRunScript = new QPushButton(parent); buttonRunScript->setObjectName(QString::fromUtf8("buttonRunScript")); gridLayout->addWidget(buttonRunScript, 1, 2, 1, 1); parent->setWindowTitle(QApplication::translate("parent", "QmitkTemplate", 0, QApplication::UnicodeUTF8)); buttonLoadScript->setText(QApplication::translate("parent", "Load Script", 0, QApplication::UnicodeUTF8)); buttonSaveScript->setText(QApplication::translate("parent", "Save Script", 0, QApplication::UnicodeUTF8)); buttonRunScript->setText(QApplication::translate("parent", "Run Script", 0, QApplication::UnicodeUTF8)); QMetaObject::connectSlotsByName(parent); connect(buttonLoadScript, SIGNAL(clicked()), this, SLOT(OpenScript())); connect(buttonSaveScript, SIGNAL(clicked()), this, SLOT(SaveScript())); connect(buttonRunScript, SIGNAL(clicked()), this, SLOT(RunScript())); QmitkPythonMediator::getInstance()->Initialize(); QmitkPythonMediator::getInstance()->registerPasteCommandClient( this ); } QmitkPythonScriptEditor::~QmitkPythonScriptEditor() { QmitkPythonMediator::getInstance()->unregisterPasteCommandClient( this ); QmitkPythonMediator::getInstance()->Finalize(); } void QmitkPythonScriptEditor::paste(const QString& command) { if( this->isVisible() ) m_TextEditor->append(command); } void QmitkPythonScriptEditor::LoadScript(const char* filename){ std::istream* fileStream = new std::ifstream(filename); char line[255]; QString qline; m_TextEditor->setText(""); m_scriptFile = fopen(filename, "r"); if(fileStream) { while(!fileStream->eof()) { fileStream->getline(line,255); qline = line; m_TextEditor->append(qline); } } else { } } void QmitkPythonScriptEditor::SaveScript(){ QString fileName = QFileDialog::getSaveFileName(this,tr("Save File"),"",tr("*.py")); if(fileName.compare("") != 0) { ofstream myfile; myfile.open(fileName.toLocal8Bit().data()); myfile << m_TextEditor->toPlainText().toLocal8Bit().data(); myfile.close(); } } void QmitkPythonScriptEditor::OpenScript(){ QString fileName = QFileDialog::getOpenFileName(NULL,mitk::CoreObjectFactory::GetInstance()->GetFileExtensions(),"",tr("*.py")); if(fileName.compare("") != 0) LoadScript(fileName.toStdString().c_str()); } void QmitkPythonScriptEditor::RunScript(){ QmitkPythonMediator::runSimpleString(m_TextEditor->toPlainText().toLocal8Bit().data()); QmitkPythonMediator::getInstance()->update(); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.h index 14303313cc..66dac40d71 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditor.h @@ -1,70 +1,69 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONSCRIPTEDITOR_H_ #define QMITKPYTHONSCRIPTEDITOR_H_ #include #include #include "QmitkPythonTextEditor.h" //#include #include "mitkQtCommonDll.h" #include #include #include #include #include #include "QmitkPythonMediator.h" class QmitkPythonScriptEditor : public QWidget, public QmitkPythonPasteClient //, berry::QtEditorPart { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: berryObjectMacro(QmitkPythonScriptEditor); static const std::string EDITOR_ID; QmitkPythonScriptEditor(QWidget *parent = 0); virtual void paste(const QString& command); ~QmitkPythonScriptEditor(); signals: void RanScript(); protected slots: /// \brief Called when the user clicks the GUI button void LoadScript(const char *); void SaveScript(); void OpenScript(); void RunScript(); protected: private: QTextEdit* m_TextEditor; FILE *m_scriptFile; QmitkPythonMediator *m_PythonMediator; }; #endif diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.cpp index e6a2aeb040..8bd79c6314 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.cpp @@ -1,111 +1,110 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonScriptEditorHighlighter.h" QmitkPythonScriptEditorHighlighter::QmitkPythonScriptEditorHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { } QmitkPythonScriptEditorHighlighter::~QmitkPythonScriptEditorHighlighter() { } void QmitkPythonScriptEditorHighlighter::highlightBlock(const QString &text) { QTextCharFormat commentFormat; commentFormat.setFontWeight(QFont::Courier); commentFormat.setForeground(Qt::darkGreen); QTextCharFormat keywordFormat; keywordFormat.setFontWeight(QFont::Bold); keywordFormat.setForeground(Qt::blue); QString pattern = "\\b(and|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|raise|return|try|while|yield|None|True|False)\\b"; QTextCharFormat qouteFormat; qouteFormat.setForeground(Qt::gray); QTextCharFormat numberFormat; numberFormat.setForeground(Qt::red); QRegExp numberExpression("\\d+"); int indexNumbers = text.indexOf(numberExpression); while (indexNumbers >= 0) { int length = numberExpression.matchedLength(); setFormat(indexNumbers, length, numberFormat); indexNumbers = text.indexOf(numberExpression, indexNumbers + length); } QRegExp qouteExpression("\""); int startQouteIndex = text.indexOf(qouteExpression); int endQouteIndex = text.indexOf(qouteExpression, startQouteIndex); QRegExp keyword(pattern); int indexKeyword = text.indexOf(keyword); QRegExp startCommentExpression("^#"); QRegExp endCommentExpression("\\n"); int startCommentIndex = text.indexOf(startCommentExpression); int endCommentIndex = text.indexOf(endCommentExpression, startCommentIndex); while (startQouteIndex >= 0) { endQouteIndex = text.indexOf(qouteExpression, startQouteIndex+1); int commentLength; if (endQouteIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startQouteIndex; } else { commentLength = endQouteIndex - startQouteIndex + qouteExpression.matchedLength(); } setFormat(startQouteIndex, commentLength, qouteFormat); startQouteIndex = text.indexOf(qouteExpression, startQouteIndex + commentLength); } if(startCommentIndex < 0) { while (indexKeyword >= 0) { int length = keyword.matchedLength(); setFormat(indexKeyword, length, keywordFormat); indexKeyword = text.indexOf(keyword, indexKeyword + length); } } while (startCommentIndex >= 0) { endCommentIndex = text.indexOf(endCommentExpression, startCommentIndex); int commentLength; if (endCommentIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startCommentIndex; } else { commentLength = endCommentIndex - startCommentIndex + endCommentExpression.matchedLength(); } setFormat(startCommentIndex, commentLength, commentFormat); startCommentIndex = text.indexOf(startCommentExpression, startCommentIndex + commentLength); } } void QmitkPythonScriptEditorHighlighter::highlightComments(const QString &text) { } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.h index 2af4a21bdc..fbf8f39219 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonScriptEditorHighlighter.h @@ -1,45 +1,44 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONSCRIPTEDITORHIGHLIGHTER_H_ #define QMITKPYTHONSCRIPTEDITORHIGHLIGHTER_H_ #include #include class QmitkPythonScriptEditorHighlighter : public QSyntaxHighlighter { // 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: QmitkPythonScriptEditorHighlighter(QTextDocument *parent); virtual ~QmitkPythonScriptEditorHighlighter(); signals: protected slots: protected: virtual void highlightBlock(const QString &text); void highlightComments(const QString &text); private: }; #endif diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.cpp index 4868747818..96dc33ff72 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.cpp @@ -1,362 +1,361 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonSnippets.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "QmitkPythonConsoleView.h" #include "mitkDataStorageEditorInput.h" // berry Includes #include #include #include #include #include #include #include #include #include #include "QmitkPythonMediator.h" #include "QmitkPythonScriptEditorHighlighter.h" const std::string QmitkPythonSnippets::VIEW_ID = "org.mitk.views.pythonsnippets"; std::map QmitkPythonSnippets::CreateDefaultSnippets() { std::map defaultSnippets; defaultSnippets["itk image processing"] = "import itk\n" "import mitkCast\n\n" "print 'using ITK ' + itk.Version.GetITKVersion()\n" "itkImage = mitkCast.node2itk( Pic3D, itk.Image.US3 )\n" "kernel = itk.strel( 3, 3 )\n" "filter = itk.GrayscaleDilateImageFilter[itkImage,itkImage,kernel].New( itkImage, Kernel=kernel )\n" "filter.Update()\n" "Pic3DFiltered = mitkCast.itk2node( filter.GetOutput(), 'Pic3DFiltered' )\n"; defaultSnippets["itk batch image processing"] = "import itk\n" "import mitkCast\n\n" "print 'using ITK ' + itk.Version.GetITKVersion()\n" "itkImage = mitkcast.node2itk( Pic3D, itk.Image.US3 )\n" "for s in range(5):\n" "kernel = itk.strel( 3, s+1 )\n" "filter = itk.GrayscaleDilateImageFilter[itkImage,itkImage,kernel].New( itkImage, Kernel=kernel )\n" "filter.Update()\n" "exec( \"newnode_\" + str(s+1) + \" = mitkcast.itk2node( filter.GetOutput(), 'demo_\" + str(s+1) + \"')\" )\n"; defaultSnippets["Import itk and vtk"] = "import itk, vtk"; return defaultSnippets; } const std::map QmitkPythonSnippets::DEFAULT_SNIPPETS = QmitkPythonSnippets::CreateDefaultSnippets(); QmitkPythonSnippets::QmitkPythonSnippets() : m_MultiWidget(NULL) , m_Controls(0) { } QmitkPythonSnippets::~QmitkPythonSnippets() { berry::IPreferencesService::Pointer _PreferencesService = berry::Platform::GetServiceRegistry().GetServiceById( berry::IPreferencesService::ID); berry::IPreferences::Pointer node = _PreferencesService->GetSystemPreferences()->Node(VIEW_ID); std::map::iterator it = m_Snippets.begin(); node->Clear(); while( it != m_Snippets.end() ) { QString snippet = QString::fromStdString(it->second); snippet = snippet.replace("\n", "
"); // std::cout << "adding " << it->first << ": " << snippet.toStdString() << std::endl; node->Put( it->first, snippet.toStdString() ); ++it; } node->Flush(); } void QmitkPythonSnippets::CreateQtPartControl(QWidget *parent) { if( !m_Controls ) { m_Controls = new Ui::QmitkPythonSnippets; m_Controls->setupUi( parent ); QmitkPythonScriptEditorHighlighter *highlighter = new QmitkPythonScriptEditorHighlighter(m_Controls->Content->document()); } // get all snippets berry::IPreferencesService::Pointer _PreferencesService = berry::Platform::GetServiceRegistry().GetServiceById( berry::IPreferencesService::ID); // insert default snippets if there were no prefs before if( !_PreferencesService->GetSystemPreferences()->NodeExists(VIEW_ID) ) { m_Snippets = DEFAULT_SNIPPETS; } else { berry::IPreferences::Pointer node = _PreferencesService->GetSystemPreferences()->Node(VIEW_ID); std::vector keys = node->Keys(); std::string snippet; for( size_t i = 0; i < keys.size(); ++i) { // std::cout << "inserting " << keys.at(i) << std::endl; snippet = node->Get( keys.at(i), "" ); QString qsnippet = QString::fromStdString(snippet); qsnippet = qsnippet.replace("
", "\n"); // std::cout << "inserting " << keys.at(i) << ": " << qsnippet.toStdString() << std::endl; m_Snippets[keys.at(i)] = qsnippet.toStdString(); } } this->Update(); connect( m_Controls->Name, SIGNAL(currentIndexChanged(int)), this, SLOT(on_Name_currentIndexChanged(int)) ); connect( m_Controls->AddNewSnippet, SIGNAL(clicked()), this, SLOT(on_AddNewSnippet_clicked()) ); connect( m_Controls->RemoveSnippet, SIGNAL(clicked()), this, SLOT(on_RemoveSnippet_clicked()) ); connect( m_Controls->PasteNow, SIGNAL(clicked()), this, SLOT(on_PasteNow_clicked()) ); connect( m_Controls->Content, SIGNAL(textChanged()), this, SLOT(on_Content_textChanged()) ); connect( m_Controls->RenameSnippet, SIGNAL(clicked()), this, SLOT(on_RenameSnippet_clicked()) ); connect( m_Controls->RestoreDefaultSnippets, SIGNAL(clicked()), this, SLOT(on_RestoreDefaultSnippets_clicked()) ); } void QmitkPythonSnippets::SetFocus () { } int QmitkPythonSnippets::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkPythonSnippets::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return 160; } else { return preferredResult; } } void QmitkPythonSnippets::on_Name_currentIndexChanged(int i) { // std::cout << "on_Name_currentIndexChanged" << std::endl; if( m_Controls->Name->count() == 0 ) return; QString name = m_Controls->Name->currentText(); m_Controls->Content->setText( QString::fromStdString(m_Snippets[name.toStdString()]) ); } void QmitkPythonSnippets::CreateUniqueName( QString& name ) { QString basename = name; size_t i = 2; while( m_Snippets.find(name.toStdString()) != m_Snippets.end() ) { name = basename + QString("_%1").arg(i); ++i; } } void QmitkPythonSnippets::on_RestoreDefaultSnippets_clicked() { QString question = QString("Really restore default Snippets?"); int remove = QMessageBox::question( QApplication::topLevelWidgets().at(0), QString("Confirm restoring"), question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No ); if( remove == QMessageBox::Yes || remove == QMessageBox::Ok ) { std::map::const_iterator it = DEFAULT_SNIPPETS.begin(); while( it != DEFAULT_SNIPPETS.end() ) { m_Snippets[it->first] = it->second; ++it; } this->Update(); } } void QmitkPythonSnippets::on_AddNewSnippet_clicked() { QString name = "newSnippet"; CreateUniqueName(name); m_Snippets[name.toStdString()] = ""; m_NameToSelect = name; this->Update(); } void QmitkPythonSnippets::on_RemoveSnippet_clicked() { if( m_Controls->Name->count() == 0 ) return; QString name = m_Controls->Name->currentText(); QString question = QString("Really remove Snippet %1?").arg(name); int remove = QMessageBox::question( QApplication::topLevelWidgets().at(0), QString("Confirm removal"), question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No ); if( remove == QMessageBox::Yes || remove == QMessageBox::Ok ) { std::map::iterator it = m_Snippets.find( name.toStdString() ); if( it!= m_Snippets.end() ) { // std::cout << "removing " << it->first << std::endl; m_Snippets.erase(it); } this->Update(); } } void QmitkPythonSnippets::on_PasteNow_clicked() { if( m_Controls->Name->count() == 0 ) return; QString name = m_Controls->Name->currentText(); QString snippet = QString::fromStdString(m_Snippets[name.toStdString()]); QmitkPythonMediator::getInstance()->paste( snippet ); QmitkPythonMediator::getInstance()->update(); } void QmitkPythonSnippets::on_Content_textChanged() { if( m_Controls->Name->count() == 0 ) return; std::string name = (m_Controls->Name->currentText()).toStdString(); std::string snippet = m_Controls->Content->toPlainText().toStdString(); if( m_Snippets.find(name) != m_Snippets.end() ) m_Snippets[name] = snippet; } void QmitkPythonSnippets::on_RenameSnippet_clicked() { // std::cout << "on_Name_editTextChanged" << std::endl; if( m_Controls->Name->count() == 0 ) return; QString newName; bool repeat = false; do { newName = QInputDialog::getText( QApplication::topLevelWidgets().at(0), "Name the Snippet", "Name:", QLineEdit::Normal, m_NameToSelect, &repeat ); if( newName != m_Controls->Name->currentText() ) { repeat = m_Snippets.find(newName.toStdString()) != m_Snippets.end() || newName.isEmpty(); if( repeat ) QMessageBox::information( QApplication::topLevelWidgets().at(0) , QString("Invalid Name"), "Invalid name. Please enter another one"); } else repeat = false; } while( repeat ); // name changed if( newName != m_Controls->Name->currentText() ) { std::map::iterator it = m_Snippets.find( m_NameToSelect.toStdString() ); std::string snippet = it->second; m_Snippets.erase(it); m_Snippets[newName.toStdString()] = snippet; m_NameToSelect = newName; this->Update(); } } void QmitkPythonSnippets::Update() { if( m_NameToSelect.isEmpty() ) { QString name = m_Controls->Name->currentText(); m_NameToSelect = name; } m_Controls->Name->clear(); std::map::iterator it = m_Snippets.begin(); while( it != m_Snippets.end() ) { m_Controls->Name->addItem( QString::fromStdString( it->first ) ); ++it; } // reselect previous or last one if there are elements or nothing if there are no snippets std::string current = m_NameToSelect.toStdString(); int index = -1; if( m_Snippets.find(current) != m_Snippets.end() ) { index = m_Controls->Name->findText( m_NameToSelect ); } else if( m_Snippets.size() > 0 ) { index = m_Controls->Name->count()-1; } if( index >= 0 ) { m_Controls->Name->setCurrentIndex(index); current = m_Controls->Name->itemText( index ).toStdString(); m_Controls->Content->setPlainText( QString::fromStdString(m_Snippets[current]) ); } // clear the current name m_NameToSelect.clear(); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.h index ffee0c7f4d..ebb33ce9df 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonSnippets.h @@ -1,99 +1,98 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QmitkPythonSnippets_H #define _QmitkPythonSnippets_H #include #include "berryISizeProvider.h" #include #include #include #include "QmitkStepperAdapter.h" #include "ui_QmitkPythonSnippets.h" #include #include "berryISizeProvider.h" #include #include #include #include #include #include #include #include /*! * \ingroup org_mitk_gui_qt_imagenavigator_internal * * \brief QmitkPythonSnippets * * Document your class here. * * \sa QmitkFunctionality */ class QmitkPythonSnippets : public QObject, public berry::QtViewPart, public berry::ISizeProvider { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; static std::map CreateDefaultSnippets(); static const std::map DEFAULT_SNIPPETS; QmitkPythonSnippets(); virtual ~QmitkPythonSnippets(); virtual void CreateQtPartControl(QWidget *parent); QmitkStdMultiWidget* GetActiveStdMultiWidget(); void SetFocus(); virtual int GetSizeFlags(bool width); virtual int ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult); protected slots: void on_Name_currentIndexChanged(int i); void on_RenameSnippet_clicked(); void on_AddNewSnippet_clicked(); void on_RemoveSnippet_clicked(); void on_PasteNow_clicked(); void on_RestoreDefaultSnippets_clicked(); void on_Content_textChanged(); protected: void Update(); void CreateUniqueName( QString& name ); QmitkStdMultiWidget* m_MultiWidget; QTableWidget *m_tableWidget; Ui::QmitkPythonSnippets* m_Controls; std::map m_Snippets; QString m_NameToSelect; }; #endif // _QmitkPythonSnippets_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.cpp index d7b8b6bae1..3e43613686 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.cpp @@ -1,73 +1,72 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonTextEditor.h" #include #include #include QmitkPythonTextEditor::QmitkPythonTextEditor(QWidget *parent) :QTextEdit(parent) { QmitkPythonMediator::getInstance()->registerPasteCommandClient( this ); } QmitkPythonTextEditor::~QmitkPythonTextEditor() { QmitkPythonMediator::getInstance()->unregisterPasteCommandClient( this ); } void QmitkPythonTextEditor::dragEnterEvent(QDragEnterEvent *event) { event->accept(); } void QmitkPythonTextEditor::paste(const QString& command) { this->insertPlainText(command + "\n"); } void QmitkPythonTextEditor::dropEvent(QDropEvent *event) { //QDropEvent drop(event->pos(),Qt::MoveAction, event->mimeData(), event->mouseButtons(), Qt::ShiftModifier, event->type()); //QTextEdit::dropEvent(&drop); QList urls = event->mimeData()->urls(); for(int i = 0; i < urls.size(); i++) { this->insertPlainText(urls[i].toString().append("\n")); } } bool QmitkPythonTextEditor::canInsertFromMimeData( const QMimeData *source ) const { return true; } /* void QmitkPythonTextEditor::insertFromMimeData( const QMimeData *source ) { if (source->hasImage()) { QImage image = qvariant_cast(source->imageData()); QTextCursor cursor = this->textCursor(); QTextDocument *document = this->document(); document->addResource(QTextDocument::ImageResource, QUrl("image"), image); cursor.insertImage("image"); } }*/ diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.h index 58b206e349..a20f962729 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonTextEditor.h @@ -1,51 +1,50 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONTEXTEDITOR_H_ #define QMITKPYTHONTEXTEDITOR_H_ #include #include #include #include "QmitkPythonMediator.h" class QmitkPythonTextEditor : public QTextEdit, public QmitkPythonPasteClient { // 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: QmitkPythonTextEditor(QWidget *parent = 0); virtual ~QmitkPythonTextEditor(); virtual void paste(const QString& command); signals: protected slots: protected: virtual void dragEnterEvent(QDragEnterEvent *event); virtual void dropEvent(QDropEvent *event); virtual bool canInsertFromMimeData( const QMimeData *source ) const; //virtual void QmitkPythonTextEditor::insertFromMimeData( const QMimeData *source ); private: }; #endif diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.cpp index 16c0d1f6c9..d5e36eab3f 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.cpp @@ -1,128 +1,127 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonVariableStack.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "QmitkPythonConsoleView.h" #include "mitkDataStorageEditorInput.h" // berry Includes #include #include #include #include #include #include #include #include "QmitkPythonMediator.h" const std::string QmitkPythonVariableStack::VIEW_ID = "org.mitk.views.pythonvariablestack"; QmitkPythonVariableStack::QmitkPythonVariableStack() : m_MultiWidget(NULL) , m_Controls(0) { } QmitkPythonVariableStack::~QmitkPythonVariableStack() { QmitkPythonMediator::getInstance()->unregisterClient(m_treeModel); } void QmitkPythonVariableStack::CreateQtPartControl(QWidget *parent) { if( !m_Controls ) { m_Controls = new Ui::QmitkPythonConsoleViewControls; m_Controls->setupUi( parent ); } m_treeModel = new QmitkPythonVariableStackTreeWidget(); m_Controls->tableView->setSelectionBehavior( QAbstractItemView::SelectRows ); m_Controls->tableView->setAlternatingRowColors(true); m_Controls->tableView->setDragEnabled(true); m_Controls->tableView->setDropIndicatorShown(true); m_Controls->tableView->setAcceptDrops(true); m_Controls->tableView->setModel( m_treeModel); QmitkPythonMediator::getInstance()->setClient(m_treeModel); //QmitkPythonMediator::getInstance()->update(); // add the multiwidget to the dings mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance( this->GetActiveStdMultiWidget()->GetRenderWindow4()->GetVtkRenderWindow() ); mitk::RendererAccess::Set3DRenderer( renderer->GetVtkRenderer() ); m_treeModel->update(); } QmitkPythonVariableStackTreeWidget* QmitkPythonVariableStack::getModel() { return m_treeModel; } void QmitkPythonVariableStack::SetFocus () { } QmitkStdMultiWidget* QmitkPythonVariableStack::GetActiveStdMultiWidget() { QmitkStdMultiWidget* activeStdMultiWidget = 0; berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->GetActiveEditor(); if (editor.Cast().IsNotNull()) { activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } else { mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false); activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } return activeStdMultiWidget; } int QmitkPythonVariableStack::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkPythonVariableStack::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return 160; } else { return preferredResult; } } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.h index 6d48dfc0dc..4e90db3624 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStack.h @@ -1,100 +1,99 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKPYTHONVARIABLESTACK_H #define _QMITKPYTHONVARIABLESTACK_H #include #include "berryISizeProvider.h" #include #include #include #include "QmitkStepperAdapter.h" #include "ui_QmitkPythonVariableStack.h" #include "QmitkPythonVariableStackTreeWidget.h" #include #include "berryISizeProvider.h" #include #include #include #include #include #include #include #include /*! * \ingroup org_mitk_gui_qt_imagenavigator_internal * * \brief QmitkPythonVariableStack * * Document your class here. * * \sa QmitkFunctionality */ class QmitkPythonVariableStack : public berry::QtViewPart, public berry::ISizeProvider { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkPythonVariableStack(); QmitkPythonVariableStack(const QmitkPythonVariableStack& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkPythonVariableStack(); virtual void CreateQtPartControl(QWidget *parent); QmitkStdMultiWidget* GetActiveStdMultiWidget(); void SetFocus(); virtual int GetSizeFlags(bool width); virtual int ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult); QmitkPythonVariableStackTreeWidget* getModel(); public slots: protected slots: protected: QmitkStdMultiWidget* m_MultiWidget; QTableWidget *m_tableWidget; Ui::QmitkPythonConsoleViewControls* m_Controls; QmitkPythonVariableStackTreeWidget* m_treeModel; private: }; #endif // _QmitkPythonVariableStack_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.cpp b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.cpp index 8e8950664d..8fb034be0f 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.cpp +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.cpp @@ -1,248 +1,253 @@ -/*====================================================================== -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +The Medical Imaging Interaction Toolkit (MITK) -=========================================================================*/ +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkPythonVariableStackTreeWidget.h" #include #include #include #include #include #include #include #include #include "QmitkPythonMediator.h" #include "QmitkCustomVariants.h" #include "QmitkNodeDescriptor.h" #include "QmitkNodeDescriptorManager.h" #include "mitkDataStorage.h" #include "mitkDataNode.h" QmitkPythonVariableStackTreeWidget::QmitkPythonVariableStackTreeWidget(QWidget* parent) :QAbstractTableModel(parent) { } QmitkPythonVariableStackTreeWidget::~QmitkPythonVariableStackTreeWidget() { } bool QmitkPythonVariableStackTreeWidget::dropMimeData ( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent ) { // Early exit, returning true, but not actually doing anything (ignoring data). if (action == Qt::IgnoreAction) return true; // Note, we are returning true if we handled it, and false otherwise bool returnValue = false; if(data->hasFormat("application/x-mitk-datanodes")) { returnValue = true; QString arg = QString(data->data("application/x-mitk-datanodes").data()); QStringList listOfDataNodeAddressPointers = arg.split(","); QStringList::iterator slIter; for (slIter = listOfDataNodeAddressPointers.begin(); slIter != listOfDataNodeAddressPointers.end(); slIter++) { long val = (*slIter).toLong(); mitk::DataNode* node = static_cast((void*)val); itk::SmartPointer * resultptr; resultptr = new itk::SmartPointer((itk::SmartPointer &)node); if(resultptr) { int i = 0; while(swig_types_initial[i] != 0) { if(swig_types_initial[i] == _swigt__p_itk__SmartPointerTmitk__DataNode_t) SWIGTYPE_p_itk__SmartPointerTmitk__DataNode_t = SWIG_TypeRegister(swig_types_initial[i]); i++; } PyObject * resultObj = SWIG_NewPointerObj((void*)(resultptr), SWIGTYPE_p_itk__SmartPointerTmitk__DataNode_t, 1); PyObject* dict = PyImport_GetModuleDict(); PyObject* object = PyDict_GetItemString(dict, "__main__"); if(object){ Py_INCREF(object); PyModule_AddObject(object, node->GetName().c_str(), resultObj); } setVariableStack(QmitkPythonMediator::getAttributeList()); } } } return returnValue; } QVariant QmitkPythonVariableStackTreeWidget::headerData(int section, Qt::Orientation orientation, int role) const { QVariant headerData; // show only horizontal header if ( role == Qt::DisplayRole ) { if( orientation == Qt::Horizontal ) { // first column: "Attribute" if(section == 0) headerData = "Attribute"; else if(section == 1) headerData = "Value"; else if(section == 2) headerData = "Type"; } } return headerData; } Qt::ItemFlags QmitkPythonVariableStackTreeWidget::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if(index.isValid()) return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags; else return Qt::ItemIsDropEnabled | flags; } int QmitkPythonVariableStackTreeWidget::rowCount(const QModelIndex &) const { return m_variableStack.size(); } int QmitkPythonVariableStackTreeWidget::columnCount(const QModelIndex &) const { return 3; } QVariant QmitkPythonVariableStackTreeWidget::data(const QModelIndex &index, int role) const { if (index.isValid() && !m_variableStack.empty()) { if(role == Qt::DisplayRole) { QStringList item = m_variableStack.at(index.row()); if(index.column() == 0) return item[0]; if(index.column() == 1) return item[1]; if(index.column() == 2) return item[2]; } } return QVariant(); } void QmitkPythonVariableStackTreeWidget::clear() { m_variableStack.clear(); QAbstractTableModel::reset(); } void QmitkPythonVariableStackTreeWidget::setVariableStack(std::vector varStack) { m_variableStack = varStack; QAbstractTableModel::reset(); } std::vector QmitkPythonVariableStackTreeWidget::getVariableStack() { return m_variableStack; } QMimeData * QmitkPythonVariableStackTreeWidget::mimeData(const QModelIndexList & indexes) const { QMimeData * ret = new QMimeData; QString dataNodeAddresses(""); for (int indexesCounter = 0; indexesCounter < indexes.size(); indexesCounter++) { QString name = m_variableStack[indexes.at(indexesCounter).row()][0]; QString type = m_variableStack[indexes.at(indexesCounter).row()][2]; if(type != "DataNode_PointerPtr") return NULL; mitk::DataNode* node; itk::SmartPointer *arg; PyObject * obj = QmitkPythonMediator::getPyObjectString(&name); int i = 0; while(swig_types_initial[i] != 0) { if(swig_types_initial[i] == _swigt__p_itk__SmartPointerTmitk__DataNode_t) SWIGTYPE_p_itk__SmartPointerTmitk__DataNode_t = SWIG_TypeRegister(swig_types_initial[i]); i++; } if ((SWIG_ConvertPtr(obj,(void **)(&arg),SWIGTYPE_p_itk__SmartPointerTmitk__DataNode_t, SWIG_POINTER_EXCEPTION | 0)) == -1) return NULL; if(arg == NULL){ return NULL; } try { node = (mitk::DataNode *)((itk::SmartPointer const *)arg)->GetPointer(); } catch(std::exception &_e) { { std::cout << "Not a DataNode" << std::endl; } } long a = reinterpret_cast(node); if (dataNodeAddresses.size() != 0) { QTextStream(&dataNodeAddresses) << ","; } QTextStream(&dataNodeAddresses) << a; ret->setData("application/x-mitk-datanodes", QByteArray(dataNodeAddresses.toAscii())); } return ret; } QStringList QmitkPythonVariableStackTreeWidget::mimeTypes() const { QStringList types; types << "application/x-mitk-datanodes"; types << "application/x-qabstractitemmodeldatalist"; return types; } Qt::DropActions QmitkPythonVariableStackTreeWidget::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction; } Qt::DropActions QmitkPythonVariableStackTreeWidget::supportedDragActions() const { return Qt::CopyAction | Qt::MoveAction; } void QmitkPythonVariableStackTreeWidget::update() { // std::cout << "QmitkPythonVariableStackTreeWidget::update()" << std::endl; setVariableStack(QmitkPythonMediator::getAttributeList()); } diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.h index 017159a636..fe4a0f7af9 100755 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/QmitkPythonVariableStackTreeWidget.h @@ -1,69 +1,68 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-09-07 13:46:44 +0200 (Di, 07 Sep 2010) $ -Version: $Revision: 25948 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKPYTHONVARIABLESTACKTREEWIDGET_H_ #define QMITKPYTHONVARIABLESTACKTREEWIDGET_H_ #include #include #include #include #include #include #include #include #include #include #include #include "QmitkPythonMediator.h" class QmitkPythonVariableStackTreeWidget : public QAbstractTableModel, public QmitkPythonClient { // 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: QmitkPythonVariableStackTreeWidget(QWidget *parent = 0); virtual ~QmitkPythonVariableStackTreeWidget(); int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; Qt::ItemFlags flags( const QModelIndex& index ) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; QStringList mimeTypes() const; void clear(); void setVariableStack(std::vector); std::vector getVariableStack(); QMimeData * mimeData(const QModelIndexList &) const; bool dropMimeData ( const QMimeData *, Qt::DropAction, int, int, const QModelIndex & ); Qt::DropActions supportedDropActions() const; Qt::DropActions supportedDragActions() const; virtual void update(); protected: std::vector m_variableStack; }; #endif diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp index d0893cd9a6..175984dde2 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp @@ -1,645 +1,644 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDeformableRegistrationView.h" #include "ui_QmitkDeformableRegistrationViewControls.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "qinputdialog.h" #include "qmessagebox.h" #include "qcursor.h" #include "qapplication.h" #include "qradiobutton.h" #include "qslider.h" #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateNot.h" #include "mitkVectorImageMapper2D.h" #include "itkImageFileReader.h" #include "itkWarpImageFilter.h" #include "mitkDataNodeObject.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" typedef itk::Vector< float, 3 > VectorType; typedef itk::Image< VectorType, 3 > DeformationFieldType; typedef itk::ImageFileReader< DeformationFieldType > ImageReaderType; const std::string QmitkDeformableRegistrationView::VIEW_ID = "org.mitk.views.deformableregistration"; using namespace berry; struct SelListenerDeformableRegistration : ISelectionListener { berryObjectMacro(SelListenerDeformableRegistration); SelListenerDeformableRegistration(QmitkDeformableRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // if(!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_SwitchImages->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.m_OpacityLabel->setEnabled(false); m_View->m_Controls.m_OpacitySlider->setEnabled(false); m_View->m_Controls.label->setEnabled(false); m_View->m_Controls.label_2->setEnabled(false); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { if (dynamic_cast(node->GetData())->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "DeformableRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_SwitchImages->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.m_OpacityLabel->setEnabled(true); m_View->m_Controls.m_OpacitySlider->setEnabled(true); m_View->m_Controls.label->setEnabled(true); m_View->m_Controls.label_2->setEnabled(true); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkDeformableRegistrationView* m_View; }; QmitkDeformableRegistrationView::QmitkDeformableRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality() , m_MultiWidget(NULL), m_MovingNode(NULL), m_FixedNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Deactivated(false) { this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkDeformableRegistrationView::DataNodeHasBeenRemoved )); } QmitkDeformableRegistrationView::~QmitkDeformableRegistrationView() { if (m_SelListener.IsNotNull()) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; } } void QmitkDeformableRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Parent->setEnabled(false); this->CreateConnections(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_DeformableTransform->hide(); if (m_Controls.m_DeformableTransform->currentIndex() == 0) { m_Controls.m_QmitkDemonsRegistrationViewControls->show(); m_Controls.m_QmitkBSplineRegistrationViewControls->hide(); } else { m_Controls.m_QmitkDemonsRegistrationViewControls->hide(); m_Controls.m_QmitkBSplineRegistrationViewControls->show(); } this->CheckCalculateEnabled(); } void QmitkDeformableRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_DeformableTransform->hide(); m_Controls.m_CalculateTransformation->setEnabled(false); } } void QmitkDeformableRegistrationView::ApplyDeformationField() { ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName( m_Controls.m_QmitkBSplineRegistrationViewControls->m_Controls.m_DeformationField->text().toStdString() ); reader->Update(); DeformationFieldType::Pointer deformationField = reader->GetOutput(); mitk::Image * mimage = dynamic_cast (m_MovingNode->GetData()); mitk::Image * fimage = dynamic_cast (m_FixedNode->GetData()); typedef itk::Image FloatImageType; FloatImageType::Pointer itkMovingImage = FloatImageType::New(); FloatImageType::Pointer itkFixedImage = FloatImageType::New(); mitk::CastToItkImage(mimage, itkMovingImage); mitk::CastToItkImage(fimage, itkFixedImage); typedef itk::WarpImageFilter< FloatImageType, FloatImageType, DeformationFieldType > WarperType; typedef itk::LinearInterpolateImageFunction< FloatImageType, double > InterpolatorType; WarperType::Pointer warper = WarperType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); warper->SetInput( itkMovingImage ); warper->SetInterpolator( interpolator ); warper->SetOutputSpacing( itkFixedImage->GetSpacing() ); warper->SetOutputOrigin( itkFixedImage->GetOrigin() ); warper->SetOutputDirection (itkFixedImage->GetDirection() ); warper->SetDeformationField( deformationField ); warper->Update(); FloatImageType::Pointer outputImage = warper->GetOutput(); mitk::Image::Pointer result = mitk::Image::New(); mitk::CastToMitkImage(outputImage, result); // Create new DataNode mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetData( result ); newNode->SetProperty( "name", mitk::StringProperty::New("warped image") ); // add the new datatree node to the datatree this->GetDefaultDataStorage()->Add(newNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //Image::Pointer outputImage = this->GetOutput(); //mitk::CastToMitkImage( warper->GetOutput(), outputImage ); } void QmitkDeformableRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); } void QmitkDeformableRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; } void QmitkDeformableRegistrationView::CreateConnections() { connect(m_Controls.m_ShowRedGreenValues, SIGNAL(toggled(bool)), this, SLOT(ShowRedGreen(bool))); connect(m_Controls.m_DeformableTransform, SIGNAL(currentChanged(int)), this, SLOT(TabChanged(int))); connect(m_Controls.m_OpacitySlider, SIGNAL(sliderMoved(int)), this, SLOT(OpacityUpdate(int))); connect(m_Controls.m_CalculateTransformation, SIGNAL(clicked()), this, SLOT(Calculate())); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect(this,SIGNAL(calculateBSplineRegistration()),m_Controls.m_QmitkBSplineRegistrationViewControls,SLOT(CalculateTransformation())); connect( (QObject*)(m_Controls.m_QmitkBSplineRegistrationViewControls->m_Controls.m_ApplyDeformationField), SIGNAL(clicked()), (QObject*) this, SLOT(ApplyDeformationField()) ); } void QmitkDeformableRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerDeformableRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); } void QmitkDeformableRegistrationView::Visible() { /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerDeformableRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener("org.mitk.views.datamanager", m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked());*/ } void QmitkDeformableRegistrationView::Deactivated() { m_Deactivated = true; this->SetImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } m_FixedNode = NULL; m_MovingNode = NULL; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; } void QmitkDeformableRegistrationView::Hidden() { /* m_Deactivated = true; this->SetImageColor(false); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } m_FixedNode = NULL; m_MovingNode = NULL; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL;*/ //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated(); } void QmitkDeformableRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if (fixedImage.IsNotNull()) { if (m_FixedNode != fixedImage) { // remove changes on previous selected node if (m_FixedNode.IsNotNull()) { this->SetImageColor(false); m_FixedNode->SetOpacity(1.0); m_FixedNode->SetVisibility(false); m_FixedNode->SetProperty("selectedFixedImage", mitk::BoolProperty::New(false)); } // get selected node m_FixedNode = fixedImage; m_FixedNode->SetOpacity(0.5); m_Controls.TextLabelFixed->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.TextLabelFixed->show(); m_Controls.m_SwitchImages->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_FixedNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_FixedNode = fixedImage; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); } this->CheckCalculateEnabled(); } void QmitkDeformableRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if (movingImage.IsNotNull()) { if (m_MovingNode != movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->SetImageColor(false); } m_MovingNode = movingImage; m_Controls.TextLabelMoving->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); m_MovingNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_MovingNode = NULL; m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); } this->CheckCalculateEnabled(); } bool QmitkDeformableRegistrationView::CheckCalculate() { if(m_MovingNode==m_FixedNode) return false; return true; } void QmitkDeformableRegistrationView::ShowRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->SetImageColor(m_ShowRedGreen); } void QmitkDeformableRegistrationView::SetImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDeformableRegistrationView::OpacityUpdate(float opacity) { m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDeformableRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkDeformableRegistrationView::CheckCalculateEnabled() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { m_Controls.m_CalculateTransformation->setEnabled(true); } else { m_Controls.m_CalculateTransformation->setEnabled(false); } } void QmitkDeformableRegistrationView::Calculate() { if (m_Controls.m_DeformableTransform->tabText(m_Controls.m_DeformableTransform->currentIndex()) == "Demons") { m_Controls.m_QmitkDemonsRegistrationViewControls->SetFixedNode(m_FixedNode); m_Controls.m_QmitkDemonsRegistrationViewControls->SetMovingNode(m_MovingNode); try { m_Controls.m_QmitkDemonsRegistrationViewControls->CalculateTransformation(); } catch (itk::ExceptionObject& excpt) { QMessageBox::information( NULL, "Registration exception", excpt.GetDescription(), QMessageBox::Ok ); return; } mitk::Image::Pointer resultImage = m_Controls.m_QmitkDemonsRegistrationViewControls->GetResultImage(); mitk::Image::Pointer resultDeformationField = m_Controls.m_QmitkDemonsRegistrationViewControls->GetResultDeformationfield(); if (resultImage.IsNotNull()) { mitk::DataNode::Pointer resultImageNode = mitk::DataNode::New(); resultImageNode->SetData(resultImage); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( resultImage ); levWinProp->SetLevelWindow(levelWindow); resultImageNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); resultImageNode->SetStringProperty("name", "DeformableRegistrationResultImage"); this->GetDataStorage()->Add(resultImageNode, m_MovingNode); } if (resultDeformationField.IsNotNull()) { mitk::DataNode::Pointer resultDeformationFieldNode = mitk::DataNode::New(); resultDeformationFieldNode->SetData(resultDeformationField); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( resultDeformationField ); levWinProp->SetLevelWindow(levelWindow); resultDeformationFieldNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); resultDeformationFieldNode->SetStringProperty("name", "DeformableRegistrationResultDeformationField"); mitk::VectorImageMapper2D::Pointer mapper = mitk::VectorImageMapper2D::New(); resultDeformationFieldNode->SetMapper(1, mapper); resultDeformationFieldNode->SetVisibility(false); this->GetDataStorage()->Add(resultDeformationFieldNode, m_MovingNode); } } else if (m_Controls.m_DeformableTransform->tabText(m_Controls.m_DeformableTransform->currentIndex()) == "B-Spline") { m_Controls.m_QmitkBSplineRegistrationViewControls->SetFixedNode(m_FixedNode); m_Controls.m_QmitkBSplineRegistrationViewControls->SetMovingNode(m_MovingNode); emit calculateBSplineRegistration(); } } void QmitkDeformableRegistrationView::SetImagesVisible(berry::ISelection::ConstPointer /*selection*/) { if (this->m_CurrentSelection->Size() == 0) { // show all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(true); } } } else { // hide all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(false); } } } } void QmitkDeformableRegistrationView::TabChanged(int index) { if (index == 0) { m_Controls.m_QmitkDemonsRegistrationViewControls->show(); m_Controls.m_QmitkBSplineRegistrationViewControls->hide(); } else { m_Controls.m_QmitkDemonsRegistrationViewControls->hide(); m_Controls.m_QmitkBSplineRegistrationViewControls->show(); } } void QmitkDeformableRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h index 3bf5785f92..c6c6bb6ec3 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h @@ -1,214 +1,213 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKDEFORMABLEREGISTRATION_H #define QMITKDEFORMABLEREGISTRATION_H #include "QmitkFunctionality.h" #include "ui_QmitkDeformableRegistrationViewControls.h" #include #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" /*! \brief The DeformableRegistration functionality is used to perform deformable registration. This functionality allows you to register two 2D as well as two 3D images in a non rigid manner. Register means to align two images, so that they become as similar as possible. Therefore you can select from different deformable registration methods. Registration results will directly be applied to the Moving Image. The result is shown in the multi-widget. For more informations see: \ref QmitkDeformableRegistrationUserManual \sa QmitkFunctionality \ingroup Functionalities \ingroup DeformableRegistration */ class REGISTRATION_EXPORT QmitkDeformableRegistrationView : public QmitkFunctionality { friend struct SelListenerDeformableRegistration; Q_OBJECT public: static const std::string VIEW_ID; /*! \brief default constructor */ QmitkDeformableRegistrationView(QObject *parent=0, const char *name=0); QmitkDeformableRegistrationView(const QmitkDeformableRegistrationView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } /*! \brief default destructor */ virtual ~QmitkDeformableRegistrationView(); /*! \brief method for creating the applications main widget */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief Sets the StdMultiWidget and connects it to the functionality. */ virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); /*! \brief Removes the StdMultiWidget and disconnects it from the functionality. */ virtual void StdMultiWidgetNotAvailable(); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief Method which is called when this functionality is selected in MITK */ virtual void Activated(); /*! \brief Method which is called whenever the functionality is deselected in MITK */ virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); void DataNodeHasBeenRemoved(const mitk::DataNode* node); signals: /*! \brief Signal that informs about that the fixed image should be reinitialized in the multi-widget. */ void reinitFixed(const mitk::Geometry3D *); /*! \brief Signal that informs about that the moving image should be reinitialized in the multi-widget. */ void reinitMoving(const mitk::Geometry3D *); /*! \brief Signal that informs about that the BSpline registration should be performed. */ void calculateBSplineRegistration(); protected slots: /*! * sets the fixed Image according to TreeNodeSelector widget */ void FixedSelected(mitk::DataNode::Pointer fixedImage); /*! * sets the moving Image according to TreeNodeSelector widget */ void MovingSelected(mitk::DataNode::Pointer movingImage); /*! * checks if registration is possible */ bool CheckCalculate(); /*! * stores whether the image will be shown in grayvalues or in red for fixed image and green for moving image * @param show if true, then images will be shown in red and green */ void ShowRedGreen(bool show); /*! * set the selected opacity for moving image * @param opacity the selected opacity */ void OpacityUpdate(float opacity); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(int opacity); /*! * sets the images to grayvalues or fixed image to red and moving image to green * @param redGreen if true, then images will be shown in red and green */ void SetImageColor(bool redGreen); /*! \brief Checks whether the registration can be performed. */ void CheckCalculateEnabled(); /*! \brief Performs the registration. */ void Calculate(); /*! * Prints the values of the deformationfield */ void ApplyDeformationField(); void SetImagesVisible(berry::ISelection::ConstPointer selection); void TabChanged(int index); void SwitchImages(); protected: berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * control widget to make all changes for Deformable registration */ Ui::QmitkDeformableRegistrationViewControls m_Controls; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_FixedNode; bool m_ShowRedGreen; float m_Opacity; float m_OriginalOpacity; mitk::Color m_FixedColor; mitk::Color m_MovingColor; bool m_Deactivated; }; #endif //QMITKDEFORMABLEREGISTRATION_H diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.cpp index 8f3ae758e0..68caa3a7c9 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.cpp @@ -1,92 +1,91 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2007-12-11 15:14:28 +0100 (Di, 11 Dez 2007) $ -Version: $Revision: 13135 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkLoadPresetDialog.h" #include #include #include #include QmitkLoadPresetDialog::QmitkLoadPresetDialog(QWidget* parent, Qt::WindowFlags f, const char* name, std::list presets) :QDialog(parent, f) { QDialog::setMinimumSize(250, 300); this->setObjectName(name); QBoxLayout * verticalLayout = new QVBoxLayout( this ); verticalLayout->setMargin(5); verticalLayout->setSpacing(5); // list of all presets lblPrompt = new QLabel( "Which preset do you want to load?", this ); verticalLayout->addWidget( lblPrompt ); lstPresets = new QListWidget( this ); verticalLayout->addWidget( lstPresets ); std::list::iterator iter; for( iter = presets.begin(); iter != presets.end(); iter++ ) { std::string preset = *iter; new QListWidgetItem(preset.c_str(), lstPresets); } lstPresets->setCurrentItem(0); // select first Item by default (might turn out to be a stupid descision) connect( lstPresets, SIGNAL(itemDoubleClicked (QListWidgetItem *)), this, SLOT(onPresetImmediatelySelected(QListWidgetItem *)) ); // buttons for closing the dialog btnOk = new QPushButton( tr("Ok"), this); btnOk->setObjectName("btnOk" ); btnOk->setDefault(true); connect( btnOk, SIGNAL(clicked()), this, SLOT(accept()) ); QPushButton* btnCancel = new QPushButton( tr("Cancel"), this); btnCancel->setObjectName("btnCancel" ); connect( btnCancel, SIGNAL(clicked()), this, SLOT(reject()) ); QWidget* buttonWidget = new QWidget(this); QBoxLayout * horizontalLayout = new QHBoxLayout( buttonWidget ); horizontalLayout->setSpacing(5); horizontalLayout->addStretch(); horizontalLayout->addWidget( btnOk ); horizontalLayout->addWidget( btnCancel ); verticalLayout->addWidget(buttonWidget); } QmitkLoadPresetDialog::~QmitkLoadPresetDialog() { } std::string QmitkLoadPresetDialog::GetPresetName() { std::string presetName = std::string(lstPresets->currentItem()->text().toAscii()); return presetName; } void QmitkLoadPresetDialog::onPresetImmediatelySelected(QListWidgetItem * ) { if ( (signed)(lstPresets->row(lstPresets->currentItem())) != (signed)(lstPresets->count()-1) ) { accept(); // close } else { // dont close } } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.h index e4feab5f3c..5fb165e227 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkLoadPresetDialog.h @@ -1,67 +1,66 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2008-02-13 14:07:17 +0100 (Mi, 13 Feb 2008) $ -Version: $Revision: 13599 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkLoadPresetDialog_h_Included #define QmitkLoadPresetDialog_h_Included #include #include #include class QLabel; class QLineEdit; class QListWidget; class QPushButton; #include /** \brief Dialog for QmitkRigidRegistration. \ingroup RigidRegistration This dialog is used to ask a user about a preset with transform, metric, optimizer and interpolator parameters to load. */ class QmitkLoadPresetDialog : public QDialog { Q_OBJECT public: QmitkLoadPresetDialog(QWidget* parent, Qt::WindowFlags f, const char* name, std::list presets); virtual ~QmitkLoadPresetDialog(); std::string GetPresetName(); signals: public slots: protected slots: void onPresetImmediatelySelected(QListWidgetItem * item); protected: QLabel* lblPrompt; QListWidget* lstPresets; QPushButton* btnOk; }; #endif diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationTesting.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationTesting.cpp index f18c914f7e..111c7cb030 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationTesting.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationTesting.cpp @@ -1,815 +1,814 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 11450 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // #include "QmitkPointBasedRegistrationView.h" // includes mitkConfig, where BUILD_TESTING is defined // #include "ui_QmitkPointBasedRegistrationViewControls.h" // // #ifdef BUILD_TESTING // only if we build a test driver // // #include "QmitkStdMultiWidget.h" // #include "QmitkSelectableGLWidget.h" // #include "QmitkUserInputSimulation.h" // #include "QmitkMessageBoxHelper.h" // #include "QmitkTreeNodeSelector.h" // #include // #include "QmitkCommonFunctionality.h" // #include "qradiobutton.h" // #include "qpushbutton.h" // #include "qslider.h" // #include "qcheckbox.h" // #include "qlistbox.h" // #include // #include // #include "QmitkMessageBoxHelper.h" // #include "QmitkPointListWidget.h" // // #include // #include // // #include // // // int QmitkPointBasedRegistration::TestYourself() // { // m_MessageBox = false; // // std::cout << std::endl; // time_t randomInit = std::time(0); // //randomInit = 1200058324; // std::cout << "Initializing random number generator with " << randomInit << std::endl; // std::srand(randomInit); // // if (m_Controls->m_FixedSelector->GetSelectedNode() == NULL) // { // std::cout << "No Fixed Image available! Won't apply test (l. " << __LINE__ << ")" << std::endl; // return EXIT_SUCCESS; // } // mitk::DataNode::Pointer node = NULL; // if (m_Controls->m_MovingSelector->GetSelectedNode() == NULL) // { // node = mitk::DataNode::New(); // //Create Image out of nowhere // mitk::Image::Pointer image; // m_Controls->m_FixedSelector->GetSelectedNode()->GetData(); // mitk::PixelType pt(typeid(int)); // unsigned int dim[]={100,100,20}; // // std::cout << "Creating image: "; // image = mitk::Image::New(); // image->Initialize(mitk::PixelType(typeid(int)), 3, dim); // int *p = (int*)image->GetData(); // // int size = dim[0]*dim[1]*dim[2]; // int i; // for(i=0; iSetData(image); // node->SetProperty("name", mitk::StringProperty::New("new created node for PointBasedRegistrationTest")); // mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); // mitk::LevelWindow levelWindow; // levelWindow.SetAuto( image ); // levWinProp->SetLevelWindow(levelWindow); // node->GetPropertyList()->SetProperty("levelwindow",levWinProp); // mitk::DataTreeIteratorClone it; // it = *m_Controls->m_FixedSelector->GetSelectedIterator(); // it->GoToParent(); // it->Add(node); // std::cout<<"[PASSED]"<m_MovingSelector->GetSelectedNode() == NULL) // { // std::cerr << "No Moving Image available! Won't apply test (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // // // test Show Images Red/Green // std::cout << "Test show images red/green:" << std::endl; // QmitkUserInputSimulation::MouseClick( m_Controls->m_ShowRedGreenValues, Qt::LeftButton ); // m_Controls->m_ShowRedGreenValues->setChecked(true); // std::cout << " [PASSED]" << std::endl; // // // test for Select model // QmitkUserInputSimulation::MouseClick( m_Controls->m_FixedPointListWidget->m_SetPoints, Qt::LeftButton ); // if (!m_Controls->m_FixedPointListWidget->m_SetPoints->isOn()) // { // std::cerr << "Select Fixed Image was not toggled (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // if (m_Controls->m_MovingPointListWidget->m_SetPoints->isOn()) // { // std::cerr << "Select Moving Image was toggled (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_SetPoints, Qt::LeftButton ); // if (!m_Controls->m_MovingPointListWidget->m_SetPoints->isOn()) // { // std::cerr << "Select Moving Image was not toggled (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // if (m_Controls->m_FixedPointListWidget->m_SetPoints->isOn()) // { // std::cerr << "Select Fixed Image was toggled (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_SetPoints, Qt::LeftButton ); // if (m_Controls->m_MovingPointListWidget->m_SetPoints->isOn()) // { // std::cerr << "Select Moving Image was toggled (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // if (m_Controls->m_FixedPointListWidget->m_SetPoints->isOn()) // { // std::cerr << "Select Fixed Image was toggled (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // // // test for undobutton at start // if (m_Controls->m_UndoTransformation->isEnabled()) // { // std::cerr << "Undo Transformation was enabled but there was no transformation before (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // // // test for redobutton at start // if (m_Controls->m_RedoTransformation->isEnabled()) // { // std::cerr << "Redo Transformation was enabled but there was no transformation before (l. " << __LINE__ << ")" << std::endl; // return EXIT_FAILURE; // } // // // test reinit buttons // std::cout << "Test reinit buttons:" << std::endl; // QmitkUserInputSimulation::MouseClick( m_Controls->m_ReinitFixedButton, Qt::LeftButton ); // QmitkUserInputSimulation::MouseClick( m_Controls->m_ReinitMovingButton, Qt::LeftButton ); // m_Controls->globalReinitClicked(); // std::cout << " [PASSED]" << std::endl; // // // test opacity slider // std::cout << "Test opacity slider:" << std::endl; // m_Controls->m_OpacitySlider->setValue(m_Controls->m_OpacitySlider->minValue()); // m_Controls->m_OpacitySlider->setValue(m_Controls->m_OpacitySlider->maxValue()); // std::cout << " [PASSED]" << std::endl; // // bool testOK = this->TestAllTools(); // // // clean up // if (m_FixedPointSetNode.IsNotNull()) // { // this->GetDefaultDataStorage()->Remove(m_FixedPointSetNode); // m_FixedPointSetNode = NULL; // } // if (m_MovingPointSetNode) // if (node.IsNotNull()) // { // this->GetDefaultDataStorage()->Remove(m_MovingPointSetNode); // m_MovingPointSetNode = NULL; // } // // // recenter all remaining datatreenodes // m_Controls->globalReinitClicked(); // // if (testOK) // { // std::cout << "Whole functionality testing [PASSED]" << std::endl; // return EXIT_SUCCESS; // } // else // { // std::cout << "Whole functionality testing [FAILED]" << std::endl; // return EXIT_FAILURE; // } // } // // bool QmitkPointBasedRegistration::TestAllTools() // { // QWidget* sliceWidget; // m_MultiWidget->changeLayoutToDefault(); // // std::cout << "Creating landmarks:" << std::endl; // QmitkUserInputSimulation::MouseClick( m_Controls->m_FixedPointListWidget->m_SetPoints, Qt::LeftButton ); // // for (unsigned int window = 1; window < 4; ++window) // { // switch (window) // { // case 1: // sliceWidget = m_MultiWidget->mitkWidget1; // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget // break; // case 2: // sliceWidget = m_MultiWidget->mitkWidget2; // break; // case 3: // default: // sliceWidget = m_MultiWidget->mitkWidget3; // break; // } // float w = (float)sliceWidget->width()-10; // float h = (float)sliceWidget->height()-10; // for (unsigned int i = 0; i < 5; ++i ) // { // double r; // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float x = r * w; // // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float y = r * h; // // QmitkUserInputSimulation::MouseDown( sliceWidget, (int)x+5, (int)y+5, Qt::LeftButton, Qt::ShiftButton ); // QmitkUserInputSimulation::MouseRelease( sliceWidget, (int)x+5, (int)y+5, Qt::LeftButton, Qt::ShiftButton ); // } // } // // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_SetPoints, Qt::LeftButton ); // // for (unsigned int window = 1; window < 4; ++window) // { // switch (window) // { // case 1: // sliceWidget = m_MultiWidget->mitkWidget1; // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget // break; // case 2: // sliceWidget = m_MultiWidget->mitkWidget2; // break; // case 3: // default: // sliceWidget = m_MultiWidget->mitkWidget3; // break; // } // float w = (float)sliceWidget->width(); // float h = (float)sliceWidget->height(); // for (unsigned int i = 0; i < 5; ++i ) // { // double r; // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float x = r * w; // // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float y = r * h; // QmitkUserInputSimulation::MouseDown( sliceWidget, (int)x, (int)y, Qt::LeftButton, Qt::ShiftButton ); // QmitkUserInputSimulation::MouseRelease( sliceWidget, (int)x, (int)y, Qt::LeftButton, Qt::ShiftButton ); // } // } // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_SetPoints, Qt::LeftButton ); // std::cout << " [PASSED]" << std::endl; // // /////// test for deleting points from fixed point list // std::cout << "Delete Landmarks out of order:" << std::endl; // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(4, true); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_FixedPointListWidget->InteractivePointList, Qt::Key_Return ); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(8,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(13,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(0,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(7,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(7,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(3,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(4,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // for (int i = 0; i < 7; i++) // { // m_Controls->m_FixedPointListWidget->InteractivePointList->setSelected(0,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // } // /////// test for deleting points from moving point list // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(0,true); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_MovingPointListWidget->InteractivePointList, Qt::Key_Return ); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(14,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(11,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(8,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(6,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(2,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(2,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(2,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // for (int i = 0; i < 7; i++) // { // m_Controls->m_MovingPointListWidget->InteractivePointList->setSelected(0,true); // QmitkUserInputSimulation::KeyboardTypeKey( sliceWidget, Qt::Key_Delete ); // } // std::cout << " [PASSED]" << std::endl; // // ////// create new points // std::cout << "Create new landmarks:" << std::endl; // std::cout << "Creating landmarks:" << std::endl; // QmitkUserInputSimulation::MouseClick( m_Controls->m_FixedPointListWidget->m_SetPoints, Qt::LeftButton ); // // for (unsigned int window = 1; window < 4; ++window) // { // switch (window) // { // case 1: // sliceWidget = m_MultiWidget->mitkWidget1; // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget // break; // case 2: // sliceWidget = m_MultiWidget->mitkWidget2; // break; // case 3: // default: // sliceWidget = m_MultiWidget->mitkWidget3; // break; // } // float w = (float)sliceWidget->width()-10; // float h = (float)sliceWidget->height()-10; // for (unsigned int i = 0; i < 5; ++i ) // { // double r; // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float x = r * w; // // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float y = r * h; // // QmitkUserInputSimulation::MouseDown( sliceWidget, (int)x+5, (int)y+5, Qt::LeftButton, Qt::ShiftButton ); // QmitkUserInputSimulation::MouseRelease( sliceWidget, (int)x+5, (int)y+5, Qt::LeftButton, Qt::ShiftButton ); // } // } // // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_SetPoints, Qt::LeftButton ); // // for (unsigned int window = 1; window < 4; ++window) // { // switch (window) // { // case 1: // sliceWidget = m_MultiWidget->mitkWidget1; // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget // break; // case 2: // sliceWidget = m_MultiWidget->mitkWidget2; // break; // case 3: // default: // sliceWidget = m_MultiWidget->mitkWidget3; // break; // } // float w = (float)sliceWidget->width(); // float h = (float)sliceWidget->height(); // for (unsigned int i = 0; i < 5; ++i ) // { // double r; // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float x = r * w; // // r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); // float y = r * h; // QmitkUserInputSimulation::MouseDown( sliceWidget, (int)x, (int)y, Qt::LeftButton, Qt::ShiftButton ); // QmitkUserInputSimulation::MouseRelease( sliceWidget, (int)x, (int)y, Qt::LeftButton, Qt::ShiftButton ); // } // } // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_SetPoints, Qt::LeftButton ); // std::cout << " [PASSED]" << std::endl; // // //// Rigid with ICP // // a helper object to close popping up message boxes // QmitkMessageBoxHelper* helper1 = new QmitkMessageBoxHelper(m_Controls); // connect( helper1, SIGNAL(DialogFound(QWidget*)), this, SLOT(RegistrationErrorDialogFound(QWidget*)) ); // helper1->WaitForDialogAndCallback( "QMessageBox" ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "Rigid with ICP [PASSED]" << std::endl; // } // else // { // std::cout << "Rigid with ICP [FAILED]" << std::endl; // helper1->StopWaitForDialogAndCallback(); // return false; // } // helper1->StopWaitForDialogAndCallback(); // if (!m_MessageBox) // { // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // std::cout << "Undo was enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_RedoTransformation, Qt::LeftButton ); // std::cout << "Redo [PASSED]" << std::endl; // } // else // { // std::cout << "Redo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // std::cout << "Redo was enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // std::cout << "Undo was enabled [FAILED]" << std::endl; // return false; // } // } // m_MessageBox = false; // // // //// Similarity with ICP // QmitkMessageBoxHelper* helper2 = new QmitkMessageBoxHelper(m_Controls); // connect( helper2, SIGNAL(DialogFound(QWidget*)), this, SLOT(RegistrationErrorDialogFound(QWidget*)) ); // helper2->WaitForDialogAndCallback( "QMessageBox" ); // m_Controls->m_SelectedTransformationClass->setFocus(); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_SelectedTransformationClass, Qt::Key_Down ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "Similarity with ICP [PASSED]" << std::endl; // } // else // { // std::cout << "Similarity with ICP [FAILED]" << std::endl; // helper2->StopWaitForDialogAndCallback(); // return false; // } // helper2->StopWaitForDialogAndCallback(); // if(!m_MessageBox) // { // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_RedoTransformation, Qt::LeftButton ); // std::cout << "Redo [PASSED]" << std::endl; // } // else // { // std::cout << "Redo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // } // m_MessageBox = false; // // // //// Affine with ICP // QmitkMessageBoxHelper* helper3 = new QmitkMessageBoxHelper(m_Controls); // connect( helper3, SIGNAL(DialogFound(QWidget*)), this, SLOT(RegistrationErrorDialogFound(QWidget*)) ); // helper3->WaitForDialogAndCallback( "QMessageBox" ); // m_Controls->m_SelectedTransformationClass->setFocus(); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_SelectedTransformationClass, Qt::Key_Down ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "Affine with ICP [PASSED]" << std::endl; // } // else // { // std::cout << "Affine with ICP [FAILED]" << std::endl; // helper3->StopWaitForDialogAndCallback(); // return false; // } // helper3->StopWaitForDialogAndCallback(); // if(!m_MessageBox) // { // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_RedoTransformation, Qt::LeftButton ); // std::cout << "Redo [PASSED]" << std::endl; // } // else // { // std::cout << "Redo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // } // m_MessageBox = false; // // //// Rigid without ICP // m_Controls->m_SelectedTransformationClass->setFocus(); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_SelectedTransformationClass, Qt::Key_Down ); // // a helper object to close popping up message boxes // QmitkMessageBoxHelper* helper4 = new QmitkMessageBoxHelper(m_Controls); // connect( helper4, SIGNAL(DialogFound(QWidget*)), this, SLOT(RegistrationErrorDialogFound(QWidget*)) ); // helper4->WaitForDialogAndCallback( "QMessageBox" ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "Rigid [PASSED]" << std::endl; // } // else // { // std::cout << "Rigid [FAILED]" << std::endl; // helper4->StopWaitForDialogAndCallback(); // return false; // } // helper4->StopWaitForDialogAndCallback(); // if(!m_MessageBox) // { // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_RedoTransformation, Qt::LeftButton ); // std::cout << "Redo [PASSED]" << std::endl; // } // else // { // std::cout << "Redo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // } // m_MessageBox = false; // // //// Similarity without ICP // m_Controls->m_SelectedTransformationClass->setFocus(); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_SelectedTransformationClass, Qt::Key_Down ); // // a helper object to close popping up message boxes // QmitkMessageBoxHelper* helper5 = new QmitkMessageBoxHelper(m_Controls); // connect( helper5, SIGNAL(DialogFound(QWidget*)), this, SLOT(RegistrationErrorDialogFound(QWidget*)) ); // helper5->WaitForDialogAndCallback( "QMessageBox" ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "Similarity [PASSED]" << std::endl; // } // else // { // std::cout << "Similarity [FAILED]" << std::endl; // helper5->StopWaitForDialogAndCallback(); // return false; // } // helper5->StopWaitForDialogAndCallback(); // if(!m_MessageBox) // { // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_RedoTransformation, Qt::LeftButton ); // std::cout << "Redo [PASSED]" << std::endl; // } // else // { // std::cout << "Redo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // } // m_MessageBox = false; // // //// Affine without ICP // m_Controls->m_SelectedTransformationClass->setFocus(); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_SelectedTransformationClass, Qt::Key_Down ); // // a helper object to close popping up message boxes // QmitkMessageBoxHelper* helper6 = new QmitkMessageBoxHelper(m_Controls); // connect( helper6, SIGNAL(DialogFound(QWidget*)), this, SLOT(RegistrationErrorDialogFound(QWidget*)) ); // helper6->WaitForDialogAndCallback( "QMessageBox" ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "Affine [PASSED]" << std::endl; // } // else // { // std::cout << "Affine [FAILED]" << std::endl; // helper6->StopWaitForDialogAndCallback(); // return false; // } // helper6->StopWaitForDialogAndCallback(); // if(!m_MessageBox) // { // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_RedoTransformation, Qt::LeftButton ); // std::cout << "Redo [PASSED]" << std::endl; // } // else // { // std::cout << "Redo was not enabled [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_UndoTransformation, Qt::LeftButton ); // std::cout << "Undo [PASSED]" << std::endl; // } // else // { // std::cout << "Undo was not enabled [FAILED]" << std::endl; // return false; // } // } // m_MessageBox = false; // /* // //// LandmarkWarping // if (dynamic_cast(m_Controls->m_FixedSelector->GetSelectedNode()->GetData()) != NULL && // (dynamic_cast(m_Controls->m_FixedSelector->GetSelectedNode()->GetData())->GetDimension() == 2 || // dynamic_cast(m_Controls->m_FixedSelector->GetSelectedNode()->GetData())->GetDimension() == 3)) // { // m_Controls->m_SelectedTransformationClass->setFocus(); // QmitkUserInputSimulation::KeyboardTypeKey( m_Controls->m_SelectedTransformationClass, Qt::Key_Down ); // if (m_Controls->m_Calculate->isEnabled()) // { // QmitkUserInputSimulation::MouseClick( m_Controls->m_Calculate, Qt::LeftButton ); // std::cout << "LandmarkWarping [PASSED]" << std::endl; // } // else // { // std::cout << "LandmarkWarping [FAILED]" << std::endl; // return false; // } // if (m_Controls->m_UndoTransformation->isEnabled()) // { // std::cout << "Undo [FAILED]" << std::endl; // return false; // } // else // { // std::cout << "Undo [PASSED]" << std::endl; // } // if (m_Controls->m_RedoTransformation->isEnabled()) // { // std::cout << "Redo [FAILED]" << std::endl; // return false; // } // else // { // std::cout << "Redo [PASSED]" << std::endl; // } // }*/ // // //// end registrationmethods test // // QmitkMessageBoxHelper* helper7 = new QmitkMessageBoxHelper(m_Controls); // connect( helper7, SIGNAL(DialogFound(QWidget*)), this, SLOT(ClearPointSetDialogFound(QWidget*)) ); // helper7->WaitForDialogAndCallback( "QMessageBox" ); // QmitkUserInputSimulation::MouseClick( m_Controls->m_FixedPointListWidget->m_ClearPointSet, Qt::LeftButton ); // // QmitkMessageBoxHelper* helper8 = new QmitkMessageBoxHelper(m_Controls); // connect( helper8, SIGNAL(DialogFound(QWidget*)), this, SLOT(ClearPointSetDialogFound(QWidget*)) ); // helper8->WaitForDialogAndCallback( "QMessageBox" ); // QmitkUserInputSimulation::MouseClick( m_Controls->m_MovingPointListWidget->m_ClearPointSet, Qt::LeftButton ); // // if(this->m_FixedLandmarks->GetSize() > 0) // { // std::cout << "Not all fixed points are deleted! [FAILED]" << std::endl; // return false; // } // if(m_MovingLandmarks->GetSize() > 0) // { // std::cout << "Not all moving points are deleted! [FAILED]" << std::endl; // return false; // } // // return true; // } // // void QmitkPointBasedRegistration::RegistrationErrorDialogFound( QWidget* widget ) // { // if (!widget) return; // // // close message box // widget->close(); // std::cout<<"Message box closed!"< #include #include #include #include #include "QmitkCommonFunctionality.h" #include "qradiobutton.h" #include "qapplication.h" #include #include #include #include #include "qmessagebox.h" #include "mitkLandmarkWarping.h" #include #include #include "mitkOperationEvent.h" #include "mitkUndoController.h" #include #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateNot.h" #include #include #include "mitkDataNodeObject.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkPointBasedRegistrationView::VIEW_ID = "org.mitk.views.pointbasedregistration"; using namespace berry; struct SelListenerPointBasedRegistration : ISelectionListener { berryObjectMacro(SelListenerPointBasedRegistration); SelListenerPointBasedRegistration(QmitkPointBasedRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // if(!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.line2->hide(); m_View->m_Controls.m_FixedPointListWidget->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.line1->hide(); m_View->m_Controls.m_MovingPointListWidget->hide(); m_View->m_Controls.m_OpacityLabel->hide(); m_View->m_Controls.m_OpacitySlider->hide(); m_View->m_Controls.label->hide(); m_View->m_Controls.label_2->hide(); m_View->m_Controls.m_SwitchImages->hide(); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::TNodePredicateDataType::Pointer isBaseData(mitk::TNodePredicateDataType::New()); mitk::TNodePredicateDataType::Pointer isPointSet(mitk::TNodePredicateDataType::New()); mitk::NodePredicateNot::Pointer notPointSet = mitk::NodePredicateNot::New(isPointSet); mitk::TNodePredicateDataType::Pointer isGeometry2DData(mitk::TNodePredicateDataType::New()); mitk::NodePredicateNot::Pointer notGeometry2DData = mitk::NodePredicateNot::New(isGeometry2DData); mitk::NodePredicateAnd::Pointer notPointSetAndNotGeometry2DData = mitk::NodePredicateAnd::New( notPointSet, notGeometry2DData ); mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New( isBaseData, notPointSetAndNotGeometry2DData ); mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = m_View->GetDataStorage()->GetSubset(predicate); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if(nodeIt->Value().GetPointer() == node.GetPointer()) { if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { if (dynamic_cast(node->GetData())->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "PointBasedRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.line2->show(); m_View->m_Controls.m_FixedPointListWidget->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.line1->show(); m_View->m_Controls.m_MovingPointListWidget->show(); m_View->m_Controls.m_OpacityLabel->show(); m_View->m_Controls.m_OpacitySlider->show(); m_View->m_Controls.label->show(); m_View->m_Controls.label_2->show(); m_View->m_Controls.m_SwitchImages->show(); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkPointBasedRegistrationView* m_View; }; QmitkPointBasedRegistrationView::QmitkPointBasedRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality(), m_SelListener(0), m_MultiWidget(NULL), m_FixedLandmarks(NULL), m_MovingLandmarks(NULL), m_MovingNode(NULL), m_FixedNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Transformation(0), m_HideFixedImage(false), m_HideMovingImage(false), m_OldFixedLabel(""), m_OldMovingLabel(""), m_Deactivated (false), m_CurrentFixedLandmarksObserverID(0), m_CurrentMovingLandmarksObserverID(0) { m_FixedLandmarksChangedCommand = itk::SimpleMemberCommand::New(); m_FixedLandmarksChangedCommand->SetCallbackFunction(this, &QmitkPointBasedRegistrationView::updateFixedLandmarksList); m_MovingLandmarksChangedCommand = itk::SimpleMemberCommand::New(); m_MovingLandmarksChangedCommand->SetCallbackFunction(this, &QmitkPointBasedRegistrationView::updateMovingLandmarksList); this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkPointBasedRegistrationView::DataNodeHasBeenRemoved )); } QmitkPointBasedRegistrationView::~QmitkPointBasedRegistrationView() { if(m_SelListener.IsNotNull()) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; } if (m_FixedPointSetNode.IsNotNull()) { m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); } if (m_MovingPointSetNode.IsNotNull()) { m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); } m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); } void QmitkPointBasedRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Parent->setEnabled(false); m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_ShowRedGreenValues->setEnabled(false); this->CreateConnections(); // let the point set widget know about the multi widget (cross hair updates) m_Controls.m_FixedPointListWidget->SetMultiWidget( m_MultiWidget ); m_Controls.m_MovingPointListWidget->SetMultiWidget( m_MultiWidget ); } void QmitkPointBasedRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); m_Controls.m_FixedPointListWidget->SetMultiWidget( m_MultiWidget ); m_Controls.m_MovingPointListWidget->SetMultiWidget( m_MultiWidget ); } void QmitkPointBasedRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; m_Controls.m_FixedPointListWidget->SetMultiWidget( NULL ); m_Controls.m_MovingPointListWidget->SetMultiWidget( NULL ); } void QmitkPointBasedRegistrationView::CreateConnections() { connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(EditPointSets(bool)), (QObject*)(m_Controls.m_MovingPointListWidget), SLOT(DeactivateInteractor(bool))); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(EditPointSets(bool)), (QObject*)(m_Controls.m_FixedPointListWidget), SLOT(DeactivateInteractor(bool))); connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(EditPointSets(bool)), this, SLOT(HideMovingImage(bool))); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(EditPointSets(bool)), this, SLOT(HideFixedImage(bool))); connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(PointListChanged()), this, SLOT(updateFixedLandmarksList())); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(PointListChanged()), this, SLOT(updateMovingLandmarksList())); connect((QObject*)(m_Controls.m_Calculate),SIGNAL(clicked()),this,SLOT(calculate())); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect((QObject*)(m_Controls.m_UndoTransformation),SIGNAL(clicked()),this,SLOT(UndoTransformation())); connect((QObject*)(m_Controls.m_RedoTransformation),SIGNAL(clicked()),this,SLOT(RedoTransformation())); connect((QObject*)(m_Controls.m_ShowRedGreenValues),SIGNAL(toggled(bool)),this,SLOT(showRedGreen(bool))); connect((QObject*)(m_Controls.m_OpacitySlider),SIGNAL(valueChanged(int)),this,SLOT(OpacityUpdate(int))); connect((QObject*)(m_Controls.m_SelectedTransformationClass),SIGNAL(activated(int)), this,SLOT(transformationChanged(int))); connect((QObject*)(m_Controls.m_UseICP),SIGNAL(toggled(bool)), this,SLOT(checkCalculateEnabled())); connect((QObject*)(m_Controls.m_UseICP),SIGNAL(toggled(bool)), this,SLOT(checkLandmarkError())); } void QmitkPointBasedRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); this->clearTransformationLists(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerPointBasedRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->showRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); } void QmitkPointBasedRegistrationView::Visible() { } void QmitkPointBasedRegistrationView::Deactivated() { m_Deactivated = true; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); this->setImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } this->clearTransformationLists(); if (m_FixedPointSetNode.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_FixedLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_FixedPointSetNode); } if (m_MovingPointSetNode.IsNotNull() && m_MovingLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_MovingPointSetNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FixedNode = NULL; m_MovingNode = NULL; if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); m_FixedLandmarks = NULL; if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); m_MovingLandmarks = NULL; m_FixedPointSetNode = NULL; m_MovingPointSetNode = NULL; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; } void QmitkPointBasedRegistrationView::Hidden() { /* m_Deactivated = true; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); this->setImageColor(false); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } this->clearTransformationLists(); if (m_FixedPointSetNode.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_FixedLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_FixedPointSetNode); } if (m_MovingPointSetNode.IsNotNull() && m_MovingLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_MovingPointSetNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FixedNode = NULL; m_MovingNode = NULL; if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); m_FixedLandmarks = NULL; if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); m_MovingLandmarks = NULL; m_FixedPointSetNode = NULL; m_MovingPointSetNode = NULL; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated();*/ } void QmitkPointBasedRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_ShowRedGreenValues->setEnabled(false); } } void QmitkPointBasedRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); if (fixedImage.IsNotNull()) { if (m_FixedNode != fixedImage) { // remove changes on previous selected node if (m_FixedNode.IsNotNull()) { this->setImageColor(false); m_FixedNode->SetOpacity(1.0); if (m_FixedPointSetNode.IsNotNull()) { m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); } } // get selected node m_FixedNode = fixedImage; m_FixedNode->SetOpacity(0.5); m_FixedNode->SetVisibility(true); m_Controls.m_FixedLabel->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.m_SwitchImages->show(); m_Controls.TextLabelFixed->show(); m_Controls.line2->show(); m_Controls.m_FixedPointListWidget->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->setImageColor(m_ShowRedGreen); bool hasPointSetNode = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_FixedNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::StringProperty::Pointer nameProp = dynamic_cast(children->GetElement(i)->GetProperty("name")); if(nameProp.IsNotNull() && nameProp->GetValueAsString()=="PointBasedRegistrationNode") { m_FixedPointSetNode=children->GetElement(i); m_FixedLandmarks = dynamic_cast (m_FixedPointSetNode->GetData()); this->GetDataStorage()->Remove(m_FixedPointSetNode); hasPointSetNode = true; break; } } if (!hasPointSetNode) { m_FixedLandmarks = mitk::PointSet::New(); m_FixedPointSetNode = mitk::DataNode::New(); m_FixedPointSetNode->SetData(m_FixedLandmarks); m_FixedPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); } m_FixedPointSetNode->GetStringProperty("label", m_OldFixedLabel); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New("F ")); m_FixedPointSetNode->SetProperty("color", mitk::ColorProperty::New(0.0f, 1.0f, 1.0f)); m_FixedPointSetNode->SetVisibility(true); m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); this->GetDataStorage()->Add(m_FixedPointSetNode, m_FixedNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if (m_FixedPointSetNode.IsNull()) { m_FixedLandmarks = mitk::PointSet::New(); m_FixedPointSetNode = mitk::DataNode::New(); m_FixedPointSetNode->SetData(m_FixedLandmarks); m_FixedPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); m_FixedPointSetNode->GetStringProperty("label", m_OldFixedLabel); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New("F ")); m_FixedPointSetNode->SetProperty("color", mitk::ColorProperty::New(0.0f, 1.0f, 1.0f)); m_FixedPointSetNode->SetVisibility(true); m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); this->GetDataStorage()->Add(m_FixedPointSetNode, m_FixedNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_FixedNode = NULL; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_FixedPointSetNode = NULL; m_FixedLandmarks = NULL; m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_SwitchImages->hide(); } if(m_FixedLandmarks.IsNotNull()) m_CurrentFixedLandmarksObserverID = m_FixedLandmarks->AddObserver(itk::ModifiedEvent(), m_FixedLandmarksChangedCommand); } void QmitkPointBasedRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); if (movingImage.IsNotNull()) { if (m_MovingNode != movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->setImageColor(false); if (m_MovingNode != m_FixedNode) { m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); } else { m_OldFixedLabel = m_OldMovingLabel; } } if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_MovingNode = movingImage; m_MovingNode->SetVisibility(true); m_Controls.m_MovingLabel->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); m_Controls.line1->show(); m_Controls.m_MovingPointListWidget->show(); m_Controls.m_OpacityLabel->show(); m_Controls.m_OpacitySlider->show(); m_Controls.label->show(); m_Controls.label_2->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->setImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); bool hasPointSetNode = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::StringProperty::Pointer nameProp = dynamic_cast(children->GetElement(i)->GetProperty("name")); if(nameProp.IsNotNull() && nameProp->GetValueAsString()=="PointBasedRegistrationNode") { m_MovingPointSetNode=children->GetElement(i); m_MovingLandmarks = dynamic_cast (m_MovingPointSetNode->GetData()); this->GetDataStorage()->Remove(m_MovingPointSetNode); hasPointSetNode = true; break; } } if (!hasPointSetNode) { m_MovingLandmarks = mitk::PointSet::New(); m_MovingPointSetNode = mitk::DataNode::New(); m_MovingPointSetNode->SetData(m_MovingLandmarks); m_MovingPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); } this->GetDataStorage()->Add(m_MovingPointSetNode, m_MovingNode); m_MovingPointSetNode->GetStringProperty("label", m_OldMovingLabel); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New("M ")); m_MovingPointSetNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f)); m_MovingPointSetNode->SetVisibility(true); m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->clearTransformationLists(); this->OpacityUpdate(m_Opacity); } if (m_MovingPointSetNode.IsNull()) { m_MovingLandmarks = mitk::PointSet::New(); m_MovingPointSetNode = mitk::DataNode::New(); m_MovingPointSetNode->SetData(m_MovingLandmarks); m_MovingPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); m_MovingPointSetNode->GetStringProperty("label", m_OldMovingLabel); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New("M ")); m_MovingPointSetNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f)); m_MovingPointSetNode->SetVisibility(true); m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); this->GetDataStorage()->Add(m_MovingPointSetNode, m_MovingNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_MovingNode = NULL; if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_MovingPointSetNode = NULL; m_MovingLandmarks = NULL; m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); } if(m_MovingLandmarks.IsNotNull()) m_CurrentMovingLandmarksObserverID = m_MovingLandmarks->AddObserver(itk::ModifiedEvent(), m_MovingLandmarksChangedCommand); } void QmitkPointBasedRegistrationView::updateMovingLandmarksList() { // mitk::PointSet* ps = mitk::PointSet::New(); // ps = dynamic_cast(m_MovingPointSetNode->GetData()); // mitk::DataNode::Pointer tmpPtr = m_MovingPointSetNode; // m_MovingLandmarks = 0; // m_MovingLandmarks = (ps); m_MovingLandmarks = dynamic_cast(m_MovingPointSetNode->GetData()); // m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); //Workaround: m_MovingPointListWidget->m_PointListView->m_PointListModel loses the pointer on the pointsetnode this->checkLandmarkError(); this->CheckCalculate(); } void QmitkPointBasedRegistrationView::updateFixedLandmarksList() { m_FixedLandmarks = dynamic_cast(m_FixedPointSetNode->GetData()); this->checkLandmarkError(); this->CheckCalculate(); } void QmitkPointBasedRegistrationView::HideFixedImage(bool hide) { m_HideFixedImage = hide; if(m_FixedNode.IsNotNull()) { m_FixedNode->SetVisibility(!hide); } if (hide) { //this->reinitMovingClicked(); } if (!m_HideMovingImage && !m_HideFixedImage) { //this->globalReinitClicked(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::HideMovingImage(bool hide) { m_HideMovingImage = hide; if(m_MovingNode.IsNotNull()) { m_MovingNode->SetVisibility(!hide); } if (hide) { //this->reinitFixedClicked(); } if (!m_HideMovingImage && !m_HideFixedImage) { //this->globalReinitClicked(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } bool QmitkPointBasedRegistrationView::CheckCalculate() { if((m_MovingPointSetNode.IsNull())||(m_FixedPointSetNode.IsNull()||m_FixedLandmarks.IsNull()||m_MovingLandmarks.IsNull())) return false; if(m_MovingNode==m_FixedNode) return false; return this->checkCalculateEnabled(); } void QmitkPointBasedRegistrationView::UndoTransformation() { if(!m_UndoPointsGeometryList.empty()) { mitk::AffineGeometryFrame3D::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_RedoPointsGeometryList.push_back(static_cast(movingLandmarksGeometry.GetPointer())); m_MovingLandmarks->SetGeometry(m_UndoPointsGeometryList.back()); m_UndoPointsGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingPointSetNode->SetMapper(1, NULL); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::AffineGeometryFrame3D::Pointer movingGeometry = movingData->GetGeometry(0)->Clone(); m_RedoGeometryList.push_back(static_cast(movingGeometry.GetPointer())); movingData->SetGeometry(m_UndoGeometryList.back()); m_UndoGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeSlicedGeometry()->UpdateInformation(); m_MovingLandmarks->GetTimeSlicedGeometry()->UpdateInformation(); m_Controls.m_RedoTransformation->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } if(!m_UndoPointsGeometryList.empty()) { m_Controls.m_UndoTransformation->setEnabled(true); } else { m_Controls.m_UndoTransformation->setEnabled(false); } } void QmitkPointBasedRegistrationView::RedoTransformation() { if(!m_RedoPointsGeometryList.empty()) { mitk::AffineGeometryFrame3D::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(static_cast(movingLandmarksGeometry.GetPointer())); m_MovingLandmarks->SetGeometry(m_RedoPointsGeometryList.back()); m_RedoPointsGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingPointSetNode->SetMapper(1, NULL); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::AffineGeometryFrame3D::Pointer movingGeometry = movingData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(static_cast(movingGeometry.GetPointer())); movingData->SetGeometry(m_RedoGeometryList.back()); m_RedoGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeSlicedGeometry()->UpdateInformation(); m_MovingLandmarks->GetTimeSlicedGeometry()->UpdateInformation(); m_Controls.m_UndoTransformation->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } if(!m_RedoPointsGeometryList.empty()) { m_Controls.m_RedoTransformation->setEnabled(true); } else { m_Controls.m_RedoTransformation->setEnabled(false); } } void QmitkPointBasedRegistrationView::showRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->setImageColor(m_ShowRedGreen); } void QmitkPointBasedRegistrationView::setImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::OpacityUpdate(float opacity) { if (opacity > 1) { opacity = opacity/100.0f; } m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkPointBasedRegistrationView::clearTransformationLists() { m_Controls.m_UndoTransformation->setEnabled(false); m_Controls.m_RedoTransformation->setEnabled(false); m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); m_UndoGeometryList.clear(); m_UndoPointsGeometryList.clear(); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); } void QmitkPointBasedRegistrationView::checkLandmarkError() { double totalDist = 0, dist = 0, dist2 = 0; mitk::Point3D point1, point2, point3; double p1[3], p2[3]; if(m_Transformation < 3) { if (m_Controls.m_UseICP->isChecked()) { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull()&& m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(0); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; dist = vtkMath::Distance2BetweenPoints(p1, p2); for(int pointId2 = 1; pointId2 < m_FixedLandmarks->GetSize(); ++pointId2) { point2 = m_FixedLandmarks->GetPoint(pointId2); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = p1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = p2[2]; dist2 = vtkMath::Distance2BetweenPoints(p1, p2); if (dist2 < dist) { dist = dist2; } } totalDist += dist; } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } else { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0 && m_MovingLandmarks->GetSize() == m_FixedLandmarks->GetSize()) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(pointId); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; totalDist += vtkMath::Distance2BetweenPoints(p1, p2); } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } } else { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0 && m_MovingLandmarks->GetSize() == m_FixedLandmarks->GetSize()) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(pointId); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; totalDist += vtkMath::Distance2BetweenPoints(p1, p2); } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } } void QmitkPointBasedRegistrationView::transformationChanged(int transform) { m_Transformation = transform; this->checkCalculateEnabled(); this->checkLandmarkError(); } // ICP with vtkLandmarkTransformation void QmitkPointBasedRegistrationView::calculateLandmarkbasedWithICP() { if(CheckCalculate()) { mitk::Geometry3D::Pointer pointsGeometry = m_MovingLandmarks->GetGeometry(0); mitk::AffineGeometryFrame3D::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(static_cast(movingLandmarksGeometry.GetPointer())); mitk::BaseData::Pointer originalData = m_MovingNode->GetData(); mitk::AffineGeometryFrame3D::Pointer originalDataGeometry = originalData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(static_cast(originalDataGeometry.GetPointer())); vtkIdType pointId; vtkPoints* vPointsSource=vtkPoints::New(); vtkCellArray* vCellsSource=vtkCellArray::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D pointSource=m_MovingLandmarks->GetPoint(pointId); vPointsSource->InsertNextPoint(pointSource[0],pointSource[1],pointSource[2]); vCellsSource->InsertNextCell(1, &pointId); } vtkPoints* vPointsTarget=vtkPoints::New(); vtkCellArray* vCellsTarget = vtkCellArray::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D pointTarget=m_FixedLandmarks->GetPoint(pointId); vPointsTarget->InsertNextPoint(pointTarget[0],pointTarget[1],pointTarget[2]); vCellsTarget->InsertNextCell(1, &pointId); } vtkPolyData* vPointSetSource=vtkPolyData::New(); vtkPolyData* vPointSetTarget=vtkPolyData::New(); vPointSetTarget->SetPoints(vPointsTarget); vPointSetTarget->SetVerts(vCellsTarget); vPointSetSource->SetPoints(vPointsSource); vPointSetSource->SetVerts(vCellsSource); vtkIterativeClosestPointTransform * icp=vtkIterativeClosestPointTransform::New(); icp->SetCheckMeanDistance(1); icp->SetSource(vPointSetSource); icp->SetTarget(vPointSetTarget); icp->SetMaximumNumberOfIterations(50); icp->StartByMatchingCentroidsOn(); vtkLandmarkTransform * transform=icp->GetLandmarkTransform(); if(m_Transformation==0) { transform->SetModeToRigidBody(); } if(m_Transformation==1) { transform->SetModeToSimilarity(); } if(m_Transformation==2) { transform->SetModeToAffine(); } vtkMatrix4x4 * matrix=icp->GetMatrix(); double determinant = fabs(matrix->Determinant()); if((determinant < mitk::eps) || (determinant > 100) || (determinant < 0.01) || (determinant==itk::NumericTraits::infinity()) || (determinant==itk::NumericTraits::quiet_NaN()) || (determinant==itk::NumericTraits::signaling_NaN()) || (determinant==-itk::NumericTraits::infinity()) || (determinant==-itk::NumericTraits::quiet_NaN()) || (determinant==-itk::NumericTraits::signaling_NaN()) || (!(determinant <= 0) && !(determinant > 0))) { QMessageBox msgBox; msgBox.setText("Suspicious determinant of matrix calculated by ICP.\n" "Please select more points or other points!" ); msgBox.exec(); return; } pointsGeometry->Compose(matrix); m_MovingLandmarks->GetTimeSlicedGeometry()->UpdateInformation(); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::Geometry3D::Pointer movingGeometry = movingData->GetGeometry(0); movingGeometry->Compose(matrix); movingData->GetTimeSlicedGeometry()->UpdateInformation(); m_Controls.m_UndoTransformation->setEnabled(true); m_Controls.m_RedoTransformation->setEnabled(false); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } } // only vtkLandmarkTransformation void QmitkPointBasedRegistrationView::calculateLandmarkbased() { if(CheckCalculate()) { mitk::Geometry3D::Pointer pointsGeometry = m_MovingLandmarks->GetGeometry(0); mitk::AffineGeometryFrame3D::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(static_cast(movingLandmarksGeometry.GetPointer())); mitk::BaseData::Pointer originalData = m_MovingNode->GetData(); mitk::AffineGeometryFrame3D::Pointer originalDataGeometry = originalData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(static_cast(originalDataGeometry.GetPointer())); vtkIdType pointId; vtkPoints* vPointsSource=vtkPoints::New(); for(pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { mitk::Point3D sourcePoint = m_MovingLandmarks->GetPoint(pointId); vPointsSource->InsertNextPoint(sourcePoint[0],sourcePoint[1],sourcePoint[2]); } vtkPoints* vPointsTarget=vtkPoints::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D targetPoint=m_FixedLandmarks->GetPoint(pointId); vPointsTarget->InsertNextPoint(targetPoint[0],targetPoint[1],targetPoint[2]); } vtkLandmarkTransform * transform= vtkLandmarkTransform::New(); transform->SetSourceLandmarks(vPointsSource); transform->SetTargetLandmarks(vPointsTarget); if(m_Transformation==0) { transform->SetModeToRigidBody(); } if(m_Transformation==1) { transform->SetModeToSimilarity(); } if(m_Transformation==2) { transform->SetModeToAffine(); } vtkMatrix4x4 * matrix=transform->GetMatrix(); double determinant = fabs(matrix->Determinant()); if((determinant < mitk::eps) || (determinant > 100) || (determinant < 0.01) || (determinant==itk::NumericTraits::infinity()) || (determinant==itk::NumericTraits::quiet_NaN()) || (determinant==itk::NumericTraits::signaling_NaN()) || (determinant==-itk::NumericTraits::infinity()) || (determinant==-itk::NumericTraits::quiet_NaN()) || (determinant==-itk::NumericTraits::signaling_NaN()) || (!(determinant <= 0) && !(determinant > 0))) { QMessageBox msgBox; msgBox.setText("Suspicious determinant of matrix calculated.\n" "Please select more points or other points!" ); msgBox.exec(); return; } pointsGeometry->Compose(matrix); m_MovingLandmarks->GetTimeSlicedGeometry()->UpdateInformation(); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::Geometry3D::Pointer movingGeometry = movingData->GetGeometry(0); movingGeometry->Compose(matrix); movingData->GetTimeSlicedGeometry()->UpdateInformation(); m_Controls.m_UndoTransformation->setEnabled(true); m_Controls.m_RedoTransformation->setEnabled(false); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } } void QmitkPointBasedRegistrationView::calculateLandmarkWarping() { mitk::LandmarkWarping* registration = new mitk::LandmarkWarping(); mitk::LandmarkWarping::FixedImageType::Pointer fixedImage = mitk::LandmarkWarping::FixedImageType::New(); mitk::Image::Pointer fimage = dynamic_cast(m_FixedNode->GetData()); mitk::LandmarkWarping::MovingImageType::Pointer movingImage = mitk::LandmarkWarping::MovingImageType::New(); mitk::Image::Pointer mimage = dynamic_cast(m_MovingNode->GetData()); if (fimage.IsNotNull() && /*fimage->GetDimension() == 2 || */ fimage->GetDimension() == 3 && mimage.IsNotNull() && mimage->GetDimension() == 3) { mitk::CastToItkImage(fimage, fixedImage); mitk::CastToItkImage(mimage, movingImage); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImage); unsigned int pointId; mitk::Point3D sourcePoint, targetPoint; mitk::LandmarkWarping::LandmarkContainerType::Pointer fixedLandmarks = mitk::LandmarkWarping::LandmarkContainerType::New(); mitk::LandmarkWarping::LandmarkPointType point; for(pointId = 0; pointId < (unsigned int)m_FixedLandmarks->GetSize(); ++pointId) { fimage->GetGeometry(0)->WorldToItkPhysicalPoint(m_FixedLandmarks->GetPoint(pointId), point); fixedLandmarks->InsertElement( pointId, point); } mitk::LandmarkWarping::LandmarkContainerType::Pointer movingLandmarks = mitk::LandmarkWarping::LandmarkContainerType::New(); for(pointId = 0; pointId < (unsigned int)m_MovingLandmarks->GetSize(); ++pointId) { mitk::BaseData::Pointer fixedData = m_FixedNode->GetData(); mitk::Geometry3D::Pointer fixedGeometry = fixedData->GetGeometry(0); fixedGeometry->WorldToItkPhysicalPoint(m_MovingLandmarks->GetPoint(pointId), point); movingLandmarks->InsertElement( pointId, point); } registration->SetLandmarks(fixedLandmarks.GetPointer(), movingLandmarks.GetPointer()); mitk::LandmarkWarping::MovingImageType::Pointer output = registration->Register(); if (output.IsNotNull()) { mitk::Image::Pointer image = mitk::Image::New(); mitk::CastToMitkImage(output, image); m_MovingNode->SetData(image); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( image ); levWinProp->SetLevelWindow(levelWindow); m_MovingNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); movingLandmarks = registration->GetTransformedTargetLandmarks(); mitk::PointSet::PointDataIterator it; it = m_MovingLandmarks->GetPointSet()->GetPointData()->Begin(); //increase the eventId to encapsulate the coming operations mitk::OperationEvent::IncCurrObjectEventId(); mitk::OperationEvent::ExecuteIncrement(); for(pointId=0; pointIdSize();++pointId, ++it) { int position = it->Index(); mitk::PointSet::PointType pt = m_MovingLandmarks->GetPoint(position); mitk::Point3D undoPoint = ( pt ); point = movingLandmarks->GetElement(pointId); fimage->GetGeometry(0)->ItkPhysicalPointToWorld(point, pt); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVE, pt, position); //undo operation mitk::PointOperation* undoOp = new mitk::PointOperation(mitk::OpMOVE, undoPoint, position); mitk::OperationEvent* operationEvent = new mitk::OperationEvent(m_MovingLandmarks, doOp, undoOp, "Move point"); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent(operationEvent); //execute the Operation m_MovingLandmarks->ExecuteOperation(doOp); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->clearTransformationLists(); this->checkLandmarkError(); } } } bool QmitkPointBasedRegistrationView::checkCalculateEnabled() { if (m_FixedLandmarks.IsNotNull() && m_MovingLandmarks.IsNotNull()) { int fixedPoints = m_FixedLandmarks->GetSize(); int movingPoints = m_MovingLandmarks->GetSize(); if (m_Transformation == 0 || m_Transformation == 1 || m_Transformation == 2) { if (m_Controls.m_UseICP->isChecked()) { if((movingPoints > 0 && fixedPoints > 0)) { m_Controls.m_Calculate->setEnabled(true); return true; } else { m_Controls.m_Calculate->setEnabled(false); return false; } } else { if ((movingPoints == fixedPoints) && movingPoints > 0) { m_Controls.m_Calculate->setEnabled(true); return true; } else { m_Controls.m_Calculate->setEnabled(false); return false; } } } else { m_Controls.m_Calculate->setEnabled(true); return true; } } else { return false; } } void QmitkPointBasedRegistrationView::calculate() { if (m_Transformation == 0 || m_Transformation == 1 || m_Transformation == 2) { if (m_Controls.m_UseICP->isChecked()) { if (m_MovingLandmarks->GetSize() == 1 && m_FixedLandmarks->GetSize() == 1) { this->calculateLandmarkbased(); } else { this->calculateLandmarkbasedWithICP(); } } else { this->calculateLandmarkbased(); } } else { this->calculateLandmarkWarping(); } } void QmitkPointBasedRegistrationView::SetImagesVisible(berry::ISelection::ConstPointer /*selection*/) { if (this->m_CurrentSelection->Size() == 0) { // show all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(true); } } } else { // hide all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(false); } } } } void QmitkPointBasedRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h index 87b33f2ac2..c44cef1bbb 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h @@ -1,305 +1,304 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #if !defined(QMITK_POINTBASEDREGISTRATION_H__INCLUDED) #define QMITK_POINTBASEDREGISTRATION_H__INCLUDED #include "QmitkFunctionality.h" #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" //#include "mitkTestingConfig.h" // IMPORTANT: this defines or undefines BUILD_TESTING ! #include #include #include #include #include #include //#include "QmitkMessageBoxHelper.h" #include "ui_QmitkPointBasedRegistrationViewControls.h" #include /*! \brief The PointBasedRegistration functionality is used to perform point based registration. This functionality allows you to register 2D as well as 3D images in a rigid and deformable manner via corresponding PointSets. Register means to align two images, so that they become as similar as possible. Therefore you have to set corresponding points in both images, which will be matched. The movement, which has to be performed on the points to align them will be performed on the moving image as well. The result is shown in the multi-widget. For more informations see: \ref QmitkPointBasedRegistrationUserManual \sa QmitkFunctionality \ingroup Functionalities \ingroup PointBasedRegistration */ class REGISTRATION_EXPORT QmitkPointBasedRegistrationView : public QmitkFunctionality { friend struct SelListenerPointBasedRegistration; Q_OBJECT public: static const std::string VIEW_ID; /*! \brief Default constructor */ QmitkPointBasedRegistrationView(QObject *parent=0, const char *name=0); QmitkPointBasedRegistrationView(const QmitkPointBasedRegistrationView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } /*! \brief Default destructor */ virtual ~QmitkPointBasedRegistrationView(); /*! \brief method for creating the applications main widget */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief Sets the StdMultiWidget and connects it to the functionality. */ virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); /*! \brief Removes the StdMultiWidget and disconnects it from the functionality. */ virtual void StdMultiWidgetNotAvailable(); /*! \brief Method for creating the connections of main and control widget */ virtual void CreateConnections(); virtual void Activated(); virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); // // #ifdef BUILD_TESTING // / ** // \brief Testing entry point // * / // virtual int TestYourself(); // // / ** // \brief Helper method for testing // * / // bool TestAllTools(); // // // protected slots: // /** // \brief Helper method for testing // */ // void RegistrationErrorDialogFound( QWidget* widget ); // // /** // \brief Helper method for testing // */ // void ClearPointSetDialogFound( QWidget* widget ); // // private: // bool m_MessageBox; // // // public: // #else // // slot function is needed, because moc ignores our #ifdefs // void RegistrationErrorDialogFound( QWidget* widget ) {} // // slot function is needed, because moc ignores our #ifdefs // void ClearPointSetDialogFound(QWidget* widget){} // #endif void DataNodeHasBeenRemoved(const mitk::DataNode* node); protected slots: /*! \brief Sets the fixed Image according to TreeNodeSelector widget */ void FixedSelected(mitk::DataNode::Pointer fixedImage); /*! \brief Sets the moving Image according to TreeNodeSelector widget */ void MovingSelected(mitk::DataNode::Pointer movingImage); /*! \brief Calculates registration with vtkLandmarkTransform */ void calculateLandmarkbased(); /*! \brief Calculates registration with itkLandmarkWarping */ void calculateLandmarkWarping(); /*! \brief Calculates registration with ICP and vtkLandmarkTransform */ void calculateLandmarkbasedWithICP(); /*! \brief lets the fixed image become invisible and the moving image visible */ void HideMovingImage(bool hide); /*! \brief lets the moving image become invisible and the fixed image visible */ void HideFixedImage(bool hide); /*! \brief Checks if registration is possible */ bool CheckCalculate(); /*! \brief Performs an undo for the last transform. */ void UndoTransformation(); /*! \brief Performs a redo for the last undo transform. */ void RedoTransformation(); /*! \brief Stores whether the image will be shown in grayvalues or in red for fixed image and green for moving image @param show if true, then images will be shown in red and green */ void showRedGreen(bool show); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(float opacity); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(int opacity); /*! \brief Updates the moving landmarks */ void updateMovingLandmarksList(); /*! \brief Updates the fixed landmarks */ void updateFixedLandmarksList(); /*! \brief Sets the images to gray values or fixed image to red and moving image to green @param redGreen if true, then images will be shown in red and green */ void setImageColor(bool redGreen); /*! \brief Clears the undo and redo transformation lists. */ void clearTransformationLists(); /*! \brief Calculates the landmark error for the selected transformation. */ void checkLandmarkError(); /*! \brief Changes the transformation type and calls checkLandmarkError(). */ void transformationChanged(int transform); /*! \brief Checks whether the registration can be performed. */ bool checkCalculateEnabled(); /*! \brief Performs the registration. */ void calculate(); void SetImagesVisible(berry::ISelection::ConstPointer /*selection*/); void SwitchImages(); protected: berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * control widget to make all changes for point based registration */ Ui::QmitkPointBasedRegistrationControls m_Controls; mitk::PointSet::Pointer m_FixedLandmarks; mitk::PointSet::Pointer m_MovingLandmarks; mitk::DataNode::Pointer m_MovingPointSetNode; mitk::DataNode::Pointer m_FixedPointSetNode; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_FixedNode; std::list m_UndoGeometryList; std::list m_UndoPointsGeometryList; std::list m_RedoGeometryList; std::list m_RedoPointsGeometryList; bool m_ShowRedGreen; float m_Opacity; float m_OriginalOpacity; mitk::Color m_FixedColor; mitk::Color m_MovingColor; int m_Transformation; bool m_HideFixedImage; bool m_HideMovingImage; std::string m_OldFixedLabel; std::string m_OldMovingLabel; bool m_Deactivated; int m_CurrentFixedLandmarksObserverID; int m_CurrentMovingLandmarksObserverID; itk::SimpleMemberCommand::Pointer m_FixedLandmarksChangedCommand; itk::SimpleMemberCommand::Pointer m_MovingLandmarksChangedCommand; }; #endif // !defined(QMITK_POINTBASEDREGISTRATION_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.cpp index 7143df6850..6df8129462 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.cpp @@ -1,775 +1,774 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: -1 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkImageTimeSelector.h" #include #include #include #include "mitkMatrixConvert.h" #include #include #include "QmitkLoadPresetDialog.h" #include #include "mitkRigidRegistrationPreset.h" #include "mitkProgressBar.h" #include "QmitkRigidRegistrationSelectorView.h" #include "QmitkTranslationTransformView.h" #include "QmitkScaleTransformView.h" #include "QmitkScaleLogarithmicTransformView.h" #include "QmitkAffineTransformView.h" #include "QmitkFixedCenterOfRotationAffineTransformView.h" #include "QmitkRigid3DTransformView.h" #include "QmitkEuler3DTransformView.h" #include "QmitkCenteredEuler3DTransformView.h" #include "QmitkQuaternionRigidTransformView.h" #include "QmitkVersorTransformView.h" #include "QmitkVersorRigid3DTransformView.h" #include "QmitkScaleSkewVersor3DTransformView.h" #include "QmitkSimilarity3DTransformView.h" #include "QmitkRigid2DTransformView.h" #include "QmitkCenteredRigid2DTransformView.h" #include "QmitkEuler2DTransformView.h" #include "QmitkSimilarity2DTransformView.h" #include "QmitkCenteredSimilarity2DTransformView.h" #include "QmitkMeanSquaresMetricView.h" #include "QmitkNormalizedCorrelationMetricView.h" #include "QmitkGradientDifferenceMetricView.h" #include "QmitkKullbackLeiblerCompareHistogramMetricView.h" #include "QmitkCorrelationCoefficientHistogramMetricView.h" #include "QmitkMeanSquaresHistogramMetricView.h" #include "QmitkMutualInformationHistogramMetricView.h" #include "QmitkNormalizedMutualInformationHistogramMetricView.h" #include "QmitkMattesMutualInformationMetricView.h" #include "QmitkMeanReciprocalSquareDifferenceMetricView.h" #include "QmitkMutualInformationMetricView.h" #include "QmitkMatchCardinalityMetricView.h" #include "QmitkKappaStatisticMetricView.h" #include "QmitkExhaustiveOptimizerView.h" #include "QmitkGradientDescentOptimizerView.h" #include "QmitkQuaternionRigidTransformGradientDescentOptimizerView.h" #include "QmitkLBFGSBOptimizerView.h" #include "QmitkOnePlusOneEvolutionaryOptimizerView.h" #include "QmitkPowellOptimizerView.h" #include "QmitkFRPROptimizerView.h" #include "QmitkRegularStepGradientDescentOptimizerView.h" #include "QmitkVersorTransformOptimizerView.h" #include "QmitkAmoebaOptimizerView.h" #include "QmitkConjugateGradientOptimizerView.h" #include "QmitkLBFGSOptimizerView.h" #include "QmitkSPSAOptimizerView.h" #include "QmitkVersorRigid3DTransformOptimizerView.h" QmitkRigidRegistrationSelectorView::QmitkRigidRegistrationSelectorView(QWidget* parent, Qt::WindowFlags f ) : QWidget( parent, f ), m_FixedNode(NULL), m_FixedMaskNode(NULL), m_MovingNode(NULL), m_MovingMaskNode(NULL), m_FixedDimension(0), m_MovingDimension(0), m_StopOptimization(false), m_GeometryItkPhysicalToWorldTransform(NULL), m_GeometryWorldToItkPhysicalTransform(NULL), m_MovingGeometry(NULL), m_ImageGeometry(NULL) { m_Controls.setupUi(parent); this->AddTransform(new QmitkTranslationTransformView(this, f)); this->AddTransform(new QmitkScaleTransformView(this, f)); this->AddTransform(new QmitkScaleLogarithmicTransformView(this, f)); this->AddTransform(new QmitkAffineTransformView(this, f)); this->AddTransform(new QmitkFixedCenterOfRotationAffineTransformView(this, f)); this->AddTransform(new QmitkEuler3DTransformView(this, f)); this->AddTransform(new QmitkCenteredEuler3DTransformView(this, f)); this->AddTransform(new QmitkQuaternionRigidTransformView(this, f)); this->AddTransform(new QmitkVersorTransformView(this, f)); this->AddTransform(new QmitkVersorRigid3DTransformView(this, f)); this->AddTransform(new QmitkScaleSkewVersor3DTransformView(this, f)); this->AddTransform(new QmitkSimilarity3DTransformView(this, f)); this->AddTransform(new QmitkRigid2DTransformView(this, f)); this->AddTransform(new QmitkCenteredRigid2DTransformView(this, f)); this->AddTransform(new QmitkEuler2DTransformView(this, f)); this->AddTransform(new QmitkSimilarity2DTransformView(this, f)); this->AddTransform(new QmitkCenteredSimilarity2DTransformView(this, f)); this->AddMetric(new QmitkMeanSquaresMetricView(this, f)); this->AddMetric(new QmitkNormalizedCorrelationMetricView(this, f)); this->AddMetric(new QmitkGradientDifferenceMetricView(this, f)); this->AddMetric(new QmitkKullbackLeiblerCompareHistogramMetricView(this, f)); this->AddMetric(new QmitkCorrelationCoefficientHistogramMetricView(this, f)); this->AddMetric(new QmitkMeanSquaresHistogramMetricView(this, f)); this->AddMetric(new QmitkMutualInformationHistogramMetricView(this, f)); this->AddMetric(new QmitkNormalizedMutualInformationHistogramMetricView(this, f)); this->AddMetric(new QmitkMattesMutualInformationMetricView(this, f)); this->AddMetric(new QmitkMeanReciprocalSquareDifferenceMetricView(this, f)); this->AddMetric(new QmitkMutualInformationMetricView(this, f)); this->AddMetric(new QmitkMatchCardinalityMetricView(this, f)); this->AddMetric(new QmitkKappaStatisticMetricView(this, f)); this->AddOptimizer(new QmitkExhaustiveOptimizerView(this, f)); this->AddOptimizer(new QmitkGradientDescentOptimizerView(this, f)); this->AddOptimizer(new QmitkQuaternionRigidTransformGradientDescentOptimizerView(this, f)); this->AddOptimizer(new QmitkLBFGSBOptimizerView(this, f)); this->AddOptimizer(new QmitkOnePlusOneEvolutionaryOptimizerView(this, f)); this->AddOptimizer(new QmitkPowellOptimizerView(this, f)); this->AddOptimizer(new QmitkFRPROptimizerView(this, f)); this->AddOptimizer(new QmitkRegularStepGradientDescentOptimizerView(this, f)); this->AddOptimizer(new QmitkVersorTransformOptimizerView(this, f)); this->AddOptimizer(new QmitkAmoebaOptimizerView(this, f)); this->AddOptimizer(new QmitkConjugateGradientOptimizerView(this, f)); this->AddOptimizer(new QmitkLBFGSOptimizerView(this, f)); this->AddOptimizer(new QmitkSPSAOptimizerView(this, f)); this->AddOptimizer(new QmitkVersorRigid3DTransformOptimizerView(this, f)); m_Observer = mitk::RigidRegistrationObserver::New(); m_Controls.m_TransformFrame->setEnabled(true); m_Controls.m_MetricFrame->setEnabled(true); m_Controls.m_OptimizerFrame->setEnabled(true); m_Controls.m_InterpolatorFrame->setEnabled(true); m_Controls.m_TransformFrame->hide(); m_Controls.m_MetricFrame->hide(); m_Controls.m_OptimizerFrame->hide(); m_Controls.m_InterpolatorFrame->hide(); m_Controls.m_TransformBox->setCurrentIndex(0); m_Controls.m_MetricBox->setCurrentIndex(0); m_Controls.m_OptimizerBox->setCurrentIndex(0); m_Controls.m_TransformWidgetStack->setCurrentIndex(0); m_Controls.m_MetricWidgetStack->setCurrentIndex(0); m_Controls.m_OptimizerWidgetStack->setCurrentIndex(0); /// and show the selected views this->TransformSelected(m_Controls.m_TransformBox->currentIndex()); this->MetricSelected(m_Controls.m_MetricBox->currentIndex()); this->OptimizerSelected(m_Controls.m_OptimizerBox->currentIndex()); //// create connections connect( m_Controls.m_TransformGroup, SIGNAL(clicked(bool)), m_Controls.m_TransformFrame, SLOT(setVisible(bool))); connect( m_Controls.m_TransformBox, SIGNAL(activated(int)), m_Controls.m_TransformWidgetStack, SLOT(setCurrentIndex(int))); connect( m_Controls.m_TransformBox, SIGNAL(activated(int)), this, SLOT(TransformSelected(int))); connect( m_Controls.m_MetricBox, SIGNAL(activated(int)), this, SLOT(MetricSelected(int))); connect( m_Controls.m_OptimizerBox, SIGNAL(activated(int)), this, SLOT(OptimizerSelected(int))); connect( m_Controls.m_MetricGroup, SIGNAL(clicked(bool)), m_Controls.m_MetricFrame, SLOT(setVisible(bool))); connect( m_Controls.m_MetricBox, SIGNAL(activated(int)), m_Controls.m_MetricWidgetStack, SLOT(setCurrentIndex(int))); connect( m_Controls.m_OptimizerGroup, SIGNAL(clicked(bool)), m_Controls.m_OptimizerFrame, SLOT(setVisible(bool))); connect( m_Controls.m_OptimizerBox, SIGNAL(activated(int)), m_Controls.m_OptimizerWidgetStack, SLOT(setCurrentIndex(int))); connect( m_Controls.m_InterpolatorGroup, SIGNAL(toggled(bool)), m_Controls.m_InterpolatorFrame, SLOT(setVisible(bool))); m_Preset = new mitk::RigidRegistrationPreset(); m_Preset->LoadPreset(); this->DoLoadRigidRegistrationPreset("AffineMutualInformationGradientDescent"); } QmitkRigidRegistrationSelectorView::~QmitkRigidRegistrationSelectorView() { } /// this method starts the registration process void QmitkRigidRegistrationSelectorView::CalculateTransformation(unsigned int timestep) { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { emit AddNewTransformationToUndoList(); mitk::Image::Pointer fimage = dynamic_cast(m_FixedNode->GetData()); mitk::Image::Pointer mimage = dynamic_cast(m_MovingNode->GetData()); mitk::Image::Pointer mmimage = NULL; mitk::Image::Pointer fmimage = NULL; if (m_MovingMaskNode.IsNotNull()) { mmimage = dynamic_cast(m_MovingMaskNode->GetData()); } if (m_FixedMaskNode.IsNotNull()) { fmimage = dynamic_cast(m_FixedMaskNode->GetData()); } mitk::ImageTimeSelector::Pointer its = mitk::ImageTimeSelector::New(); if(fimage->GetDimension()>3) { its->SetInput(fimage); its->SetTimeNr(timestep); its->Update(); fimage = its->GetOutput(); } if(mimage->GetDimension()>3) { its->SetInput(mimage); its->SetTimeNr(timestep); its->Update(); mimage = its->GetOutput(); } // Initial moving image geometry m_ImageGeometry = m_MovingNode->GetData()->GetGeometry()->Clone(); std::cout << "Moving Image Geometry (IndexToWorldTransform)" << std::endl; std::cout << m_ImageGeometry->GetIndexToWorldTransform()->GetMatrix(); mitk::Geometry3D::TransformType::InputPointType center = m_ImageGeometry->GetIndexToWorldTransform()->GetCenter(); std::cout << "center " << center[0] << " " << center[1] << " " << center[2] << std::endl; mitk::Geometry3D::TransformType::OutputVectorType offset = m_ImageGeometry->GetIndexToWorldTransform()->GetOffset(); std::cout << "offset " << offset[0] << " " << offset[1] << " " << offset[2] << std::endl; std::cout << std::endl; // Fixed image geometry // mitk::AffineGeometryFrame3D::Pointer m_FixedGeometryCopy = m_FixedNode->GetData()->GetGeometry()->Clone(); // std::cout << "Fixed Image Geometry (IndexToWorldTransform)" << std::endl; // std::cout << m_FixedGeometryCopy->GetIndexToWorldTransform()->GetMatrix(); // center = m_FixedGeometryCopy->GetIndexToWorldTransform()->GetCenter(); // std::cout << "center " << center[0] << " " << center[1] << " " << center[2] << std::endl; // offset = m_FixedGeometryCopy->GetIndexToWorldTransform()->GetOffset(); // std::cout << "offset " << offset[0] << " " << offset[1] << " " << offset[2] << std::endl; // std::cout << std::endl; // Calculate the World to ITK-Physical transform for the moving image m_MovingGeometry = m_MovingNode->GetData()->GetGeometry(); unsigned long size; size = m_MovingNodeChildren->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { m_ChildNodes.insert(std::pair(m_MovingNodeChildren->GetElement(i), m_MovingNodeChildren->GetElement(i)->GetData()->GetGeometry())); m_ChildNodes2.insert(std::pair(m_MovingNodeChildren->GetElement(i), m_MovingNodeChildren->GetElement(i)->GetData()->GetGeometry()->Clone())); } m_GeometryWorldToItkPhysicalTransform = mitk::Geometry3D::TransformType::New(); GetWorldToItkPhysicalTransform(m_MovingGeometry, m_GeometryWorldToItkPhysicalTransform.GetPointer()); // std::cout << "Moving Image: World to ITK-physical transform" << std::endl; // std::cout << m_GeometryWorldToItkPhysicalTransform->GetMatrix(); // center = m_GeometryWorldToItkPhysicalTransform->GetCenter(); // std::cout << "center " << center[0] << " " << center[1] << " " << center[2] << std::endl; // offset = m_GeometryWorldToItkPhysicalTransform->GetOffset(); // std::cout << "offset " << offset[0] << " " << offset[1] << " " << offset[2] << std::endl; // std::cout << std::endl; // Calculate the ITK-Physical to World transform for the fixed image m_GeometryItkPhysicalToWorldTransform = mitk::Geometry3D::TransformType::New(); mitk::Geometry3D::TransformType::Pointer fixedWorld2Phys = mitk::Geometry3D::TransformType::New(); GetWorldToItkPhysicalTransform(m_FixedNode->GetData()->GetGeometry(), fixedWorld2Phys.GetPointer()); fixedWorld2Phys->GetInverse(m_GeometryItkPhysicalToWorldTransform); // std::cout << "Fixed Image: ITK-physical to World transform" << std::endl; // std::cout << m_GeometryItkPhysicalToWorldTransform->GetMatrix(); // center = m_GeometryItkPhysicalToWorldTransform->GetCenter(); // std::cout << "center " << center[0] << " " << center[1] << " " << center[2] << std::endl; // offset = m_GeometryItkPhysicalToWorldTransform->GetOffset(); // std::cout << "offset " << offset[0] << " " << offset[1] << " " << offset[2] << std::endl; // std::cout << std::endl; // init callback itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkRigidRegistrationSelectorView::SetOptimizerValue); int observer = m_Observer->AddObserver( itk::AnyEvent(), command ); std::vector presets; // init registration method mitk::ImageRegistrationMethod::Pointer registration = mitk::ImageRegistrationMethod::New(); registration->SetObserver(m_Observer); registration->SetInterpolator(m_Controls.m_InterpolatorBox->currentIndex()); registration->SetReferenceImage(fimage); registration->SetInput(mimage); if (mmimage.IsNotNull()) { registration->SetMovingMask(mmimage); } if (fmimage.IsNotNull()) { registration->SetFixedMask(fmimage); } dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->SetFixedImage(dynamic_cast(m_FixedNode->GetData())); dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->SetMovingImage(dynamic_cast(m_MovingNode->GetData())); registration->SetOptimizerScales(dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->GetScales()); registration->SetTransform(dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->GetTransform()); dynamic_cast(m_Controls.m_MetricWidgetStack->currentWidget())->SetMovingImage(dynamic_cast(m_MovingNode->GetData())); registration->SetMetric(dynamic_cast(m_Controls.m_MetricWidgetStack->currentWidget())->GetMetric()); registration->SetOptimizer(dynamic_cast(m_Controls.m_OptimizerWidgetStack->currentWidget())->GetOptimizer()); double time(0.0); double tstart(0.0); tstart = clock(); try { registration->Update(); } catch (itk::ExceptionObject e) { MITK_INFO << "Caught exception: "<Progress(20); } time += clock() - tstart; time = time / CLOCKS_PER_SEC; //printOut of the Time MITK_INFO << "Registration Time: " << time; m_Observer->RemoveObserver(observer); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationSelectorView::SetFixedNode( mitk::DataNode * fixedNode ) { m_FixedNode = fixedNode; m_Controls.m_TransformBox->setCurrentIndex(m_Controls.m_TransformBox->currentIndex()); } void QmitkRigidRegistrationSelectorView::SetFixedDimension( int dimension ) { m_FixedDimension = dimension; } void QmitkRigidRegistrationSelectorView::SetMovingNode( mitk::DataNode * movingNode ) { m_MovingNode = movingNode; this->TransformSelected(m_Controls.m_TransformBox->currentIndex()); } void QmitkRigidRegistrationSelectorView::SetMovingDimension(int dimension ) { m_MovingDimension = dimension; } // this is a callback function that retrieves the current transformation // parameters after every step of progress in the optimizer. // depending on the choosen transformation, we construct a vtktransform // that will be applied to the geometry of the moving image. // the values are delivered by mitkRigidRgistrationObserver.cpp void QmitkRigidRegistrationSelectorView::SetOptimizerValue( const itk::EventObject & ) { if (m_StopOptimization) { m_Observer->SetStopOptimization(true); m_StopOptimization = false; } // retreive optimizer value for the current transformation double value = m_Observer->GetCurrentOptimizerValue(); // retreive current parameterset of the transformation itk::Array transformParams = m_Observer->GetCurrentTranslation(); // init an empty affine transformation that will be filled with // the corresponding transformation parameters in the following vtkMatrix4x4* vtkmatrix = vtkMatrix4x4::New(); vtkmatrix->Identity(); // init a transform that will be initialized with the vtkmatrix later vtkTransform* vtktransform = vtkTransform::New(); if (m_MovingNode.IsNotNull()) { vtktransform = dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->Transform(vtkmatrix, vtktransform, transformParams); // the retrieved transform goes from fixed to moving space. // invert the transform in order to go from moving to fixed space. vtkMatrix4x4* vtkmatrix_inv = vtkMatrix4x4::New(); vtktransform->GetInverse(vtkmatrix_inv); // now adapt the moving geometry accordingly m_MovingGeometry->GetIndexToWorldTransform()->SetIdentity(); // the next view lines: Phi(Phys2World)*Phi(Result)*Phi(World2Phy)*Phi(Initial) // set moving image geometry to registration result m_MovingGeometry->SetIndexToWorldTransformByVtkMatrix(vtkmatrix_inv); /*std::cout << std::endl; std::cout << m_MovingGeometry->GetIndexToWorldTransform()->GetMatrix(); mitk::Geometry3D::TransformType::OutputVectorType offset = m_MovingGeometry->GetIndexToWorldTransform()->GetOffset(); std::cout << "offset " << offset[0] << " " << offset[1] << " " << offset[2] << std::endl;*/ #if !defined(ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE) // the next few lines: Phi(Phys2World)*Phi(Result)*Phi(World2Phy)*Phi(Initial) // go to itk physical space before applying the registration result m_MovingGeometry->Compose(m_GeometryWorldToItkPhysicalTransform, 1); // right in the beginning, transform by initial moving image geometry m_MovingGeometry->Compose(m_ImageGeometry->GetIndexToWorldTransform(), 1); // in the end, go back to world space m_MovingGeometry->Compose(m_GeometryItkPhysicalToWorldTransform, 0); #else m_MovingGeometry->Compose(m_ImageGeometry->GetIndexToWorldTransform(), 1); #endif /*std::cout << std::endl << m_MovingGeometry->GetIndexToWorldTransform()->GetMatrix(); offset = m_MovingGeometry->GetIndexToWorldTransform()->GetOffset(); std::cout << "offset " << offset[0] << " " << offset[1] << " " << offset[2] << std::endl << std::endl;*/ // now adapt all children geometries accordingly if children exist std::map::iterator iter; std::map::iterator iter2; mitk::DataNode::Pointer childNode; for( iter = m_ChildNodes.begin(); iter != m_ChildNodes.end(); iter++ ) { childNode = (*iter).first; if (childNode.IsNotNull()) { mitk::Geometry3D* childGeometry; mitk::AffineGeometryFrame3D::Pointer childImageGeometry; // Calculate the World to ITK-Physical transform for the moving mask childGeometry = (*iter).second; iter2 = m_ChildNodes2.find(childNode); childImageGeometry = (*iter2).second; childGeometry->GetIndexToWorldTransform()->SetIdentity(); // the next view lines: Phi(Phys2World)*Phi(Result)*Phi(World2Phy)*Phi(Initial) // set moving mask geometry to registration result childGeometry->SetIndexToWorldTransformByVtkMatrix(vtkmatrix_inv); #if !defined(ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE) // the next few lines: Phi(Phys2World)*Phi(Result)*Phi(World2Phy)*Phi(Initial) // go to itk physical space before applying the registration result childGeometry->Compose(m_GeometryWorldToItkPhysicalTransform, 1); // right in the beginning, transform by initial moving image geometry childGeometry->Compose(childImageGeometry->GetIndexToWorldTransform(), 1); // in the end, go back to world space childGeometry->Compose(m_GeometryItkPhysicalToWorldTransform, 0); #else childGeometry->Compose(childImageGeometry->GetIndexToWorldTransform(), 1); #endif } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } emit OptimizerChanged(value); } /// this method is called whenever the combobox with the selectable transforms changes /// responsible for showing the selected transform parameters void QmitkRigidRegistrationSelectorView::TransformSelected( int transform ) { if (m_FixedNode.IsNotNull()) { dynamic_cast(m_Controls.m_TransformWidgetStack->widget(transform))->SetFixedImage(dynamic_cast(m_FixedNode->GetData())); } if (m_MovingNode.IsNotNull()) { dynamic_cast(m_Controls.m_TransformWidgetStack->widget(transform))->SetMovingImage(dynamic_cast(m_MovingNode->GetData())); } int numberOfTransformParameters = dynamic_cast(m_Controls.m_TransformWidgetStack->widget(transform))->GetNumberOfTransformParameters(); dynamic_cast(m_Controls.m_OptimizerWidgetStack->currentWidget())->SetNumberOfTransformParameters(numberOfTransformParameters); //set fixed height m_Controls.m_TransformWidgetStack->setFixedHeight( dynamic_cast(m_Controls.m_TransformWidgetStack->widget(transform))->minimumSizeHint().height() ); this->OptimizerSelected(m_Controls.m_OptimizerWidgetStack->currentIndex()); } /// this method is called whenever the combobox with the selectable metrics changes /// responsible for showing the selected metric parameters void QmitkRigidRegistrationSelectorView::MetricSelected( int metric ) { if (m_FixedNode.IsNotNull()) { dynamic_cast(m_Controls.m_MetricWidgetStack->widget(metric))->SetMovingImage(dynamic_cast(m_MovingNode->GetData())); } //set fixed height m_Controls.m_MetricWidgetStack->setFixedHeight( dynamic_cast(m_Controls.m_MetricWidgetStack->widget(metric))->minimumSizeHint().height() ); } /// this method is called whenever the combobox with the selectable optimizers changes /// responsible for showing the selected optimizer parameters void QmitkRigidRegistrationSelectorView::OptimizerSelected( int optimizer ) { int numberOfTransformParameters = dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->GetNumberOfTransformParameters(); dynamic_cast(m_Controls.m_OptimizerWidgetStack->widget(optimizer))->SetNumberOfTransformParameters(numberOfTransformParameters); //set fixed height m_Controls.m_OptimizerWidgetStack->setFixedHeight( dynamic_cast(m_Controls.m_OptimizerWidgetStack->widget(optimizer))->minimumSizeHint().height() ); } void QmitkRigidRegistrationSelectorView::LoadRigidRegistrationParameter() { this->DoLoadRigidRegistrationParameter(); } void QmitkRigidRegistrationSelectorView::DoLoadRigidRegistrationParameter() { std::map > existingPresets; existingPresets = m_Preset->getTransformValuesPresets(); std::map >::iterator iter; std::list presets; for( iter = existingPresets.begin(); iter != existingPresets.end(); iter++ ) { presets.push_back( (*iter).first ); } if (presets.empty()) { QMessageBox::warning( NULL, "RigidRegistrationParameters.xml", "RigidRegistrationParameters.xml is empty/does not exist. There are no presets to select."); return; } presets.sort(); // ask about the name to load a preset QmitkLoadPresetDialog dialog( this, 0, "Load Preset", presets ); // needs a QWidget as parent int dialogReturnValue = dialog.exec(); if ( dialogReturnValue == QDialog::Rejected ) return; // user clicked cancel or pressed Esc or something similar this->DoLoadRigidRegistrationPreset(dialog.GetPresetName()); } void QmitkRigidRegistrationSelectorView::DoLoadRigidRegistrationPreset(std::string presetName) { itk::Array transformValues; transformValues = m_Preset->getTransformValues(presetName); m_Controls.m_TransformGroup->setChecked(true); m_Controls.m_TransformFrame->setVisible(true); m_Controls.m_TransformBox->setCurrentIndex((int)transformValues[0]); m_Controls.m_TransformWidgetStack->setCurrentIndex((int)transformValues[0]); this->TransformSelected((int)transformValues[0]); itk::Array transformValuesForGUI; transformValuesForGUI.SetSize(transformValues.Size()); transformValuesForGUI.fill(0); for (unsigned int i = 1; i < transformValues.Size(); i++) { transformValuesForGUI[i-1] = transformValues[i]; } dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->SetTransformParameters(transformValuesForGUI); itk::Array metricValues; metricValues = m_Preset->getMetricValues(presetName); m_Controls.m_MetricGroup->setChecked(true); m_Controls.m_MetricFrame->setVisible(true); m_Controls.m_MetricBox->setCurrentIndex((int)metricValues[0]); m_Controls.m_MetricWidgetStack->setCurrentIndex((int)metricValues[0]); this->MetricSelected((int)metricValues[0]); itk::Array metricValuesForGUI; metricValuesForGUI.SetSize(metricValues.Size()); metricValuesForGUI.fill(0); for (unsigned int i = 1; i < metricValues.Size(); i++) { metricValuesForGUI[i-1] = metricValues[i]; } dynamic_cast(m_Controls.m_MetricWidgetStack->currentWidget())->SetMetricParameters(metricValuesForGUI); itk::Array optimizerValues; optimizerValues = m_Preset->getOptimizerValues(presetName); m_Controls.m_OptimizerGroup->setChecked(true); m_Controls.m_OptimizerFrame->setVisible(true); m_Controls.m_OptimizerBox->setCurrentIndex((int)optimizerValues[0]); m_Controls.m_OptimizerWidgetStack->setCurrentIndex((int)optimizerValues[0]); this->OptimizerSelected((int)optimizerValues[0]); itk::Array optimizerValuesForGUI; optimizerValuesForGUI.SetSize(optimizerValues.Size()); optimizerValuesForGUI.fill(0); for (unsigned int i = 1; i < optimizerValues.Size(); i++) { optimizerValuesForGUI[i-1] = optimizerValues[i]; } dynamic_cast(m_Controls.m_OptimizerWidgetStack->currentWidget())->SetOptimizerParameters(optimizerValuesForGUI); itk::Array interpolatorValues; interpolatorValues = m_Preset->getInterpolatorValues(presetName); m_Controls.m_InterpolatorGroup->setChecked(true); m_Controls.m_InterpolatorFrame->setVisible(true); m_Controls.m_InterpolatorBox->setCurrentIndex((int)interpolatorValues[0]); } void QmitkRigidRegistrationSelectorView::SaveRigidRegistrationParameter() { this->DoSaveRigidRegistrationParameter(); } void QmitkRigidRegistrationSelectorView::DoSaveRigidRegistrationParameter() { bool ok; QString text = QInputDialog::getText(this, "Save Parameter Preset", "Enter name for preset:", QLineEdit::Normal, QString::null, &ok ); if ( ok ) { std::map > existingPresets; existingPresets = m_Preset->getTransformValuesPresets(); std::map >::iterator iter = existingPresets.find(std::string((const char*)text.toLatin1())); if (iter != existingPresets.end()) { QMessageBox::critical( this, "Preset definition", "Presetname already exists."); return; } if (text.isEmpty()) { QMessageBox::critical( this, "Preset definition", "Presetname has to be set.\n" "You have to enter a Presetname." ); return; } itk::Array transformValues; transformValues.SetSize(25); transformValues.fill(0); transformValues[0] = m_Controls.m_TransformBox->currentIndex(); itk::Array transformValuesFromGUI = dynamic_cast(m_Controls.m_TransformWidgetStack->currentWidget())->GetTransformParameters(); for (unsigned int i = 0; i < transformValuesFromGUI.Size(); i++) { transformValues[i+1] = transformValuesFromGUI[i]; } std::map > transformMap; transformMap = m_Preset->getTransformValuesPresets(); transformMap[std::string((const char*)text.toLatin1())] = transformValues; itk::Array metricValues; metricValues.SetSize(25); metricValues.fill(0); metricValues[0] = m_Controls.m_MetricBox->currentIndex(); itk::Array metricValuesFromGUI = dynamic_cast(m_Controls.m_MetricWidgetStack->currentWidget())->GetMetricParameters(); for (unsigned int i = 0; i < metricValuesFromGUI.Size(); i++) { metricValues[i+1] = metricValuesFromGUI[i]; } std::map > metricMap; metricMap = m_Preset->getMetricValuesPresets(); metricMap[std::string((const char*)text.toLatin1())] = metricValues; itk::Array optimizerValues; optimizerValues.SetSize(25); optimizerValues.fill(0); optimizerValues[0] = m_Controls.m_OptimizerBox->currentIndex(); itk::Array optimizerValuesFromGUI = dynamic_cast(m_Controls.m_OptimizerWidgetStack->currentWidget())->GetOptimizerParameters(); for (unsigned int i = 0; i < optimizerValuesFromGUI.Size(); i++) { optimizerValues[i+1] = optimizerValuesFromGUI[i]; } std::map > optimizerMap; optimizerMap = m_Preset->getOptimizerValuesPresets(); optimizerMap[std::string((const char*)text.toLatin1())] = optimizerValues; itk::Array interpolatorValues; interpolatorValues.SetSize(25); interpolatorValues.fill(0); interpolatorValues[0] = m_Controls.m_InterpolatorBox->currentIndex(); std::map > interpolatorMap; interpolatorMap = m_Preset->getInterpolatorValuesPresets(); interpolatorMap[std::string((const char*)text.toLatin1())] = interpolatorValues; m_Preset->newPresets(transformMap, metricMap, optimizerMap, interpolatorMap); } else { // user pressed Cancel } } void QmitkRigidRegistrationSelectorView::StopOptimization(bool stopOptimization) { m_StopOptimization = stopOptimization; } int QmitkRigidRegistrationSelectorView::GetSelectedTransform() { return m_Controls.m_TransformBox->currentIndex(); } void QmitkRigidRegistrationSelectorView::SetFixedMaskNode( mitk::DataNode * fixedMaskNode ) { m_FixedMaskNode = fixedMaskNode; this->TransformSelected(m_Controls.m_TransformBox->currentIndex()); } void QmitkRigidRegistrationSelectorView::SetMovingMaskNode( mitk::DataNode * movingMaskNode ) { m_MovingMaskNode = movingMaskNode; this->TransformSelected(m_Controls.m_TransformBox->currentIndex()); } void QmitkRigidRegistrationSelectorView::SetMovingNodeChildren(mitk::DataStorage::SetOfObjects::ConstPointer children) { m_MovingNodeChildren = children; } void QmitkRigidRegistrationSelectorView::AddTransform(QmitkRigidRegistrationTransformsGUIBase* transform) { m_Controls.m_TransformBox->addItem(transform->GetName()); int i = 0; if (!dynamic_cast(m_Controls.m_TransformWidgetStack->widget(i))) { m_Controls.m_TransformWidgetStack->addWidget(transform); m_Controls.m_TransformWidgetStack->removeWidget(m_Controls.m_TransformWidgetStack->widget(i)); transform->SetupUI(m_Controls.m_TransformWidgetStack->widget(i)); } else { i = m_Controls.m_TransformWidgetStack->addWidget(transform); transform->SetupUI(m_Controls.m_TransformWidgetStack->widget(i)); } } void QmitkRigidRegistrationSelectorView::AddMetric(QmitkRigidRegistrationMetricsGUIBase* metric) { m_Controls.m_MetricBox->addItem(metric->GetName()); int i = 0; if (!dynamic_cast(m_Controls.m_MetricWidgetStack->widget(i))) { m_Controls.m_MetricWidgetStack->addWidget(metric); m_Controls.m_MetricWidgetStack->removeWidget(m_Controls.m_MetricWidgetStack->widget(i)); metric->SetupUI(m_Controls.m_MetricWidgetStack->widget(i)); } else { i = m_Controls.m_MetricWidgetStack->addWidget(metric); metric->SetupUI(m_Controls.m_MetricWidgetStack->widget(i)); } } void QmitkRigidRegistrationSelectorView::AddOptimizer(QmitkRigidRegistrationOptimizerGUIBase* optimizer) { m_Controls.m_OptimizerBox->addItem(optimizer->GetName()); int i = 0; if (!dynamic_cast(m_Controls.m_OptimizerWidgetStack->widget(i))) { m_Controls.m_OptimizerWidgetStack->addWidget(optimizer); m_Controls.m_OptimizerWidgetStack->removeWidget(m_Controls.m_OptimizerWidgetStack->widget(i)); optimizer->SetupUI(m_Controls.m_OptimizerWidgetStack->widget(i)); } else { i = m_Controls.m_OptimizerWidgetStack->addWidget(optimizer); optimizer->SetupUI(m_Controls.m_OptimizerWidgetStack->widget(i)); } } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.h index 894f910e57..0d0656ba4c 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationSelectorView.h @@ -1,111 +1,110 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 1.12 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkRigidRegistrationSelectorViewWidgetHIncluded #define QmitkRigidRegistrationSelectorViewWidgetHIncluded #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "ui_QmitkRigidRegistrationSelector.h" #include "qobject.h" #include #include "QmitkRigidRegistrationTransformsGUIBase.h" #include "QmitkRigidRegistrationMetricsGUIBase.h" #include "QmitkRigidRegistrationOptimizerGUIBase.h" /*! * \brief Widget for rigid registration * * Displays options for rigid registration. */ class REGISTRATION_EXPORT QmitkRigidRegistrationSelectorView : public QWidget { Q_OBJECT public: QmitkRigidRegistrationSelectorView( QWidget* parent = 0, Qt::WindowFlags f = 0 ); ~QmitkRigidRegistrationSelectorView(); signals: void TransformChanged(); void OptimizerChanged(double value); void AddNewTransformationToUndoList(); public slots: void SetFixedNode( mitk::DataNode * fixedNode ); void SetFixedMaskNode(mitk::DataNode * fixedMaskNode ); void SetFixedDimension( int dimension ); void SetMovingNode( mitk::DataNode * movingNode ); void SetMovingNodeChildren(mitk::DataStorage::SetOfObjects::ConstPointer children); void SetMovingMaskNode(mitk::DataNode * movingMaskNode ); void SetMovingDimension(int dimension ); int GetSelectedTransform(); void CalculateTransformation(unsigned int timestep = 0); void StopOptimization(bool stopOptimization); protected slots: // this is a callback function that retrieves the current transformation // parameters after every step of progress in the optimizer. // depending on the choosen transformation, we construct a vtktransform // that will be applied to the geometry of the moving image. // the values are delivered by mitkRigidRgistrationObserver.cpp void SetOptimizerValue( const itk::EventObject & ); /// this method is called whenever the combobox with the selectable transforms changes /// responsible for showing the selected transformparameters void TransformSelected( int transform ); /// this method is called whenever the combobox with the selectable metrics changes /// responsible for showing the selected metricparameters void MetricSelected( int metric ); /// this method is called whenever the combobox with the selectable optimizer changes /// responsible for showing the selected optimizerparameters void OptimizerSelected( int optimizer ); void LoadRigidRegistrationParameter(); void SaveRigidRegistrationParameter(); //void LoadRigidRegistrationTestParameter(); //void SaveRigidRegistrationTestParameter(); void DoLoadRigidRegistrationParameter(); void DoLoadRigidRegistrationPreset(std::string presetName); void DoSaveRigidRegistrationParameter(); void AddTransform(QmitkRigidRegistrationTransformsGUIBase* transform); void AddMetric(QmitkRigidRegistrationMetricsGUIBase* metric); void AddOptimizer(QmitkRigidRegistrationOptimizerGUIBase* optimizer); protected: Ui::QmitkRigidRegistrationSelector m_Controls; mitk::DataNode::Pointer m_FixedNode; mitk::DataNode::Pointer m_FixedMaskNode; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_MovingMaskNode; int m_FixedDimension; int m_MovingDimension; bool m_StopOptimization; mitk::RigidRegistrationPreset* m_Preset; mitk::Geometry3D::TransformType::Pointer m_GeometryItkPhysicalToWorldTransform; mitk::Geometry3D::TransformType::Pointer m_GeometryWorldToItkPhysicalTransform; mitk::Geometry3D* m_MovingGeometry; mitk::AffineGeometryFrame3D::Pointer m_ImageGeometry; mitk::RigidRegistrationObserver::Pointer m_Observer; mitk::DataStorage::SetOfObjects::ConstPointer m_MovingNodeChildren; std::map m_ChildNodes; std::map m_ChildNodes2; }; #endif diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp index d0935a52ce..fcc768b10f 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp @@ -1,1276 +1,1275 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkRigidRegistrationView.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "qinputdialog.h" #include "qmessagebox.h" #include "qcursor.h" #include "qapplication.h" #include "qradiobutton.h" #include "qslider.h" #include "qtooltip.h" #include #include "mitkDataNodeObject.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkRigidRegistrationView::VIEW_ID = "org.mitk.views.rigidregistration"; using namespace berry; struct SelListenerRigidRegistration : ISelectionListener { berryObjectMacro(SelListenerRigidRegistration); SelListenerRigidRegistration(QmitkRigidRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // if (!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.m_OpacityLabel->setEnabled(false); m_View->m_Controls.m_OpacitySlider->setEnabled(false); m_View->m_Controls.label->setEnabled(false); m_View->m_Controls.label_2->setEnabled(false); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); m_View->m_Controls.m_SwitchImages->hide(); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { if (dynamic_cast(node->GetData())->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "RigidRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.m_OpacityLabel->setEnabled(true); m_View->m_Controls.m_OpacitySlider->setEnabled(true); m_View->m_Controls.label->setEnabled(true); m_View->m_Controls.label_2->setEnabled(true); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkRigidRegistrationView* m_View; }; QmitkRigidRegistrationView::QmitkRigidRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality(), m_MultiWidget(NULL), m_MovingNode(NULL), m_MovingMaskNode(NULL), m_FixedNode(NULL), m_FixedMaskNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Deactivated(false),m_FixedDimension(0), m_MovingDimension(0) { m_TranslateSliderPos[0] = 0; m_TranslateSliderPos[1] = 0; m_TranslateSliderPos[2] = 0; m_RotateSliderPos[0] = 0; m_RotateSliderPos[1] = 0; m_RotateSliderPos[2] = 0; m_ScaleSliderPos[0] = 0; m_ScaleSliderPos[1] = 0; m_ScaleSliderPos[2] = 0; translationParams = new int[3]; rotationParams = new int[3]; scalingParams = new int[3]; m_TimeStepperAdapter = NULL; this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkRigidRegistrationView::DataNodeHasBeenRemoved )); } QmitkRigidRegistrationView::~QmitkRigidRegistrationView() { if(m_SelListener.IsNotNull()) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; } } void QmitkRigidRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Controls.m_ManualFrame->hide(); m_Controls.timeSlider->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_UseFixedImageMask->hide(); m_Controls.m_UseMovingImageMask->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_SwitchImages->hide(); if (m_Controls.m_RigidTransform->currentIndex() == 1) { m_Controls.frame->show(); } else { m_Controls.frame->hide(); } m_Controls.m_ManualFrame->setEnabled(false); m_Parent->setEnabled(false); this->CreateConnections(); this->CheckCalculateEnabled(); } void QmitkRigidRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); } void QmitkRigidRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; } void QmitkRigidRegistrationView::CreateConnections() { connect( m_Controls.m_ManualRegistrationCheckbox, SIGNAL(toggled(bool)), this, SLOT(ShowManualRegistrationFrame(bool))); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect(m_Controls.m_ShowRedGreenValues, SIGNAL(toggled(bool)), this, SLOT(ShowRedGreen(bool))); connect(m_Controls.m_UseFixedImageMask, SIGNAL(toggled(bool)), this, SLOT(UseFixedMaskImageChecked(bool))); connect(m_Controls.m_UseMovingImageMask, SIGNAL(toggled(bool)), this, SLOT(UseMovingMaskImageChecked(bool))); connect(m_Controls.m_RigidTransform, SIGNAL(currentChanged(int)), this, SLOT(TabChanged(int))); connect(m_Controls.m_OpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityUpdate(int))); connect(m_Controls.m_CalculateTransformation, SIGNAL(clicked()), this, SLOT(Calculate())); connect(m_Controls.m_UndoTransformation,SIGNAL(clicked()),this,SLOT(UndoTransformation())); connect(m_Controls.m_RedoTransformation,SIGNAL(clicked()),this,SLOT(RedoTransformation())); connect(m_Controls.m_AutomaticTranslation,SIGNAL(clicked()),this,SLOT(AlignCenters())); connect(m_Controls.m_StopOptimization,SIGNAL(clicked()), this , SLOT(StopOptimizationClicked())); connect(m_Controls.m_XTransSlider, SIGNAL(valueChanged(int)), this, SLOT(xTrans_valueChanged(int))); connect(m_Controls.m_YTransSlider, SIGNAL(valueChanged(int)), this, SLOT(yTrans_valueChanged(int))); connect(m_Controls.m_ZTransSlider, SIGNAL(valueChanged(int)), this, SLOT(zTrans_valueChanged(int))); connect(m_Controls.m_XRotSlider, SIGNAL(valueChanged(int)), this, SLOT(xRot_valueChanged(int))); connect(m_Controls.m_YRotSlider, SIGNAL(valueChanged(int)), this, SLOT(yRot_valueChanged(int))); connect(m_Controls.m_ZRotSlider, SIGNAL(valueChanged(int)), this, SLOT(zRot_valueChanged(int))); connect(m_Controls.m_XScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(xScale_valueChanged(int))); connect(m_Controls.m_YScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(yScale_valueChanged(int))); connect(m_Controls.m_ZScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(zScale_valueChanged(int))); connect(m_Controls.m_LoadRigidRegistrationParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(LoadRigidRegistrationParameter())); connect(m_Controls.m_SaveRigidRegistrationParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(SaveRigidRegistrationParameter())); connect(m_Controls.m_LoadRigidRegistrationTestParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(LoadRigidRegistrationTestParameter())); connect(m_Controls.m_SaveRigidRegistrationTestParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(SaveRigidRegistrationTestParameter())); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(OptimizerChanged(double)),this,SLOT(SetOptimizerValue( double ))); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(TransformChanged()),this,SLOT(CheckCalculateEnabled())); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(AddNewTransformationToUndoList()),this,SLOT(AddNewTransformationToUndoList())); } void QmitkRigidRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled(); /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/ *"org.mitk.views.datamanager",* / m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled();*/ } void QmitkRigidRegistrationView::Visible() { /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener("org.mitk.views.datamanager", m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled();*/ } void QmitkRigidRegistrationView::Deactivated() { m_Deactivated = true; this->SetImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; /* m_Deactivated = true; this->SetImageColor(false); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Deactivated();*/ } void QmitkRigidRegistrationView::Hidden() { /*m_Deactivated = true; this->SetImageColor(false); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated();*/ } void QmitkRigidRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_SwitchImages->hide(); } } void QmitkRigidRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if (m_FixedNode.IsNotNull()) { this->SetImageColor(false); m_FixedNode->SetOpacity(1.0); } m_FixedNode = fixedImage; if (m_FixedNode.IsNotNull()) { m_FixedNode->SetOpacity(0.5); m_FixedNode->SetVisibility(true); m_Controls.TextLabelFixed->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.TextLabelFixed->show(); m_Controls.m_SwitchImages->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if (dynamic_cast(m_FixedNode->GetData())) { m_FixedDimension = dynamic_cast(m_FixedNode->GetData())->GetDimension(); m_Controls.qmitkRigidRegistrationSelector1->SetFixedDimension(m_FixedDimension); m_Controls.qmitkRigidRegistrationSelector1->SetFixedNode(m_FixedNode); } bool hasMask = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_FixedNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::BoolProperty::Pointer isMaskProp = dynamic_cast(children->GetElement(i)->GetProperty("binary")); if(isMaskProp.IsNotNull() && isMaskProp->GetValue() == true) { m_FixedMaskNode = children->GetElement(i); hasMask = true; this->CheckForMaskImages(); break; } } if (!hasMask) { this->CheckForMaskImages(); m_FixedMaskNode = NULL; } } else { m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); } this->CheckCalculateEnabled(); if(this->GetActiveStdMultiWidget()) { m_TimeStepperAdapter = new QmitkStepperAdapter((QObject*) m_Controls.timeSlider, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromRigidRegistration"); connect( m_TimeStepperAdapter, SIGNAL( Refetch() ), this, SLOT( UpdateTimestep() ) ); } } void QmitkRigidRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->SetImageColor(false); } m_MovingNode = movingImage; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetVisibility(true); m_Controls.TextLabelMoving->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); bool hasMask = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNodeChildren(children); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::BoolProperty::Pointer isMaskProp = dynamic_cast(children->GetElement(i)->GetProperty("binary")); if(isMaskProp.IsNotNull() && isMaskProp->GetValue() == true) { m_MovingMaskNode = children->GetElement(i); hasMask = true; this->CheckForMaskImages(); break; } } if (!hasMask) { m_MovingMaskNode = NULL; this->CheckForMaskImages(); } } else { m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->MovingImageChanged(); this->CheckCalculateEnabled(); } bool QmitkRigidRegistrationView::CheckCalculate() { if(m_MovingNode==m_FixedNode) return false; return true; } void QmitkRigidRegistrationView::AddNewTransformationToUndoList() { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_UndoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size = children->Size(); std::map childGeometries; for (unsigned long i = 0; i < size; ++i) { childGeometries.insert(std::pair(children->GetElement(i), children->GetElement(i)->GetData()->GetGeometry())); } m_UndoChildGeometryList.push_back(childGeometries); m_RedoGeometryList.clear(); m_RedoChildGeometryList.clear(); this->SetUndoEnabled(true); this->SetRedoEnabled(false); } void QmitkRigidRegistrationView::UndoTransformation() { if(!m_UndoGeometryList.empty()) { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_RedoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size = children->Size(); std::map childGeometries; for (unsigned long i = 0; i < size; ++i) { childGeometries.insert(std::pair(children->GetElement(i), children->GetElement(i)->GetData()->GetGeometry())); } m_RedoChildGeometryList.push_back(childGeometries); movingData->SetGeometry(m_UndoGeometryList.back()); m_UndoGeometryList.pop_back(); std::map oldChildGeometries; oldChildGeometries = m_UndoChildGeometryList.back(); m_UndoChildGeometryList.pop_back(); std::map::iterator iter; for (unsigned long j = 0; j < size; ++j) { iter = oldChildGeometries.find(children->GetElement(j)); children->GetElement(j)->GetData()->SetGeometry((*iter).second); } //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeSlicedGeometry()->UpdateInformation(); this->SetRedoEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if(!m_UndoGeometryList.empty()) { this->SetUndoEnabled(true); } else { this->SetUndoEnabled(false); } this->CheckCalculateEnabled(); } void QmitkRigidRegistrationView::RedoTransformation() { if(!m_RedoGeometryList.empty()) { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_UndoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size = children->Size(); std::map childGeometries; for (unsigned long i = 0; i < size; ++i) { childGeometries.insert(std::pair(children->GetElement(i), children->GetElement(i)->GetData()->GetGeometry())); } m_UndoChildGeometryList.push_back(childGeometries); movingData->SetGeometry(m_RedoGeometryList.back()); m_RedoGeometryList.pop_back(); std::map oldChildGeometries; oldChildGeometries = m_RedoChildGeometryList.back(); m_RedoChildGeometryList.pop_back(); std::map::iterator iter; for (unsigned long j = 0; j < size; ++j) { iter = oldChildGeometries.find(children->GetElement(j)); children->GetElement(j)->GetData()->SetGeometry((*iter).second); } //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeSlicedGeometry()->UpdateInformation(); this->SetUndoEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if(!m_RedoGeometryList.empty()) { this->SetRedoEnabled(true); } else { this->SetRedoEnabled(false); } } void QmitkRigidRegistrationView::ShowRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->SetImageColor(m_ShowRedGreen); } void QmitkRigidRegistrationView::SetImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::OpacityUpdate(float opacity) { m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkRigidRegistrationView::ClearTransformationLists() { this->SetUndoEnabled(false); this->SetRedoEnabled(false); m_UndoGeometryList.clear(); m_UndoChildGeometryList.clear(); m_RedoGeometryList.clear(); m_RedoChildGeometryList.clear(); } void QmitkRigidRegistrationView::Translate(int* translateVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D translateVec; translateVec[0] = translateVector[0] - m_TranslateSliderPos[0]; translateVec[1] = translateVector[1] - m_TranslateSliderPos[1]; translateVec[2] = translateVector[2] - m_TranslateSliderPos[2]; m_TranslateSliderPos[0] = translateVector[0]; m_TranslateSliderPos[1] = translateVector[1]; m_TranslateSliderPos[2] = translateVector[2]; vtkMatrix4x4* translationMatrix = vtkMatrix4x4::New(); translationMatrix->Identity(); double (*transMatrix)[4] = translationMatrix->Element; transMatrix[0][3] = -translateVec[0]; transMatrix[1][3] = -translateVec[1]; transMatrix[2][3] = -translateVec[2]; translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); m_MovingNode->GetData()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::Rotate(int* rotateVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D rotateVec; rotateVec[0] = rotateVector[0] - m_RotateSliderPos[0]; rotateVec[1] = rotateVector[1] - m_RotateSliderPos[1]; rotateVec[2] = rotateVector[2] - m_RotateSliderPos[2]; m_RotateSliderPos[0] = rotateVector[0]; m_RotateSliderPos[1] = rotateVector[1]; m_RotateSliderPos[2] = rotateVector[2]; vtkMatrix4x4* rotationMatrix = vtkMatrix4x4::New(); vtkMatrix4x4* translationMatrix = vtkMatrix4x4::New(); rotationMatrix->Identity(); translationMatrix->Identity(); double (*rotMatrix)[4] = rotationMatrix->Element; double (*transMatrix)[4] = translationMatrix->Element; mitk::Point3D centerBB = m_MovingNode->GetData()->GetGeometry()->GetCenter(); transMatrix[0][3] = centerBB[0]; transMatrix[1][3] = centerBB[1]; transMatrix[2][3] = centerBB[2]; translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } double radianX = rotateVec[0] * vnl_math::pi / 180; double radianY = rotateVec[1] * vnl_math::pi / 180; double radianZ = rotateVec[2] * vnl_math::pi / 180; if ( rotateVec[0] != 0 ) { rotMatrix[1][1] = cos( radianX ); rotMatrix[1][2] = -sin( radianX ); rotMatrix[2][1] = sin( radianX ); rotMatrix[2][2] = cos( radianX ); } else if ( rotateVec[1] != 0 ) { rotMatrix[0][0] = cos( radianY ); rotMatrix[0][2] = sin( radianY ); rotMatrix[2][0] = -sin( radianY ); rotMatrix[2][2] = cos( radianY ); } else if ( rotateVec[2] != 0 ) { rotMatrix[0][0] = cos( radianZ ); rotMatrix[0][1] = -sin( radianZ ); rotMatrix[1][0] = sin( radianZ ); rotMatrix[1][1] = cos( radianZ ); } m_MovingNode->GetData()->GetGeometry()->Compose( rotationMatrix ); for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( rotationMatrix ); childNode->GetData()->Modified(); } translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( rotationMatrix ); childNode->GetData()->Modified(); } m_MovingNode->GetData()->Modified(); m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::Scale(int* scaleVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D scaleVec; scaleVec[0] = scaleVector[0] - m_ScaleSliderPos[0]; scaleVec[1] = scaleVector[1] - m_ScaleSliderPos[1]; scaleVec[2] = scaleVector[2] - m_ScaleSliderPos[2]; m_ScaleSliderPos[0] = scaleVector[0]; m_ScaleSliderPos[1] = scaleVector[1]; m_ScaleSliderPos[2] = scaleVector[2]; vtkMatrix4x4* scalingMatrix = vtkMatrix4x4::New(); scalingMatrix->Identity(); double (*scaleMatrix)[4] = scalingMatrix->Element; if (scaleVec[0] >= 0) { for(int i = 0; i= 0) { for(int i = 0; i= 0) { for(int i = 0; iInvert(); m_MovingNode->GetData()->GetGeometry()->Compose( scalingMatrix ); m_MovingNode->GetData()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( scalingMatrix ); childNode->GetData()->Modified(); } m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::AlignCenters() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { mitk::Point3D fixedPoint = m_FixedNode->GetData()->GetGeometry()->GetCenter(); mitk::Point3D movingPoint = m_MovingNode->GetData()->GetGeometry()->GetCenter(); mitk::Vector3D translateVec; translateVec = fixedPoint - movingPoint; m_Controls.m_XTransSlider->setValue((int)m_Controls.m_XTransSlider->value() + (int)translateVec[0]); m_Controls.m_YTransSlider->setValue((int)m_Controls.m_YTransSlider->value() + (int)translateVec[1]); m_Controls.m_ZTransSlider->setValue((int)m_Controls.m_ZTransSlider->value() + (int)translateVec[2]); } } void QmitkRigidRegistrationView::SetUndoEnabled( bool enable ) { m_Controls.m_UndoTransformation->setEnabled(enable); } void QmitkRigidRegistrationView::SetRedoEnabled( bool enable ) { m_Controls.m_RedoTransformation->setEnabled(enable); } void QmitkRigidRegistrationView::CheckCalculateEnabled() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { m_Controls.m_ManualFrame->setEnabled(true); m_Controls.m_CalculateTransformation->setEnabled(true); if ( (m_FixedDimension != m_MovingDimension && std::max(m_FixedDimension, m_MovingDimension) != 4) || m_FixedDimension < 2 /*|| m_FixedDimension > 3*/) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if (m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() < 5 && (m_FixedDimension < 2) /*|| m_FixedDimension > 3)*/) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if ((m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() > 4 && m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() < 13) && !(m_FixedDimension > 2)) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if (m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() > 12 && m_FixedDimension != 2) { m_Controls.m_CalculateTransformation->setEnabled(false); } } else { m_Controls.m_CalculateTransformation->setEnabled(false); m_Controls.m_ManualFrame->setEnabled(false); } } void QmitkRigidRegistrationView::xTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=v; translationParams[1]=m_Controls.m_YTransSlider->value(); translationParams[2]=m_Controls.m_ZTransSlider->value(); Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=m_Controls.m_XTransSlider->value(); translationParams[1]=v; translationParams[2]=m_Controls.m_ZTransSlider->value(); Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=m_Controls.m_XTransSlider->value(); translationParams[1]=m_Controls.m_YTransSlider->value(); translationParams[2]=v; Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::xRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=v; rotationParams[1]=m_Controls.m_YRotSlider->value(); rotationParams[2]=m_Controls.m_ZRotSlider->value(); Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=m_Controls.m_XRotSlider->value(); rotationParams[1]=v; rotationParams[2]=m_Controls.m_ZRotSlider->value(); Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=m_Controls.m_XRotSlider->value(); rotationParams[1]=m_Controls.m_YRotSlider->value(); rotationParams[2]=v; Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::xScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=v; scalingParams[1]=m_Controls.m_YScaleSlider->value(); scalingParams[2]=m_Controls.m_ZScaleSlider->value(); Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=m_Controls.m_XScaleSlider->value(); scalingParams[1]=v; scalingParams[2]=m_Controls.m_ZScaleSlider->value(); Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=m_Controls.m_XScaleSlider->value(); scalingParams[1]=m_Controls.m_YScaleSlider->value(); scalingParams[2]=v; Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::MovingImageChanged() { if (dynamic_cast(m_MovingNode->GetData())) { m_Controls.m_XTransSlider->setValue(0); m_Controls.m_YTransSlider->setValue(0); m_Controls.m_ZTransSlider->setValue(0); translationParams[0]=0; translationParams[1]=0; translationParams[2]=0; m_Controls.m_XRotSlider->setValue(0); m_Controls.m_YRotSlider->setValue(0); m_Controls.m_ZRotSlider->setValue(0); rotationParams[0]=0; rotationParams[1]=0; rotationParams[2]=0; m_Controls.m_XScaleSlider->setValue(0); m_Controls.m_YScaleSlider->setValue(0); m_Controls.m_ZScaleSlider->setValue(0); scalingParams[0]=0; scalingParams[1]=0; scalingParams[2]=0; m_MovingDimension = dynamic_cast(m_MovingNode->GetData())->GetDimension(); m_Controls.qmitkRigidRegistrationSelector1->SetMovingDimension(m_MovingDimension); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNode(m_MovingNode); this->CheckCalculateEnabled(); } } void QmitkRigidRegistrationView::Calculate() { m_Controls.qmitkRigidRegistrationSelector1->SetFixedNode(m_FixedNode); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNode(m_MovingNode); if (m_FixedMaskNode.IsNotNull() && m_Controls.m_UseFixedImageMask->isChecked()) { m_Controls.qmitkRigidRegistrationSelector1->SetFixedMaskNode(m_FixedMaskNode); } else { m_Controls.qmitkRigidRegistrationSelector1->SetFixedMaskNode(NULL); } if (m_MovingMaskNode.IsNotNull() && m_Controls.m_UseMovingImageMask->isChecked()) { m_Controls.qmitkRigidRegistrationSelector1->SetMovingMaskNode(m_MovingMaskNode); } else { m_Controls.qmitkRigidRegistrationSelector1->SetMovingMaskNode(NULL); } m_Controls.frame_2->setEnabled(false); m_Controls.frame_3->setEnabled(false); m_Controls.m_CalculateTransformation->setEnabled(false); m_Controls.m_StopOptimization->setEnabled(true); m_Controls.qmitkRigidRegistrationSelector1->CalculateTransformation(((QmitkSliderNavigatorWidget*)m_Controls.timeSlider)->GetPos()); m_Controls.m_StopOptimization->setEnabled(false); m_Controls.frame_2->setEnabled(true); m_Controls.frame_3->setEnabled(true); m_Controls.m_CalculateTransformation->setEnabled(true); m_Controls.qmitkRigidRegistrationSelector1->StopOptimization(false); } void QmitkRigidRegistrationView::SetOptimizerValue( double value ) { m_Controls.m_OptimizerValueLCD->display(value); } void QmitkRigidRegistrationView::StopOptimizationClicked() { m_Controls.qmitkRigidRegistrationSelector1->StopOptimization(true); } void QmitkRigidRegistrationView::UpdateTimestep() { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::ShowManualRegistrationFrame(bool show) { if (show) { m_Controls.m_ManualFrame->show(); } else { m_Controls.m_ManualFrame->hide(); } } void QmitkRigidRegistrationView::SetImagesVisible(berry::ISelection::ConstPointer /*selection*/) { if (this->m_CurrentSelection->Size() == 0) { // show all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(true); } } } else { // hide all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(false); } } } } void QmitkRigidRegistrationView::CheckForMaskImages() { if (m_FixedMaskNode.IsNotNull()) { m_Controls.m_UseFixedImageMask->show(); } else { m_Controls.m_UseFixedImageMask->hide(); } if (m_MovingMaskNode.IsNotNull()) { m_Controls.m_UseMovingImageMask->show(); } else { m_Controls.m_UseMovingImageMask->hide(); } } void QmitkRigidRegistrationView::UseFixedMaskImageChecked(bool checked) { if (checked) { m_FixedMaskNode->SetVisibility(true); } else { m_FixedMaskNode->SetVisibility(false); } } void QmitkRigidRegistrationView::UseMovingMaskImageChecked(bool checked) { if (checked) { m_MovingMaskNode->SetVisibility(true); } else { m_MovingMaskNode->SetVisibility(false); } } void QmitkRigidRegistrationView::TabChanged(int index) { if (index == 0) { m_Controls.frame->hide(); } else { m_Controls.frame->show(); } } void QmitkRigidRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h index e635acc2b1..55d8f48ef5 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h @@ -1,298 +1,297 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKRIGIDREGISTRATION_H #define QMITKRIGIDREGISTRATION_H #include "QmitkFunctionality.h" #include "ui_QmitkRigidRegistrationViewControls.h" #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include // Time Slider related #include /*! \brief This functionality allows you to register 2D as well as 3D images in a rigid manner. Register means to align two images, so that they become as similar as possible. Therefore you can select from different transforms, metrics and optimizers. Registration results will directly be applied to the Moving Image. \sa QmitkFunctionality \ingroup Functionalities \ingroup RigidRegistration \author Daniel Stein */ class REGISTRATION_EXPORT QmitkRigidRegistrationView : public QmitkFunctionality { friend struct SelListenerRigidRegistration; Q_OBJECT public: static const std::string VIEW_ID; /*! \brief default constructor */ QmitkRigidRegistrationView(QObject *parent=0, const char *name=0); QmitkRigidRegistrationView(const QmitkRigidRegistrationView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } /*! \brief default destructor */ virtual ~QmitkRigidRegistrationView(); /*! \brief method for creating the applications main widget */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief Sets the StdMultiWidget and connects it to the functionality. */ virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); /*! \brief Removes the StdMultiWidget and disconnects it from the functionality. */ virtual void StdMultiWidgetNotAvailable(); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief Method which is called when this functionality is selected in MITK */ virtual void Activated(); /*! \brief Method which is called whenever the functionality is deselected in MITK */ virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); void DataNodeHasBeenRemoved(const mitk::DataNode* node); signals: protected slots: /*! * sets the fixed Image according to TreeNodeSelector widget */ void FixedSelected(mitk::DataNode::Pointer fixedImage); /*! * sets the moving Image according to TreeNodeSelector widget */ void MovingSelected(mitk::DataNode::Pointer movingImage); /*! * checks if registration is possible */ bool CheckCalculate(); /*! * \brief Undo the last registration. */ void UndoTransformation(); /*! * \brief Redo the last registration */ void RedoTransformation(); /*! * \brief Adds a new Transformation to the undo list and enables the undo button. */ void AddNewTransformationToUndoList(); /*! * \brief Translates the moving image in x, y and z direction given by translateVector * * @param translateVector Contains the translation in x, y and z direction. */ void Translate(int* translateVector); /*! * \brief Rotates the moving image in x, y and z direction given by rotateVector * * @param rotateVector Contains the rotation around x, y and z axis. */ void Rotate(int* rotateVector); /*! * \brief Scales the moving image in x, y and z direction given by scaleVector * * @param scaleVector Contains the scaling around x, y and z axis. */ void Scale(int* scaleVector); /*! * \brief Automatically aligns the image centers. */ void AlignCenters(); /*! * \brief Stores whether the image will be shown in gray values or in red for fixed image and green for moving image * @param show if true, then images will be shown in red and green */ void ShowRedGreen(bool show); /*! * \brief Changes the visibility of the manual registration methods accordingly to the checkbox "Manual Registration" in GUI * @param show if true, then manual registration methods will be shown */ void ShowManualRegistrationFrame(bool show); /*! * \brief Sets the selected opacity for moving image * @param opacity the selected opacity */ void OpacityUpdate(float opacity); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(int opacity); /*! * \brief Sets the images to grayvalues or fixed image to red and moving image to green * @param redGreen if true, then images will be shown in red and green */ void SetImageColor(bool redGreen); /*! * \brief Clears the undo and redo lists and sets the undo and redo buttons to disabled. */ void ClearTransformationLists(); void SetUndoEnabled( bool enable ); void SetRedoEnabled( bool enable ); void CheckCalculateEnabled(); void xTrans_valueChanged( int v ); void yTrans_valueChanged( int v ); void zTrans_valueChanged( int v ); void xRot_valueChanged( int v ); void yRot_valueChanged( int v ); void zRot_valueChanged( int v ); void xScale_valueChanged( int v ); void yScale_valueChanged( int v ); void zScale_valueChanged( int v ); void MovingImageChanged(); /*! * \brief Starts the registration process. */ void Calculate(); void SetOptimizerValue( double value ); void StopOptimizationClicked(); void UpdateTimestep(); void SetImagesVisible(berry::ISelection::ConstPointer /*selection*/); void CheckForMaskImages(); void UseFixedMaskImageChecked(bool checked); void UseMovingMaskImageChecked(bool checked); void TabChanged(int index); void SwitchImages(); protected: berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * control widget to make all changes for Deformable registration */ Ui::QmitkRigidRegistrationViewControls m_Controls; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_MovingMaskNode; mitk::DataNode::Pointer m_FixedNode; mitk::DataNode::Pointer m_FixedMaskNode; std::list m_UndoGeometryList; std::list > m_UndoChildGeometryList; std::list m_RedoGeometryList; std::list > m_RedoChildGeometryList; bool m_ShowRedGreen; float m_Opacity; float m_OriginalOpacity; bool m_Deactivated; int m_FixedDimension; int m_MovingDimension; int * translationParams; int * rotationParams; int * scalingParams; mitk::Color m_FixedColor; mitk::Color m_MovingColor; int m_TranslateSliderPos[3]; int m_RotateSliderPos[3]; int m_ScaleSliderPos[3]; QmitkStepperAdapter* m_TimeStepperAdapter; }; #endif //QMITKRigidREGISTRATION_H diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.cpp index 38838a6e7c..da8ec7c606 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.cpp @@ -1,125 +1,124 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkLandmarkWarping.h" mitk::LandmarkWarping::LandmarkWarping() { m_Deformer = DeformationSourceType::New(); m_LandmarkDeformer = DeformationSourceType::New(); } mitk::LandmarkWarping::~LandmarkWarping() { } void mitk::LandmarkWarping::SetFixedImage(FixedImageType::Pointer fixedImage) { m_FixedImage = fixedImage; m_Deformer->SetOutputSpacing( m_FixedImage->GetSpacing() ); m_Deformer->SetOutputOrigin( m_FixedImage->GetOrigin() ); m_Deformer->SetOutputRegion( m_FixedImage->GetLargestPossibleRegion() ); } void mitk::LandmarkWarping::SetMovingImage(MovingImageType::Pointer movingImage) { m_MovingImage = movingImage; m_LandmarkDeformer->SetOutputSpacing( m_MovingImage->GetSpacing() ); m_LandmarkDeformer->SetOutputOrigin( m_MovingImage->GetOrigin() ); m_LandmarkDeformer->SetOutputRegion( m_MovingImage->GetLargestPossibleRegion() ); } void mitk::LandmarkWarping::SetLandmarks(LandmarkContainerType::Pointer source, LandmarkContainerType::Pointer target) { m_SourceLandmarks = source; m_TargetLandmarks = target; m_Deformer->SetSourceLandmarks( source ); m_Deformer->SetTargetLandmarks( target ); m_LandmarkDeformer->SetSourceLandmarks( target ); m_LandmarkDeformer->SetTargetLandmarks( source ); } mitk::LandmarkWarping::MovingImageType::Pointer mitk::LandmarkWarping::Register() { try { m_Observer = Observer::New(); unsigned long obs = m_Deformer->AddObserver(itk::ProgressEvent(), m_Observer); mitk::ProgressBar::GetInstance()->AddStepsToDo(120); m_Deformer->UpdateLargestPossibleRegion(); m_Deformer->RemoveObserver(obs); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << std::endl; std::cerr << excp << std::endl; return NULL; } try { unsigned long obs2 = m_LandmarkDeformer->AddObserver(itk::ProgressEvent(), m_Observer); m_LandmarkDeformer->UpdateLargestPossibleRegion(); m_LandmarkDeformer->RemoveObserver(obs2); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << std::endl; std::cerr << excp << std::endl; return NULL; } m_DeformationField = m_Deformer->GetOutput(); m_InverseDeformationField = m_LandmarkDeformer->GetOutput(); m_Warper = FilterType::New(); typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); m_Warper->SetInterpolator( interpolator ); m_Warper->SetOutputSpacing( m_DeformationField->GetSpacing() ); m_Warper->SetOutputOrigin( m_DeformationField->GetOrigin() ); m_Warper->SetDeformationField( m_DeformationField ); m_Warper->SetInput( m_MovingImage ); unsigned long obs3 = m_Warper->AddObserver(itk::ProgressEvent(), m_Observer); m_Warper->UpdateLargestPossibleRegion(); m_Warper->RemoveObserver(obs3); return m_Warper->GetOutput(); } mitk::LandmarkWarping::LandmarkContainerType::Pointer mitk::LandmarkWarping::GetTransformedTargetLandmarks() { LandmarkContainerType::Pointer landmarks = LandmarkContainerType::New(); LandmarkWarping::LandmarkPointType transformedTargetPoint; for(unsigned int pointId=0; pointIdSize();++pointId) { LandmarkWarping::LandmarkPointType targetPoint=m_TargetLandmarks->GetElement(pointId); transformedTargetPoint = m_LandmarkDeformer->GetKernelTransform()->TransformPoint(targetPoint); landmarks->InsertElement(pointId, transformedTargetPoint ); } return landmarks; } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.h b/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.h index 16659eb8eb..1cfdd78bd9 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/mitkLandmarkWarping.h @@ -1,115 +1,114 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKLANDMARKWARPING_H #define MITKLANDMARKWARPING_H #include "itkDeformationFieldSource.h" #include "itkWarpImageFilter.h" #include "itkCommand.h" #include "mitkProgressBar.h" namespace mitk { class LandmarkWarping { public: LandmarkWarping(); ~LandmarkWarping(); static const unsigned int Dimension = 3; typedef float VectorComponentType; typedef itk::Vector< VectorComponentType, Dimension > VectorType; typedef itk::Image< VectorType, Dimension > DeformationFieldType; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::DeformationFieldSource< DeformationFieldType > DeformationSourceType; typedef DeformationSourceType::LandmarkContainerPointer LandmarkContainerPointer; typedef DeformationSourceType::LandmarkContainer LandmarkContainerType; typedef DeformationSourceType::LandmarkPointType LandmarkPointType; typedef itk::WarpImageFilter< MovingImageType, MovingImageType, DeformationFieldType > FilterType; FixedImageType::Pointer m_FixedImage; MovingImageType::Pointer m_MovingImage; DeformationSourceType::Pointer m_Deformer; DeformationSourceType::Pointer m_LandmarkDeformer; LandmarkWarping::LandmarkContainerType::Pointer m_TargetLandmarks; LandmarkWarping::LandmarkContainerType::Pointer m_SourceLandmarks; FilterType::Pointer m_Warper; DeformationFieldType::ConstPointer m_DeformationField; DeformationFieldType::ConstPointer m_InverseDeformationField; void SetFixedImage(FixedImageType::Pointer fi); void SetMovingImage(MovingImageType::Pointer mi); void SetLandmarks(LandmarkContainerType::Pointer source, LandmarkContainerType::Pointer target); MovingImageType::Pointer Register(); LandmarkContainerType::Pointer GetTransformedTargetLandmarks(); protected: // observerclass to react on changes on pointsetnodes class Observer : public itk::Command { public: typedef Observer Self; typedef itk::Command Superclass; typedef itk::SmartPointer Pointer; itkNewMacro( Self ); protected: Observer() { m_Counter = 0; }; unsigned int m_Counter; public: void Execute(itk::Object *object, const itk::EventObject & event) { Execute( (const itk::Object*) object, event ); } void Execute(const itk::Object * object, const itk::EventObject & /*event*/) { const itk::ProcessObject * internalFilter = dynamic_cast( object ); if (!(internalFilter->GetProgress() == 0 || internalFilter->GetProgress() == 1)) { ++m_Counter; mitk::ProgressBar::GetInstance()->Progress(); } if (internalFilter->GetProgress() == 1 && m_Counter > 20 && m_Counter < 120) { mitk::ProgressBar::GetInstance()->Progress(120 - m_Counter); m_Counter = 120; } } }; Observer::Pointer m_Observer; }; } #endif // MITKLANDMARKWARPING_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp index 4207b84100..671a268ebd 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp @@ -1,182 +1,181 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkSegmentationPreferencePage.h" #include #include #include #include #include #include #include #include #include #include QmitkSegmentationPreferencePage::QmitkSegmentationPreferencePage() : m_MainControl(0) , m_Initializing(false) { } QmitkSegmentationPreferencePage::~QmitkSegmentationPreferencePage() { } void QmitkSegmentationPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkSegmentationPreferencePage::CreateQtControl(QWidget* parent) { m_Initializing = true; berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); m_SegmentationPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); m_MainControl = new QWidget(parent); QVBoxLayout* displayOptionsLayout = new QVBoxLayout; m_RadioOutline = new QRadioButton( "Draw as outline", m_MainControl); displayOptionsLayout->addWidget( m_RadioOutline ); m_RadioOverlay = new QRadioButton( "Draw as transparent overlay", m_MainControl); displayOptionsLayout->addWidget( m_RadioOverlay ); QFormLayout *formLayout = new QFormLayout; formLayout->setHorizontalSpacing(8); formLayout->setVerticalSpacing(24); formLayout->addRow( "2D display", displayOptionsLayout ); m_VolumeRenderingCheckBox = new QCheckBox( "Show as volume rendering", m_MainControl ); formLayout->addRow( "3D display", m_VolumeRenderingCheckBox ); connect( m_VolumeRenderingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnVolumeRenderingCheckboxChecked(int)) ); QFormLayout* surfaceLayout = new QFormLayout; surfaceLayout->setSpacing(8); m_SmoothingCheckBox = new QCheckBox("Use image spacing as smoothing value hint", m_MainControl); surfaceLayout->addRow(m_SmoothingCheckBox); connect(m_SmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnSmoothingCheckboxChecked(int))); m_SmoothingSpinBox = new QDoubleSpinBox(m_MainControl); m_SmoothingSpinBox->setMinimum(0.0); m_SmoothingSpinBox->setSingleStep(0.5); m_SmoothingSpinBox->setValue(1.0); m_SmoothingSpinBox->setToolTip("The Smoothing value is used as variance for a gaussian blur."); surfaceLayout->addRow("Smoothing value (mm)", m_SmoothingSpinBox); m_DecimationSpinBox = new QDoubleSpinBox(m_MainControl); m_DecimationSpinBox->setMinimum(0.0); m_DecimationSpinBox->setMaximum(0.99); m_DecimationSpinBox->setSingleStep(0.1); m_DecimationSpinBox->setValue(0.5); m_DecimationSpinBox->setToolTip("Valid range is [0, 1). High values increase decimation, especially when very close to 1. A value of 0 disables decimation."); surfaceLayout->addRow("Decimation rate", m_DecimationSpinBox); m_ClosingSpinBox = new QDoubleSpinBox(m_MainControl); m_ClosingSpinBox->setMinimum(0.0); m_ClosingSpinBox->setMaximum(1.0); m_ClosingSpinBox->setSingleStep(0.1); m_ClosingSpinBox->setValue(0.0); m_ClosingSpinBox->setToolTip("Valid range is [0, 1]. Higher values increase closing. A value of 0 disables closing."); surfaceLayout->addRow("Closing Ratio", m_ClosingSpinBox); formLayout->addRow("Smoothed surface creation", surfaceLayout); m_MainControl->setLayout(formLayout); this->Update(); m_Initializing = false; } QWidget* QmitkSegmentationPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkSegmentationPreferencePage::PerformOk() { m_SegmentationPreferencesNode->PutBool("draw outline", m_RadioOutline->isChecked()); m_SegmentationPreferencesNode->PutBool("volume rendering", m_VolumeRenderingCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("smoothing hint", m_SmoothingCheckBox->isChecked()); m_SegmentationPreferencesNode->PutDouble("smoothing value", m_SmoothingSpinBox->value()); m_SegmentationPreferencesNode->PutDouble("decimation rate", m_DecimationSpinBox->value()); m_SegmentationPreferencesNode->PutDouble("closing ratio", m_ClosingSpinBox->value()); return true; } void QmitkSegmentationPreferencePage::PerformCancel() { } void QmitkSegmentationPreferencePage::Update() { //m_EnableSingleEditing->setChecked(m_SegmentationPreferencesNode->GetBool("Single click property editing", true)); if (m_SegmentationPreferencesNode->GetBool("draw outline", true) ) { m_RadioOutline->setChecked( true ); } else { m_RadioOverlay->setChecked( true ); } m_VolumeRenderingCheckBox->setChecked( m_SegmentationPreferencesNode->GetBool("volume rendering", false) ); if (m_SegmentationPreferencesNode->GetBool("smoothing hint", true)) { m_SmoothingCheckBox->setChecked(true); m_SmoothingSpinBox->setDisabled(true); } else { m_SmoothingCheckBox->setChecked(false); m_SmoothingSpinBox->setEnabled(true); } m_SmoothingSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("smoothing value", 1.0)); m_DecimationSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("decimation rate", 0.5)); m_ClosingSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("closing ratio", 0.0)); } void QmitkSegmentationPreferencePage::OnVolumeRenderingCheckboxChecked(int state) { if (m_Initializing) return; if ( state != Qt::Unchecked ) { QMessageBox::information(NULL, "Memory warning", "Turning on volume rendering of segmentations will make the application more memory intensive (and potentially prone to crashes).\n\n" "If you encounter out-of-memory problems, try turning off volume rendering again."); } } void QmitkSegmentationPreferencePage::OnSmoothingCheckboxChecked(int state) { if (state != Qt::Unchecked) m_SmoothingSpinBox->setDisabled(true); else m_SmoothingSpinBox->setEnabled(true); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h index 5b88637d5e..cde83c25b4 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h @@ -1,84 +1,83 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date$ - Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkSegmentationPreferencePage_h_included #define QmitkSegmentationPreferencePage_h_included #include "berryIQtPreferencePage.h" #include "org_mitk_gui_qt_segmentation_Export.h" #include class QWidget; class QCheckBox; class QRadioButton; class QDoubleSpinBox; class MITK_QT_SEGMENTATION QmitkSegmentationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkSegmentationPreferencePage(); ~QmitkSegmentationPreferencePage(); void Init(berry::IWorkbench::Pointer workbench); void CreateQtControl(QWidget* widget); QWidget* GetQtControl() const; /// /// \see IPreferencePage::PerformOk() /// virtual bool PerformOk(); /// /// \see IPreferencePage::PerformCancel() /// virtual void PerformCancel(); /// /// \see IPreferencePage::Update() /// virtual void Update(); protected slots: void OnVolumeRenderingCheckboxChecked(int); void OnSmoothingCheckboxChecked(int); protected: QWidget* m_MainControl; QRadioButton* m_RadioOutline; QRadioButton* m_RadioOverlay; QCheckBox* m_VolumeRenderingCheckBox; QCheckBox* m_SmoothingCheckBox; QDoubleSpinBox* m_SmoothingSpinBox; QDoubleSpinBox* m_DecimationSpinBox; QDoubleSpinBox* m_ClosingSpinBox; bool m_Initializing; berry::IPreferences::Pointer m_SegmentationPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.cpp index 9c4cceeb1f..7021746654 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.cpp @@ -1,244 +1,242 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkBooleanOperationsView.h" #include #include #include #include #include #include #include #include #include #include QmitkBooleanOperationsView::QmitkBooleanOperationsView() : m_Parent(NULL) { } QmitkBooleanOperationsView::~QmitkBooleanOperationsView() { } void QmitkBooleanOperationsView::CreateQtPartControl(QWidget *parent) { mitk::DataStorage::Pointer dataStorage = GetDefaultDataStorage(); mitk::NodePredicateAnd::Pointer segmentationPredicate = mitk::NodePredicateAnd::New( mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)), mitk::NodePredicateNot::New( mitk::NodePredicateProperty::New("helper object"))); m_Parent = parent; m_Controls.setupUi(parent); m_Controls.cmbSegmentationImage1->SetDataStorage(dataStorage); m_Controls.cmbSegmentationImage1->SetPredicate(segmentationPredicate); m_Controls.cmbSegmentationImage2->SetPredicate(segmentationPredicate); m_Controls.cmbSegmentationImage2->SetDataStorage(dataStorage); connect(m_Controls.cmbSegmentationImage1, SIGNAL(OnSelectionChanged(const mitk::DataNode *)), this, SLOT(OnSegmentationImage1Changed(const mitk::DataNode *))); connect(m_Controls.cmbSegmentationImage2, SIGNAL(OnSelectionChanged(const mitk::DataNode *)), this, SLOT(OnSegmentationImage2Changed(const mitk::DataNode *))); connect(m_Controls.btnDifference, SIGNAL(clicked()), this, SLOT(OnDifferenceButtonClicked())); connect(m_Controls.btnUnion, SIGNAL(clicked()), this, SLOT(OnUnionButtonClicked())); connect(m_Controls.btnIntersection, SIGNAL(clicked()), this, SLOT(OnIntersectionButtonClicked())); } bool QmitkBooleanOperationsView::CheckSegmentationImages() { mitk::Image::Pointer image1 = dynamic_cast(m_Controls.cmbSegmentationImage1->GetSelectedNode()->GetData()); mitk::Image::Pointer image2 = dynamic_cast(m_Controls.cmbSegmentationImage2->GetSelectedNode()->GetData()); if (image1.IsNull() || image2.IsNull()) { MITK_ERROR << "At least one input segmentation image is invalid!"; return false; } if (image1->GetDimension() != image2->GetDimension()) { MITK_ERROR << "Dimensions of input segmentation images are different!"; return false; } if (image1->GetDimension() == 4) { unsigned int time = GetActiveStdMultiWidget()->GetTimeNavigationController()->GetTime()->GetPos(); if (time >= image1->GetDimension(3) || time >= image2->GetDimension(3)) { MITK_ERROR << "At least one input segmentation image has no data for current time slice!"; return false; } } return true; } mitk::Image::Pointer QmitkBooleanOperationsView::To3D(const mitk::Image::Pointer &image) { if (image->GetDimension() == 4) { mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New(); imageTimeSelector->SetInput(image); imageTimeSelector->SetTimeNr(static_cast(GetActiveStdMultiWidget()->GetTimeNavigationController()->GetTime()->GetPos())); imageTimeSelector->UpdateLargestPossibleRegion(); return imageTimeSelector->GetOutput(); } else { return image; } } void QmitkBooleanOperationsView::AddToDataStorage(const mitk::Image::Pointer &image, const std::string &prefix) const { mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); dataNode->SetBoolProperty("binary", true); dataNode->SetName(prefix + m_Controls.cmbSegmentationImage2->GetSelectedNode()->GetName()); dataNode->SetData(image); GetDefaultDataStorage()->Add(dataNode, m_Controls.cmbSegmentationImage1->GetSelectedNode()); } void QmitkBooleanOperationsView::EnableButtons(bool enable) { m_Controls.lblInputImagesWarning->setVisible(!enable); m_Controls.btnDifference->setEnabled(enable); m_Controls.btnUnion->setEnabled(enable); m_Controls.btnIntersection->setEnabled(enable); } void QmitkBooleanOperationsView::DisableButtons() { EnableButtons(false); } void QmitkBooleanOperationsView::OnSegmentationImage1Changed(const mitk::DataNode *dataNode) { if (dataNode != m_Controls.cmbSegmentationImage2->GetSelectedNode()) EnableButtons(); else DisableButtons(); } void QmitkBooleanOperationsView::OnSegmentationImage2Changed(const mitk::DataNode *dataNode) { if (dataNode != m_Controls.cmbSegmentationImage1->GetSelectedNode()) EnableButtons(); else DisableButtons(); } void QmitkBooleanOperationsView::OnDifferenceButtonClicked() { if (!CheckSegmentationImages()) return; mitk::Image::Pointer image1 = To3D(dynamic_cast(m_Controls.cmbSegmentationImage1->GetSelectedNode()->GetData())); mitk::Image::Pointer image2 = To3D(dynamic_cast(m_Controls.cmbSegmentationImage2->GetSelectedNode()->GetData())); typedef itk::Image ImageType; ImageType::Pointer itkImage1 = ImageType::New(); ImageType::Pointer itkImage2 = ImageType::New(); mitk::CastToItkImage(image1, itkImage1); mitk::CastToItkImage(image2, itkImage2); itk::NotImageFilter::Pointer notFilter = itk::NotImageFilter::New(); notFilter->SetInput(itkImage2); itk::AndImageFilter::Pointer andFilter = itk::AndImageFilter::New(); andFilter->SetInput1(itkImage1); andFilter->SetInput2(notFilter->GetOutput()); andFilter->UpdateLargestPossibleRegion(); mitk::Image::Pointer image3 = mitk::Image::New(); mitk::CastToMitkImage(andFilter->GetOutput(), image3); image3->DisconnectPipeline(); AddToDataStorage(image3, "Difference_"); } void QmitkBooleanOperationsView::OnUnionButtonClicked() { if (!CheckSegmentationImages()) return; mitk::Image::Pointer image1 = To3D(dynamic_cast(m_Controls.cmbSegmentationImage1->GetSelectedNode()->GetData())); mitk::Image::Pointer image2 = To3D(dynamic_cast(m_Controls.cmbSegmentationImage2->GetSelectedNode()->GetData())); typedef itk::Image ImageType; ImageType::Pointer itkImage1 = ImageType::New(); ImageType::Pointer itkImage2 = ImageType::New(); mitk::CastToItkImage(image1, itkImage1); mitk::CastToItkImage(image2, itkImage2); itk::OrImageFilter::Pointer orFilter = itk::OrImageFilter::New(); orFilter->SetInput1(itkImage1); orFilter->SetInput2(itkImage2); orFilter->UpdateLargestPossibleRegion(); mitk::Image::Pointer image3 = mitk::Image::New(); mitk::CastToMitkImage(orFilter->GetOutput(), image3); image3->DisconnectPipeline(); AddToDataStorage(image3, "Union_"); } void QmitkBooleanOperationsView::OnIntersectionButtonClicked() { if (!CheckSegmentationImages()) return; mitk::Image::Pointer image1 = To3D(dynamic_cast(m_Controls.cmbSegmentationImage1->GetSelectedNode()->GetData())); mitk::Image::Pointer image2 = To3D(dynamic_cast(m_Controls.cmbSegmentationImage2->GetSelectedNode()->GetData())); typedef itk::Image ImageType; ImageType::Pointer itkImage1 = ImageType::New(); ImageType::Pointer itkImage2 = ImageType::New(); mitk::CastToItkImage(image1, itkImage1); mitk::CastToItkImage(image2, itkImage2); itk::AndImageFilter::Pointer andFilter = itk::AndImageFilter::New(); andFilter->SetInput1(itkImage1); andFilter->SetInput2(itkImage2); andFilter->UpdateLargestPossibleRegion(); mitk::Image::Pointer image3 = mitk::Image::New(); mitk::CastToMitkImage(andFilter->GetOutput(), image3); image3->DisconnectPipeline(); AddToDataStorage(image3, "Intersection_"); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.h index ebf43cde57..a7f527027a 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkBooleanOperationsView.h @@ -1,54 +1,52 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKBOOLEANOPERATIONSVIEW_H #define QMITKBOOLEANOPERATIONSVIEW_H #include #include class QmitkBooleanOperationsView : public QmitkFunctionality { Q_OBJECT public: QmitkBooleanOperationsView(); ~QmitkBooleanOperationsView(); protected: void CreateQtPartControl(QWidget *parent); private slots: void OnSegmentationImage1Changed(const mitk::DataNode *dataNode); void OnSegmentationImage2Changed(const mitk::DataNode *dataNode); void OnDifferenceButtonClicked(); void OnUnionButtonClicked(); void OnIntersectionButtonClicked(); private: bool CheckSegmentationImages(); mitk::Image::Pointer To3D(const mitk::Image::Pointer &image); void AddToDataStorage(const mitk::Image::Pointer &image, const std::string &prefix) const; void EnableButtons(bool enable = true); void DisableButtons(); QWidget *m_Parent; Ui::QmitkBooleanOperationsView m_Controls; }; #endif diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.cpp index 6100df511f..85ee16b202 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.cpp @@ -1,537 +1,535 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkDeformableClippingPlaneView.h" #include "mitkClippingPlaneDeformationTool.h" #include "mitkClippingPlaneRotationTool.h" #include "mitkClippingPlaneTranslationTool.h" #include "mitkHeightFieldSurfaceClipImageFilter.h" #include "mitkImageToSurfaceFilter.h" #include "mitkInteractionConst.h" #include "mitkLabeledImageLookupTable.h" #include "mitkLabeledImageVolumeCalculator.h" #include "mitkLevelWindowProperty.h" #include "mitkLookupTableProperty.h" #include "mitkPlane.h" #include "mitkRotationOperation.h" #include "mitkSurfaceVtkMapper3D.h" #include "mitkVtkRepresentationProperty.h" #include "vtkFloatArray.h" #include "vtkPointData.h" #include "vtkProperty.h" const std::string QmitkDeformableClippingPlaneView::VIEW_ID = "org.mitk.views.deformableclippingplane"; QmitkDeformableClippingPlaneView::QmitkDeformableClippingPlaneView() : QmitkFunctionality() , m_MultiWidget(NULL) , m_ToolManager(NULL) { //Current fix for bug 10707. Waiting for a solution of bug 10834. itk::Object::Pointer o; o = mitk::ClippingPlaneRotationTool::New(); o = mitk::ClippingPlaneDeformationTool::New(); o = mitk::ClippingPlaneTranslationTool::New(); } QmitkDeformableClippingPlaneView::~QmitkDeformableClippingPlaneView() { } void QmitkDeformableClippingPlaneView::CreateQtPartControl(QWidget *parent) { // create GUI widgets m_Controls.setupUi(parent); this->CreateConnections(); } void QmitkDeformableClippingPlaneView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkDeformableClippingPlaneView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkDeformableClippingPlaneView::CreateConnections() { m_ToolManager = m_Controls.interactionToolSelectionBox->GetToolManager(); m_ToolManager->SetDataStorage(*(this->GetDefaultDataStorage())); assert(m_ToolManager); mitk::NodePredicateProperty::Pointer clipPredicate = mitk::NodePredicateProperty::New("clippingPlane",mitk::BoolProperty::New(true)); //set only clipping planes in the list of the selector m_Controls.clippingPlaneSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls.clippingPlaneSelector->SetPredicate(clipPredicate); //Shows and set the tool buttons m_Controls.interactionToolSelectionBox->SetGenerateAccelerators(true); m_Controls.interactionToolSelectionBox->SetDisplayedToolGroups("ClippingTool"); m_Controls.interactionToolSelectionBox->SetLayoutColumns(3); m_Controls.interactionToolSelectionBox->SetEnabledMode(QmitkToolSelectionBox::EnabledWithWorkingData); //No working data set, yet m_Controls.volumeGroupBox->setEnabled(false); m_Controls.noSelectedImageLabel->show(); m_Controls.planesWarningLabel->hide(); connect (m_Controls.createNewPlanePushButton, SIGNAL(clicked()), this, SLOT(OnCreateNewClippingPlane())); connect (m_Controls.updateVolumePushButton, SIGNAL(clicked()), this, SLOT(OnCalculateClippingVolume())); connect (m_Controls.clippingPlaneSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode*)), this, SLOT(OnComboBoxSelectionChanged(const mitk::DataNode*))); } void QmitkDeformableClippingPlaneView::Activated() { QmitkFunctionality::Activated(); } void QmitkDeformableClippingPlaneView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkDeformableClippingPlaneView::OnComboBoxSelectionChanged( const mitk::DataNode* node ) { mitk::DataNode* selectedNode = const_cast(node); if( selectedNode != NULL ) { //remember the active tool int toolID = m_ToolManager->GetActiveToolID(); m_ToolManager->SetWorkingData(selectedNode); //reset Tool m_ToolManager->ActivateTool(-1); //set tool again with new working data (calls activated() in Tool) m_ToolManager->ActivateTool(toolID); } this->UpdateView(); } void QmitkDeformableClippingPlaneView::OnSelectionChanged(mitk::DataNode* node) { std::vector nodes; nodes.push_back(node); this->OnSelectionChanged(nodes); } void QmitkDeformableClippingPlaneView::OnSelectionChanged(std::vector nodes) { bool isClippingPlane(false); for(unsigned int i = 0; i < nodes.size(); ++i) { if(nodes.at(i)->GetBoolProperty("clippingPlane", isClippingPlane)) m_Controls.clippingPlaneSelector->setCurrentIndex( m_Controls.clippingPlaneSelector->Find(nodes.at(i)) ); else { if(dynamic_cast (nodes.at(i)->GetData())&& nodes.at(i)) { if(m_ToolManager->GetReferenceData(0)!= NULL && nodes.at(i)->GetData()==m_ToolManager->GetReferenceData(0)->GetData()) return; m_ToolManager->SetReferenceData(nodes.at(i)); } } } this->UpdateView(); } void::QmitkDeformableClippingPlaneView::NodeChanged(const mitk::DataNode* /*node*/) { this->UpdateView(); } void QmitkDeformableClippingPlaneView::NodeRemoved(const mitk::DataNode* node) { bool isClippingPlane(false); if (node->GetBoolProperty("clippingPlane", isClippingPlane)) { if(this->GetAllClippingPlanes()->empty()) { m_ToolManager->SetWorkingData(NULL); this->UpdateView(); } else this->OnSelectionChanged(GetAllClippingPlanes()->front()); } else { if(m_ToolManager->GetReferenceData(0)!= NULL) { if(node->GetData() == m_ToolManager->GetReferenceData(0)->GetData()) { m_ToolManager->SetReferenceData(NULL); m_Controls.volumeList->clear(); } this->OnSelectionChanged(mitk::DataNode::New()); } } } void QmitkDeformableClippingPlaneView::UpdateView() { if (m_ToolManager->GetReferenceData(0)!= NULL) { m_Controls.volumeGroupBox->setEnabled(m_ToolManager->GetWorkingData(0)!= NULL); m_Controls.noSelectedImageLabel->hide(); m_Controls.selectedImageLabel->setText(QString::fromUtf8(m_ToolManager->GetReferenceData(0)->GetName().c_str())); //clear list --> than search for all shown clipping plans (max 7 planes) m_Controls.selectedVolumePlanesLabel->setText(""); m_Controls.planesWarningLabel->hide(); int volumePlanes=0; mitk::DataStorage::SetOfObjects::ConstPointer allClippingPlanes = this->GetAllClippingPlanes(); for (mitk::DataStorage::SetOfObjects::ConstIterator itPlanes = allClippingPlanes->Begin(); itPlanes != allClippingPlanes->End(); itPlanes++) { bool isVisible(false); itPlanes.Value()->GetBoolProperty("visible",isVisible); if (isVisible) { if (volumePlanes<7) { volumePlanes ++; m_Controls.selectedVolumePlanesLabel->setText(m_Controls.selectedVolumePlanesLabel->text().append(QString::fromStdString(itPlanes.Value()->GetName()+"\n"))); } else { m_Controls.planesWarningLabel->show(); return; } } } } else { m_Controls.volumeGroupBox->setEnabled(false); m_Controls.noSelectedImageLabel->show(); m_Controls.selectedImageLabel->setText(""); m_Controls.selectedVolumePlanesLabel->setText(""); m_Controls.planesWarningLabel->hide(); } } void QmitkDeformableClippingPlaneView::OnCreateNewClippingPlane() { mitk::DataNode* referenceNode = m_ToolManager->GetReferenceData(0); mitk::Image::Pointer referenceImage = mitk::Image::New(); //the new clipping plane mitk::Plane::Pointer plane = mitk::Plane::New(); double imageDiagonal = 200; if (referenceNode != NULL) { referenceImage = dynamic_cast (referenceNode->GetData()); if (referenceImage.IsNotNull()) { // check if user wants a surface model if(m_Controls.surfaceModelCheckBox->isChecked()) { //Check if there is a surface node from the image. If not, create one bool createSurfaceFromImage(true); mitk::TNodePredicateDataType::Pointer isSurface = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer childNodes = m_ToolManager->GetDataStorage()->GetDerivations(referenceNode,isSurface, true); for (mitk::DataStorage::SetOfObjects::ConstIterator itChildNodes = childNodes->Begin(); itChildNodes != childNodes->End(); itChildNodes++) { if (itChildNodes.Value().IsNotNull()) createSurfaceFromImage=false; } if(createSurfaceFromImage) { //Lsg 2: Surface for the 3D-perspective mitk::ImageToSurfaceFilter::Pointer surfaceFilter = mitk::ImageToSurfaceFilter::New(); surfaceFilter->SetInput(referenceImage); surfaceFilter->SetThreshold(1); surfaceFilter->SetSmooth(true); //Downsampling surfaceFilter->SetDecimate(mitk::ImageToSurfaceFilter::DecimatePro); mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetData(surfaceFilter->GetOutput()); surfaceNode->SetProperty("color", referenceNode->GetProperty("color")); surfaceNode->SetOpacity(0.5); surfaceNode->SetName(referenceNode->GetName()); m_ToolManager->GetDataStorage()->Add(surfaceNode, referenceNode); } } //If an image is selected trim the plane to this. imageDiagonal = referenceImage->GetGeometry()->GetDiagonalLength(); plane->SetOrigin( referenceImage->GetGeometry()->GetCenter()); // Rotate plane mitk::Vector3D rotationAxis; mitk::FillVector3D(rotationAxis, 0.0, 1.0, 0.0); mitk::RotationOperation op(mitk::OpROTATE, referenceImage->GetGeometry()->GetCenter(), rotationAxis, 90.0); plane->GetGeometry()->ExecuteOperation(&op); } } //set some properties for the clipping plane plane->SetExtent(imageDiagonal * 0.9, imageDiagonal * 0.9); plane->SetResolution(64, 64); // Set scalars (for colorization of plane) vtkFloatArray *scalars = vtkFloatArray::New(); scalars->SetName("Distance"); scalars->SetNumberOfComponents(1); for ( unsigned int i = 0; i < plane->GetVtkPolyData(0)->GetNumberOfPoints(); ++i) { scalars->InsertNextValue(-1.0); } plane->GetVtkPolyData(0)->GetPointData()->SetScalars(scalars); plane->GetVtkPolyData(0)->GetPointData()->Update(); mitk::DataNode::Pointer planeNode = mitk::DataNode::New(); planeNode->SetData(plane); std::stringstream planeName; planeName << "ClippingPlane "; planeName << this->GetAllClippingPlanes()->Size() + 1; planeNode->SetName(planeName.str()); planeNode->AddProperty("clippingPlane",mitk::BoolProperty::New(true)); // Make plane pickable planeNode->SetBoolProperty("pickable", true); mitk::SurfaceVtkMapper3D::SetDefaultProperties(planeNode); // Don't include plane in bounding box! planeNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); // Set lookup table for plane surface visualization vtkLookupTable *lookupTable = vtkLookupTable::New(); lookupTable->SetHueRange(0.6, 0.0); lookupTable->SetSaturationRange(1.0, 1.0); lookupTable->SetValueRange(1.0, 1.0); lookupTable->SetTableRange(-1.0, 1.0); lookupTable->Build(); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); lut->SetVtkLookupTable(lookupTable); mitk::LookupTableProperty::Pointer prop = mitk::LookupTableProperty::New(lut); planeNode->SetProperty("LookupTable", prop); planeNode->SetBoolProperty("scalar visibility", true); planeNode->SetBoolProperty("color mode", true); planeNode->SetFloatProperty("ScalarsRangeMinimum", -1.0); planeNode->SetFloatProperty("ScalarsRangeMaximum", 1.0); // Configure material so that only scalar colors are shown planeNode->SetColor(0.0f,0.0f,0.0f); planeNode->SetOpacity(1.0f); planeNode->SetFloatProperty("material.wireframeLineWidth",2.0f); //Set view of plane to wireframe planeNode->SetProperty("material.representation", mitk::VtkRepresentationProperty::New(VTK_WIREFRAME)); //Set the plane as working data for the tools and selected it this->OnSelectionChanged (planeNode); //Add the plane to data storage this->GetDataStorage()->Add(planeNode); //Change the index of the selector to the new generated node m_Controls.clippingPlaneSelector->setCurrentIndex( m_Controls.clippingPlaneSelector->Find(planeNode) ); // set crosshair invisible mitk::DataNode* dataNode; dataNode = this->m_MultiWidget->GetWidgetPlane1(); if(dataNode) dataNode->SetVisibility(false); dataNode = this->m_MultiWidget->GetWidgetPlane2(); if(dataNode) dataNode->SetVisibility(false); dataNode = this->m_MultiWidget->GetWidgetPlane3(); if(dataNode) dataNode->SetVisibility(false); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDeformableClippingPlaneView::OnCalculateClippingVolume() { mitk::DataNode::Pointer imageNode = m_ToolManager->GetReferenceData(0); bool isSegmentation(false); imageNode->GetBoolProperty("binary", isSegmentation); if(imageNode.IsNull() || !isSegmentation) { MITK_INFO << "No segmentation selected! Can't calculate volume"; return; } std::vector clippingPlanes; mitk::DataStorage::SetOfObjects::ConstPointer allClippingPlanes = this->GetAllClippingPlanes(); for (mitk::DataStorage::SetOfObjects::ConstIterator itPlanes = allClippingPlanes->Begin(); itPlanes != allClippingPlanes->End(); itPlanes++) { bool isVisible(false); itPlanes.Value()->GetBoolProperty("visible",isVisible); mitk::Surface* plane = dynamic_cast(itPlanes.Value()->GetData()); if (isVisible && plane) clippingPlanes.push_back(plane); } if (clippingPlanes.empty()) { MITK_INFO << "No clipping plane selected! Can't calculate volume"; return; } //deactivate Tools m_ToolManager->ActivateTool(-1); //Clear the list of volumes, before calculating the new values m_Controls.volumeList->clear(); imageNode->SetBoolProperty("visible", false); //set some properties for clipping the image-->Output: labled Image mitk::HeightFieldSurfaceClipImageFilter::Pointer surfaceClipFilter = mitk::HeightFieldSurfaceClipImageFilter::New(); surfaceClipFilter->SetInput(dynamic_cast (imageNode->GetData())); surfaceClipFilter->SetClippingModeToMultiPlaneValue(); surfaceClipFilter->SetClippingSurfaces(clippingPlanes); surfaceClipFilter->Update(); //delete the old clipped image node mitk::DataStorage::SetOfObjects::ConstPointer oldClippedNode = this->GetDataStorage()->GetSubset(mitk::NodePredicateProperty::New("name", mitk::StringProperty::New("Clipped Image"))); if (oldClippedNode.IsNotNull()) this->GetDataStorage()->Remove(oldClippedNode); //add the new clipped image node mitk::DataNode::Pointer clippedNode = mitk::DataNode::New(); mitk::Image::Pointer clippedImage = surfaceClipFilter->GetOutput(); clippedImage->DisconnectPipeline(); clippedNode->SetData(clippedImage); //clippedNode->SetProperty("helper object", mitk::BoolProperty::New(true)); clippedNode->SetName("Clipped Image"); clippedNode->SetColor(1.0,1.0,1.0); // color property will not be used, labeled image lookuptable will be used instead clippedNode->SetProperty ("use color", mitk::BoolProperty::New(false)); clippedNode->SetOpacity(0.4); this->GetDataStorage()->Add(clippedNode); mitk::LabeledImageVolumeCalculator::Pointer volumeCalculator = mitk::LabeledImageVolumeCalculator::New(); volumeCalculator->SetImage(clippedImage); volumeCalculator->Calculate(); std::vector volumes = volumeCalculator->GetVolumes(); mitk::LabeledImageLookupTable::Pointer lut = mitk::LabeledImageLookupTable::New(); int lablesWithVolume=0; for(unsigned int i = 1; i < volumes.size(); ++i) { if(volumes.at(i)!=0) { lablesWithVolume++; mitk::Color color (GetLabelColor(lablesWithVolume)); lut->SetColorForLabel(i,color.GetRed(), color.GetGreen(), color.GetBlue(), 1.0); QColor qcolor; qcolor.setRgbF(color.GetRed(), color.GetGreen(), color.GetBlue(), 0.7); //output volume as string "x.xx ml" std::stringstream stream; stream<< std::fixed << std::setprecision(2)<setText(QString::fromStdString(stream.str())); item->setBackgroundColor(qcolor); m_Controls.volumeList->addItem(item); } } mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New(lut.GetPointer()); clippedNode->SetProperty("LookupTable", lutProp); // it is absolutely important, to use the LevelWindow settings provided by // the LUT generator, otherwise, it is not guaranteed, that colors show // up correctly. clippedNode->SetProperty("levelwindow", mitk::LevelWindowProperty::New(lut->GetLevelWindow())); } mitk::DataStorage::SetOfObjects::ConstPointer QmitkDeformableClippingPlaneView::GetAllClippingPlanes() { mitk::NodePredicateProperty::Pointer clipPredicate= mitk::NodePredicateProperty::New("clippingPlane",mitk::BoolProperty::New(true)); mitk::DataStorage::SetOfObjects::ConstPointer allPlanes = m_ToolManager->GetDataStorage()->GetSubset(clipPredicate); return allPlanes; } mitk::Color QmitkDeformableClippingPlaneView::GetLabelColor(int label) { float red, green, blue; switch ( label % 6 ) { case 0: {red = 1.0; green = 0.0; blue = 0.0; break;} case 1: {red = 0.0; green = 1.0; blue = 0.0; break;} case 2: {red = 0.0; green = 0.0; blue = 1.0;break;} case 3: {red = 1.0; green = 1.0; blue = 0.0;break;} case 4: {red = 1.0; green = 0.0; blue = 1.0;break;} case 5: {red = 0.0; green = 1.0; blue = 1.0;break;} default: {red = 0.0; green = 0.0; blue = 0.0;} } float tmp[3] = { red, green, blue }; double factor; int outerCycleNr = label / 6; int cycleSize = pow(2.0,(int)(log((double)(outerCycleNr))/log( 2.0 ))); if (cycleSize==0) cycleSize = 1; int insideCycleCounter = outerCycleNr % cycleSize; if ( outerCycleNr == 0) factor = 255; else factor = ( 256 / ( 2 * cycleSize ) ) + ( insideCycleCounter * ( 256 / cycleSize ) ); tmp[0]= tmp[0]/256*factor; tmp[1]= tmp[1]/256*factor; tmp[2]= tmp[2]/256*factor; return mitk::Color(tmp); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h index 3530edef7e..33f499b3cd 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h @@ -1,98 +1,96 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Module: $RCSfile$ -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QMITKDEFORMABLECLIPPINGPLANEVIEW_H_INCLUDED #define _QMITKDEFORMABLECLIPPINGPLANEVIEW_H_INCLUDED #include "ui_QmitkDeformableClippingPlaneViewControls.h" #include #include "mitkImage.h" #include "mitkToolManager.h" typedef itk::RGBPixel< float > Color; /*! * \ingroup org_mitk_gui_qt_deformableSurface * * \brief QmitkDeformableClippingPlaneView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkDeformableClippingPlaneView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkDeformableClippingPlaneView(); virtual ~QmitkDeformableClippingPlaneView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); /// \brief Called when the functionality is deactivated virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /// \brief Called when the user clicks the GUI button/makes a selection void OnComboBoxSelectionChanged(const mitk::DataNode* node); void OnCreateNewClippingPlane(); void OnCalculateClippingVolume(); protected: /*! \brief Invoked when the DataManager selection changed */ virtual void OnSelectionChanged(mitk::DataNode* node); virtual void OnSelectionChanged(std::vector nodes); virtual void NodeRemoved(const mitk::DataNode* node); virtual void NodeChanged(const mitk::DataNode* node); void UpdateView(); QmitkStdMultiWidget* m_MultiWidget; Ui::QmitkDeformableClippingPlaneViewControls m_Controls; mitk::ToolManager::Pointer m_ToolManager; private: mitk::DataStorage::SetOfObjects::ConstPointer GetAllClippingPlanes(); mitk::Color GetLabelColor(int label); }; #endif // _QMITKDEFORMABLECLIPPINGPLANEVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationOrganNamesHandling.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationOrganNamesHandling.cpp index 11118e1a2b..2be03306ad 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationOrganNamesHandling.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationOrganNamesHandling.cpp @@ -1,102 +1,101 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2005/06/28 12:37:25 $ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include QStringList QmitkSegmentationView::GetDefaultOrganColorString() { QStringList organColors; AppendToOrganList(organColors, "Ankle", 255, 255, 153); AppendToOrganList(organColors, "Appendix", 161, 107, 54); AppendToOrganList(organColors, "Blood vessels", 255, 49, 49); AppendToOrganList(organColors, "Bone", 255, 255, 153); AppendToOrganList(organColors, "Brain", 255, 156, 202); AppendToOrganList(organColors, "Bronchial tree", 0, 160, 209); AppendToOrganList(organColors, "Coccyx", 255, 255, 153); AppendToOrganList(organColors, "Colon", 161, 107, 54); AppendToOrganList(organColors, "Cyst", 150, 189, 228); AppendToOrganList(organColors, "Elbow", 255, 255, 153); AppendToOrganList(organColors, "Eye", 18, 7, 161); AppendToOrganList(organColors, "Fallopian tube", 161, 19, 39); AppendToOrganList(organColors, "Fat", 237, 255, 41); AppendToOrganList(organColors, "Gall Bladder", 86, 127, 24); AppendToOrganList(organColors, "Hand", 255, 222, 199); AppendToOrganList(organColors, "Heart", 153, 0, 0); AppendToOrganList(organColors, "Hip", 255, 255, 153); AppendToOrganList(organColors, "Kidney", 250, 89, 0); AppendToOrganList(organColors, "Knee", 255, 255, 153); AppendToOrganList(organColors, "Larynx", 102, 0, 0); AppendToOrganList(organColors, "Liver", 194, 142, 0); AppendToOrganList(organColors, "Lung", 107, 220, 255); AppendToOrganList(organColors, "Lymph node", 10, 250, 56); AppendToOrganList(organColors, "Muscle", 102, 0, 0); AppendToOrganList(organColors, "Nerve", 255, 234, 79); AppendToOrganList(organColors, "Nose", 255, 222, 199); AppendToOrganList(organColors, "Oesophagus", 102, 0, 0); AppendToOrganList(organColors, "Ovaries", 234, 0, 117); AppendToOrganList(organColors, "Pancreas", 249, 171, 61); AppendToOrganList(organColors, "Pelvis", 255, 255, 153); AppendToOrganList(organColors, "Penis", 255, 222, 199); AppendToOrganList(organColors, "Pharynx", 102, 0, 0); AppendToOrganList(organColors, "Prostate", 209, 163, 117); AppendToOrganList(organColors, "Rectum", 161, 107, 54); AppendToOrganList(organColors, "Sacrum", 255, 255, 153); AppendToOrganList(organColors, "Seminal vesicle", 199, 232, 255); AppendToOrganList(organColors, "Shoulder", 255, 255, 153); AppendToOrganList(organColors, "Spinal cord", 255, 234, 79); AppendToOrganList(organColors, "Spleen", 249, 108, 61); AppendToOrganList(organColors, "Stomach", 161, 107, 54); AppendToOrganList(organColors, "Teeth", 255, 252, 216); AppendToOrganList(organColors, "Testicles", 199, 232, 255); AppendToOrganList(organColors, "Thyroid", 255, 179, 184); AppendToOrganList(organColors, "Tongue", 102, 0, 0); AppendToOrganList(organColors, "Tumor", 147, 112, 17); AppendToOrganList(organColors, "Urethra", 197, 204, 0); AppendToOrganList(organColors, "Urinary bladder", 197, 204, 0); AppendToOrganList(organColors, "Uterus", 161, 19, 39); AppendToOrganList(organColors, "Vagina", 161, 19, 39); AppendToOrganList(organColors, "Vertebra", 255, 255, 153); AppendToOrganList(organColors, "Wrist", 255, 255, 153); return organColors; } void QmitkSegmentationView::UpdateOrganList(QStringList& organColors, const QString& organname, mitk::Color color) { QString listElement( organname + QColor(color.GetRed() * 255 , color.GetGreen() * 255 , color.GetBlue() * 255).name() ); // remove previous definition if necessary int oldIndex = organColors.indexOf( QRegExp(QRegExp::escape(organname) + "#......", Qt::CaseInsensitive)); if (oldIndex < 0 || organColors.at(oldIndex) != listElement ) { if (oldIndex >= 0) { organColors.removeAt( oldIndex ); } // add colored organ name AND sort list organColors.append( listElement ); organColors.sort(); } } void QmitkSegmentationView::AppendToOrganList(QStringList& organColors, const QString& organname, int r, int g, int b) { organColors.append( organname + QColor(r, g, b).name() ); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.cpp index d074440176..9abb432071 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.cpp @@ -1,426 +1,425 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkSegmentationPostProcessing.h" #include "QmitkNodeDescriptorManager.h" #include "QmitkToolGUI.h" #include "mitkAutoCropImageFilter.h" #include "mitkBinaryThresholdTool.h" #include "mitkRenderingManager.h" #include "mitkShowSegmentationAsSurface.h" #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkImageCast.h" #include "mitkDataNodeObject.h" #include #include #include QmitkSegmentationPostProcessing::QmitkSegmentationPostProcessing(mitk::DataStorage* storage, QmitkFunctionality* functionality, QObject* parent) :QObject(parent) ,m_BlueBerryView(functionality) ,m_DataStorage(storage) { // register a couple of additional actions for DataManager's context menu QmitkNodeDescriptor* imageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("NoneBinaryImage"); if (imageDataNodeDescriptor) { m_ThresholdAction = new QAction("Threshold..", parent); imageDataNodeDescriptor->AddAction(m_ThresholdAction); connect( m_ThresholdAction, SIGNAL( triggered(bool) ) , this, SLOT( ThresholdImage(bool) ) ); } else { MITK_WARN << "Could not get datamanager's node descriptor for 'Image'"; } // register a couple of additional actions for DataManager's context menu QmitkNodeDescriptor* binaryImageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("ImageMask"); if (binaryImageDataNodeDescriptor) { m_CreateSurfaceAction = new QAction("Create polygon model", parent); binaryImageDataNodeDescriptor->AddAction(m_CreateSurfaceAction); connect( m_CreateSurfaceAction, SIGNAL( triggered(bool) ) , this, SLOT( CreateSurface(bool) ) ); m_CreateSmoothSurfaceAction = new QAction("Create smoothed polygon model", parent); binaryImageDataNodeDescriptor->AddAction(m_CreateSmoothSurfaceAction); connect( m_CreateSmoothSurfaceAction, SIGNAL( triggered(bool) ) , this, SLOT( CreateSmoothedSurface(bool) ) ); m_StatisticsAction = new QAction("Statistics", parent); binaryImageDataNodeDescriptor->AddAction(m_StatisticsAction); berry::IBundle::Pointer imageStatisticsBundle = berry::Platform::GetBundle("org.mitk.gui.qt.imagestatistics"); if(imageStatisticsBundle.IsNotNull()) connect( m_StatisticsAction, SIGNAL( triggered(bool) ) , this, SLOT( ImageStatistics(bool) ) ); else m_StatisticsAction->setEnabled( false ); m_AutocropAction = new QAction("Autocrop", parent); binaryImageDataNodeDescriptor->AddAction(m_AutocropAction); connect( m_AutocropAction, SIGNAL( triggered(bool) ) , this, SLOT( AutocropSelected(bool) ) ); } else { MITK_WARN << "Could not get datamanager's node descriptor for 'ImageMask'"; } // register for blueberry selection events m_SelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter(this, &QmitkSegmentationPostProcessing::SelectionChanged)); m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelectionListener); } QmitkSegmentationPostProcessing::~QmitkSegmentationPostProcessing() { berry::ISelectionService* s = m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(m_SelectionListener); } // unregister a couple of additional actions for DataManager's context menu QmitkNodeDescriptor* imageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image"); if (imageDataNodeDescriptor) { imageDataNodeDescriptor->RemoveAction( m_ThresholdAction ); } else { MITK_WARN << "Could not get datamanager's node descriptor for 'Image'"; } // unregister a couple of additional actions for DataManager's context menu QmitkNodeDescriptor* binaryImageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("ImageMask"); if (binaryImageDataNodeDescriptor) { binaryImageDataNodeDescriptor->RemoveAction( m_CreateSurfaceAction ); binaryImageDataNodeDescriptor->RemoveAction( m_CreateSmoothSurfaceAction ); binaryImageDataNodeDescriptor->RemoveAction( m_StatisticsAction ); binaryImageDataNodeDescriptor->RemoveAction( m_AutocropAction ); } else { MITK_WARN << "Could not get datamanager's node descriptor for 'ImageMask'"; } } void QmitkSegmentationPostProcessing::SelectionChanged(berry::IWorkbenchPart::Pointer /*sourcepart*/, berry::ISelection::ConstPointer selection) { if ( selection.IsNull() ) { return; } // save current selection in member variable m_CurrentSelection = selection.Cast(); } QmitkSegmentationPostProcessing::NodeList QmitkSegmentationPostProcessing::GetSelectedNodes() const { NodeList result; if (m_CurrentSelection) { // iterate selection for (mitk::DataNodeSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); result.push_back( node ); } } } return result; } void QmitkSegmentationPostProcessing::ThresholdImage(bool) { NodeList selection = this->GetSelectedNodes(); m_ThresholdingToolManager = mitk::ToolManager::New( m_DataStorage ); m_ThresholdingToolManager->RegisterClient(); m_ThresholdingToolManager->ActiveToolChanged += mitk::MessageDelegate( this, &QmitkSegmentationPostProcessing::OnThresholdingToolManagerToolModified ); m_ThresholdingDialog = new QDialog(qobject_cast(parent())); connect( m_ThresholdingDialog, SIGNAL(finished(int)), this, SLOT(ThresholdingDone(int)) ); QVBoxLayout* layout = new QVBoxLayout; layout->setContentsMargins(0, 0, 0, 0); mitk::Tool* tool = m_ThresholdingToolManager->GetToolById( m_ThresholdingToolManager->GetToolIdByToolType() ); if (tool) { itk::Object::Pointer possibleGUI = tool->GetGUI("Qmitk", "GUI"); QmitkToolGUI* gui = dynamic_cast( possibleGUI.GetPointer() ); if (gui) { gui->SetTool(tool); gui->setParent(m_ThresholdingDialog); layout->addWidget(gui); m_ThresholdingDialog->setLayout(layout); layout->activate(); m_ThresholdingDialog->setFixedSize(300,75); m_ThresholdingDialog->open(); } } for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter ) { mitk::DataNode* node = *iter; if (node) { m_ThresholdingToolManager->SetReferenceData( node ); m_ThresholdingToolManager->ActivateTool( m_ThresholdingToolManager->GetToolIdByToolType() ); } } } void QmitkSegmentationPostProcessing::ThresholdingDone(int result) { if (result == QDialog::Rejected) m_ThresholdingToolManager->ActivateTool(-1); MITK_INFO << "Thresholding done, cleaning up"; m_ThresholdingDialog->deleteLater(); m_ThresholdingDialog = NULL; m_ThresholdingToolManager->SetReferenceData( NULL ); m_ThresholdingToolManager->SetWorkingData( NULL ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationPostProcessing::OnThresholdingToolManagerToolModified() { if ( m_ThresholdingToolManager.IsNull() ) return; //MITK_INFO << "Now got tool " << m_ThresholdingToolManager->GetActiveToolID(); if ( m_ThresholdingToolManager->GetActiveToolID() < 0) { if (m_ThresholdingDialog) m_ThresholdingDialog->accept(); } } void QmitkSegmentationPostProcessing::CreateSmoothedSurface(bool) { InternalCreateSurface(true); } void QmitkSegmentationPostProcessing::CreateSurface(bool) { InternalCreateSurface(false); } void QmitkSegmentationPostProcessing::InternalCreateSurface(bool smoothed) { NodeList selection = this->GetSelectedNodes(); for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter ) { mitk::DataNode* node = *iter; if (node) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNull()) return; try { mitk::ShowSegmentationAsSurface::Pointer surfaceFilter = mitk::ShowSegmentationAsSurface::New(); // attach observer to get notified about result itk::SimpleMemberCommand::Pointer goodCommand = itk::SimpleMemberCommand::New(); goodCommand->SetCallbackFunction(this, &QmitkSegmentationPostProcessing::OnSurfaceCalculationDone); surfaceFilter->AddObserver(mitk::ResultAvailable(), goodCommand); itk::SimpleMemberCommand::Pointer badCommand = itk::SimpleMemberCommand::New(); badCommand->SetCallbackFunction(this, &QmitkSegmentationPostProcessing::OnSurfaceCalculationDone); surfaceFilter->AddObserver(mitk::ProcessingError(), badCommand); mitk::DataNode::Pointer nodepointer = node; surfaceFilter->SetPointerParameter("Input", image); surfaceFilter->SetPointerParameter("Group node", nodepointer); surfaceFilter->SetParameter("Show result", true ); surfaceFilter->SetParameter("Sync visibility", false ); surfaceFilter->SetDataStorage( *m_DataStorage ); if (smoothed) { surfaceFilter->SetParameter("Smooth", true ); //surfaceFilter->SetParameter("Apply median", true ); surfaceFilter->SetParameter("Apply median", false ); // median makes the resulting surfaces look like lego models surfaceFilter->SetParameter("Median kernel size", 3u ); surfaceFilter->SetParameter("Gaussian SD", 2.5f ); surfaceFilter->SetParameter("Decimate mesh", true ); surfaceFilter->SetParameter("Decimation rate", 0.80f ); } else { surfaceFilter->SetParameter("Smooth", false ); surfaceFilter->SetParameter("Apply median", false ); surfaceFilter->SetParameter("Median kernel size", 3u ); surfaceFilter->SetParameter("Gaussian SD", 1.5f ); surfaceFilter->SetParameter("Decimate mesh", true ); surfaceFilter->SetParameter("Decimation rate", 0.8f ); } mitk::ProgressBar::GetInstance()->AddStepsToDo(10); mitk::ProgressBar::GetInstance()->Progress(2); mitk::StatusBar::GetInstance()->DisplayText("Surface creation started in background..."); surfaceFilter->StartAlgorithm(); } catch(...) { MITK_ERROR << "surface creation filter had an error"; } } else { MITK_INFO << " a NULL node selected"; } } } void QmitkSegmentationPostProcessing::OnSurfaceCalculationDone() { mitk::ProgressBar::GetInstance()->Progress(8); } void QmitkSegmentationPostProcessing::ImageStatistics(bool) { if (m_BlueBerryView) { m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagestatistics"); } } void QmitkSegmentationPostProcessing::AutocropSelected(bool) { NodeList selection = this->GetSelectedNodes(); for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter ) { mitk::DataNode* node = *iter; if (node) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNull()) return; mitk::ProgressBar::GetInstance()->AddStepsToDo(10); mitk::ProgressBar::GetInstance()->Progress(2); qApp->processEvents(); mitk::AutoCropImageFilter::Pointer cropFilter = mitk::AutoCropImageFilter::New(); cropFilter->SetInput( image ); cropFilter->SetBackgroundValue( 0 ); try { cropFilter->Update(); image = cropFilter->GetOutput(); if (image.IsNotNull()) { node->SetData( this->IncreaseCroppedImageSize(image) ); // bug fix 3145 } } catch(...) { MITK_ERROR << "Cropping image failed..."; } mitk::ProgressBar::GetInstance()->Progress(8); } else { MITK_INFO << " a NULL node selected"; } } } mitk::Image::Pointer QmitkSegmentationPostProcessing::IncreaseCroppedImageSize( mitk::Image::Pointer image ) { typedef itk::Image< short, 3 > ImageType; typedef itk::Image< unsigned char, 3 > PADOutputImageType; ImageType::Pointer itkTransformImage = ImageType::New(); mitk::CastToItkImage( image, itkTransformImage ); typedef itk::ConstantPadImageFilter< ImageType, PADOutputImageType > PadFilterType; PadFilterType::Pointer padFilter = PadFilterType::New(); unsigned long upperPad[3]; unsigned long lowerPad[3]; int borderLiner = 6; mitk::Point3D mitkOriginPoint; double origin[3]; origin[0]=0; origin[1]=0; origin[2]=0; itkTransformImage->SetOrigin(origin); lowerPad[0]=borderLiner/2; lowerPad[1]=borderLiner/2; lowerPad[2]=borderLiner/2; upperPad[0]=borderLiner/2; upperPad[1]=borderLiner/2; upperPad[2]=borderLiner/2; padFilter->SetInput(itkTransformImage); padFilter->SetConstant(0); padFilter->SetPadUpperBound(upperPad); padFilter->SetPadLowerBound(lowerPad); padFilter->UpdateLargestPossibleRegion(); mitk::Image::Pointer paddedImage = mitk::Image::New(); mitk::CastToMitkImage(padFilter->GetOutput(), paddedImage); paddedImage->SetGeometry(image->GetGeometry()); //calculate translation vector according to padding to get the new origin mitk::Vector3D transVector = image->GetGeometry()->GetSpacing(); transVector[0] = -(borderLiner/2); transVector[1] = -(borderLiner/2); transVector[2] = -(borderLiner/2); mitk::Vector3D newTransVectorInmm = image->GetGeometry()->GetSpacing(); image->GetGeometry()->IndexToWorld(transVector, newTransVectorInmm); paddedImage->GetGeometry()->Translate(newTransVectorInmm); //paddedImage->SetRequestedRegionToLargestPossibleRegion(); return paddedImage; } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.h index 08256b016c..931372143a 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationPostProcessing.h @@ -1,91 +1,90 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2005/06/28 12:37:25 $ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkSegmentationPostProcessing_h #define QmitkSegmentationPostProcessing_h #include "QmitkFunctionality.h" #include "mitkDataStorage.h" #include "mitkToolManager.h" #include "mitkDataNodeSelection.h" #include #include /** * \brief Provide context-menus for segmentations in data manager * * This class is mainly meant as a helper to the org.mitk.gui.qt.segmentation * view. Independency of this class has been attempted, so it might * also be useful in a different context. */ class QmitkSegmentationPostProcessing : public QObject { Q_OBJECT public: // construction/destruction QmitkSegmentationPostProcessing(mitk::DataStorage* storage, QmitkFunctionality* functionality, QObject* parent = 0); virtual ~QmitkSegmentationPostProcessing(); // for receiving messages void OnSurfaceCalculationDone(); void OnThresholdingToolManagerToolModified(); void SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection); protected slots: // reactions to context menu items void ThresholdImage(bool); void CreateSurface(bool); void CreateSmoothedSurface(bool); void ImageStatistics(bool); void AutocropSelected(bool); // class internal slots void ThresholdingDone(int); void InternalCreateSurface(bool smoothed); protected: typedef std::vector NodeList; NodeList GetSelectedNodes() const; mitk::Image::Pointer IncreaseCroppedImageSize( mitk::Image::Pointer image ); // variables QmitkFunctionality* m_BlueBerryView; mitk::DataStorage::Pointer m_DataStorage; QAction* m_CreateSurfaceAction; QAction* m_CreateSmoothSurfaceAction; QAction* m_StatisticsAction; QAction* m_AutocropAction; QAction* m_ThresholdAction; QDialog* m_ThresholdingDialog; mitk::ToolManager::Pointer m_ThresholdingToolManager; berry::ISelectionListener::Pointer m_SelectionListener; mitk::DataNodeSelection::ConstPointer m_CurrentSelection; friend struct berry::SelectionChangedAdapter; }; #endif diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp index 39be172557..f530ac6789 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp @@ -1,1230 +1,1229 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 1.12 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkDataNodeObject.h" #include "mitkProperties.h" #include "mitkSegTool2D.h" #include "mitkGlobalInteraction.h" #include "QmitkStdMultiWidget.h" #include "QmitkNewSegmentationDialog.h" #include #include #include "QmitkSegmentationView.h" #include "QmitkSegmentationPostProcessing.h" #include "QmitkSegmentationOrganNamesHandling.cpp" #include #include //For Segmentation in rotated slices //TODO clean up includes #include "mitkVtkResliceInterpolationProperty.h" #include "mitkPlanarCircle.h" #include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleRegistry.h" #include "mitkSegmentationObjectFactory.h" const std::string QmitkSegmentationView::VIEW_ID = "org.mitk.views.segmentation"; // public methods QmitkSegmentationView::QmitkSegmentationView() :m_Parent(NULL) ,m_Controls(NULL) ,m_MultiWidget(NULL) ,m_RenderingManagerObserverTag(0) { RegisterSegmentationObjectFactory(); } QmitkSegmentationView::~QmitkSegmentationView() { // delete m_PostProcessing; delete m_Controls; } void QmitkSegmentationView::NewNodesGenerated() { // ForceDisplayPreferencesUponAllImages(); } void QmitkSegmentationView::NewNodeObjectsGenerated(mitk::ToolManager::DataVectorType* nodes) { if (!nodes) return; mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox->GetToolManager(); if (!toolManager) return; for (mitk::ToolManager::DataVectorType::iterator iter = nodes->begin(); iter != nodes->end(); ++iter) { this->FireNodeSelected( *iter ); // only last iteration meaningful, multiple generated objects are not taken into account here } } void QmitkSegmentationView::Activated() { // should be moved to ::BecomesVisible() or similar if( m_Controls ) { m_Controls->m_ManualToolSelectionBox->setEnabled( true ); m_Controls->m_OrganToolSelectionBox->setEnabled( true ); m_Controls->m_LesionToolSelectionBox->setEnabled( true ); m_Controls->m_SlicesInterpolator->Enable3DInterpolation( m_Controls->widgetStack->currentWidget() == m_Controls->pageManual ); //TODO Remove Observer itk::ReceptorMemberCommand::Pointer command1 = itk::ReceptorMemberCommand::New(); command1->SetCallbackFunction( this, &QmitkSegmentationView::RenderingManagerReinitialized ); m_RenderingManagerObserverTag = mitk::RenderingManager::GetInstance()->AddObserver( mitk::RenderingManagerViewsInitializedEvent(), command1 ); //Adding observers for node visibility to existing segmentations mitk::TNodePredicateDataType::Pointer isImage = mitk::TNodePredicateDataType::New(); mitk::NodePredicateProperty::Pointer isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); mitk::NodePredicateAnd::Pointer isSegmentation = mitk::NodePredicateAnd::New( isImage, isBinary ); mitk::DataStorage::SetOfObjects::ConstPointer segmentations = this->GetDefaultDataStorage()->GetSubset( isSegmentation ); for ( mitk::DataStorage::SetOfObjects::const_iterator iter = segmentations->begin(); iter != segmentations->end(); ++iter) { mitk::DataNode* node = *iter; itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( node, node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); } if(segmentations->Size() > 0) { FireNodeSelected(segmentations->ElementAt(0)); segmentations->ElementAt(0)->GetProperty("visible")->Modified(); } } } void QmitkSegmentationView::Deactivated() { if( m_Controls ) { mitk::RenderingManager::GetInstance()->RemoveObserver( m_RenderingManagerObserverTag ); m_Controls->m_ManualToolSelectionBox->setEnabled( false ); //deactivate all tools m_Controls->m_ManualToolSelectionBox->GetToolManager()->ActivateTool(-1); m_Controls->m_OrganToolSelectionBox->setEnabled( false ); m_Controls->m_LesionToolSelectionBox->setEnabled( false ); m_Controls->m_SlicesInterpolator->EnableInterpolation( false ); //Removing all observers for ( NodeTagMapType::iterator dataIter = m_WorkingDataObserverTags.begin(); dataIter != m_WorkingDataObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("visible")->RemoveObserver( (*dataIter).second ); } m_WorkingDataObserverTags.clear(); // gets the context of the "Mitk" (Core) module (always has id 1) // TODO Workaround until CTL plugincontext is available mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); // Workaround end mitk::ServiceReference serviceRef = context->GetServiceReference(); //mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); mitk::PlanePositionManagerService* service = dynamic_cast(context->GetService(serviceRef)); service->RemoveAllPlanePositions(); } } void QmitkSegmentationView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { SetMultiWidget(&stdMultiWidget); } void QmitkSegmentationView::StdMultiWidgetNotAvailable() { SetMultiWidget(NULL); } void QmitkSegmentationView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { SetMultiWidget(NULL); } void QmitkSegmentationView::SetMultiWidget(QmitkStdMultiWidget* multiWidget) { if (m_MultiWidget) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if (coordinator) { coordinator->RemoveObserver( m_SlicesRotationObserverTag1 ); } coordinator = m_MultiWidget->GetSlicesSwiveller(); if (coordinator) { coordinator->RemoveObserver( m_SlicesRotationObserverTag2 ); } } // save the current multiwidget as the working widget m_MultiWidget = multiWidget; //TODO Remove Observers if (m_MultiWidget) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkSegmentationView::SliceRotation ); m_SlicesRotationObserverTag1 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } coordinator = m_MultiWidget->GetSlicesSwiveller(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkSegmentationView::SliceRotation ); m_SlicesRotationObserverTag2 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } } //TODO End Remove Observers if (m_Parent) { m_Parent->setEnabled(m_MultiWidget); } // tell the interpolation about toolmanager and multiwidget (and data storage) if (m_Controls && m_MultiWidget) { mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox->GetToolManager(); m_Controls->m_SlicesInterpolator->SetDataStorage( *(this->GetDefaultDataStorage())); m_Controls->m_SlicesInterpolator->Initialize( toolManager, m_MultiWidget ); } } void QmitkSegmentationView::OnPreferencesChanged(const berry::IBerryPreferences*) { ForceDisplayPreferencesUponAllImages(); } //TODO remove function void QmitkSegmentationView::RenderingManagerReinitialized(const itk::EventObject&) { CheckImageAlignment(); } //TODO remove function void QmitkSegmentationView::SliceRotation(const itk::EventObject&) { CheckImageAlignment(); } // protected slots void QmitkSegmentationView::CreateNewSegmentation() { mitk::DataNode::Pointer node = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull()) { if (image->GetDimension()>1) { // ask about the name and organ type of the new segmentation QmitkNewSegmentationDialog* dialog = new QmitkNewSegmentationDialog( m_Parent ); // needs a QWidget as parent, "this" is not QWidget QString storedList = QString::fromStdString( this->GetPreferences()->GetByteArray("Organ-Color-List","") ); QStringList organColors; if (storedList.isEmpty()) { organColors = GetDefaultOrganColorString(); } else { /* a couple of examples of how organ names are stored: a simple item is built up like 'name#AABBCC' where #AABBCC is the hexadecimal notation of a color as known from HTML items are stored separated by ';' this makes it necessary to escape occurrences of ';' in name. otherwise the string "hugo;ypsilon#AABBCC;eugen#AABBCC" could not be parsed as two organs but we would get "hugo" and "ypsilon#AABBCC" and "eugen#AABBCC" so the organ name "hugo;ypsilon" is stored as "hugo\;ypsilon" and must be unescaped after loading the following lines could be one split with Perl's negative lookbehind */ // recover string list from BlueBerry view's preferences QString storedString = QString::fromStdString( this->GetPreferences()->GetByteArray("Organ-Color-List","") ); MITK_DEBUG << "storedString: " << storedString.toStdString(); // match a string consisting of any number of repetitions of either "anything but ;" or "\;". This matches everything until the next unescaped ';' QRegExp onePart("(?:[^;]|\\\\;)*"); MITK_DEBUG << "matching " << onePart.pattern().toStdString(); int count = 0; int pos = 0; while( (pos = onePart.indexIn( storedString, pos )) != -1 ) { ++count; int length = onePart.matchedLength(); if (length == 0) break; QString matchedString = storedString.mid(pos, length); MITK_DEBUG << " Captured length " << length << ": " << matchedString.toStdString(); pos += length + 1; // skip separating ';' // unescape possible occurrences of '\;' in the string matchedString.replace("\\;", ";"); // add matched string part to output list organColors << matchedString; } MITK_DEBUG << "Captured " << count << " organ name/colors"; } dialog->SetSuggestionList( organColors ); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; // user clicked cancel or pressed Esc or something similar // ask the user about an organ type and name, add this information to the image's (!) propertylist // create a new image of the same dimensions and smallest possible pixel type mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox->GetToolManager(); mitk::Tool* firstTool = toolManager->GetToolById(0); if (firstTool) { try { mitk::DataNode::Pointer emptySegmentation = firstTool->CreateEmptySegmentationNode( image, dialog->GetSegmentationName().toStdString(), dialog->GetColor() ); //Here we change the reslice interpolation mode for a segmentation, so that contours in rotated slice can be shown correctly emptySegmentation->SetProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New(VTK_RESLICE_LINEAR) ); // initialize showVolume to false to prevent recalculating the volume while working on the segmentation emptySegmentation->SetProperty( "showVolume", mitk::BoolProperty::New( false ) ); if (!emptySegmentation) return; // could be aborted by user UpdateOrganList( organColors, dialog->GetSegmentationName(), dialog->GetColor() ); /* escape ';' here (replace by '\;'), see longer comment above */ std::string stringForStorage = organColors.replaceInStrings(";","\\;").join(";").toStdString(); MITK_DEBUG << "Will store: " << stringForStorage; this->GetPreferences()->PutByteArray("Organ-Color-List", stringForStorage ); this->GetPreferences()->Flush(); if(m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetWorkingData(0)) { m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetWorkingData(0)->SetSelected(false); } emptySegmentation->SetSelected(true); this->GetDefaultDataStorage()->Add( emptySegmentation, node ); // add as a child, because the segmentation "derives" from the original this->FireNodeSelected( emptySegmentation ); this->OnSelectionChanged( emptySegmentation ); this->SetToolManagerSelection(node, emptySegmentation); } catch (std::bad_alloc) { QMessageBox::warning(NULL,"Create new segmentation","Could not allocate memory for new segmentation"); } } } else { QMessageBox::information(NULL,"Segmentation","Segmentation is currently not supported for 2D images"); } } } else { MITK_ERROR << "'Create new segmentation' button should never be clickable unless a patient image is selected..."; } } void QmitkSegmentationView::OnWorkingNodeVisibilityChanged(/*const itk::Object* caller, const itk::EventObject& e*/) { if (!m_Parent || !m_Parent->isVisible()) return; // The new selection behaviour is: // // When clicking on the checkbox of a segmentation the node will e selected and its reference node either // The previous selected segmentation (if there is one) will be deselected. Additionally a reinit on the // selected segmenation will be performed. // If more than one segmentation is selected the tools will be disabled. if (!m_Controls) return; // might happen on initialization (preferences loaded) mitk::DataNode::Pointer referenceDataNew = mitk::DataNode::New(); mitk::DataNode::Pointer workingData; bool workingNodeIsVisible (true); unsigned int numberOfSelectedSegmentations (0); // iterate all images mitk::TNodePredicateDataType::Pointer isImage = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer allImages = this->GetDefaultDataStorage()->GetSubset( isImage ); for ( mitk::DataStorage::SetOfObjects::const_iterator iter = allImages->begin(); iter != allImages->end(); ++iter) { mitk::DataNode* node = *iter; // apply display preferences ApplyDisplayOptions(node); bool isSegmentation(false); node->GetBoolProperty("binary", isSegmentation); if (node->IsSelected() && isSegmentation) { workingNodeIsVisible = node->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); if (!workingNodeIsVisible) return; numberOfSelectedSegmentations++; workingData = node; if (this->GetDefaultDataStorage()->GetSources(node)->Size() != 0) { referenceDataNew = this->GetDefaultDataStorage()->GetSources(node)->ElementAt(0); } bool isBinary(false); //Find topmost source or first source which is no binary image while (referenceDataNew && this->GetDefaultDataStorage()->GetSources(referenceDataNew)->Size() != 0) { referenceDataNew = this->GetDefaultDataStorage()->GetSources(referenceDataNew)->ElementAt(0); referenceDataNew->GetBoolProperty("binary",isBinary); if (!isBinary) break; } if (workingNodeIsVisible && referenceDataNew) { //Since the binary property of a segmentation can be set to false and afterwards you can create a new segmentation out of it //->could lead to a deadloop NodeTagMapType::iterator searchIter = m_WorkingDataObserverTags.find( referenceDataNew ); if ( searchIter != m_WorkingDataObserverTags.end()) { referenceDataNew->GetProperty("visible")->RemoveObserver( (*searchIter).second ); } referenceDataNew->SetVisibility(true); } //set comboBox to reference image disconnect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->refImageSelector->setCurrentIndex( m_Controls->refImageSelector->Find(referenceDataNew) ); connect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); continue; } if (workingData.IsNull() || (workingNodeIsVisible && node != referenceDataNew)) { node->SetVisibility((false)); } } if(numberOfSelectedSegmentations == 1) SetToolManagerSelection(referenceDataNew, workingData); mitk::DataStorage::SetOfObjects::Pointer temp = mitk::DataStorage::SetOfObjects::New(); temp->InsertElement(0,workingData); mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(temp); // initialize the views to the bounding geometry /*mitk::RenderingManager::GetInstance()->InitializeViews(bounds); mitk::RenderingManager::GetInstance()->RequestUpdateAll();*/ } void QmitkSegmentationView::NodeRemoved(const mitk::DataNode* node) { bool isSeg(false); bool isHelperObject(false); node->GetBoolProperty("helper object", isHelperObject); node->GetBoolProperty("binary", isSeg); if(isSeg && !isHelperObject) { mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = this->GetDataStorage()->GetDerivations(node, mitk::NodePredicateProperty::New("isContourMarker" , mitk::BoolProperty::New(true))); // gets the context of the "Mitk" (Core) module (always has id 1) // TODO Workaround until CTL plugincontext is available mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); // Workaround end mitk::ServiceReference serviceRef = context->GetServiceReference(); //mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); mitk::PlanePositionManagerService* service = dynamic_cast(context->GetService(serviceRef)); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; service->RemovePlanePosition(id); this->GetDataStorage()->Remove(it->Value()); } mitk::DataNode* tempNode = const_cast(node); node->GetProperty("visible")->RemoveObserver( m_WorkingDataObserverTags[tempNode] ); m_WorkingDataObserverTags.erase(tempNode); this->SetToolManagerSelection(NULL, NULL); } } void QmitkSegmentationView::CreateSegmentationFromSurface() { mitk::DataNode::Pointer surfaceNode = m_Controls->MaskSurfaces->GetSelectedNode(); mitk::Surface::Pointer surface(0); if(surfaceNode.IsNotNull()) surface = dynamic_cast ( surfaceNode->GetData() ); if(surface.IsNull()) { this->HandleException( "No surface selected.", m_Parent, true); return; } mitk::DataNode::Pointer imageNode = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0); mitk::Image::Pointer image(0); if (imageNode.IsNotNull()) image = dynamic_cast( imageNode->GetData() ); if(image.IsNull()) { this->HandleException( "No image selected.", m_Parent, true); return; } mitk::SurfaceToImageFilter::Pointer s2iFilter = mitk::SurfaceToImageFilter::New(); s2iFilter->MakeOutputBinaryOn(); s2iFilter->SetInput(surface); s2iFilter->SetImage(image); s2iFilter->Update(); mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); std::string nameOfResultImage = imageNode->GetName(); nameOfResultImage.append(surfaceNode->GetName()); resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); resultNode->SetProperty("binary", mitk::BoolProperty::New(true) ); resultNode->SetData( s2iFilter->GetOutput() ); this->GetDataStorage()->Add(resultNode, imageNode); } void QmitkSegmentationView::ManualToolSelected(int id) { // disable crosshair movement when a manual drawing tool is active (otherwise too much visual noise) if (m_MultiWidget) { if (id >= 0) { m_MultiWidget->DisableNavigationControllerEventListening(); } else { m_MultiWidget->EnableNavigationControllerEventListening(); } } } void QmitkSegmentationView::ToolboxStackPageChanged(int id) { // interpolation only with manual tools visible m_Controls->m_SlicesInterpolator->EnableInterpolation( id == 0 ); if( id == 0 ) { mitk::DataNode::Pointer workingData = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetWorkingData(0); if( workingData.IsNotNull() ) { m_Controls->lblSegmentation->setText( workingData->GetName().c_str() ); m_Controls->lblSegImage->show(); m_Controls->lblSegmentation->show(); } } else { m_Controls->lblSegImage->hide(); m_Controls->lblSegmentation->hide(); } // this is just a workaround, should be removed when all tools support 3D+t if (id==2) // lesions { mitk::DataNode::Pointer node = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull()) { if (image->GetDimension()>3) { m_Controls->widgetStack->setCurrentIndex(0); QMessageBox::information(NULL,"Segmentation","Lesion segmentation is currently not supported for 4D images"); } } } } } // protected void QmitkSegmentationView::OnComboBoxSelectionChanged( const mitk::DataNode* node ) { mitk::DataNode* selectedNode = const_cast(node); if( selectedNode != NULL ) { m_Controls->refImageSelector->show(); m_Controls->lblReferenceImageSelectionWarning->hide(); bool isBinary(false); selectedNode->GetBoolProperty("binary", isBinary); if ( isBinary ) { FireNodeSelected(selectedNode); selectedNode->SetVisibility(true); } else if (node != m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0)) { if (m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0)) m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0)->SetVisibility(false); if (m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetWorkingData(0)) { m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetWorkingData(0)->SetVisibility(false); } FireNodeSelected(selectedNode); selectedNode->SetVisibility(true); SetToolManagerSelection(selectedNode, NULL); } } else { m_Controls->refImageSelector->hide(); m_Controls->lblReferenceImageSelectionWarning->show(); } } void QmitkSegmentationView::OnShowMarkerNodes (bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetTools().size(); for(unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetToolById(i)); if (manualSegmentationTool) { if(state == true) { manualSegmentationTool->SetShowMarkerNodes( true ); } else { manualSegmentationTool->SetShowMarkerNodes( false ); } } } } void QmitkSegmentationView::On3DInterpolationEnabled (bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetTools().size(); for(unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetToolById(i)); if (manualSegmentationTool) { manualSegmentationTool->Enable3DInterpolation( state ); } } } void QmitkSegmentationView::OnSelectionChanged(mitk::DataNode* node) { std::vector nodes; nodes.push_back( node ); this->OnSelectionChanged( nodes ); } void QmitkSegmentationView::OnSurfaceSelectionChanged() { // if Image and Surface are selected, enable button if ( (m_Controls->refImageSelector->GetSelectedNode().IsNull()) || (m_Controls->MaskSurfaces->GetSelectedNode().IsNull())) m_Controls->CreateSegmentationFromSurface->setEnabled(false); else m_Controls->CreateSegmentationFromSurface->setEnabled(true); } void QmitkSegmentationView::OnSelectionChanged(std::vector nodes) { // if the selected node is a contourmarker if ( !nodes.empty() ) { std::string markerName = "Position"; unsigned int numberOfNodes = nodes.size(); std::string nodeName = nodes.at( 0 )->GetName(); if ( ( numberOfNodes == 1 ) && ( nodeName.find( markerName ) == 0) ) { this->OnContourMarkerSelected( nodes.at( 0 ) ); } } // if Image and Surface are selected, enable button if ( (m_Controls->refImageSelector->GetSelectedNode().IsNull()) || (m_Controls->MaskSurfaces->GetSelectedNode().IsNull())) m_Controls->CreateSegmentationFromSurface->setEnabled(false); else m_Controls->CreateSegmentationFromSurface->setEnabled(true); if (!m_Parent || !m_Parent->isVisible()) return; // reaction to BlueBerry selection events // this method will try to figure out if a relevant segmentation and its corresponding original image were selected // a warning is issued if the selection is invalid // appropriate reactions are triggered otherwise mitk::DataNode::Pointer referenceData = FindFirstRegularImage( nodes ); //m_Controls->refImageSelector->GetSelectedNode(); //FindFirstRegularImage( nodes ); mitk::DataNode::Pointer workingData = FindFirstSegmentation( nodes ); if(referenceData.IsNull() && workingData.IsNull()) return; bool invalidSelection( !nodes.empty() && ( nodes.size() > 2 || // maximum 2 selected nodes (nodes.size() == 2 && (workingData.IsNull() || referenceData.IsNull()) ) || // with two nodes, one must be the original image, one the segmentation ( workingData.GetPointer() == referenceData.GetPointer() ) //one node is selected as reference and working image // one item is always ok (might be working or reference or nothing ) ); if (invalidSelection) { // TODO visible warning when two images are selected MITK_ERROR << "WARNING: No image, too many (>2) or two equal images were selected."; workingData = NULL; if( m_Controls->refImageSelector->GetSelectedNode().IsNull() ) referenceData = NULL; } if ( workingData.IsNotNull() && referenceData.IsNull() ) { // find the DataStorage parent of workingData // try to find a "normal image" parent, select this as reference image mitk::TNodePredicateDataType::Pointer isImage = mitk::TNodePredicateDataType::New(); mitk::NodePredicateProperty::Pointer isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); mitk::NodePredicateNot::Pointer isNotBinary = mitk::NodePredicateNot::New( isBinary ); mitk::NodePredicateAnd::Pointer isNormalImage = mitk::NodePredicateAnd::New( isImage, isNotBinary ); mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( workingData, isNormalImage ); if (possibleParents->size() > 0) { if (possibleParents->size() > 1) { // TODO visible warning for this rare case MITK_ERROR << "Selected binary image has multiple parents. Using arbitrary first one for segmentation."; } referenceData = (*possibleParents)[0]; } NodeTagMapType::iterator searchIter = m_WorkingDataObserverTags.find( workingData ); if ( searchIter == m_WorkingDataObserverTags.end() ) { //MITK_INFO<<"Creating new observer"; itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( workingData, workingData->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); workingData->GetProperty("visible")->Modified(); return; } if(workingData->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) { //set comboBox to reference image disconnect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->refImageSelector->setCurrentIndex( m_Controls->refImageSelector->Find(workingData) ); connect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); // if Image and Surface are selected, enable button if ( (m_Controls->refImageSelector->GetSelectedNode().IsNull()) || (m_Controls->MaskSurfaces->GetSelectedNode().IsNull()) || (!referenceData)) m_Controls->CreateSegmentationFromSurface->setEnabled(false); else m_Controls->CreateSegmentationFromSurface->setEnabled(true); SetToolManagerSelection(referenceData, workingData); FireNodeSelected(workingData); } else { SetToolManagerSelection(NULL, NULL); FireNodeSelected(workingData); } } else { //set comboBox to reference image disconnect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->refImageSelector->setCurrentIndex( m_Controls->refImageSelector->Find(referenceData) ); connect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); // if Image and Surface are selected, enable button if ( (m_Controls->refImageSelector->GetSelectedNode().IsNull()) || (m_Controls->MaskSurfaces->GetSelectedNode().IsNull()) || (!referenceData)) m_Controls->CreateSegmentationFromSurface->setEnabled(false); else m_Controls->CreateSegmentationFromSurface->setEnabled(true); SetToolManagerSelection(referenceData, workingData); FireNodeSelected(referenceData); } } void QmitkSegmentationView::OnContourMarkerSelected(const mitk::DataNode *node) { //TODO renderWindow anders bestimmen, siehe CheckAlignment QmitkRenderWindow* selectedRenderWindow = 0; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); bool PlanarFigureInitializedWindow = false; // find initialized renderwindow if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } // make node visible if (selectedRenderWindow) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; // gets the context of the "Mitk" (Core) module (always has id 1) // TODO Workaround until CTL plugincontext is available mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); // Workaround end mitk::ServiceReference serviceRef = context->GetServiceReference(); //mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); mitk::PlanePositionManagerService* service = dynamic_cast(context->GetService(serviceRef)); selectedRenderWindow->GetSliceNavigationController()->ExecuteOperation(service->GetPlanePosition(id)); selectedRenderWindow->GetRenderer()->GetDisplayGeometry()->Fit(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } mitk::DataNode::Pointer QmitkSegmentationView::FindFirstRegularImage( std::vector nodes ) { if (nodes.empty()) return NULL; for(unsigned int i = 0; i < nodes.size(); ++i) { //mitk::DataNode::Pointer node = i.value() bool isImage(false); if (nodes.at(i)->GetData()) { isImage = dynamic_cast(nodes.at(i)->GetData()) != NULL; } // make sure this is not a binary image bool isSegmentation(false); nodes.at(i)->GetBoolProperty("binary", isSegmentation); // return first proper mitk::Image if (isImage && !isSegmentation) return nodes.at(i); } return NULL; } mitk::DataNode::Pointer QmitkSegmentationView::FindFirstSegmentation( std::vector nodes ) { if (nodes.empty()) return NULL; for(unsigned int i = 0; i < nodes.size(); ++i) { bool isImage(false); if (nodes.at(i)->GetData()) { isImage = dynamic_cast(nodes.at(i)->GetData()) != NULL; } bool isSegmentation(false); nodes.at(i)->GetBoolProperty("binary", isSegmentation); // return first proper binary mitk::Image if (isImage && isSegmentation) { return nodes.at(i); } } return NULL; } void QmitkSegmentationView::SetToolManagerSelection(const mitk::DataNode* referenceData, const mitk::DataNode* workingData) { // called as a result of new BlueBerry selections // tells the ToolManager for manual segmentation about new selections // updates GUI information about what the user should select mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox->GetToolManager(); toolManager->SetReferenceData(const_cast(referenceData)); toolManager->SetWorkingData( const_cast(workingData)); // check original image m_Controls->btnNewSegmentation->setEnabled(referenceData != NULL); if (referenceData) { m_Controls->lblReferenceImageSelectionWarning->hide(); } else { m_Controls->lblReferenceImageSelectionWarning->show(); m_Controls->lblWorkingImageSelectionWarning->hide(); m_Controls->lblSegImage->hide(); m_Controls->lblSegmentation->hide(); } //TODO remove statement // check, wheter reference image is aligned like render windows. Otherwise display a visible warning (because 2D tools will probably not work) CheckImageAlignment(); // check segmentation if (referenceData) { if (!workingData) { m_Controls->lblWorkingImageSelectionWarning->show(); if( m_Controls->widgetStack->currentIndex() == 0 ) { m_Controls->lblSegImage->hide(); m_Controls->lblSegmentation->hide(); } } else { m_Controls->lblWorkingImageSelectionWarning->hide(); this->FireNodeSelected(const_cast(workingData)); if( m_Controls->widgetStack->currentIndex() == 0 ) { m_Controls->lblSegmentation->setText( workingData->GetName().c_str() ); m_Controls->lblSegmentation->show(); m_Controls->lblSegImage->show(); } } } } //TODO remove function void QmitkSegmentationView::CheckImageAlignment() { bool wrongAlignment(true); mitk::DataNode::Pointer node = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull() && m_MultiWidget) { wrongAlignment = !( IsRenderWindowAligned(m_MultiWidget->GetRenderWindow1(), image ) && IsRenderWindowAligned(m_MultiWidget->GetRenderWindow2(), image ) && IsRenderWindowAligned(m_MultiWidget->GetRenderWindow3(), image ) ); } if (wrongAlignment) { m_Controls->lblAlignmentWarning->show(); } } } //TODO remove function bool QmitkSegmentationView::IsRenderWindowAligned(QmitkRenderWindow* renderWindow, mitk::Image* image) { if (!renderWindow) return false; // for all 2D renderwindows of m_MultiWidget check alignment mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast( renderWindow->GetRenderer()->GetCurrentWorldGeometry2D() ); if (displayPlane.IsNull()) return false; int affectedDimension(-1); int affectedSlice(-1); return mitk::SegTool2D::DetermineAffectedImageSlice( image, displayPlane, affectedDimension, affectedSlice ); } //TODO remove function void QmitkSegmentationView::ForceDisplayPreferencesUponAllImages() { if (!m_Parent || !m_Parent->isVisible()) return; // check all images and segmentations in DataStorage: // (items in brackets are implicitly done by previous steps) // 1. // if a reference image is selected, // show the reference image // and hide all other images (orignal and segmentation), // (and hide all segmentations of the other original images) // and show all the reference's segmentations // if no reference image is selected, do do nothing // // 2. // if a segmentation is selected, // show it // (and hide all all its siblings (childs of the same parent, incl, NULL parent)) // if no segmentation is selected, do nothing if (!m_Controls) return; // might happen on initialization (preferences loaded) mitk::DataNode::Pointer referenceData = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetReferenceData(0); mitk::DataNode::Pointer workingData = m_Controls->m_ManualToolSelectionBox->GetToolManager()->GetWorkingData(0); // 1. if (referenceData.IsNotNull()) { // iterate all images mitk::TNodePredicateDataType::Pointer isImage = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer allImages = this->GetDefaultDataStorage()->GetSubset( isImage ); //mitk::DataStorage::SetOfObjects::ConstPointer allSegmentationChilds = this->GetDefaultDataStorage()->GetDerivations(referenceData, isImage ); for ( mitk::DataStorage::SetOfObjects::const_iterator iter = allImages->begin(); iter != allImages->end(); ++iter) { mitk::DataNode* node = *iter; // apply display preferences ApplyDisplayOptions(node); // set visibility if(!node->IsSelected() || (node->IsSelected() && !node->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))))) node->SetVisibility((node == referenceData) || node->IsSelected() ); } } // 2. //if (workingData.IsNotNull() && !workingData->IsSelected()) //{ // workingData->SetVisibility(true); //} mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::ApplyDisplayOptions(mitk::DataNode* node) { if (!node) return; bool isBinary(false); node->GetPropertyValue("binary", isBinary); if (isBinary) { node->SetProperty( "outline binary", mitk::BoolProperty::New( this->GetPreferences()->GetBool("draw outline", true)) ); node->SetProperty( "outline width", mitk::FloatProperty::New( 2.0 ) ); node->SetProperty( "opacity", mitk::FloatProperty::New( this->GetPreferences()->GetBool("draw outline", true) ? 1.0 : 0.3 ) ); node->SetProperty( "volumerendering", mitk::BoolProperty::New( this->GetPreferences()->GetBool("volume rendering", false) ) ); } } void QmitkSegmentationView::CreateQtPartControl(QWidget* parent) { // setup the basic GUI of this view m_Parent = parent; m_Controls = new Ui::QmitkSegmentationControls; m_Controls->setupUi(parent); m_Controls->lblWorkingImageSelectionWarning->hide(); m_Controls->lblAlignmentWarning->hide(); m_Controls->lblSegImage->hide(); m_Controls->lblSegmentation->hide(); m_Controls->refImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->refImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); if( m_Controls->refImageSelector->GetSelectedNode().IsNotNull() ) m_Controls->lblReferenceImageSelectionWarning->hide(); else m_Controls->refImageSelector->hide(); mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox->GetToolManager(); toolManager->SetDataStorage( *(this->GetDefaultDataStorage()) ); assert ( toolManager ); // all part of open source MITK m_Controls->m_ManualToolSelectionBox->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer ); m_Controls->m_ManualToolSelectionBox->SetDisplayedToolGroups("Add Subtract Paint Wipe 'Region Growing' Correction Fill Erase"); m_Controls->m_ManualToolSelectionBox->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingData ); // available only in the 3M application if ( !m_Controls->m_OrganToolSelectionBox->children().count() ) { m_Controls->widgetStack->setItemEnabled( 1, false ); } m_Controls->m_OrganToolSelectionBox->SetToolManager( *toolManager ); m_Controls->m_OrganToolSelectionBox->SetToolGUIArea( m_Controls->m_OrganToolGUIContainer ); m_Controls->m_OrganToolSelectionBox->SetDisplayedToolGroups("'Hippocampus left' 'Hippocampus right' 'Lung left' 'Lung right' 'Liver' 'Heart LV' 'Endocard LV' 'Epicard LV' 'Prostate'"); m_Controls->m_OrganToolSelectionBox->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceData ); // available only in the 3M application if ( !m_Controls->m_LesionToolSelectionBox->children().count() ) { m_Controls->widgetStack->setItemEnabled( 2, false ); } m_Controls->m_LesionToolSelectionBox->SetToolManager( *toolManager ); m_Controls->m_LesionToolSelectionBox->SetToolGUIArea( m_Controls->m_LesionToolGUIContainer ); m_Controls->m_LesionToolSelectionBox->SetDisplayedToolGroups("'Lymph Node'"); m_Controls->m_LesionToolSelectionBox->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceData ); toolManager->NewNodesGenerated += mitk::MessageDelegate( this, &QmitkSegmentationView::NewNodesGenerated ); // update the list of segmentations toolManager->NewNodeObjectsGenerated += mitk::MessageDelegate1( this, &QmitkSegmentationView::NewNodeObjectsGenerated ); // update the list of segmentations // create signal/slot connections connect( m_Controls->refImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->btnNewSegmentation, SIGNAL(clicked()), this, SLOT(CreateNewSegmentation()) ); connect( m_Controls->CreateSegmentationFromSurface, SIGNAL(clicked()), this, SLOT(CreateSegmentationFromSurface()) ); connect( m_Controls->m_ManualToolSelectionBox, SIGNAL(ToolSelected(int)), this, SLOT(ManualToolSelected(int)) ); connect( m_Controls->widgetStack, SIGNAL(currentChanged(int)), this, SLOT(ToolboxStackPageChanged(int)) ); connect(m_Controls->MaskSurfaces, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSurfaceSelectionChanged( ) ) ); connect(m_Controls->MaskSurfaces, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSurfaceSelectionChanged( ) ) ); connect(m_Controls->m_SlicesInterpolator, SIGNAL(SignalShowMarkerNodes(bool)), this, SLOT(OnShowMarkerNodes(bool))); connect(m_Controls->m_SlicesInterpolator, SIGNAL(Signal3DInterpolationEnabled(bool)), this, SLOT(On3DInterpolationEnabled(bool))); m_Controls->MaskSurfaces->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->MaskSurfaces->SetPredicate(mitk::NodePredicateDataType::New("Surface")); //// create helper class to provide context menus for segmentations in data manager // m_PostProcessing = new QmitkSegmentationPostProcessing(this->GetDefaultDataStorage(), this, m_Parent); } //void QmitkSegmentationView::OnPlaneModeChanged(int i) //{ // //if plane mode changes, disable all tools // if (m_MultiWidget) // { // mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox->GetToolManager(); // // if (toolManager) // { // if (toolManager->GetActiveToolID() >= 0) // { // toolManager->ActivateTool(-1); // } // else // { // m_MultiWidget->EnableNavigationControllerEventListening(); // } // } // } //} // ATTENTION some methods for handling the known list of (organ names, colors) are defined in QmitkSegmentationOrganNamesHandling.cpp diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h index 4da59269b7..ee3296d2ac 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h @@ -1,168 +1,168 @@ -/*====================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ #ifndef QmitkSegmentationView_h #define QmitkSegmentationView_h #include "QmitkFunctionality.h" #include #include "ui_QmitkSegmentationControls.h" class QmitkRenderWindow; // class QmitkSegmentationPostProcessing; /** * \ingroup ToolManagerEtAl * \ingroup org_mitk_gui_qt_segmentation_internal * \warning Implementation of this class is split up into two .cpp files to make things more compact. Check both this file and QmitkSegmentationOrganNamesHandling.cpp */ class QmitkSegmentationView : public QmitkFunctionality { Q_OBJECT public: QmitkSegmentationView(); virtual ~QmitkSegmentationView(); typedef std::map NodeTagMapType; /*! \brief Invoked when the DataManager selection changed */ virtual void OnSelectionChanged(mitk::DataNode* node); virtual void OnSelectionChanged(std::vector nodes); // reaction to new segmentations being created by segmentation tools void NewNodesGenerated(); void NewNodeObjectsGenerated(mitk::ToolManager::DataVectorType*); // QmitkFunctionality's activate/deactivate virtual void Activated(); virtual void Deactivated(); // QmitkFunctionality's changes regarding THE QmitkStdMultiWidget virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void StdMultiWidgetClosed(QmitkStdMultiWidget& stdMultiWidget); // BlueBerry's notification about preference changes (e.g. from a dialog) virtual void OnPreferencesChanged(const berry::IBerryPreferences*); // observer to mitk::RenderingManager's RenderingManagerViewsInitializedEvent event void RenderingManagerReinitialized(const itk::EventObject&); // observer to mitk::SliceController's SliceRotation event void SliceRotation(const itk::EventObject&); static const std::string VIEW_ID; protected slots: void OnComboBoxSelectionChanged(const mitk::DataNode* node); // reaction to the button "New segmentation" void CreateNewSegmentation(); // reaction to the button "New segmentation" void CreateSegmentationFromSurface(); // called when a segmentation tool is activated void ManualToolSelected(int id); // called when one of "Manual", "Organ", "Lesion" pages of the QToolbox is selected void ToolboxStackPageChanged(int id); void OnSurfaceSelectionChanged(); //called when the checkbox Remember Contour Positions is selected/deselected void OnWorkingNodeVisibilityChanged(); void OnShowMarkerNodes(bool); void On3DInterpolationEnabled(bool); protected: // a type for handling lists of DataNodes typedef std::vector NodeList; // set available multiwidget void SetMultiWidget(QmitkStdMultiWidget* multiWidget); // actively query the current selection of data manager //void PullCurrentDataManagerSelection(); // reactions to selection events from data manager (and potential other senders) //void BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection); mitk::DataNode::Pointer FindFirstRegularImage( std::vector nodes ); mitk::DataNode::Pointer FindFirstSegmentation( std::vector nodes ); // propagate BlueBerry selection to ToolManager for manual segmentation void SetToolManagerSelection(const mitk::DataNode* referenceData, const mitk::DataNode* workingData); // checks if selected reference image is aligned with the slices stack orientation of the StdMultiWidget void CheckImageAlignment(); // checks if given render window aligns with the slices of given image bool IsRenderWindowAligned(QmitkRenderWindow* renderWindow, mitk::Image* image); // make sure all images/segmentations look as selected by the users in this view's preferences void ForceDisplayPreferencesUponAllImages(); // decorates a DataNode according to the user preference settings void ApplyDisplayOptions(mitk::DataNode* node); // GUI setup void CreateQtPartControl(QWidget* parent); // handling of a list of known (organ name, organ color) combination // ATTENTION these methods are defined in QmitkSegmentationOrganNamesHandling.cpp QStringList GetDefaultOrganColorString(); void UpdateOrganList(QStringList& organColors, const QString& organname, mitk::Color colorname); void AppendToOrganList(QStringList& organColors, const QString& organname, int r, int g, int b); // If a contourmarker is selected, the plane in the related widget will be reoriented according to the marker`s geometry void OnContourMarkerSelected (const mitk::DataNode* node); void NodeRemoved(const mitk::DataNode* node); // the Qt parent of our GUI (NOT of this object) QWidget* m_Parent; // our GUI Ui::QmitkSegmentationControls * m_Controls; // THE currently existing QmitkStdMultiWidget QmitkStdMultiWidget * m_MultiWidget; // QmitkSegmentationPostProcessing* m_PostProcessing; unsigned long m_RenderingManagerObserverTag; unsigned long m_SlicesRotationObserverTag1; unsigned long m_SlicesRotationObserverTag2; unsigned long m_VisibilityChangedObserverTag; NodeTagMapType m_WorkingDataObserverTags; }; #endif /*QMITKsegmentationVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.cpp index c3b2bbcd69..a1280b58c7 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.cpp @@ -1,88 +1,87 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkRegionGrowingView.h" #include "QmitkStdMultiWidget.h" const std::string QmitkRegionGrowingView::VIEW_ID = "org.mitk.views.regiongrowing"; QmitkRegionGrowingView::QmitkRegionGrowingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkRegionGrowingView::~QmitkRegionGrowingView() { } void QmitkRegionGrowingView::Deactivated() { } void QmitkRegionGrowingView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkRegionGrowingViewControls; m_Controls->setupUi( parent ); m_Controls->m_AdaptiveRGWidget->SetDataStorage(this->GetDataStorage()); m_Controls->m_AdaptiveRGWidget->CreateConnections(); } } void QmitkRegionGrowingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; m_Controls->m_AdaptiveRGWidget->SetMultiWidget(&stdMultiWidget); } void QmitkRegionGrowingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkRegionGrowingView::OnSelectionChanged( std::vector nodes ) { // iterate all selected objects, adjust warning visibility for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_Controls->lblWarning->setVisible( false ); m_Controls->m_AdaptiveRGWidget->SetInputImageNode(node); return; } } m_Controls->lblWarning->setVisible( true ); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.h index f286d80523..f67cbc22a2 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/regiongrowing/QmitkRegionGrowingView.h @@ -1,82 +1,81 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 17495 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkRegionGrowingView_h #define QmitkRegionGrowingView_h #include #include #include "ui_QmitkRegionGrowingViewControls.h" /*! \brief QmitkRegionGrowingView Functionality for demonstration of MITK basics. This functionality allows the user to set some seed points that are used for a simple region growing algorithm from ITK. \warning This is only for demonstration, it is NOT meant to be useful! \sa QmitkFunctionality \ingroup Functionalities */ class QmitkRegionGrowingView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkRegionGrowingView(); virtual ~QmitkRegionGrowingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void Deactivated(); protected slots: protected: /*! \brief ITK image processing function This function is templated like an ITK image. The MITK-Macro AccessByItk determines the actual pixel type and dimensionality of a given MITK image and calls this function for further processing (in our case region growing) */ template < typename TPixel, unsigned int VImageDimension > void ItkImageProcessing( itk::Image< TPixel, VImageDimension >* itkImage, mitk::Geometry3D* imageGeometry, mitk::DataNode* parent, int thresholdOffset, unsigned int t ); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkRegionGrowingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; }; #endif // _QMITKREGIONGROWINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/segmentation.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/segmentation.h index 05f54459cb..8ee1447fe9 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/segmentation.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/segmentation.h @@ -1,101 +1,100 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _QEMBED_1804289383 #define _QEMBED_1804289383 #include #include static const QRgb segmentation_data[] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1000000, 0x3000000,0x3000000,0x3000000,0x2000000,0x1000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x1000000,0x36000000,0x84000000,0xa3000000,0xff000000,0xff000000,0xff000000,0xb4000000,0x93000000,0x54000000,0x1a000000, 0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xa000000,0x9b000000,0xee4b4b4a,0xffb4b2b1,0xffdfdedd, 0xffe4e3e0,0xffe3e1dd,0xffc2beb5,0xffc1bdb4,0xffbab5ab,0xffd1cdc7,0xff919191,0xbc292929,0x69000000,0x11000000,0x1000000,0x0,0x0,0x0, 0x0,0x1000000,0x29000000,0xff414140,0xffd9d9d7,0xfff0efef,0xffc8c7c5,0xff6d6b6a,0xff494947,0xff2b2b2b,0xff161616,0xff262522,0xff3e3d39,0xff56534e, 0xff87837d,0xffd0ceca,0xff6f6e6d,0x71000000,0x9000000,0x1000000,0x0,0x0,0x3000000,0x18000000,0xff474544,0xffe3e2e1,0xffb9b9b8,0xe8242424, 0xbb0a0a0a,0x76000000,0x60000000,0x50000000,0x49000000,0x6b000000,0x51000000,0x79000000,0xca000000,0xff343230,0xffb7b4ad,0xbe000000,0x1b000000,0x6000000, 0x0,0x0,0xd000000,0xff494947,0xffd1d1d0,0xff656564,0x9a000000,0x55000000,0x36000000,0x29000000,0x20000000,0x1c000000,0x1c000000,0x1c000000, 0x1c000000,0x1c000000,0x67000000,0xeb333333,0xffc1bfbc,0xff000000,0x2f000000,0xe000000,0x0,0x0,0xb4000000,0xffd5d5d2,0xff747371,0x7f000000, 0x42000000,0x26000000,0x14000000,0xb000000,0x6000000,0x4000000,0x4000000,0x4000000,0x29000000,0x8b131313,0xdb6a6a6a,0xffd7d6d4,0xff969692,0xcb000000, 0x39000000,0x14000000,0x0,0x2000000,0xff000000,0xffd8d6d2,0xff000000,0x4e000000,0x2b000000,0xe000000,0x4000000,0x1000000,0x0,0x1000000, 0x5e000000,0xbe3d3d3d,0xe26c6c6c,0xf8d6d6d4,0xffe0dfde,0xff787774,0xff22211f,0x66000000,0x2f000000,0xe000000,0x0,0x2000000,0x91000000,0xff8b8881, 0xff262422,0xe8201f1e,0xac000000,0x12000000,0x8000000,0x59000000,0xa2202020,0xdf727272,0xffa3a3a2,0xffe4e2df,0xffe7e5e3,0xff71706c,0xff262624,0xff000000, 0x61000000,0x3e000000,0x1b000000,0x6000000,0x0,0x2000000,0x3b000000,0xff000000,0xffd7d7d3,0xffe2e0dc,0xffe2dfdc,0xff0b0b0b,0xff484846,0xff939291, 0xffc4c1be,0xffd6d4ce,0xffa7a49e,0xff383735,0xf0090908,0xcc000000,0x53000000,0x48000000,0x3c000000,0x21000000,0xa000000,0x1000000,0x0,0x1000000, 0xe5000000,0xffe0dedd,0xffcfcbc4,0xff63605c,0xffb8b5b0,0xffb2b1ad,0xff5c5b57,0xff837f79,0xff3c3a36,0xea000000,0xde000000,0x54000000,0x46000000,0x3c000000, 0x2f000000,0x22000000,0x16000000,0x9000000,0x2000000,0x0,0x0,0x2000000,0xb7000000,0xffd0cdc6,0xff999692,0xff66645d,0xff151515,0xffa6a5a1, 0xff000000,0xd8000000,0x60000000,0x46000000,0x3a000000,0x2f000000,0x21000000,0x16000000,0xe000000,0x7000000,0x3000000,0x1000000,0x0,0x0, 0x0,0x2000000,0xf000000,0xff363636,0xff817f7b,0xff393633,0xff8c8884,0xff0b0b0b,0x7a000000,0x4a000000,0x34000000,0x21000000,0x16000000,0xe000000, 0x7000000,0x3000000,0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7000000,0x1d000000,0xc2000000,0xff000000, 0xffafaca6,0xd8000000,0x4c000000,0x2a000000,0x12000000,0x7000000,0x3000000,0x2000000,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x2000000,0xa000000,0x1f000000,0xdc6c6965,0xffdbdad5,0xd5000000,0x3c000000,0x17000000,0x4000000,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2000000, 0xd40c0c0c,0xffdad7d2,0xf4212121,0x9b000000,0x2e000000,0xe000000,0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1000000,0xc000000,0xd0000000,0x71000000,0x37000000,0x1a000000,0x6000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x6000000,0x17000000,0x24000000,0x1a000000,0x9000000,0x1000000,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1000000,0x6000000,0xa000000,0x6000000, 0x1000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x1000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0 }; /* Generated by qembed */ static struct EmbedImage { int width, height, depth; const unsigned char *data; int numColors; const QRgb *colorTable; bool alpha; const char *name; } embed_image_vec[] = { { 22, 22, 32, (const unsigned char*)segmentation_data, 0, 0, TRUE, "segmentation" }, { 0, 0, 0, 0, 0, 0, 0, 0 } }; static const QImage& qembed_findImage( const QString& name ) { static QDict dict; QImage* img = dict.find( name ); if ( !img ) { for ( int i = 0; embed_image_vec[i].data; i++ ) { if ( strcmp(embed_image_vec[i].name, name.latin1()) == 0 ) { img = new QImage((uchar*)embed_image_vec[i].data, embed_image_vec[i].width, embed_image_vec[i].height, embed_image_vec[i].depth, (QRgb*)embed_image_vec[i].colorTable, embed_image_vec[i].numColors, QImage::BigEndian ); if ( embed_image_vec[i].alpha ) img->setAlphaBuffer( TRUE ); dict.insert( name, img ); break; } } if ( !img ) { static QImage dummy; return dummy; } } return *img; } #endif diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp index 144d9de965..1f8e7b4b0c 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp @@ -1,407 +1,406 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkStdMultiWidgetEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include class QmitkStdMultiWidgetEditorPrivate { public: QmitkStdMultiWidgetEditorPrivate(); ~QmitkStdMultiWidgetEditorPrivate(); QmitkStdMultiWidget* m_StdMultiWidget; QmitkMouseModeSwitcher* m_MouseModeToolbar; std::string m_FirstBackgroundColor; std::string m_SecondBackgroundColor; berry::IPartListener::Pointer m_PartListener; QHash m_RenderWindows; }; struct QmitkStdMultiWidgetPartListener : public berry::IPartListener { berryObjectMacro(QmitkStdMultiWidgetPartListener) QmitkStdMultiWidgetPartListener(QmitkStdMultiWidgetEditorPrivate* dd) : d(dd) {} Events::Types GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartClosed (berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void PartHidden (berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void PartVisible (berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->AddPlanesToDataStorage(); } } } private: QmitkStdMultiWidgetEditorPrivate* const d; }; QmitkStdMultiWidgetEditorPrivate::QmitkStdMultiWidgetEditorPrivate() : m_StdMultiWidget(0), m_MouseModeToolbar(0) , m_PartListener(new QmitkStdMultiWidgetPartListener(this)) {} QmitkStdMultiWidgetEditorPrivate::~QmitkStdMultiWidgetEditorPrivate() { } const std::string QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : d(new QmitkStdMultiWidgetEditorPrivate) { } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { this->GetSite()->GetPage()->RemovePartListener(d->m_PartListener); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return d->m_StdMultiWidget; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetActiveRenderWindow() const { if (d->m_StdMultiWidget) return d->m_StdMultiWidget->GetRenderWindow1(); return 0; } QHash QmitkStdMultiWidgetEditor::GetRenderWindows() const { return d->m_RenderWindows; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetRenderWindow(const QString &id) const { if (d->m_RenderWindows.contains(id)) return d->m_RenderWindows[id]; return 0; } mitk::Point3D QmitkStdMultiWidgetEditor::GetSelectedPosition(const QString & /*id*/) const { return d->m_StdMultiWidget->GetCrossPosition(); } void QmitkStdMultiWidgetEditor::SetSelectedPosition(const mitk::Point3D &pos, const QString &/*id*/) { d->m_StdMultiWidget->MoveCrossToPosition(pos); } void QmitkStdMultiWidgetEditor::EnableDecorations(bool enable, const QStringList &decorations) { if (decorations.isEmpty() || decorations.contains(DECORATION_BORDER)) { enable ? d->m_StdMultiWidget->EnableColoredRectangles() : d->m_StdMultiWidget->DisableColoredRectangles(); } if (decorations.isEmpty() || decorations.contains(DECORATION_LOGO)) { enable ? d->m_StdMultiWidget->EnableDepartmentLogo() : d->m_StdMultiWidget->DisableDepartmentLogo(); } if (decorations.isEmpty() || decorations.contains(DECORATION_MENU)) { d->m_StdMultiWidget->ActivateMenuWidget(enable); } if (decorations.isEmpty() || decorations.contains(DECORATION_BACKGROUND)) { enable ? d->m_StdMultiWidget->EnableGradientBackground() : d->m_StdMultiWidget->DisableGradientBackground(); } } bool QmitkStdMultiWidgetEditor::IsDecorationEnabled(const QString &decoration) const { if (decoration == DECORATION_BORDER) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_LOGO) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_MENU) { return d->m_StdMultiWidget->IsMenuWidgetEnabled(); } else if (decoration == DECORATION_BACKGROUND) { return d->m_StdMultiWidget->GetGradientBackgroundFlag(); } return false; } QStringList QmitkStdMultiWidgetEditor::GetDecorations() const { QStringList decorations; decorations << DECORATION_BORDER << DECORATION_LOGO << DECORATION_MENU << DECORATION_BACKGROUND; return decorations; } mitk::SlicesRotator* QmitkStdMultiWidgetEditor::GetSlicesRotator() const { return d->m_StdMultiWidget->GetSlicesRotator(); } mitk::SlicesSwiveller* QmitkStdMultiWidgetEditor::GetSlicesSwiveller() const { return d->m_StdMultiWidget->GetSlicesSwiveller(); } void QmitkStdMultiWidgetEditor::EnableSlicingPlanes(bool enable) { d->m_StdMultiWidget->SetWidgetPlanesVisibility(enable); } bool QmitkStdMultiWidgetEditor::IsSlicingPlanesEnabled() const { mitk::DataNode::Pointer node = this->d->m_StdMultiWidget->GetWidgetPlane1(); if (node.IsNotNull()) { bool visible = false; node->GetVisibility(visible, 0); return visible; } else { return false; } } void QmitkStdMultiWidgetEditor::EnableLinkedNavigation(bool enable) { enable ? d->m_StdMultiWidget->EnableNavigationControllerEventListening() : d->m_StdMultiWidget->DisableNavigationControllerEventListening(); } bool QmitkStdMultiWidgetEditor::IsLinkedNavigationEnabled() const { return d->m_StdMultiWidget->IsCrosshairNavigationEnabled(); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (d->m_StdMultiWidget == 0) { QVBoxLayout* layout = new QVBoxLayout(parent); layout->setContentsMargins(0,0,0,0); if (d->m_MouseModeToolbar == NULL) { d->m_MouseModeToolbar = new QmitkMouseModeSwitcher(parent); // delete by Qt via parent layout->addWidget(d->m_MouseModeToolbar); } d->m_StdMultiWidget = new QmitkStdMultiWidget(parent); d->m_RenderWindows.insert("transversal", d->m_StdMultiWidget->GetRenderWindow1()); d->m_RenderWindows.insert("sagittal", d->m_StdMultiWidget->GetRenderWindow2()); d->m_RenderWindows.insert("coronal", d->m_StdMultiWidget->GetRenderWindow3()); d->m_RenderWindows.insert("3d", d->m_StdMultiWidget->GetRenderWindow4()); d->m_MouseModeToolbar->setMouseModeSwitcher( d->m_StdMultiWidget->GetMouseModeSwitcher() ); connect( d->m_MouseModeToolbar, SIGNAL( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ), d->m_StdMultiWidget, SLOT( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ) ); layout->addWidget(d->m_StdMultiWidget); mitk::DataStorage::Pointer ds = this->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render d->m_StdMultiWidget->SetDataStorage(ds); // Initialize views as transversal, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view d->m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider d->m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D d->m_StdMultiWidget->AddDisplayPlaneSubTree(); d->m_StdMultiWidget->EnableNavigationControllerEventListening(); this->GetSite()->GetPage()->AddPartListener(d->m_PartListener); berry::IPreferences::Pointer prefs = this->GetPreferences(); this->OnPreferencesChanged(dynamic_cast(prefs.GetPointer())); this->RequestUpdate(); } } void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { // enable change of logo std::string departmentLogoLocation = prefs->Get("DepartmentLogo",""); if (departmentLogoLocation.empty()) { d->m_StdMultiWidget->DisableDepartmentLogo(); } else { d->m_StdMultiWidget->SetDepartmentLogoPath(departmentLogoLocation.c_str()); d->m_StdMultiWidget->EnableDepartmentLogo(); } // preferences for gradient background float color = 255.0; QString firstColorName = QString::fromStdString (prefs->GetByteArray("first background color", "")); QColor firstColor(firstColorName); mitk::Color upper; if (firstColorName=="") // default values { upper[0] = 0.1; upper[1] = 0.1; upper[2] = 0.1; } else { upper[0] = firstColor.red() / color; upper[1] = firstColor.green() / color; upper[2] = firstColor.blue() / color; } QString secondColorName = QString::fromStdString (prefs->GetByteArray("second background color", "")); QColor secondColor(secondColorName); mitk::Color lower; if (secondColorName=="") // default values { lower[0] = 0.5; lower[1] = 0.5; lower[2] = 0.5; } else { lower[0] = secondColor.red() / color; lower[1] = secondColor.green() / color; lower[2] = secondColor.blue() / color; } d->m_StdMultiWidget->SetGradientBackgroundColors(upper, lower); d->m_StdMultiWidget->EnableGradientBackground(); // Set preferences respecting zooming and padding bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // level window setting bool showLevelWindowWidget = prefs->GetBool("Show level/window widget", true); if (showLevelWindowWidget) { d->m_StdMultiWidget->EnableStandardLevelWindow(); } else { d->m_StdMultiWidget->DisableStandardLevelWindow(); } // mouse modes toolbar bool newMode = prefs->GetBool("PACS like mouse interaction", false); d->m_MouseModeToolbar->setVisible( newMode ); d->m_StdMultiWidget->GetMouseModeSwitcher()->SetInteractionScheme( newMode ? mitk::MouseModeSwitcher::PACS : mitk::MouseModeSwitcher::MITK ); } void QmitkStdMultiWidgetEditor::SetFocus() { if (d->m_StdMultiWidget != 0) d->m_StdMultiWidget->setFocus(); } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h index 81632f42c4..f0012cfa36 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h @@ -1,117 +1,116 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKSTDMULTIWIDGETEDITOR_H_ #define QMITKSTDMULTIWIDGETEDITOR_H_ #include #include #include class QmitkStdMultiWidget; class QmitkMouseModeSwitcher; class QmitkStdMultiWidgetEditorPrivate; /** * \ingroup org_mitk_gui_qt_stdmultiwidgeteditor */ class ORG_MITK_GUI_QT_STDMULTIWIDGETEDITOR QmitkStdMultiWidgetEditor : public QmitkAbstractRenderEditor, public mitk::ILinkedRenderWindowPart { Q_OBJECT public: berryObjectMacro(QmitkStdMultiWidgetEditor) static const std::string EDITOR_ID; QmitkStdMultiWidgetEditor(); ~QmitkStdMultiWidgetEditor(); QmitkStdMultiWidget* GetStdMultiWidget(); // ------------------- mitk::IRenderWindowPart ---------------------- /** * \see mitk::IRenderWindowPart::GetActiveRenderWindow() */ QmitkRenderWindow* GetActiveRenderWindow() const; /** * \see mitk::IRenderWindowPart::GetRenderWindows() */ QHash GetRenderWindows() const; /** * \see mitk::IRenderWindowPart::GetRenderWindow(QString) */ QmitkRenderWindow* GetRenderWindow(const QString& id) const; /** * \see mitk::IRenderWindowPart::GetSelectionPosition() */ mitk::Point3D GetSelectedPosition(const QString& id = QString()) const; /** * \see mitk::IRenderWindowPart::SetSelectedPosition() */ void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()); /** * \see mitk::IRenderWindowPart::EnableDecorations() */ void EnableDecorations(bool enable, const QStringList& decorations = QStringList()); /** * \see mitk::IRenderWindowPart::IsDecorationEnabled() */ bool IsDecorationEnabled(const QString& decoration) const; /** * \see mitk::IRenderWindowPart::GetDecorations() */ QStringList GetDecorations() const; // ------------------- mitk::ILinkedRenderWindowPart ---------------------- mitk::SlicesRotator* GetSlicesRotator() const; mitk::SlicesSwiveller* GetSlicesSwiveller() const; void EnableSlicingPlanes(bool enable); bool IsSlicingPlanesEnabled() const; void EnableLinkedNavigation(bool enable); bool IsLinkedNavigationEnabled() const; protected: void SetFocus(); void OnPreferencesChanged(const berry::IBerryPreferences*); void CreateQtPartControl(QWidget* parent); private: const QScopedPointer d; }; #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 9aa9d871f0..f2c3677d20 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp @@ -1,222 +1,221 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-07-07 16:57:15 +0200 (Di, 07 Jul 2009) $ - Version: $Revision: 18019 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkStdMultiWidgetEditorPreferencePage.h" #include "QmitkStdMultiWidgetEditor.h" #include #include #include #include #include #include #include QmitkStdMultiWidgetEditorPreferencePage::QmitkStdMultiWidgetEditorPreferencePage() : m_MainControl(0) { } void QmitkStdMultiWidgetEditorPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkStdMultiWidgetEditorPreferencePage::CreateQtControl(QWidget* parent) { berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); m_StdMultiWidgetEditorPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkStdMultiWidgetEditor::EDITOR_ID); m_MainControl = new QWidget(parent); m_EnableFlexibleZooming = new QCheckBox; m_ShowLevelWindowWidget = new QCheckBox; m_PACSLikeMouseMode = new QCheckBox; QFormLayout *formLayout = new QFormLayout; formLayout->addRow("&Use constrained zooming and padding", m_EnableFlexibleZooming); formLayout->addRow("&Show level/window widget", m_ShowLevelWindowWidget); formLayout->addRow("&PACS like mouse interactions (select left mouse button action)", m_PACSLikeMouseMode); // gradient background QLabel* gBName = new QLabel; gBName->setText("Gradient background"); formLayout->addRow(gBName); // color m_ColorButton1 = new QPushButton; m_ColorButton1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); m_ColorButton2 = new QPushButton; m_ColorButton2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); QPushButton* resetButton = new QPushButton; resetButton->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); resetButton->setText("Reset"); QLabel* colorLabel1 = new QLabel("first color : "); colorLabel1->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); QLabel* colorLabel2 = new QLabel("second color: "); colorLabel2->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); QHBoxLayout* colorWidgetLayout = new QHBoxLayout; colorWidgetLayout->setContentsMargins(4,4,4,4); colorWidgetLayout->addWidget(colorLabel1); colorWidgetLayout->addWidget(m_ColorButton1); colorWidgetLayout->addWidget(colorLabel2); colorWidgetLayout->addWidget(m_ColorButton2); colorWidgetLayout->addWidget(resetButton); QWidget* colorWidget = new QWidget; colorWidget->setLayout(colorWidgetLayout); //spacer QSpacerItem *spacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); QVBoxLayout* vBoxLayout = new QVBoxLayout; vBoxLayout->addLayout(formLayout); vBoxLayout->addWidget(colorWidget); vBoxLayout->addSpacerItem(spacer); m_MainControl->setLayout(vBoxLayout); QObject::connect( m_ColorButton1, SIGNAL( clicked() ) , this, SLOT( FirstColorChanged() ) ); QObject::connect( m_ColorButton2, SIGNAL( clicked() ) , this, SLOT( SecondColorChanged() ) ); QObject::connect( resetButton, SIGNAL( clicked() ) , this, SLOT( ResetColors() ) ); this->Update(); } QWidget* QmitkStdMultiWidgetEditorPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkStdMultiWidgetEditorPreferencePage::PerformOk() { m_StdMultiWidgetEditorPreferencesNode->Put("first background color style sheet", m_FirstColorStyleSheet.toStdString()); m_StdMultiWidgetEditorPreferencesNode->Put("second background color style sheet", m_SecondColorStyleSheet.toStdString()); m_StdMultiWidgetEditorPreferencesNode->PutByteArray("first background color", m_FirstColor); m_StdMultiWidgetEditorPreferencesNode->PutByteArray("second background color", m_SecondColor); m_StdMultiWidgetEditorPreferencesNode->PutBool("Use constrained zooming and padding" , m_EnableFlexibleZooming->isChecked()); m_StdMultiWidgetEditorPreferencesNode->PutBool("Show level/window widget", m_ShowLevelWindowWidget->isChecked()); m_StdMultiWidgetEditorPreferencesNode->PutBool("PACS like mouse interaction", m_PACSLikeMouseMode->isChecked()); return true; } void QmitkStdMultiWidgetEditorPreferencePage::PerformCancel() { } void QmitkStdMultiWidgetEditorPreferencePage::Update() { m_EnableFlexibleZooming->setChecked(m_StdMultiWidgetEditorPreferencesNode->GetBool("Use constrained zooming and padding", true)); m_ShowLevelWindowWidget->setChecked(m_StdMultiWidgetEditorPreferencesNode->GetBool("Show level/window widget", true)); m_PACSLikeMouseMode->setChecked(m_StdMultiWidgetEditorPreferencesNode->GetBool("PACS like mouse interaction", false)); m_FirstColorStyleSheet = QString::fromStdString(m_StdMultiWidgetEditorPreferencesNode->Get("first background color style sheet", "")); m_SecondColorStyleSheet = QString::fromStdString(m_StdMultiWidgetEditorPreferencesNode->Get("second background color style sheet", "")); m_FirstColor = m_StdMultiWidgetEditorPreferencesNode->GetByteArray("first background color", ""); m_SecondColor = m_StdMultiWidgetEditorPreferencesNode->GetByteArray("second background color", ""); if (m_FirstColorStyleSheet=="") { m_FirstColorStyleSheet = "background-color:rgb(25,25,25)"; } if (m_SecondColorStyleSheet=="") { m_SecondColorStyleSheet = "background-color:rgb(127,127,127)"; } if (m_FirstColor=="") { m_FirstColor = "#191919"; } if (m_SecondColor=="") { m_SecondColor = "#7F7F7F"; } m_ColorButton1->setStyleSheet(m_FirstColorStyleSheet); m_ColorButton2->setStyleSheet(m_SecondColorStyleSheet); } void QmitkStdMultiWidgetEditorPreferencePage::FirstColorChanged() { QColor color = QColorDialog::getColor(); m_ColorButton1->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_ColorButton1->setStyleSheet(styleSheet); m_FirstColorStyleSheet = styleSheet; QStringList firstColor; firstColor << color.name(); m_FirstColor = firstColor.replaceInStrings(";","\\;").join(";").toStdString(); } void QmitkStdMultiWidgetEditorPreferencePage::SecondColorChanged() { QColor color = QColorDialog::getColor(); m_ColorButton2->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_ColorButton2->setStyleSheet(styleSheet); m_SecondColorStyleSheet = styleSheet; QStringList secondColor; secondColor << color.name(); m_SecondColor = secondColor.replaceInStrings(";","\\;").join(";").toStdString(); } void QmitkStdMultiWidgetEditorPreferencePage::ResetColors() { m_FirstColorStyleSheet = "background-color:rgb(25,25,25)"; m_SecondColorStyleSheet = "background-color:rgb(127,127,127)"; m_FirstColor = "#191919"; m_SecondColor = "#7F7F7F"; m_ColorButton1->setStyleSheet(m_FirstColorStyleSheet); m_ColorButton2->setStyleSheet(m_SecondColorStyleSheet); } void QmitkStdMultiWidgetEditorPreferencePage::UseGradientBackgroundSelected() { } void QmitkStdMultiWidgetEditorPreferencePage::ColorActionChanged() { } 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 726897c82a..91fa63e97c 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h @@ -1,86 +1,85 @@ -/*========================================================================= +/*=================================================================== - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-02-10 14:14:32 +0100 (Di, 10 Feb 2009) $ - Version: $Revision: 16224 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKSTDMULTIWIDGETEDITORPREFERENCEPAGE_H_ #define QMITKSTDMULTIWIDGETEDITORPREFERENCEPAGE_H_ #include "berryIQtPreferencePage.h" #include class QWidget; class QCheckBox; class QPushButton; class QWidgetAction; struct QmitkStdMultiWidgetEditorPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkStdMultiWidgetEditorPreferencePage(); void Init(berry::IWorkbench::Pointer workbench); void CreateQtControl(QWidget* widget); QWidget* GetQtControl() const; /// /// \see IPreferencePage::PerformOk() /// virtual bool PerformOk(); /// /// \see IPreferencePage::PerformCancel() /// virtual void PerformCancel(); /// /// \see IPreferencePage::Update() /// virtual void Update(); public slots: void FirstColorChanged(); void SecondColorChanged(); void UseGradientBackgroundSelected(); void ColorActionChanged(); void ResetColors(); protected: QWidget* m_MainControl; QCheckBox* m_EnableFlexibleZooming; QCheckBox* m_ShowLevelWindowWidget; QCheckBox* m_UseGradientBackground; QCheckBox* m_ChangeBackgroundColors; QCheckBox* m_PACSLikeMouseMode; QPushButton* m_ColorButton1; QPushButton* m_ColorButton2; std::string m_FirstColor; std::string m_SecondColor; QString m_FirstColorStyleSheet; QString m_SecondColorStyleSheet; berry::IPreferences::Pointer m_StdMultiWidgetEditorPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp index 345d66e9b2..6ee70122e0 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp @@ -1,39 +1,38 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h" #include "../QmitkStdMultiWidgetEditor.h" #include "QmitkStdMultiWidgetEditorPreferencePage.h" void org_mitk_gui_qt_stdmultiwidgeteditor_Activator::start(ctkPluginContext* context) { Q_UNUSED(context) BERRY_REGISTER_EXTENSION_CLASS(QmitkStdMultiWidgetEditor, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkStdMultiWidgetEditorPreferencePage, context) } void org_mitk_gui_qt_stdmultiwidgeteditor_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_stdmultiwidgeteditor, org_mitk_gui_qt_stdmultiwidgeteditor_Activator) diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h index d3a5631cca..8bcd924fa9 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h @@ -1,40 +1,39 @@ -/*========================================================================= +/*=================================================================== - Program: MITK Platform - Language: C++ - Date: $Date$ - Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef org_mitk_gui_qt_stdmultiwidgeteditor_Activator_H_ #define org_mitk_gui_qt_stdmultiwidgeteditor_Activator_H_ #include /** * \ingroup org_mitk_gui_qt_stdmultiwidgeteditor */ class org_mitk_gui_qt_stdmultiwidgeteditor_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; #endif /* org_mitk_gui_qt_stdmultiwidgeteditor_Activator_H_ */ diff --git a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.cpp b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.cpp index bd980acdae..8c51fc17d0 100644 --- a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.cpp +++ b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.cpp @@ -1,196 +1,195 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +See LICENSE.txt or http://www.mitk.org for details. -=========================================================================*/ +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkToFTutorialView.h" #include "QmitkStdMultiWidget.h" // Qt #include // mitk includes #include // class holding the intrinsic parameters of the according camera #include // MITK-ToF related includes #include #include // configuration file holding e.g. plugin paths or path to test file directory #include // filter from module ToFProcessing that calculates a surface from the given range image #include // allows access to images provided by the ToF camera const std::string QmitkToFTutorialView::VIEW_ID = "org.mitk.views.toftutorial"; QmitkToFTutorialView::QmitkToFTutorialView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkToFTutorialView::~QmitkToFTutorialView() { } void QmitkToFTutorialView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkToFTutorialViewControls; m_Controls->setupUi( parent ); connect( m_Controls->step1Button, SIGNAL(clicked()), this, SLOT(OnStep1()) ); connect( m_Controls->step2Button, SIGNAL(clicked()), this, SLOT(OnStep2()) ); } } void QmitkToFTutorialView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkToFTutorialView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkToFTutorialView::OnStep1() { // clean up data storage RemoveAllNodesFromDataStorage(); // Create an instance of ToFImageGrabber that holds a ToFCameraMITKPlayerDevice for playing ToF data mitk::ToFImageGrabber::Pointer tofImageGrabber = mitk::ToFImageGrabber::New(); tofImageGrabber->SetCameraDevice(mitk::ToFCameraMITKPlayerDevice::New()); // set paths to test data std::string distanceFileName = MITK_TOF_DATA_DIR; distanceFileName.append("/PMDCamCube2_MF0_IT0_20Images_DistanceImage.pic"); std::string amplitudeFileName = MITK_TOF_DATA_DIR; amplitudeFileName.append("/PMDCamCube2_MF0_IT0_20Images_AmplitudeImage.pic"); std::string intensityFileName = MITK_TOF_DATA_DIR; intensityFileName.append("/PMDCamCube2_MF0_IT0_20Images_IntensityImage.pic"); // set file name property in image grabber. This will be propagated to the corresponding device and controller class tofImageGrabber->SetProperty("DistanceImageFileName",mitk::StringProperty::New(distanceFileName)); tofImageGrabber->SetProperty("AmplitudeImageFileName",mitk::StringProperty::New(amplitudeFileName)); tofImageGrabber->SetProperty("IntensityImageFileName",mitk::StringProperty::New(intensityFileName)); // connect to device if (tofImageGrabber->ConnectCamera()) { //// start camera (internally starts thread that continuously grabs images from the camera) tofImageGrabber->StartCamera(); // update image grabber which itself represents the source of a MITK filter pipeline tofImageGrabber->Update(); // grab distance image mitk::Image::Pointer distanceImage = tofImageGrabber->GetOutput(0); // grab amplitude image mitk::Image::Pointer amplitudeImage = tofImageGrabber->GetOutput(1); // grab intensity image mitk::Image::Pointer intensityImage = tofImageGrabber->GetOutput(2); //add distance image to data storage mitk::DataNode::Pointer distanceNode = mitk::DataNode::New(); distanceNode->SetName("Distance Image"); distanceNode->SetData(distanceImage); this->GetDefaultDataStorage()->Add(distanceNode); //add amplitude image to data storage mitk::DataNode::Pointer amplitudeNode = mitk::DataNode::New(); amplitudeNode->SetName("Amplitude Image"); amplitudeNode->SetData(amplitudeImage); this->GetDefaultDataStorage()->Add(amplitudeNode); //add intensity image to data storage mitk::DataNode::Pointer intensityNode = mitk::DataNode::New(); intensityNode->SetName("Intensity Image"); intensityNode->SetData(intensityImage); this->GetDefaultDataStorage()->Add(intensityNode); // stop camera (terminate internally used thread) tofImageGrabber->StopCamera(); //// disconnect from camera tofImageGrabber->DisconnectCamera(); // adjust views to new data in DataStorage mitk::RenderingManager::GetInstance()->InitializeViews(distanceImage->GetGeometry()); } else { MITK_ERROR<<"Connection to ToF camera could not be established"; } } void QmitkToFTutorialView::OnStep2() { // Check if distance image is available mitk::DataNode::Pointer distanceNode = this->GetDefaultDataStorage()->GetNamedNode("Distance Image"); if (distanceNode.IsNotNull()) { // get distance image from node and check if node contains image mitk::Image::Pointer distanceImage = dynamic_cast(distanceNode->GetData()); if (distanceImage.IsNotNull()) { // create object of CameraIntrinsics that holds intrinsic parameters of the ToF camera mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); // set focal length in pixel cameraIntrinsics->SetFocalLength(295.8,296.1); // set principal point in pixel cameraIntrinsics->SetPrincipalPoint(113.2,97.1); // set up filter for surface calculation mitk::ToFDistanceImageToSurfaceFilter::Pointer surfaceFilter = mitk::ToFDistanceImageToSurfaceFilter::New(); // apply intrinsic parameters to filter surfaceFilter->SetCameraIntrinsics(cameraIntrinsics); // set distance between pixels on chip in mm (in this example squared pixel) mitk::ToFProcessingCommon::ToFPoint2D interPixelDistance; interPixelDistance[0] = 0.045; interPixelDistance[1] = 0.045; surfaceFilter->SetInterPixelDistance(interPixelDistance); // set distance image as input surfaceFilter->SetInput(distanceImage); // update the filter surfaceFilter->Update(); // get surface from filter mitk::Surface::Pointer surface = surfaceFilter->GetOutput(); // add surface to data storage mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetName("ToF surface"); surfaceNode->SetData(surface); this->GetDefaultDataStorage()->Add(surfaceNode); // adjust views to new data in DataStorage mitk::RenderingManager::GetInstance()->InitializeViews(surface->GetGeometry()); mitk::RenderingManager::GetInstance()->InitializeViews(surface->GetGeometry()); } else { QMessageBox::warning(NULL,"ToF Tutorial","Node 'Distance Image' contains no image"); } } else { QMessageBox::warning(NULL,"ToF Tutorial","Perform Step 1 first to acquire a distance image"); } } void QmitkToFTutorialView::RemoveAllNodesFromDataStorage() { mitk::DataStorage::SetOfObjects::ConstPointer allNodes = this->GetDefaultDataStorage()->GetAll(); this->GetDefaultDataStorage()->Remove(allNodes); } diff --git a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.h b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.h index 862fd1fb72..94fbb534c0 100644 --- a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.h +++ b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/QmitkToFTutorialView.h @@ -1,75 +1,74 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkToFTutorialView_h #define QmitkToFTutorialView_h #include #include #include "ui_QmitkToFTutorialViewControls.h" /*! \brief QmitkToFTutorialView is a tutorial showing the basic implementation techniques of MITK-ToF Step 1 shows how to acquire images from a tof camera Step 2 shows how to apply a processing filter to generate a surface from a range image \sa QmitkFunctionality \ingroup Functionalities */ class QmitkToFTutorialView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkToFTutorialView(); virtual ~QmitkToFTutorialView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /// \brief Called when the user clicks the Step 1 button void OnStep1(); /// \brief Called when the user clicks the Step 2 button void OnStep2(); protected: void RemoveAllNodesFromDataStorage(); Ui::QmitkToFTutorialViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; }; #endif // _QMITKTOFTUTORIALVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.cpp b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.cpp index b449f425d3..f242822b22 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.cpp +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.cpp @@ -1,256 +1,255 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-05-03 17:20:26 +0200 (Mo, 03 Mai 2010) $ -Version: $Revision: 22675 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkToFImageBackground.h" // MITK includes #include "mitkVtkLayerController.h" #include "mitkRenderingManager.h" // VTK includes #include "vtkSystemIncludes.h" #include "vtkRenderer.h" #include "vtkMapper.h" #include "vtkObjectFactory.h" #include "vtkImageActor.h" #include "vtkRenderWindow.h" #include "vtkImageImport.h" #include "vtkCommand.h" #include "vtkCamera.h" QmitkToFImageBackground::QmitkToFImageBackground() { ResetBackground(); } void QmitkToFImageBackground::ResetBackground() { m_renderWindowVectorInfo.clear(); } QmitkToFImageBackground::~QmitkToFImageBackground() { if ( m_renderWindowVectorInfo.size() > 0 ) { } } /** * Sets the renderwindow, in which the Video background * will be shown. Make sure, you have called this function * before calling Enable() */ /* void QmitkToFImageBackground::AddRenderWindow(vtkRenderWindow* renderWindow ) { RemoveRenderWindow(renderWindow); vtkRenderer* videoRenderer = vtkRenderer::New(); vtkImageActor* videoActor = vtkImageActor::New(); vtkImageImport* videoImport = vtkImageImport::New(); videoImport->SetDataScalarTypeToUnsignedChar(); videoImport->SetNumberOfScalarComponents(3); if(m_VideoSource->GetImageWidth() == 0) m_VideoSource->FetchFrame(); videoImport->SetWholeExtent(0,m_VideoSource->GetImageWidth()-1,0,m_VideoSource->GetImageHeight()-1,0,1-1); videoImport->SetDataExtentToWholeExtent(); mitk::VideoBackgroundVectorInfo v; v.renWin = renderWindow; v.videoRenderer = videoRenderer; v.videoActor = videoActor; v.videoImport = videoImport; m_renderWindowVectorInfo.push_back(v); Modified(); } */ void QmitkToFImageBackground::AddRenderWindow(vtkRenderWindow* renderWindow, int width, int height ) { RemoveRenderWindow(renderWindow); vtkRenderer* videoRenderer = vtkRenderer::New(); vtkImageActor* videoActor = vtkImageActor::New(); vtkImageImport* videoImport = vtkImageImport::New(); videoImport->SetDataScalarTypeToUnsignedChar(); videoImport->SetNumberOfScalarComponents(3); // if(m_VideoSource->GetImageWidth() == 0) // m_VideoSource->FetchFrame(); videoImport->SetWholeExtent(0,width-1,0,height-1,0,1-1); videoImport->SetDataExtentToWholeExtent(); mitk::ToFImageBackgroundVectorInfo v; v.renWin = renderWindow; v.videoRenderer = videoRenderer; v.videoActor = videoActor; v.videoImport = videoImport; m_renderWindowVectorInfo.push_back(v); //Modified(); for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { (*it).videoActor->SetInput((*it).videoImport->GetOutput()); (*it).videoRenderer->AddActor2D((*it).videoActor); (*it).videoRenderer->ResetCamera(); (*it).videoRenderer->InteractiveOff(); (*it).videoRenderer->GetActiveCamera()->ParallelProjectionOn(); (*it).videoRenderer->GetActiveCamera()->SetParallelScale(height/2); if(!mitk::VtkLayerController::GetInstance((*it).renWin)->IsRendererInserted((*it).videoRenderer)) mitk::VtkLayerController::GetInstance((*it).renWin)->InsertBackgroundRenderer((*it).videoRenderer,true); } } void QmitkToFImageBackground::RemoveRenderWindow(vtkRenderWindow* renderWindow ) { for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { if((*it).renWin == renderWindow) { // unregister video backround renderer from renderwindow mitk::VtkLayerController::GetInstance((*it).renWin)->RemoveRenderer((*it).videoRenderer); (*it).videoRenderer->Delete(); (*it).videoActor->Delete(); (*it).videoImport->Delete(); m_renderWindowVectorInfo.erase(it); return; //delete &(*it); // memory leak renderwindowvectorinfo ?? } } } bool QmitkToFImageBackground::IsRenderWindowIncluded(vtkRenderWindow* renderWindow ) { for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { if((*it).renWin == renderWindow) return true; } return false; } /** * Enables drawing of the color Video background. * If you want to disable it, call the Disable() function. */ /* void QmitkToFImageBackground::Enable() { UpdateVideo(); Modified(); m_QTimer->start(m_TimerDelay); } */ /** * Disables drawing of the color Video background. * If you want to enable it, call the Enable() function. */ /* void QmitkToFImageBackground::Disable() { if ( this->IsEnabled() ) { /*for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { mitk::VtkLayerController::GetInstance((*it).renWin)->RemoveRenderer((*it).videoRenderer); }* / m_QTimer->stop(); } } */ /** * Checks, if the Video background is currently * enabled (visible) */ /* bool QmitkToFImageBackground::IsEnabled() { if (m_QTimer->isActive()) return true; else return false; } */ /* void QmitkToFImageBackground::UpdateVideo() { unsigned char *src = 0; src = m_VideoSource->GetVideoTexture(); if(src) { if(m_renderWindowVectorInfo.size()>0) { for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { (*it).videoImport->SetImportVoidPointer(src); (*it).videoImport->Modified(); (*it).videoImport->Update(); mitk::RenderingManager::GetInstance()->RequestUpdate((*it).renWin); } } } emit NewFrameAvailable ( m_VideoSource ); } */ void QmitkToFImageBackground::UpdateBackground(unsigned char *src) { if(src) { if(m_renderWindowVectorInfo.size()>0) { for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { (*it).videoImport->SetImportVoidPointer(src); (*it).videoImport->Modified(); (*it).videoImport->Update(); mitk::RenderingManager::GetInstance()->RequestUpdate((*it).renWin); } } } //emit NewFrameAvailable ( m_VideoSource ); } void QmitkToFImageBackground::Modified() { // ensures registration of video backrounds in each renderwindow for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { (*it).videoActor->SetInput((*it).videoImport->GetOutput()); (*it).videoRenderer->AddActor2D((*it).videoActor); (*it).videoRenderer->ResetCamera(); (*it).videoRenderer->InteractiveOff(); (*it).videoRenderer->GetActiveCamera()->ParallelProjectionOn(); //(*it).videoRenderer->GetActiveCamera()->SetParallelScale(m_VideoSource->GetImageHeight()/2); if(!mitk::VtkLayerController::GetInstance((*it).renWin)->IsRendererInserted((*it).videoRenderer)) mitk::VtkLayerController::GetInstance((*it).renWin)->InsertBackgroundRenderer((*it).videoRenderer,true); } } diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.h b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.h index d0054bcda3..b4147e2b70 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.h +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFImageBackground.h @@ -1,81 +1,80 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-05-03 17:20:26 +0200 (Mo, 03 Mai 2010) $ -Version: $Revision: 22675 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _Qmitk_ToF_Image_Background_h_ #define _Qmitk_ToF_Image_Background_h_ #include "mitkTOFUIExports.h" #include "qobject.h" #include class vtkRenderer; class vtkRenderWindow; class vtkImageActor; class vtkImageImport; class vtkActor2D; class vtkVideoSizeCallback; namespace mitk { struct ToFImageBackgroundVectorInfo { vtkRenderWindow* renWin; vtkRenderer* videoRenderer; vtkImageActor* videoActor; vtkImageImport* videoImport; }; } /** * Displays a char image in the background directly * */ class QmitkToFImageBackground : public QObject { Q_OBJECT public: QmitkToFImageBackground(); ~QmitkToFImageBackground(); ////##Documentation ////## @brief sets the mitkRenderWindow in which the video is displayed. ////## must be initialized before enabling the background. void AddRenderWindow(vtkRenderWindow* renderWindow, int width, int height ); void RemoveRenderWindow(vtkRenderWindow* renderWindow); bool IsRenderWindowIncluded(vtkRenderWindow* renderWindow); public slots: void UpdateBackground(unsigned char *src); protected: void ResetBackground(); void Modified(); typedef std::vector RenderWindowVectorInfoType; RenderWindowVectorInfoType m_renderWindowVectorInfo; }; #endif diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.cpp b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.cpp index a7bdc343f9..51127b9dc8 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.cpp +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.cpp @@ -1,521 +1,520 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Qmitk #include "QmitkToFUtilView.h" #include #include // Qt #include #include // MITK #include #include #include #include #include #include // VTK #include // ITK #include const std::string QmitkToFUtilView::VIEW_ID = "org.mitk.views.tofutil"; QmitkToFUtilView::QmitkToFUtilView() : QmitkFunctionality() , m_Controls(NULL), m_MultiWidget( NULL ) , m_MitkDistanceImage(NULL), m_MitkAmplitudeImage(NULL), m_MitkIntensityImage(NULL), m_Surface(NULL) , m_DistanceImageNode(NULL), m_AmplitudeImageNode(NULL), m_IntensityImageNode(NULL), m_SurfaceNode(NULL) , m_ToFImageRecorder(NULL), m_ToFImageGrabber(NULL), m_ToFDistanceImageToSurfaceFilter(NULL), m_ToFCompositeFilter(NULL) , m_SurfaceDisplayCount(0), m_2DDisplayCount(0) , m_RealTimeClock(NULL) , m_StepsForFramerate(100) , m_2DTimeBefore(0.0) , m_2DTimeAfter(0.0) , m_VideoEnabled(false) { this->m_Frametimer = new QTimer(this); this->m_ToFDistanceImageToSurfaceFilter = mitk::ToFDistanceImageToSurfaceFilter::New(); this->m_ToFCompositeFilter = mitk::ToFCompositeFilter::New(); this->m_ToFImageRecorder = mitk::ToFImageRecorder::New(); this->m_ToFSurfaceVtkMapper3D = mitk::ToFSurfaceVtkMapper3D::New(); } QmitkToFUtilView::~QmitkToFUtilView() { OnToFCameraStopped(); OnToFCameraDisconnected(); } void QmitkToFUtilView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkToFUtilViewControls; m_Controls->setupUi( parent ); connect(m_Frametimer, SIGNAL(timeout()), this, SLOT(OnUpdateCamera())); connect( (QObject*)(m_Controls->m_ToFConnectionWidget), SIGNAL(ToFCameraConnected()), this, SLOT(OnToFCameraConnected()) ); connect( (QObject*)(m_Controls->m_ToFConnectionWidget), SIGNAL(ToFCameraDisconnected()), this, SLOT(OnToFCameraDisconnected()) ); connect( (QObject*)(m_Controls->m_ToFConnectionWidget), SIGNAL(ToFCameraSelected(const QString)), this, SLOT(OnToFCameraSelected(const QString)) ); connect( (QObject*)(m_Controls->m_ToFRecorderWidget), SIGNAL(ToFCameraStarted()), this, SLOT(OnToFCameraStarted()) ); connect( (QObject*)(m_Controls->m_ToFRecorderWidget), SIGNAL(ToFCameraStopped()), this, SLOT(OnToFCameraStopped()) ); connect( (QObject*)(m_Controls->m_ToFRecorderWidget), SIGNAL(RecordingStarted()), this, SLOT(OnToFCameraStopped()) ); connect( (QObject*)(m_Controls->m_ToFRecorderWidget), SIGNAL(RecordingStopped()), this, SLOT(OnToFCameraStarted()) ); connect( (QObject*)(m_Controls->m_TextureCheckBox), SIGNAL(toggled(bool)), this, SLOT(OnTextureCheckBoxChecked(bool)) ); connect( (QObject*)(m_Controls->m_VideoTextureCheckBox), SIGNAL(toggled(bool)), this, SLOT(OnVideoTextureCheckBoxChecked(bool)) ); } } void QmitkToFUtilView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkToFUtilView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkToFUtilView::Activated() { QmitkFunctionality::Activated(); // configure views m_MultiWidget->SetWidgetPlanesVisibility(false); m_MultiWidget->mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Transversal); m_MultiWidget->mitkWidget1->GetSliceNavigationController()->SliceLockedOn(); m_MultiWidget->mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Transversal); m_MultiWidget->mitkWidget2->GetSliceNavigationController()->SliceLockedOn(); m_MultiWidget->mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Transversal); m_MultiWidget->mitkWidget3->GetSliceNavigationController()->SliceLockedOn(); m_MultiWidget->ResetCrosshair(); mitk::RenderingManager::GetInstance()->InitializeViews(); this->UseToFVisibilitySettings(true); m_Controls->m_ToFCompositeFilterWidget->SetToFCompositeFilter(this->m_ToFCompositeFilter); m_Controls->m_ToFCompositeFilterWidget->SetDataStorage(this->GetDefaultDataStorage()); if (this->m_ToFImageGrabber.IsNull()) { m_Controls->m_ToFRecorderWidget->setEnabled(false); m_Controls->m_ToFVisualisationSettingsWidget->setEnabled(false); } } void QmitkToFUtilView::Deactivated() { m_MultiWidget->SetWidgetPlanesVisibility(true); m_MultiWidget->mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Transversal); m_MultiWidget->mitkWidget1->GetSliceNavigationController()->SliceLockedOff(); m_MultiWidget->mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Sagittal); m_MultiWidget->mitkWidget2->GetSliceNavigationController()->SliceLockedOff(); m_MultiWidget->mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Frontal); m_MultiWidget->mitkWidget3->GetSliceNavigationController()->SliceLockedOff(); m_MultiWidget->ResetCrosshair(); this->UseToFVisibilitySettings(false); mitk::RenderingManager::GetInstance()->InitializeViews(); QmitkFunctionality::Deactivated(); } void QmitkToFUtilView::OnToFCameraConnected() { this->m_SurfaceDisplayCount = 0; this->m_2DDisplayCount = 0; this->m_ToFImageGrabber = m_Controls->m_ToFConnectionWidget->GetToFImageGrabber(); this->m_ToFImageRecorder->SetCameraDevice(this->m_ToFImageGrabber->GetCameraDevice()); m_Controls->m_ToFRecorderWidget->SetParameter(this->m_ToFImageGrabber, this->m_ToFImageRecorder); m_Controls->m_ToFRecorderWidget->setEnabled(true); m_Controls->m_ToFRecorderWidget->ResetGUIToInitial(); m_Controls->m_ToFVisualisationSettingsWidget->setEnabled(true); //TODO this->m_RealTimeClock = mitk::RealTimeClock::New(); this->m_2DTimeBefore = this->m_RealTimeClock->GetCurrentStamp(); try { this->m_VideoSource = mitk::OpenCVVideoSource::New(); this->m_VideoSource->SetVideoCameraInput(0, false); this->m_VideoSource->StartCapturing(); if(!this->m_VideoSource->IsCapturingEnabled()) { MITK_INFO << "unable to initialize video grabbing/playback"; this->m_VideoEnabled = false; m_Controls->m_VideoTextureCheckBox->setEnabled(false); } else { this->m_VideoEnabled = true; m_Controls->m_VideoTextureCheckBox->setEnabled(true); } if (this->m_VideoEnabled) { this->m_VideoSource->FetchFrame(); this->m_VideoCaptureHeight = this->m_VideoSource->GetImageHeight(); this->m_VideoCaptureWidth = this->m_VideoSource->GetImageWidth(); int videoTexSize = this->m_VideoCaptureWidth * this->m_VideoCaptureHeight * 3; // for each pixel three values for rgb are needed!! this->m_VideoTexture = this->m_VideoSource->GetVideoTexture(); unsigned int dimensions[2]; dimensions[0] = this->m_VideoCaptureWidth; dimensions[1] = this->m_VideoCaptureHeight; this->m_ToFDistanceImageToSurfaceFilter->SetTextureImageWidth(this->m_VideoCaptureWidth); this->m_ToFDistanceImageToSurfaceFilter->SetTextureImageHeight(this->m_VideoCaptureHeight); this->m_ToFSurfaceVtkMapper3D->SetTextureWidth(this->m_VideoCaptureWidth); this->m_ToFSurfaceVtkMapper3D->SetTextureHeight(this->m_VideoCaptureHeight); } m_MultiWidget->DisableGradientBackground(); } catch (std::logic_error& e) { QMessageBox::warning(NULL, "Warning", QString(e.what())); MITK_ERROR << e.what(); return; } mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkToFUtilView::OnToFCameraDisconnected() { m_Controls->m_ToFRecorderWidget->OnStop(); m_Controls->m_ToFRecorderWidget->setEnabled(false); m_Controls->m_ToFVisualisationSettingsWidget->setEnabled(false); if(this->m_VideoSource) { this->m_VideoSource->StopCapturing(); this->m_VideoSource = NULL; } mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkToFUtilView::OnToFCameraStarted() { if (m_ToFImageGrabber.IsNotNull()) { // initial update of image grabber this->m_ToFImageGrabber->Update(); this->m_ToFCompositeFilter->SetInput(0,this->m_ToFImageGrabber->GetOutput(0)); this->m_ToFCompositeFilter->SetInput(1,this->m_ToFImageGrabber->GetOutput(1)); this->m_ToFCompositeFilter->SetInput(2,this->m_ToFImageGrabber->GetOutput(2)); // initial update of composite filter this->m_ToFCompositeFilter->Update(); this->m_MitkDistanceImage = m_ToFCompositeFilter->GetOutput(0); this->m_DistanceImageNode = ReplaceNodeData("Distance image",m_MitkDistanceImage); this->m_MitkAmplitudeImage = m_ToFCompositeFilter->GetOutput(1); this->m_AmplitudeImageNode = ReplaceNodeData("Amplitude image",m_MitkAmplitudeImage); this->m_MitkIntensityImage = m_ToFCompositeFilter->GetOutput(2); this->m_IntensityImageNode = ReplaceNodeData("Intensity image",m_MitkIntensityImage); this->m_ToFDistanceImageToSurfaceFilter->SetInput(0,m_MitkDistanceImage); this->m_ToFDistanceImageToSurfaceFilter->SetInput(1,m_MitkAmplitudeImage); this->m_ToFDistanceImageToSurfaceFilter->SetInput(2,m_MitkIntensityImage); this->m_Surface = this->m_ToFDistanceImageToSurfaceFilter->GetOutput(0); this->m_SurfaceNode = ReplaceNodeData("Surface",m_Surface); this->UseToFVisibilitySettings(true); this->m_Frametimer->start(0); m_Controls->m_ToFCompositeFilterWidget->UpdateFilterParameter(); // initialize visualization widget m_Controls->m_ToFVisualisationSettingsWidget->Initialize(this->m_MitkDistanceImage, this->m_MitkAmplitudeImage, this->m_MitkIntensityImage); if (m_Controls->m_TextureCheckBox->isChecked()) { OnTextureCheckBoxChecked(true); } if (m_Controls->m_VideoTextureCheckBox->isChecked()) { OnVideoTextureCheckBoxChecked(true); } } m_Controls->m_TextureCheckBox->setEnabled(true); // initialize point set measurement m_Controls->tofMeasurementWidget->InitializeWidget(m_MultiWidget,this->GetDefaultDataStorage(),m_MitkDistanceImage); } void QmitkToFUtilView::OnToFCameraStopped() { this->m_Frametimer->stop(); } void QmitkToFUtilView::OnToFCameraSelected(const QString selected) { if ((selected=="PMD CamBoard")||(selected=="PMD O3D")) { MITK_INFO<<"Surface representation currently not available for CamBoard and O3. Intrinsic parameters missing."; this->m_Controls->m_SurfaceCheckBox->setEnabled(false); this->m_Controls->m_TextureCheckBox->setEnabled(false); this->m_Controls->m_VideoTextureCheckBox->setEnabled(false); this->m_Controls->m_SurfaceCheckBox->setChecked(false); this->m_Controls->m_TextureCheckBox->setChecked(false); this->m_Controls->m_VideoTextureCheckBox->setChecked(false); } else { this->m_Controls->m_SurfaceCheckBox->setEnabled(true); this->m_Controls->m_TextureCheckBox->setEnabled(true); // TODO enable when bug 8106 is solved this->m_Controls->m_VideoTextureCheckBox->setEnabled(true); } } void QmitkToFUtilView::OnUpdateCamera() { if (m_Controls->m_VideoTextureCheckBox->isChecked() && this->m_VideoEnabled && this->m_VideoSource) { this->m_VideoTexture = this->m_VideoSource->GetVideoTexture(); ProcessVideoTransform(); } vtkColorTransferFunction* colorTransferFunction1; colorTransferFunction1 = m_Controls->m_ToFVisualisationSettingsWidget->GetWidget1ColorTransferFunction(); mitk::TransferFunction::Pointer tf1 = mitk::TransferFunction::New(); tf1->SetColorTransferFunction( colorTransferFunction1 ); m_DistanceImageNode->SetProperty("Image Rendering.Transfer Function",mitk::TransferFunctionProperty::New(tf1)); vtkColorTransferFunction* colorTransferFunction2; colorTransferFunction2 = m_Controls->m_ToFVisualisationSettingsWidget->GetWidget2ColorTransferFunction(); mitk::TransferFunction::Pointer tf2 = mitk::TransferFunction::New(); tf2->SetColorTransferFunction( colorTransferFunction2 ); m_AmplitudeImageNode->SetProperty("Image Rendering.Transfer Function",mitk::TransferFunctionProperty::New(tf2)); vtkColorTransferFunction* colorTransferFunction3; colorTransferFunction3 = m_Controls->m_ToFVisualisationSettingsWidget->GetWidget3ColorTransferFunction(); mitk::TransferFunction::Pointer tf3 = mitk::TransferFunction::New(); tf3->SetColorTransferFunction( colorTransferFunction3 ); m_IntensityImageNode->SetProperty("Image Rendering.Transfer Function",mitk::TransferFunctionProperty::New(tf3)); if (m_Controls->m_SurfaceCheckBox->isChecked()) { // update surface m_ToFDistanceImageToSurfaceFilter->SetTextureIndex(m_Controls->m_ToFVisualisationSettingsWidget->GetSelectedImageIndex()); this->m_Surface->Update(); vtkColorTransferFunction* colorTransferFunction = m_Controls->m_ToFVisualisationSettingsWidget->GetSelectedColorTransferFunction(); this->m_ToFSurfaceVtkMapper3D->SetVtkScalarsToColors(colorTransferFunction); if (this->m_SurfaceDisplayCount<2) { this->m_SurfaceNode->SetData(this->m_Surface); this->m_SurfaceNode->SetMapper(mitk::BaseRenderer::Standard3D, m_ToFSurfaceVtkMapper3D); mitk::RenderingManager::GetInstance()->InitializeViews( this->m_Surface->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS, true); mitk::Point3D surfaceCenter= this->m_Surface->GetGeometry()->GetCenter(); m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer()->GetActiveCamera()->SetPosition(0,0,-50); m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer()->GetActiveCamera()->SetViewUp(0,-1,0); m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer()->GetActiveCamera()->SetFocalPoint(0,0,surfaceCenter[2]); m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer()->GetActiveCamera()->SetViewAngle(40); m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer()->GetActiveCamera()->SetClippingRange(1, 10000); } this->m_SurfaceDisplayCount++; } else { // update pipeline this->m_MitkDistanceImage->Update(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->m_2DDisplayCount++; if ((this->m_2DDisplayCount % this->m_StepsForFramerate) == 0) { this->m_2DTimeAfter = this->m_RealTimeClock->GetCurrentStamp() - this->m_2DTimeBefore; MITK_INFO << " 2D-Display-framerate (fps): " << this->m_StepsForFramerate / (this->m_2DTimeAfter/1000); this->m_2DTimeBefore = this->m_RealTimeClock->GetCurrentStamp(); } } void QmitkToFUtilView::ProcessVideoTransform() { IplImage *src, *dst; src = cvCreateImageHeader(cvSize(this->m_VideoCaptureWidth, this->m_VideoCaptureHeight), IPL_DEPTH_8U, 3); src->imageData = (char*)this->m_VideoTexture; CvPoint2D32f srcTri[3], dstTri[3]; CvMat* rot_mat = cvCreateMat(2,3,CV_32FC1); CvMat* warp_mat = cvCreateMat(2,3,CV_32FC1); dst = cvCloneImage(src); dst->origin = src->origin; cvZero( dst ); int xOffset = 0;//m_Controls->m_XOffsetSpinBox->value(); int yOffset = 0;//m_Controls->m_YOffsetSpinBox->value(); int zoom = 0;//m_Controls->m_ZoomSpinBox->value(); // Compute warp matrix srcTri[0].x = 0 + zoom; srcTri[0].y = 0 + zoom; srcTri[1].x = src->width - 1 - zoom; srcTri[1].y = 0 + zoom; srcTri[2].x = 0 + zoom; srcTri[2].y = src->height - 1 - zoom; dstTri[0].x = 0; dstTri[0].y = 0; dstTri[1].x = src->width - 1; dstTri[1].y = 0; dstTri[2].x = 0; dstTri[2].y = src->height - 1; cvGetAffineTransform( srcTri, dstTri, warp_mat ); cvWarpAffine( src, dst, warp_mat ); cvCopy ( dst, src ); // Compute warp matrix srcTri[0].x = 0; srcTri[0].y = 0; srcTri[1].x = src->width - 1; srcTri[1].y = 0; srcTri[2].x = 0; srcTri[2].y = src->height - 1; dstTri[0].x = srcTri[0].x + xOffset; dstTri[0].y = srcTri[0].y + yOffset; dstTri[1].x = srcTri[1].x + xOffset; dstTri[1].y = srcTri[1].y + yOffset; dstTri[2].x = srcTri[2].x + xOffset; dstTri[2].y = srcTri[2].y + yOffset; cvGetAffineTransform( srcTri, dstTri, warp_mat ); cvWarpAffine( src, dst, warp_mat ); cvCopy ( dst, src ); src->imageData = NULL; cvReleaseImage( &src ); cvReleaseImage( &dst ); cvReleaseMat( &rot_mat ); cvReleaseMat( &warp_mat ); } void QmitkToFUtilView::OnTextureCheckBoxChecked(bool checked) { if(m_SurfaceNode.IsNotNull()) { if (checked) { this->m_SurfaceNode->SetBoolProperty("scalar visibility", true); } else { this->m_SurfaceNode->SetBoolProperty("scalar visibility", false); } } } void QmitkToFUtilView::OnVideoTextureCheckBoxChecked(bool checked) { if (checked) { if (this->m_VideoEnabled) { this->m_ToFSurfaceVtkMapper3D->SetTexture(this->m_VideoTexture); } else { this->m_ToFSurfaceVtkMapper3D->SetTexture(NULL); } } else { this->m_ToFSurfaceVtkMapper3D->SetTexture(NULL); } } mitk::DataNode::Pointer QmitkToFUtilView::ReplaceNodeData( std::string nodeName, mitk::BaseData* data ) { mitk::DataNode::Pointer node = this->GetDefaultDataStorage()->GetNamedNode(nodeName); if (node.IsNull()) { node = mitk::DataNode::New(); node->SetData(data); node->SetName(nodeName); this->GetDefaultDataStorage()->Add(node); } else { node->SetData(data); } return node; } void QmitkToFUtilView::UseToFVisibilitySettings(bool useToF) { // set node properties if (m_DistanceImageNode.IsNotNull()) { this->m_DistanceImageNode->SetProperty( "visible" , mitk::BoolProperty::New( true )); this->m_DistanceImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget2->GetRenderWindow() ) ); this->m_DistanceImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget3->GetRenderWindow() ) ); this->m_DistanceImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow() ) ); this->m_DistanceImageNode->SetBoolProperty("use color",!useToF); this->m_DistanceImageNode->GetPropertyList()->DeleteProperty("LookupTable"); } if (m_AmplitudeImageNode.IsNotNull()) { this->m_AmplitudeImageNode->SetProperty( "visible" , mitk::BoolProperty::New( true )); this->m_AmplitudeImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget1->GetRenderWindow() ) ); this->m_AmplitudeImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget3->GetRenderWindow() ) ); this->m_AmplitudeImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow() ) ); this->m_AmplitudeImageNode->SetBoolProperty("use color",!useToF); this->m_AmplitudeImageNode->GetPropertyList()->DeleteProperty("LookupTable"); } if (m_IntensityImageNode.IsNotNull()) { this->m_IntensityImageNode->SetProperty( "visible" , mitk::BoolProperty::New( true )); this->m_IntensityImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget1->GetRenderWindow() ) ); this->m_IntensityImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget2->GetRenderWindow() ) ); this->m_IntensityImageNode->SetVisibility( !useToF, mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow() ) ); this->m_IntensityImageNode->SetBoolProperty("use color",!useToF); this->m_IntensityImageNode->GetPropertyList()->DeleteProperty("LookupTable"); } // initialize images if (m_MitkDistanceImage.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( this->m_MitkDistanceImage->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_2DWINDOWS, true); } } diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.h b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.h index 204653aad4..fde34de736 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.h +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFUtilView.h @@ -1,170 +1,169 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkToFUtilView_h #define QmitkToFUtilView_h #include #include #include #include #include #include #include #include #include #include #include #include /*! \brief QmitkToFUtilView Application that allows simple playing, recording, visualization, processing and measurement of Time-of-Flight (ToF) data. Currently the following features are implemented:
  • Connecting and showing ToF data from various cameras (PMD CamCube 2/3, PMD CamBoard, PMD O3, MESA SwissRanger)
  • Recording and playing of ToF data
  • Color coded visualization of ToF images
  • Preprocessing of the distance data: Threshold, median, average and bilateral filtering; surface generation
  • Simple measurement and PointSet definition
\sa QmitkFunctionality \ingroup Functionalities */ class QmitkToFUtilView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkToFUtilView(); ~QmitkToFUtilView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Called when the functionality is activated virtual void Activated(); /// \brief Called when the functionality is deactivated virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /*! \brief Slot triggered from the timer to update the images and visualization */ void OnUpdateCamera(); /*! \brief Slot called when the "Connect" button of the ConnectionWidget is pressed */ void OnToFCameraConnected(); /*! \brief Slot called when the "Disconnect" button of the ConnectionWidget is pressed */ void OnToFCameraDisconnected(); /*! \brief Slot called when the camera selection in the ConnectionWidget has changed */ void OnToFCameraSelected(const QString selected); /*! \brief Slot called when the "Start" button of the RecorderWidget is pressed */ void OnToFCameraStarted(); /*! \brief Slot called when the "Stop" button of the RecorderWidget is pressed */ void OnToFCameraStopped(); /*! \brief Slot invoked when the texture checkbox is checked. Enables the scalar visibility of the surface */ void OnTextureCheckBoxChecked(bool checked); /*! \brief Slot invoked when the video texture checkbox is checked. Enables the texture of the surface */ void OnVideoTextureCheckBoxChecked(bool checked); protected: /*! \brief initialize the visibility settings of ToF data (images + surface) \param useToF true: distance image: widget1, amplitude image: widget 2, intensity image: widget 3; false: standard */ void UseToFVisibilitySettings(bool useToF); Ui::QmitkToFUtilViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; QTimer* m_Frametimer; ///< Timer used to continuously update the images mitk::Image::Pointer m_MitkDistanceImage; ///< member holding a pointer to the distance image of the selected camera mitk::Image::Pointer m_MitkAmplitudeImage; ///< member holding a pointer to the amplitude image of the selected camera mitk::Image::Pointer m_MitkIntensityImage; ///< member holding a pointer to the intensity image of the selected camera mitk::Surface::Pointer m_Surface; ///< member holding a pointer to the surface generated from the distance image of the selected camera mitk::DataNode::Pointer m_DistanceImageNode; ///< DataNode holding the distance image of the selected camera mitk::DataNode::Pointer m_AmplitudeImageNode; ///< DataNode holding the amplitude image of the selected camera mitk::DataNode::Pointer m_IntensityImageNode; ///< DataNode holding the intensity image of the selected camera mitk::DataNode::Pointer m_SurfaceNode; ///< DataNode holding the surface generated from the distanc image of the selected camera // ToF processing and recording filter mitk::ToFImageRecorder::Pointer m_ToFImageRecorder; ///< ToF image recorder used for lossless recording of ToF image data mitk::ToFImageGrabber::Pointer m_ToFImageGrabber; ///< Source of a ToF image processing pipeline. Provides pointers to distance, amplitude and intensity image mitk::ToFDistanceImageToSurfaceFilter::Pointer m_ToFDistanceImageToSurfaceFilter; ///< Filter for calculating a surface representation from a given distance image mitk::ToFCompositeFilter::Pointer m_ToFCompositeFilter; ///< Filter combining several processing steps (thresholding, Median filtering, Bilateral filtering) int m_SurfaceDisplayCount; ///< member used to determine whether surface is initialized or not int m_2DDisplayCount; ///< member used to determine whether frame rate output should be shown // members for calculating the frame rate mitk::RealTimeClock::Pointer m_RealTimeClock; ///< real time clock used to calculate the display framerate int m_StepsForFramerate; ///< number of steps used for calculating the display framerate double m_2DTimeBefore; ///< holds the time stamp at the beginning of the display framerate measurement double m_2DTimeAfter; ///< holds the time stamp at the end of the display framerate measurement // members used for displaying an external video source mitk::OpenCVVideoSource::Pointer m_VideoSource; ///< OpenCV video source to connect a video device unsigned char* m_VideoTexture; ///< texture used to show video image int m_VideoCaptureWidth; ///< width of the video image int m_VideoCaptureHeight; ///< height of the video image bool m_VideoEnabled; ///< flag indicating whether video grabbing is enabled. Set via the RGB texture checkbox private: /*! \brief helper method to replace data of the specified node. If node does not exist it will be created \param nodeName Name of the node \param data Data object to be replaced \return returns the node */ mitk::DataNode::Pointer ReplaceNodeData(std::string nodeName, mitk::BaseData* data); void ProcessVideoTransform(); mitk::ToFSurfaceVtkMapper3D::Pointer m_ToFSurfaceVtkMapper3D; }; #endif // _QMITKTOFUTILVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp index 53ae45a723..c2b7016ed2 100644 --- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp +++ b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp @@ -1,302 +1,301 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkUGVisualizationView.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include class UGVisVolumeObserver : public mitk::PropertyView { public: UGVisVolumeObserver(mitk::BoolProperty* property, QmitkUGVisualizationView* view) : PropertyView(property), m_View(view), m_BoolProperty(property) { } protected: virtual void PropertyChanged() { m_View->m_VolumeMode = m_BoolProperty->GetValue(); m_View->UpdateEnablement(); } virtual void PropertyRemoved() { m_View->m_VolumeMode = false; m_Property = 0; m_BoolProperty = 0; } QmitkUGVisualizationView* m_View; mitk::BoolProperty* m_BoolProperty; }; const std::string QmitkUGVisualizationView::VIEW_ID = "org.mitk.views.ugvisualization"; QmitkUGVisualizationView::QmitkUGVisualizationView() : QmitkFunctionality(), m_MultiWidget(0), m_Outline2DAction(0), m_Outline2DWidget(0), m_LODAction(0), m_ScalarVisibilityAction(0), m_ScalarVisibilityWidget(0), m_FirstVolumeRepId(-1), m_ShowTFGeneratorWidget(true), m_ShowScalarOpacityWidget(false), m_ShowColorWidget(true), m_ShowGradientOpacityWidget(false), m_ShowTFGeneratorAction(0), m_ShowScalarOpacityAction(0), m_ShowColorAction(0), m_ShowGradientOpacityAction(0), m_VolumeModeObserver(0) { } QmitkUGVisualizationView::QmitkUGVisualizationView(const QmitkUGVisualizationView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkUGVisualizationView::~QmitkUGVisualizationView() { delete m_VolumeModeObserver; } void QmitkUGVisualizationView::CreateQtPartControl( QWidget *parent ) { m_Controls.setupUi( parent ); m_Outline2DWidget = new QmitkBoolPropertyWidget("Outline 2D polygons", parent); m_Outline2DAction = new QWidgetAction(this); m_Outline2DAction->setDefaultWidget(m_Outline2DWidget); m_LODAction = new QAction("Enable LOD (Level Of Detail)", this); m_LODAction->setCheckable(true); m_ScalarVisibilityWidget = new QmitkBoolPropertyWidget("Visualize scalars", parent); m_ScalarVisibilityAction = new QWidgetAction(this); m_ScalarVisibilityAction->setDefaultWidget(m_ScalarVisibilityWidget); m_ShowColorAction = new QAction("Show color transfer function", this); m_ShowColorAction->setCheckable(true); m_ShowColorAction->setChecked(m_ShowColorWidget); m_ShowGradientOpacityAction = new QAction("Show gradient opacity function", this); m_ShowGradientOpacityAction->setCheckable(true); m_ShowGradientOpacityAction->setChecked(m_ShowGradientOpacityWidget); m_ShowScalarOpacityAction = new QAction("Show scalar opacity function", this); m_ShowScalarOpacityAction->setCheckable(true); m_ShowScalarOpacityAction->setChecked(m_ShowScalarOpacityWidget); m_ShowTFGeneratorAction = new QAction("Show transfer function generator", this); m_ShowTFGeneratorAction->setCheckable(true); m_ShowTFGeneratorAction->setChecked(m_ShowTFGeneratorWidget); QMenu* menu = new QMenu(parent); menu->addAction(m_ScalarVisibilityAction); menu->addAction(m_Outline2DAction); //menu->addAction(m_LODAction); menu->addSeparator(); menu->addAction(m_ShowTFGeneratorAction); menu->addAction(m_ShowScalarOpacityAction); menu->addAction(m_ShowColorAction); menu->addAction(m_ShowGradientOpacityAction); m_Controls.m_OptionsButton->setMenu(menu); m_Controls.m_TransferFunctionWidget->SetScalarLabel("Scalar value"); // const mitk::EnumerationProperty::EnumStringsContainerType& scalarStrings = scalarProp->GetEnumStrings(); // for (mitk::EnumerationProperty::EnumStringsContainerType::const_iterator it = scalarStrings.begin(); // it != scalarStrings.end(); ++it) // { // MITK_INFO << "ADding: " << it->first; // m_Controls.m_ScalarModeComboBox->addItem(QString::fromStdString(it->first), it->second); // } this->UpdateGUI(); CreateConnections(); } void QmitkUGVisualizationView::CreateConnections() { connect(m_Controls.m_ScalarModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateRenderWindow())); connect(m_Controls.m_RepresentationComboBox, SIGNAL(activated(int)), this, SLOT(UpdateRenderWindow())); connect(m_Outline2DWidget, SIGNAL(toggled(bool)), this, SLOT(UpdateRenderWindow())); connect(m_ScalarVisibilityWidget, SIGNAL(toggled(bool)), this, SLOT(UpdateRenderWindow())); connect(m_Controls.m_TransferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()), m_Controls.m_TransferFunctionWidget, SLOT(OnUpdateCanvas())); connect(m_ShowColorAction, SIGNAL(triggered(bool)), this, SLOT(ShowColorWidget(bool))); connect(m_ShowGradientOpacityAction, SIGNAL(triggered(bool)), this, SLOT(ShowGradientOpacityWidget(bool))); connect(m_ShowScalarOpacityAction, SIGNAL(triggered(bool)), this, SLOT(ShowScalarOpacityWidget(bool))); connect(m_ShowTFGeneratorAction, SIGNAL(triggered(bool)), this, SLOT(ShowTFGeneratorWidget(bool))); } void QmitkUGVisualizationView::UpdateRenderWindow() { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkUGVisualizationView::ShowTFGeneratorWidget(bool show) { m_ShowTFGeneratorWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::ShowScalarOpacityWidget(bool show) { m_ShowScalarOpacityWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::ShowColorWidget(bool show) { m_ShowColorWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::ShowGradientOpacityWidget(bool show) { m_ShowGradientOpacityWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::UpdateEnablement() { m_Controls.m_TransferFunctionGeneratorWidget->setVisible(m_ShowTFGeneratorWidget); m_Controls.m_TransferFunctionWidget->ShowScalarOpacityFunction(m_ShowScalarOpacityWidget); m_Controls.m_TransferFunctionWidget->ShowColorFunction(m_ShowColorWidget); m_Controls.m_TransferFunctionWidget->ShowGradientOpacityFunction(m_ShowGradientOpacityWidget); m_Controls.m_TransferFunctionGeneratorWidget->SetThresholdTabEnabled(m_VolumeMode); m_Controls.m_TransferFunctionGeneratorWidget->SetBellTabEnabled(m_VolumeMode); m_Controls.m_TransferFunctionWidget->SetScalarOpacityFunctionEnabled(m_VolumeMode); m_Controls.m_TransferFunctionWidget->SetGradientOpacityFunctionEnabled(m_VolumeMode); } void QmitkUGVisualizationView::UpdateGUI() { bool enable = false; mitk::DataNode* node = 0; std::vector nodes = this->GetDataManagerSelection(); if (!nodes.empty()) { node = nodes.front(); if (node) { // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item mitk::BaseData* data = node->GetData(); if (data) { // test if this data item is an unstructured grid enable = dynamic_cast( data ); } } } m_Controls.m_SelectedLabel->setVisible(enable); m_Controls.m_ErrorLabel->setVisible(!enable); m_Controls.m_ContainerWidget->setEnabled(enable); m_Controls.m_OptionsButton->setEnabled(enable); if (enable) { m_VolumeMode = false; node->GetBoolProperty("volumerendering", m_VolumeMode); m_Controls.m_SelectedLabel->setText(QString("Selected UG: ") + node->GetName().c_str()); m_Controls.m_TransferFunctionGeneratorWidget->SetDataNode(node); m_Controls.m_TransferFunctionWidget->SetDataNode(node); mitk::BoolProperty* outlineProp = 0; node->GetProperty(outlineProp, "outline polygons"); m_Outline2DWidget->SetProperty(outlineProp); mitk::BoolProperty* scalarVisProp = 0; node->GetProperty(scalarVisProp, "scalar visibility"); m_ScalarVisibilityWidget->SetProperty(scalarVisProp); mitk::VtkScalarModeProperty* scalarProp = 0; if (node->GetProperty(scalarProp, "scalar mode")) { m_Controls.m_ScalarModeComboBox->SetProperty(scalarProp); } mitk::GridRepresentationProperty* gridRepProp = 0; mitk::GridVolumeMapperProperty* gridVolumeProp = 0; mitk::BoolProperty* volumeProp = 0; node->GetProperty(gridRepProp, "grid representation"); node->GetProperty(gridVolumeProp, "volumerendering.mapper"); node->GetProperty(volumeProp, "volumerendering"); m_Controls.m_RepresentationComboBox->SetProperty(gridRepProp, gridVolumeProp, volumeProp); if (m_VolumeModeObserver) { delete m_VolumeModeObserver; m_VolumeModeObserver = 0; } if (volumeProp) { m_VolumeModeObserver = new UGVisVolumeObserver(volumeProp, this); } } UpdateEnablement(); } void QmitkUGVisualizationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkUGVisualizationView::StdMultiWidgetNotAvailable() { m_MultiWidget = 0; } void QmitkUGVisualizationView::OnSelectionChanged( std::vector nodes ) { UpdateGUI(); } diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h index 7992a88e2a..984d96a864 100644 --- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h +++ b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h @@ -1,118 +1,117 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision$ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QmitkUGVisualizationView_h #define QmitkUGVisualizationView_h #include #include #include "ui_QmitkUGVisualizationViewControls.h" class QWidgetAction; class QmitkBoolPropertyWidget; namespace mitk { class PropertyObserver; } /*! \brief QmitkUGVisualizationView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkUGVisualizationView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkUGVisualizationView(); QmitkUGVisualizationView(const QmitkUGVisualizationView& other); virtual ~QmitkUGVisualizationView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: void UpdateRenderWindow(); void ShowTFGeneratorWidget(bool show); void ShowScalarOpacityWidget(bool show); void ShowColorWidget(bool show); void ShowGradientOpacityWidget(bool show); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); void CreateConnections(); private: friend class UGVisVolumeObserver; void UpdateGUI(); void UpdateEnablement(); Ui::QmitkUGVisualizationViewControls m_Controls; QmitkStdMultiWidget* m_MultiWidget; QWidgetAction* m_Outline2DAction; QmitkBoolPropertyWidget* m_Outline2DWidget; QAction* m_LODAction; QWidgetAction* m_ScalarVisibilityAction; QmitkBoolPropertyWidget* m_ScalarVisibilityWidget; int m_FirstVolumeRepId; QHash m_MapRepComboToEnumId; bool m_VolumeMode; bool m_ShowTFGeneratorWidget; bool m_ShowScalarOpacityWidget; bool m_ShowColorWidget; bool m_ShowGradientOpacityWidget; QAction* m_ShowTFGeneratorAction; QAction* m_ShowScalarOpacityAction; QAction* m_ShowColorAction; QAction* m_ShowGradientOpacityAction; mitk::PropertyObserver* m_VolumeModeObserver; }; #endif // _QMITKUGVISUALIZATIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp index 67ab188aac..5042fbfe12 100755 --- a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp +++ b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp @@ -1,344 +1,343 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 15646 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "QmitkVolumeVisualizationView.h" #include #include #include #include //#include #include #include #include #include #include #include #include "mitkHistogramGenerator.h" #include "QmitkPiecewiseFunctionCanvas.h" #include "QmitkColorTransferFunctionCanvas.h" #include "mitkBaseRenderer.h" #include "mitkGPUVolumeMapper3D.h" #include "mitkVtkVolumeRenderingProperty.h" #include #include const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization"; enum RenderMode { RM_CPU_COMPOSITE_RAYCAST = 0, RM_CPU_MIP_RAYCAST = 1, RM_GPU_COMPOSITE_SLICING = 2, RM_GPU_COMPOSITE_RAYCAST = 3, RM_GPU_MIP_RAYCAST = 4 }; QmitkVolumeVisualizationView::QmitkVolumeVisualizationView() : QmitkFunctionality(), m_Controls(NULL) { } QmitkVolumeVisualizationView::~QmitkVolumeVisualizationView() { } void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { m_Controls = new Ui::QmitkVolumeVisualizationViewControls; m_Controls->setupUi(parent); m_Controls->m_TransferFunctionWidget->SetIntegerMode(true); // Fill the tf presets in the generator widget std::vector names; mitk::TransferFunctionInitializer::GetPresetNames(names); for (std::vector::const_iterator it = names.begin(); it != names.end(); ++it) { m_Controls->m_TransferFunctionGeneratorWidget->AddPreset(QString::fromStdString(*it)); } m_Controls->m_RenderMode->addItem("CPU raycast"); m_Controls->m_RenderMode->addItem("CPU MIP raycast"); m_Controls->m_RenderMode->addItem("GPU slicing"); // Only with VTK 5.6 or above #if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) m_Controls->m_RenderMode->addItem("GPU raycast"); m_Controls->m_RenderMode->addItem("GPU MIP raycast"); #endif connect( m_Controls->m_EnableRenderingCB, SIGNAL( toggled(bool) ),this, SLOT( OnEnableRendering(bool) )); connect( m_Controls->m_EnableLOD, SIGNAL( toggled(bool) ),this, SLOT( OnEnableLOD(bool) )); connect( m_Controls->m_RenderMode, SIGNAL( activated(int) ),this, SLOT( OnRenderMode(int) )); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL( SignalUpdateCanvas( ) ), m_Controls->m_TransferFunctionWidget, SLOT( OnUpdateCanvas( ) ) ); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)), SLOT(OnMitkInternalPreset(int))); m_Controls->m_EnableRenderingCB->setEnabled(false); m_Controls->m_EnableLOD->setEnabled(false); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); } } void QmitkVolumeVisualizationView::OnMitkInternalPreset( int mode ) { if (m_SelectedNode.IsNull()) return; mitk::DataNode::Pointer node(m_SelectedNode.GetPointer()); mitk::TransferFunctionProperty::Pointer transferFuncProp; if (node->GetProperty(transferFuncProp, "TransferFunction")) { //first item is only information if( --mode == -1 ) return; // -- Creat new TransferFunction mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue()); tfInit->SetTransferFunctionMode(mode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_Controls->m_TransferFunctionWidget->OnUpdateCanvas(); } } void QmitkVolumeVisualizationView::OnSelectionChanged( std::vector nodes ) { bool weHadAnImageButItsNotThreeDeeOrFourDee = false; mitk::DataNode::Pointer node; for (std::vector::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) { mitk::DataNode::Pointer currentNode = *iter; if( currentNode.IsNotNull() && dynamic_cast(currentNode->GetData()) ) { if( dynamic_cast(currentNode->GetData())->GetDimension()>=3 ) { if (node.IsNull()) { node = currentNode; } } else { weHadAnImageButItsNotThreeDeeOrFourDee = true; } } } if( node.IsNotNull() ) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_SelectedImageLabel->show(); std::string infoText; if (node->GetName().empty()) infoText = std::string("Selected Image: [currently selected image has no name]"); else infoText = std::string("Selected Image: ") + node->GetName(); m_Controls->m_SelectedImageLabel->setText( QString( infoText.c_str() ) ); m_SelectedNode = node; } else { if(weHadAnImageButItsNotThreeDeeOrFourDee) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->show(); std::string infoText; infoText = std::string("only 3D or 4D images are supported"); m_Controls->m_ErrorImageLabel->setText( QString( infoText.c_str() ) ); } else { m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); } m_SelectedNode = 0; } UpdateInterface(); } void QmitkVolumeVisualizationView::UpdateInterface() { if(m_SelectedNode.IsNull()) { // turnoff all m_Controls->m_EnableRenderingCB->setChecked(false); m_Controls->m_EnableRenderingCB->setEnabled(false); m_Controls->m_EnableLOD->setChecked(false); m_Controls->m_EnableLOD->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } bool enabled = false; m_SelectedNode->GetBoolProperty("volumerendering",enabled); m_Controls->m_EnableRenderingCB->setEnabled(true); m_Controls->m_EnableRenderingCB->setChecked(enabled); if(!enabled) { // turnoff all except volumerendering checkbox m_Controls->m_EnableLOD->setChecked(false); m_Controls->m_EnableLOD->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } // otherwise we can activate em all enabled = false; m_SelectedNode->GetBoolProperty("volumerendering.uselod",enabled); m_Controls->m_EnableLOD->setEnabled(true); m_Controls->m_EnableLOD->setChecked(enabled); m_Controls->m_RenderMode->setEnabled(true); // Determine Combo Box mode { bool usegpu=false; bool useray=false; bool usemip=false; m_SelectedNode->GetBoolProperty("volumerendering.usegpu",usegpu); // Only with VTK 5.6 or above #if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) m_SelectedNode->GetBoolProperty("volumerendering.useray",useray); #endif m_SelectedNode->GetBoolProperty("volumerendering.usemip",usemip); int mode = 0; if(useray) { if(usemip) mode=RM_GPU_MIP_RAYCAST; else mode=RM_GPU_COMPOSITE_RAYCAST; } else if(usegpu) mode=RM_GPU_COMPOSITE_SLICING; else { if(usemip) mode=RM_CPU_MIP_RAYCAST; else mode=RM_CPU_COMPOSITE_RAYCAST; } m_Controls->m_RenderMode->setCurrentIndex(mode); } m_Controls->m_TransferFunctionWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionWidget->setEnabled(true); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(true); } void QmitkVolumeVisualizationView::OnEnableRendering(bool state) { if(m_SelectedNode.IsNull()) return; m_SelectedNode->SetProperty("volumerendering",mitk::BoolProperty::New(state)); UpdateInterface(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkVolumeVisualizationView::OnEnableLOD(bool state) { if(m_SelectedNode.IsNull()) return; m_SelectedNode->SetProperty("volumerendering.uselod",mitk::BoolProperty::New(state)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkVolumeVisualizationView::OnRenderMode(int mode) { if(m_SelectedNode.IsNull()) return; bool usegpu=mode==RM_GPU_COMPOSITE_SLICING; // Only with VTK 5.6 or above #if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) bool useray=(mode==RM_GPU_COMPOSITE_RAYCAST)||(mode==RM_GPU_MIP_RAYCAST); #endif bool usemip=(mode==RM_GPU_MIP_RAYCAST)||(mode==RM_CPU_MIP_RAYCAST); m_SelectedNode->SetProperty("volumerendering.usegpu",mitk::BoolProperty::New(usegpu)); // Only with VTK 5.6 or above #if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) m_SelectedNode->SetProperty("volumerendering.useray",mitk::BoolProperty::New(useray)); #endif m_SelectedNode->SetProperty("volumerendering.usemip",mitk::BoolProperty::New(usemip)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkVolumeVisualizationView::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h index 6de9dd9ea6..f3ff866ece 100755 --- a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h +++ b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h @@ -1,89 +1,88 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 15646 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef QMITKVOLUMEVISUALIZATIONVIEW_H_ #define QMITKVOLUMEVISUALIZATIONVIEW_H_ #include #include #include #include #include #include "mitkDataStorage.h" #include #include #include #include "ui_QmitkVolumeVisualizationViewControls.h" /** * \ingroup org_mitk_gui_qt_volumevisualization_internal */ class QmitkVolumeVisualizationView : public QmitkFunctionality { Q_OBJECT public: void SetFocus(); QmitkVolumeVisualizationView(); virtual ~QmitkVolumeVisualizationView(); virtual void CreateQtPartControl(QWidget *parent); /// /// Invoked when the DataManager selection changed /// virtual void OnSelectionChanged( std::vector nodes ); static const std::string VIEW_ID; protected slots: void OnMitkInternalPreset( int mode ); void OnEnableRendering( bool state ); void OnEnableLOD( bool state ); void OnRenderMode( int mode ); protected: /// /// A selection listener for datatreenode events /// berry::ISelectionListener::Pointer m_SelectionListener; Ui::QmitkVolumeVisualizationViewControls* m_Controls; private: mitk::WeakPointer m_SelectedNode; void UpdateInterface(); }; #endif /*QMITKVOLUMEVISUALIZATIONVIEW_H_*/ diff --git a/Plugins/org.mitk.inputdevices.spacenavigator/manifest.cpp b/Plugins/org.mitk.inputdevices.spacenavigator/manifest.cpp index 8da064de7e..3cb721c265 100644 --- a/Plugins/org.mitk.inputdevices.spacenavigator/manifest.cpp +++ b/Plugins/org.mitk.inputdevices.spacenavigator/manifest.cpp @@ -1,26 +1,25 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include "src/internal/mitkSpaceNavigatorActivator.h" POCO_BEGIN_NAMED_MANIFEST(mitkIInputDevice, mitk::IInputDevice) POCO_EXPORT_CLASS(mitk::SpaceNavigatorActivator) POCO_END_MANIFEST diff --git a/Plugins/org.mitk.inputdevices.spacenavigator/src/SpacenavigatorDll.h b/Plugins/org.mitk.inputdevices.spacenavigator/src/SpacenavigatorDll.h index e27de57038..d3d7526bc3 100644 --- a/Plugins/org.mitk.inputdevices.spacenavigator/src/SpacenavigatorDll.h +++ b/Plugins/org.mitk.inputdevices.spacenavigator/src/SpacenavigatorDll.h @@ -1,43 +1,42 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _SPACENAVIGATOR_EXPORT_DLL_H_ #define _SPACENAVIGATOR_EXPORT_DLL_H_ // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the org_mitk_inputdevices_spacenavigator_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // org_mitk_inputdevices_spacenavigator_EXPORTS functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && !defined(MITK_STATIC) #if defined(org_mitk_inputdevices_spacenavigator_EXPORTS) #define SPACENAVIGATOR_EXPORT __declspec(dllexport) #else #define SPACENAVIGATOR_EXPORT __declspec(dllimport) #endif #endif #if !defined(SPACENAVIGATOR_EXPORT) #define SPACENAVIGATOR_EXPORT #endif #endif /*_SPACENAVIGATOR_EXPORT_DLL_H_*/ diff --git a/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.cpp b/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.cpp index cb222252e5..5a4fa7adb0 100644 --- a/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.cpp +++ b/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.cpp @@ -1,67 +1,66 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkSpaceNavigatorActivator.h" #include #include #include mitk::SpaceNavigatorActivator::SpaceNavigatorActivator() : m_IsRegistered(false), m_Controller(mitk::SpaceNavigatorVtkCameraController::New()) { } bool mitk::SpaceNavigatorActivator::RegisterInputDevice() { if(!this->m_IsRegistered) { mitk::GlobalInteraction::GetInstance()->AddListener(m_Controller); mitk::EventMapper* eventMapper(mitk::GlobalInteraction::GetInstance()->GetEventMapper()); if (eventMapper != NULL) { eventMapper->AddEventMapperAddOn(mitk::SpaceNavigatorAddOn::GetInstance()); this->m_IsRegistered = true; } else { return false; } } return true; } bool mitk::SpaceNavigatorActivator::UnRegisterInputDevice() { if(this->m_IsRegistered) { mitk::GlobalInteraction::GetInstance()->RemoveListener(m_Controller); mitk::EventMapper* eventMapper(mitk::GlobalInteraction::GetInstance()->GetEventMapper()); if(eventMapper != NULL) { eventMapper->RemoveEventMapperAddOn(mitk::SpaceNavigatorAddOn::GetInstance()); this->m_IsRegistered = false; } else { return false; } } return true; } diff --git a/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.h b/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.h index fc5aea2426..639d962a25 100644 --- a/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.h +++ b/Plugins/org.mitk.inputdevices.spacenavigator/src/internal/mitkSpaceNavigatorActivator.h @@ -1,66 +1,65 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITK_SPACENAVIGATORACTIVATOR_H_ #define MITK_SPACENAVIGATORACTIVATOR_H_ #include #include #include #include #include namespace mitk { /** * Documentation in the interface. * * @ingroup org_mitk_inputdevices_spacenavigator */ class SpaceNavigatorActivator : public IInputDevice { public: /** * @see mitk::IInputDevice::RegisterInputDevice() */ bool RegisterInputDevice(); /** * @see mitk::IInputDevice::UnRegisterInputDevice() */ bool UnRegisterInputDevice(); /** * Default constructor */ SpaceNavigatorActivator(); protected: private: bool m_IsRegistered; mitk::SpaceNavigatorVtkCameraController::Pointer m_Controller; }; // end class SpaceNavigatorActivator } // end namespace mitk #endif /* MITK_SPACENAVIGATORACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.inputdevices.wiimote/manifest.cpp b/Plugins/org.mitk.inputdevices.wiimote/manifest.cpp index 3b43a83c2c..9d02368a5f 100644 --- a/Plugins/org.mitk.inputdevices.wiimote/manifest.cpp +++ b/Plugins/org.mitk.inputdevices.wiimote/manifest.cpp @@ -1,26 +1,25 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include #include #include "src/internal/mitkWiiMoteActivator.h" POCO_BEGIN_NAMED_MANIFEST(mitkIInputDevice, mitk::IInputDevice) POCO_EXPORT_CLASS(mitk::WiiMoteActivator) POCO_END_MANIFEST diff --git a/Plugins/org.mitk.inputdevices.wiimote/src/WiimoteDll.h b/Plugins/org.mitk.inputdevices.wiimote/src/WiimoteDll.h index f04d7f4b5a..e334fe8507 100644 --- a/Plugins/org.mitk.inputdevices.wiimote/src/WiimoteDll.h +++ b/Plugins/org.mitk.inputdevices.wiimote/src/WiimoteDll.h @@ -1,43 +1,42 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef _WIIMOTE_EXPORT_DLL_H_ #define _WIIMOTE_EXPORT_DLL_H_ // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the org_mitk_inputdevices_wiimote_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // org_mitk_inputdevices_wiimote_EXPORTS functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && !defined(MITK_STATIC) #if defined(org_mitk_inputdevices_wiimote_EXPORTS) #define WIIMOTE_EXPORT __declspec(dllexport) #else #define WIIMOTE_EXPORT __declspec(dllimport) #endif #endif #if !defined(WIIMOTE_EXPORT) #define WIIMOTE_EXPORT #endif #endif /*_WIIMOTE_EXPORT_DLL_H_*/ diff --git a/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp b/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp index cc84456b44..513d7fc4e6 100644 --- a/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp +++ b/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp @@ -1,191 +1,190 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkWiiMoteActivator.h" #include "mitkWiiMoteAddOn.h" //mitk #include "mitkGlobalInteraction.h" #include "mitkCoreExtConstants.h" #include #include #include mitk::WiiMoteActivator::WiiMoteActivator() : m_IsRegistered(false) , m_Controller(mitk::WiiMoteVtkCameraController::New()) , m_Interactor(NULL) , m_Node(NULL) { m_PrefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); } mitk::WiiMoteActivator::~WiiMoteActivator() { } bool mitk::WiiMoteActivator::RegisterInputDevice() { if(!this->m_IsRegistered) { mitk::WiiMoteAddOn::GetInstance()->ActivateWiiMotes(); mitk::EventMapper* eventMapper(mitk::GlobalInteraction::GetInstance()->GetEventMapper()); if (eventMapper != NULL) { eventMapper->AddEventMapperAddOn(mitk::WiiMoteAddOn::GetInstance()); this->m_IsRegistered = true; } else { MITK_ERROR << "Eventmapper is not initialized!"; return false; } } // get the current preferences m_WiiMotePreferencesNode = m_PrefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES); // modus change between Surface Interaction and VR Headtracking if(m_WiiMotePreferencesNode->GetBool(CoreExtConstants::WIIMOTE_SURFACEINTERACTION,false)) { if(mitk::GlobalInteraction::GetInstance()->ListenerRegistered(m_Controller)) { mitk::GlobalInteraction::GetInstance()->RemoveListener(m_Controller); } this->AddSurfaceInteractor(); } else { // Headtracking listener already registered if(!(mitk::GlobalInteraction::GetInstance()->ListenerRegistered(m_Controller))) { mitk::GlobalInteraction::GetInstance()->AddListener(m_Controller); } this->RemoveSurfaceInteractor(); } return true; } bool mitk::WiiMoteActivator::UnRegisterInputDevice() { if(this->m_IsRegistered) { mitk::WiiMoteAddOn::GetInstance()->DeactivateWiiMotes(); // remove Headtracking listener if(mitk::GlobalInteraction::GetInstance()->ListenerRegistered(m_Controller)) { mitk::GlobalInteraction::GetInstance()->RemoveListener(m_Controller); } this->RemoveSurfaceInteractor(); mitk::EventMapper* eventMapper(mitk::GlobalInteraction::GetInstance()->GetEventMapper()); if(eventMapper != NULL) { eventMapper->RemoveEventMapperAddOn(mitk::WiiMoteAddOn::GetInstance()); this->m_IsRegistered = false; } else { MITK_ERROR << "Eventmapper is not initialized!"; return false; } } return true; } mitk::DataStorage::Pointer mitk::WiiMoteActivator::GetDataStorage() { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry(). GetServiceById(mitk::IDataStorageService::ID); if (service.IsNotNull()) { return service->GetActiveDataStorage()->GetDataStorage(); } return 0; } void mitk::WiiMoteActivator::AddSurfaceInteractor() { mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); // model was designed by Patrick Grubb std::string fileName = MITK_ROOT; fileName += "Modules/InputDevices/WiiMote/WiiMoteModel.obj"; try { nodeReader->SetFileName(fileName.c_str()); nodeReader->Update(); m_Node = nodeReader->GetOutput(); if(m_Interactor.IsNull()) { m_Interactor = mitk::WiiMoteInteractor::New("WiiMoteSurfaceInteraction",m_Node); } m_Node->SetInteractor(m_Interactor); this->GetDataStorage()->Add(m_Node); if(!(mitk::GlobalInteraction::GetInstance()->InteractorRegistered(m_Interactor))) { mitk::GlobalInteraction::GetInstance()->AddInteractor(m_Interactor); } mitk::WiiMoteAddOn::GetInstance()->SetWiiMoteSurfaceIModus(true); } catch(...) { MITK_ERROR << "Wiimote Surface Interaction could not be initialized"; } } void mitk::WiiMoteActivator::RemoveSurfaceInteractor() { try { if(m_Node.IsNotNull()) { this->GetDataStorage()->Remove(m_Node); } if(m_Interactor.IsNotNull() && mitk::GlobalInteraction::GetInstance()->InteractorRegistered(m_Interactor)) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_Interactor); } mitk::WiiMoteAddOn::GetInstance()->SetWiiMoteSurfaceIModus(false); } catch(...) { MITK_ERROR << "Wiimote Surface Interactor could not be properly removed"; } } \ No newline at end of file diff --git a/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.h b/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.h index 1bc6a2b54a..0bc62d9d86 100644 --- a/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.h +++ b/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.h @@ -1,82 +1,81 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ -Version: $Revision: 21975 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITK_WIIMOTEACTIVATOR_H_ #define MITK_WIIMOTEACTIVATOR_H_ // berry #include #include #include // mitk #include "mitkIInputDevice.h" #include "mitkWiiMoteVtkCameraController.h" #include #include namespace mitk { class WiiMoteActivator : public IInputDevice { public: WiiMoteActivator(); ~WiiMoteActivator(); /** * @see mitk::IInputDevice::RegisterInputDevice() */ bool RegisterInputDevice(); /** * @see mitk::IInputDevice::UnRegisterInputDevice() */ bool UnRegisterInputDevice(); protected: private: bool m_IsRegistered; // listener for headtracking and interactor for surface interaction mitk::WiiMoteVtkCameraController::Pointer m_Controller; mitk::WiiMoteInteractor::Pointer m_Interactor; // for xml accesss berry::IPreferences::Pointer m_WiiMotePreferencesNode; berry::IPreferencesService::Pointer m_PrefService; // needed for surface interaction mitk::DataNode::Pointer m_Node; /** * Gets the current active data storage.
* * @return the current data storage, if it fails NULL */ mitk::DataStorage::Pointer GetDataStorage(); void AddSurfaceInteractor(); void RemoveSurfaceInteractor(); }; // end class WiiMoteActivator } // end namespace mitk #endif // MITK_WIIMOTEACTIVATOR_H_ diff --git a/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.cpp b/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.cpp index 7321402025..125d632095 100644 --- a/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.cpp +++ b/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.cpp @@ -1,69 +1,68 @@ -/*========================================================================= +/*=================================================================== -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. -=========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkPlanarFigureActivator.h" #include "mitkPlanarFigureObjectFactory.h" #include "QmitkNodeDescriptorManager.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateAnd.h" #include void mitk::PlanarFigureActivator::start(ctkPluginContext* /*context*/) { QmitkNodeDescriptorManager* descriptorManager = QmitkNodeDescriptorManager::GetInstance(); // Adding "PlanarLine" mitk::NodePredicateDataType::Pointer isPlanarLine = mitk::NodePredicateDataType::New("PlanarLine"); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarLine"), QString(":/QmitkExt/PlanarLine_48.png"), isPlanarLine, descriptorManager)); // Adding "PlanarCircle" mitk::NodePredicateDataType::Pointer isPlanarCircle = mitk::NodePredicateDataType::New("PlanarCircle"); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarCircle"), QString(":/QmitkExt/PlanarCircle_48.png"), isPlanarCircle, descriptorManager)); // Adding "PlanarAngle" mitk::NodePredicateDataType::Pointer isPlanarAngle = mitk::NodePredicateDataType::New("PlanarAngle"); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarAngle"), QString(":/QmitkExt/PlanarAngle_48.png"), isPlanarAngle, descriptorManager)); // Adding "PlanarFourPointAngle" mitk::NodePredicateDataType::Pointer isPlanarFourPointAngle = mitk::NodePredicateDataType::New("PlanarFourPointAngle"); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarFourPointAngle"), QString(":/QmitkExt/PlanarFourPointAngle_48.png"), isPlanarFourPointAngle, descriptorManager)); // Adding "PlanarRectangle" mitk::NodePredicateDataType::Pointer isPlanarRectangle = mitk::NodePredicateDataType::New("PlanarRectangle"); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarRectangle"), QString(":/QmitkExt/PlanarRectangle_48.png"), isPlanarRectangle, descriptorManager)); // Adding "PlanarPolygon" mitk::NodePredicateDataType::Pointer isPlanarPolygon = mitk::NodePredicateDataType::New("PlanarPolygon"); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarPolygon"), QString(":/QmitkExt/PlanarPolygon_48.png"), isPlanarPolygon, descriptorManager)); // Adding "PlanarPath" mitk::NodePredicateProperty::Pointer isNotClosedPolygon = mitk::NodePredicateProperty::New("ClosedPlanarPolygon", mitk::BoolProperty::New(false)); mitk::NodePredicateAnd::Pointer isPlanarPath = mitk::NodePredicateAnd::New(isNotClosedPolygon, isPlanarPolygon); descriptorManager->AddDescriptor(new QmitkNodeDescriptor(QObject::tr("PlanarPath"), QString(":/QmitkExt/PlanarPath_48.png"), isPlanarPath, descriptorManager)); } void mitk::PlanarFigureActivator::stop(ctkPluginContext* /*context*/) { } Q_EXPORT_PLUGIN2(org_mitk_planarfigure, mitk::PlanarFigureActivator) diff --git a/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.h b/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.h index 6174f3d097..cce03d1109 100644 --- a/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.h +++ b/Plugins/org.mitk.planarfigure/src/internal/mitkPlanarFigureActivator.h @@ -1,53 +1,52 @@ -/*========================================================================= +/*=================================================================== - Program: MITK Platform - Language: C++ - Date: $Date: 2009-05-19 15:45:39 +0200 (Di, 19 Mai 2009) $ - Version: $Revision: 17020 $ +The Medical Imaging Interaction Toolkit (MITK) - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. - =========================================================================*/ +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #ifndef MITKPLANARFIGUREACTIVATOR_H_ #define MITKPLANARFIGUREACTIVATOR_H_ #include namespace mitk { /** * \ingroup org_mitk_planarfigure_internal * * \brief The plug-in activator for the planar figure module * * When the plug-in is started by the framework, it initialzes planar figure specific things. */ class PlanarFigureActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: /** * Registers sandbox core object factories. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; } #endif /* MITKPLANARFIGUREACTIVATOR_H_ */