diff --git a/Core/Code/IO/mitkIOUtil.cpp b/Core/Code/IO/mitkIOUtil.cpp index 71eef6e604..37dc199f77 100644 --- a/Core/Code/IO/mitkIOUtil.cpp +++ b/Core/Code/IO/mitkIOUtil.cpp @@ -1,317 +1,317 @@ /*=================================================================== 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 "mitkIOUtil.h" #include "mitkDataNodeFactory.h" #include "mitkImageWriter.h" #include "mitkPointSetWriter.h" #include "mitkSurfaceVtkWriter.h" #include #include #include #include #include //ITK #include //VTK #include #include #include namespace mitk { const std::string IOUtil::DEFAULTIMAGEEXTENSION = ".nrrd"; const std::string IOUtil::DEFAULTSURFACEEXTENSION = ".stl"; const std::string IOUtil::DEFAULTPOINTSETEXTENSION = ".mps"; int IOUtil::LoadFiles(const std::vector &fileNames, DataStorage &ds) { // Get the set of registered mitk::IDataNodeReader services - ModuleContext* context = GetModuleContext(); + ModuleContext* context = mitk::GetModuleContext(); const std::list refs = context->GetServiceReferences(); std::vector services; services.reserve(refs.size()); for (std::list::const_iterator i = refs.begin(); i != refs.end(); ++i) { IDataNodeReader* s = context->GetService(*i); if (s != 0) { services.push_back(s); } } mitk::ProgressBar::GetInstance()->AddStepsToDo(2*fileNames.size()); // Iterate over all file names and use the IDataNodeReader services // to load them. int nodesRead = 0; for (std::vector::const_iterator i = fileNames.begin(); i != fileNames.end(); ++i) { for (std::vector::const_iterator readerIt = services.begin(); readerIt != services.end(); ++readerIt) { try { int n = (*readerIt)->Read(*i, ds); nodesRead += n; if (n > 0) break; } catch (const std::exception& e) { MITK_WARN << e.what(); } } mitk::ProgressBar::GetInstance()->Progress(2); } for (std::list::const_iterator i = refs.begin(); i != refs.end(); ++i) { context->UngetService(*i); } return nodesRead; } DataStorage::Pointer IOUtil::LoadFiles(const std::vector& fileNames) { mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); LoadFiles(fileNames, *ds); return ds.GetPointer(); } DataNode::Pointer IOUtil::LoadDataNode(const std::string path) { mitk::DataNodeFactory::Pointer reader = mitk::DataNodeFactory::New(); try { reader->SetFileName( path ); reader->Update(); if((reader->GetNumberOfOutputs()<1)) { MITK_ERROR << "Could not find data '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says could not find data."; } mitk::DataNode::Pointer node = reader->GetOutput(0); if(node.IsNull()) { MITK_ERROR << "Could not find path: '" << path << "'" << " datanode is NULL" ; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says datanode is NULL."; } return reader->GetOutput( 0 ); } catch ( itk::ExceptionObject & e ) { MITK_ERROR << "Exception occured during load data of '" << path << "': Exception: " << e.what(); mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: " << e.what(); } } Image::Pointer IOUtil::LoadImage(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::Image::Pointer image = dynamic_cast(node->GetData()); if(image.IsNull()) { MITK_ERROR << "Image is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the image " << path << ". Exception says: Image is NULL."; } return image; } Surface::Pointer IOUtil::LoadSurface(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if(surface.IsNull()) { MITK_ERROR << "Surface is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: Surface is NULL."; } return surface; } PointSet::Pointer IOUtil::LoadPointSet(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::PointSet::Pointer pointset = dynamic_cast(node->GetData()); if(pointset.IsNull()) { MITK_ERROR << "PointSet is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: Pointset is NULL."; } return pointset; } bool IOUtil::SaveImage(mitk::Image::Pointer image, const std::string path) { std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); std::string finalFileName = dir + "/" + baseFilename; mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); //check if an extension is given, else use the defaul extension if( extension == "" ) { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTIMAGEEXTENSION; extension = DEFAULTIMAGEEXTENSION; } // check if extension is suitable for writing image data if (!imageWriter->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown. Extension set to default: " << finalFileName << DEFAULTIMAGEEXTENSION; extension = DEFAULTIMAGEEXTENSION; } try { //write the data imageWriter->SetInput(image); imageWriter->SetFileName(finalFileName.c_str()); imageWriter->SetExtension(extension.c_str()); imageWriter->Write(); } catch ( std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName + extension << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; } bool IOUtil::SaveSurface(Surface::Pointer surface, const std::string path) { std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); std::string finalFileName = dir + "/" + baseFilename; if (extension == "") // if no extension has been set we use the default extension { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTSURFACEEXTENSION; extension = DEFAULTSURFACEEXTENSION; } try { finalFileName += extension; if(extension == ".stl" ) { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); // check if surface actually consists of triangles; if not, the writer will not do anything; so, convert to triangles... vtkPolyData* polys = surface->GetVtkPolyData(); if( polys->GetNumberOfStrips() > 0 ) { vtkSmartPointer triangleFilter = vtkSmartPointer::New(); triangleFilter->SetInput(polys); triangleFilter->Update(); polys = triangleFilter->GetOutput(); polys->Register(NULL); surface->SetVtkPolyData(polys); } surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->GetVtkWriter()->SetFileTypeToBinary(); surfaceWriter->Write(); } else if(extension == ".vtp") { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->GetVtkWriter()->SetDataModeToBinary(); surfaceWriter->Write(); } else if(extension == ".vtk") { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->Write(); } else { // file extension not suitable for writing specified data type MITK_ERROR << "File extension is not suitable for writing'" << finalFileName; mitkThrow() << "An exception occured during writing the file " << finalFileName << ". File extension " << extension << " is not suitable for writing."; } } catch(std::exception& e) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; } bool IOUtil::SavePointSet(PointSet::Pointer pointset, const std::string path) { mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New(); std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); std::string finalFileName = dir + "/" + baseFilename; if (extension == "") // if no extension has been entered manually into the filename { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTPOINTSETEXTENSION; extension = DEFAULTPOINTSETEXTENSION; } // check if extension is valid if (!pointSetWriter->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown. Extension set to default: " << finalFileName << DEFAULTPOINTSETEXTENSION; extension = DEFAULTPOINTSETEXTENSION; } try { pointSetWriter->SetInput( pointset ); finalFileName += extension; pointSetWriter->SetFileName( finalFileName.c_str() ); pointSetWriter->Update(); } catch( std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; } } diff --git a/Modules/Python/CMakeLists.txt b/Modules/Python/CMakeLists.txt index 48409dc23e..582129e58e 100644 --- a/Modules/Python/CMakeLists.txt +++ b/Modules/Python/CMakeLists.txt @@ -1,8 +1,8 @@ MITK_CREATE_MODULE(mitkPython - DEPENDS Mitk CTK + DEPENDS Mitk EXPORT_DEFINE MITK_PYTHON_EXPORT - PACKAGE_DEPENDS QT + PACKAGE_DEPENDS QT CTK QT_MODULE ) configure_file(PythonPath.h.in "${CMAKE_CURRENT_BINARY_DIR}/PythonPath.h" @ONLY) diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkCtkPythonShell.cpp b/Modules/Python/QmitkCtkPythonShell.cpp similarity index 66% rename from Plugins/org.mitk.gui.qt.python/src/internal/QmitkCtkPythonShell.cpp rename to Modules/Python/QmitkCtkPythonShell.cpp index 76b899e2f9..2d14edd4a3 100644 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkCtkPythonShell.cpp +++ b/Modules/Python/QmitkCtkPythonShell.cpp @@ -1,71 +1,72 @@ /*=================================================================== 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 "QmitkCtkPythonShell.h" #include #include #include #include #include +#include "mitkPythonService.h" +#include +#include +#include struct QmitkCtkPythonShellData { - ctkAbstractPythonManager *m_PythonManager; + mitk::PythonService* m_PythonService; }; QmitkCtkPythonShell::QmitkCtkPythonShell(QWidget* parent) : ctkPythonConsole(parent), d( new QmitkCtkPythonShellData ) { - d->m_PythonManager = 0; + mitk::ModuleContext* context = mitk::GetModuleContext(); + mitk::ServiceReference serviceRef = context->GetServiceReference(); + d->m_PythonService = dynamic_cast ( context->GetService(serviceRef) ); + + assert( d->m_PythonService ); + this->initialize( d->m_PythonService->GetPythonManager() ); } QmitkCtkPythonShell::~QmitkCtkPythonShell() { delete d; } -void QmitkCtkPythonShell::SetPythonManager(ctkAbstractPythonManager *_PythonManager) -{ - d->m_PythonManager = _PythonManager; - this->initialize( _PythonManager ); -} - void QmitkCtkPythonShell::dragEnterEvent(QDragEnterEvent *event) { event->accept(); } void QmitkCtkPythonShell::dropEvent(QDropEvent *event) { QList urls = event->mimeData()->urls(); for(int i = 0; i < urls.size(); i++) { - d->m_PythonManager->executeString(urls[i].toString()); + d->m_PythonService->Execute( urls[i].toString(), mitk::IPythonService::SINGLE_LINE_COMMAND ); } } bool QmitkCtkPythonShell::canInsertFromMimeData( const QMimeData *source ) const { return true; } void QmitkCtkPythonShell::executeCommand(const QString& command) { - emit executeCommandSignal(command); ctkPythonConsole::executeCommand(command); - - emit newCommandExecuted(); + d->m_PythonService->NotifyObserver(command); } diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkCtkPythonShell.h b/Modules/Python/QmitkCtkPythonShell.h similarity index 85% rename from Plugins/org.mitk.gui.qt.python/src/internal/QmitkCtkPythonShell.h rename to Modules/Python/QmitkCtkPythonShell.h index 9eed7b5f34..1b737cc26d 100644 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkCtkPythonShell.h +++ b/Modules/Python/QmitkCtkPythonShell.h @@ -1,63 +1,58 @@ /*=================================================================== 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 QmitkCtkPythonShell_h #define QmitkCtkPythonShell_h #include #include +#include "mitkPythonExports.h" /// /// forward declarations /// struct QmitkCtkPythonShellData; class ctkAbstractPythonManager; class QDragEnterEvent; class QDropEvent; class QMimeData; /// /// Reimplements the ctkPythonConsole with drag and drop functionality for text +/// Furthermore it calls NotifyObserver() on the IPythonService to inform listeners /// -class QmitkCtkPythonShell : public ctkPythonConsole +class MITK_PYTHON_EXPORT QmitkCtkPythonShell : public ctkPythonConsole { Q_OBJECT public: QmitkCtkPythonShell(QWidget* parent = 0); ~QmitkCtkPythonShell(); - - void SetPythonManager( ctkAbstractPythonManager* _PythonManager ); - protected: void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); bool canInsertFromMimeData( const QMimeData *source ) const; void executeCommand(const QString& command); -signals: - void executeCommandSignal(const QString&); - void newCommandExecuted(); - private: QmitkCtkPythonShellData* d; }; #endif // QmitkCtkPythonShell_h diff --git a/Modules/Python/QmitkPythonVariableStackTableModel.cpp b/Modules/Python/QmitkPythonVariableStackTableModel.cpp new file mode 100755 index 0000000000..650580a304 --- /dev/null +++ b/Modules/Python/QmitkPythonVariableStackTableModel.cpp @@ -0,0 +1,185 @@ +/*=================================================================== + +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 "QmitkPythonVariableStackTableModel.h" +#include +#include +#include +#include +#include +#include + +const QString QmitkPythonVariableStackTableModel::m_PythonImagesDictName("images"); + +QmitkPythonVariableStackTableModel::QmitkPythonVariableStackTableModel(QObject *parent) + :QAbstractTableModel(parent) +{ + mitk::ModuleContext* context = mitk::GetModuleContext(); + mitk::ServiceReference serviceRef = context->GetServiceReference(); + m_PythonService = context->GetService(serviceRef); +} + +QmitkPythonVariableStackTableModel::~QmitkPythonVariableStackTableModel() +{ +} + +bool QmitkPythonVariableStackTableModel::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")) + { + MITK_INFO << "dropped MITK DataNode"; + 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); + mitk::Image* mitkImage = dynamic_cast(node->GetData()); + + m_PythonService->Execute(CreateDictionaryCommandIfNecessary(), mitk::IPythonService::MULTI_LINE_COMMAND ); + + QString varName = GetDictionaryVarNameForNodeName(node->GetName()); + MITK_DEBUG("varName") << "varName" << varName; + m_PythonService->CopyToPythonAsItkImage( mitkImage, varName ); + } + } + return returnValue; +} + +QVariant QmitkPythonVariableStackTableModel::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 QmitkPythonVariableStackTableModel::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 QmitkPythonVariableStackTableModel::rowCount(const QModelIndex &) const +{ + return m_VariableStack.size(); +} + +int QmitkPythonVariableStackTableModel::columnCount(const QModelIndex &) const +{ + return 3; +} + +QVariant QmitkPythonVariableStackTableModel::data(const QModelIndex &index, int role) const +{ + if (index.isValid() && !m_VariableStack.empty()) + { + if(role == Qt::DisplayRole) + { + mitk::PythonVariable item = m_VariableStack.at(index.row()); + if(index.column() == 0) + return item.m_Name; + if(index.column() == 1) + return item.m_Value; + if(index.column() == 2) + return item.m_Type; + } + } + return QVariant(); +} + +QStringList QmitkPythonVariableStackTableModel::mimeTypes() const +{ + return QAbstractTableModel::mimeTypes(); + QStringList types; + types << "application/x-mitk-datanodes"; + types << "application/x-qabstractitemmodeldatalist"; + return types; +} + +Qt::DropActions QmitkPythonVariableStackTableModel::supportedDropActions() const +{ + return Qt::CopyAction | Qt::MoveAction; +} + +void QmitkPythonVariableStackTableModel::CommandExecuted(const QString &pythonCommand) +{ + m_VariableStack = m_PythonService->GetVariableStack(); + QAbstractTableModel::reset(); +} + +QList QmitkPythonVariableStackTableModel::GetVariableStack() const +{ + return m_VariableStack; +} + + +QString QmitkPythonVariableStackTableModel::CreateDictionaryCommandIfNecessary() +{ + QString command; + command.append( QString("try:\n") ); + command.append( QString(" %1" ) .arg( m_PythonImagesDictName ) ); + command.append( QString("except NameError:\n") ); + command.append( QString(" %1 = {}\n") .arg( m_PythonImagesDictName ) ); + return command; +} + +QString QmitkPythonVariableStackTableModel::GetDictionaryVarNameForNodeName(const std::string &nodeName) +{ + QString varName = QString("%1['%2']") .arg( m_PythonImagesDictName ) .arg( QString::fromStdString( nodeName ) ); + return varName; +} + +std::string QmitkPythonVariableStackTableModel::GetNodeNameForDictionaryVarName(const QString &varName) +{ + QString qNodeName = varName; + qNodeName = qNodeName.replace( m_PythonImagesDictName+"['", "" ); + qNodeName = qNodeName.replace("']", ""); + MITK_DEBUG("QmitkPythonVariableStackTableModel") << "qNodeName " << qNodeName.toStdString(); + return qNodeName.toStdString(); +} diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonVariableStackTableModel.h b/Modules/Python/QmitkPythonVariableStackTableModel.h similarity index 71% rename from Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonVariableStackTableModel.h rename to Modules/Python/QmitkPythonVariableStackTableModel.h index 346db2f208..1dc619ca60 100755 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonVariableStackTableModel.h +++ b/Modules/Python/QmitkPythonVariableStackTableModel.h @@ -1,68 +1,63 @@ /*=================================================================== 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 QmitkPythonVariableStackTableModel_h #define QmitkPythonVariableStackTableModel_h #include -#include #include #include -#include -#include -#include -#include +#include "mitkIPythonService.h" +#include "mitkPythonExports.h" /// /// implements a table model to show the variables of the Python "__main__" dictionary /// furthermore implements dragging and dropping of datanodes (conversion from and to python) /// -class QmitkPythonVariableStackTableModel : public QAbstractTableModel +class MITK_PYTHON_EXPORT QmitkPythonVariableStackTableModel : public QAbstractTableModel, public mitk::PythonCommandObserver { Q_OBJECT public: + static const QString m_PythonImagesDictName; + static QString CreateDictionaryCommandIfNecessary(); + static QString GetDictionaryVarNameForNodeName(const std::string& nodeName); + static std::string GetNodeNameForDictionaryVarName(const QString& varName); + QmitkPythonVariableStackTableModel(QObject *parent = 0); virtual ~QmitkPythonVariableStackTableModel(); 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(QList); - QList getVariableStack(); + QStringList mimeTypes() const; bool dropMimeData ( const QMimeData *, Qt::DropAction, int, int, const QModelIndex & ); Qt::DropActions supportedDropActions() const; Qt::DropActions supportedDragActions() const; -public slots: - void Update(); -protected: - QList getAttributeList(); - PyObject* getPyObject(PyObject* object); - PyObject* getPyObjectString(const QString& objectName); + void CommandExecuted(const QString& pythonCommand); + QList GetVariableStack() const; private: - QList m_VariableStack; + QList m_VariableStack; + mitk::IPythonService* m_PythonService; }; #endif // QmitkPythonVariableStackTableModel_h diff --git a/Modules/Python/QmitkPythonVariableStackTableView.cpp b/Modules/Python/QmitkPythonVariableStackTableView.cpp new file mode 100755 index 0000000000..d733cddf1d --- /dev/null +++ b/Modules/Python/QmitkPythonVariableStackTableView.cpp @@ -0,0 +1,80 @@ +/*=================================================================== + +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 "QmitkPythonVariableStackTableView.h" +#include +#include +#include +#include + +QmitkPythonVariableStackTableView::QmitkPythonVariableStackTableView(QWidget *parent) + :QTableView(parent) +{ + m_TableModel = new QmitkPythonVariableStackTableModel(parent); + m_TableModel->CommandExecuted(""); + + this->setSelectionBehavior( QAbstractItemView::SelectRows ); + this->setAlternatingRowColors(true); + this->setDropIndicatorShown(true); + this->setAcceptDrops(true); + this->setModel( m_TableModel ); + + mitk::ModuleContext* context = mitk::GetModuleContext(); + mitk::ServiceReference serviceRef = context->GetServiceReference(); + m_PythonService = context->GetService(serviceRef); + + connect( this, SIGNAL(doubleClicked ( const QModelIndex& )), this, SLOT( OnVariableStackDoubleClicked(const QModelIndex&) ) ); +} + +QmitkPythonVariableStackTableView::~QmitkPythonVariableStackTableView() +{ +} + +void QmitkPythonVariableStackTableView::SetDataStorage(mitk::DataStorage *_DataStorage) +{ + m_DataStorage = _DataStorage; +} + +void QmitkPythonVariableStackTableView::OnVariableStackDoubleClicked(const QModelIndex &index) +{ + if( m_DataStorage.IsNull() || m_PythonService == 0 ) + { + MITK_ERROR << "QmitkPythonVariableStackTableView not configured correctly. Quit"; + return; + } + + QList variableStack = m_TableModel->GetVariableStack(); + QString varName = variableStack.at(index.row()).m_Name; + + MITK_DEBUG("QmitkPythonVariableStackTableView") << varName; + mitk::Image::Pointer mitkImage = m_PythonService->CopyItkImageFromPython(varName); + + if( mitkImage.IsNotNull() ) + { + std::string nodeName = QmitkPythonVariableStackTableModel::GetNodeNameForDictionaryVarName(varName); + + mitk::DataNode::Pointer node = m_DataStorage->GetNamedNode( nodeName.c_str() ); + if( node.IsNull() ) + { + node = mitk::DataNode::New(); + m_DataStorage->Add(node); + } + + node->SetData( mitkImage ); + + mitk::RenderingManager::GetInstance()->RequestUpdateAll(); + } +} diff --git a/Modules/Python/QmitkPythonVariableStackTableView.h b/Modules/Python/QmitkPythonVariableStackTableView.h new file mode 100755 index 0000000000..d486512a44 --- /dev/null +++ b/Modules/Python/QmitkPythonVariableStackTableView.h @@ -0,0 +1,50 @@ +/*=================================================================== + +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 QmitkPythonVariableStackTableView_h +#define QmitkPythonVariableStackTableView_h + +#include +#include +#include "QmitkPythonVariableStackTableModel.h" +#include +#include "mitkPythonExports.h" + +/// +/// implements the table view for the variable stack +/// purpose of this class: 1. Setup the view correctly, 2. Implement the double click to write back results +/// to the datastorage +/// +class MITK_PYTHON_EXPORT QmitkPythonVariableStackTableView : public QTableView +{ + Q_OBJECT + +public: + QmitkPythonVariableStackTableView(QWidget *parent = 0); + virtual ~QmitkPythonVariableStackTableView(); + + void SetDataStorage(mitk::DataStorage* _DataStorage); + +protected slots: + void OnVariableStackDoubleClicked(const QModelIndex &index); + +private: + QmitkPythonVariableStackTableModel* m_TableModel; + mitk::DataStorage::Pointer m_DataStorage; + mitk::IPythonService* m_PythonService; +}; + +#endif // QmitkPythonVariableStackTableView_h diff --git a/Modules/Python/files.cmake b/Modules/Python/files.cmake index dced6d26a9..cde5a394de 100644 --- a/Modules/Python/files.cmake +++ b/Modules/Python/files.cmake @@ -1,21 +1,23 @@ SET(CPP_FILES mitkPythonActivator.cpp mitkIPythonService.cpp mitkPythonService.cpp + QmitkCtkPythonShell.cpp + QmitkPythonVariableStackTableModel.cpp + QmitkPythonVariableStackTableView.cpp ) -#SET(CPP_FILES - #Qmitk/QmitkKinectParameterWidget.cpp -#) #SET(UI_FILES #Qmitk/QmitkKinectParameterWidgetControls.ui #) -#SET(MOC_H_FILES - #Qmitk/QmitkKinectParameterWidget.h -#) +SET(MOC_H_FILES + QmitkCtkPythonShell.h + QmitkPythonVariableStackTableModel.h + QmitkPythonVariableStackTableView.h +) # uncomment the following line if you want to use Qt resources #set(QRC_FILES #resources/QmitkToFUtilWidget.qrc #) diff --git a/Modules/Python/mitkIPythonService.h b/Modules/Python/mitkIPythonService.h index fbe5f54666..e0392eb813 100644 --- a/Modules/Python/mitkIPythonService.h +++ b/Modules/Python/mitkIPythonService.h @@ -1,78 +1,79 @@ /*=================================================================== 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 mitkIPythonService_h #define mitkIPythonService_h // mitk #include "mitkPythonExports.h" #include "mitkImage.h" //for microservices #include // Qt #include #include #include namespace mitk { /// /// describes a python variable (data container) /// \see IPythonService::GetVariableStack() /// struct PythonVariable { QString m_Name; QString m_Type; QString m_Value; }; /// /// a PythonCommandObserver gets informed as soon as a python command was issued /// \see IPythonService::AddPythonCommandObserver() /// class PythonCommandObserver { public: virtual void CommandExecuted(const QString& pythonCommand) = 0; }; /// - /// describes a python variable (data container) + /// The central service for issuing Python Code + /// The class also enables to transfer mitk images to python as itk::Image and vice versa /// \see IPythonService::GetVariableStack() /// class MITK_PYTHON_EXPORT IPythonService { public: static const int SINGLE_LINE_COMMAND = 0; static const int MULTI_LINE_COMMAND = 1; static const int EVAL_COMMAND = 2; virtual ~IPythonService(); // leer in mitkIPythonService.cpp implementieren virtual QVariant Execute( const QString& pythonCommand, int commandType = SINGLE_LINE_COMMAND ) = 0; virtual QList GetVariableStack() const = 0; virtual void AddPythonCommandObserver( PythonCommandObserver* observer ) = 0; virtual void RemovePythonCommandObserver( PythonCommandObserver* observer ) = 0; virtual void NotifyObserver( const QString& command ) = 0; virtual bool CopyToPythonAsItkImage( mitk::Image* image, const QString& varName ) = 0; virtual mitk::Image::Pointer CopyItkImageFromPython( const QString& varName ) = 0; }; } //US_DECLARE_SERVICE_INTERFACE(mitk::IPythonService, "org.mitk.services.IPythonService") #endif diff --git a/Modules/Python/mitkPythonService.cpp b/Modules/Python/mitkPythonService.cpp index 16872491db..18f5f0423d 100644 --- a/Modules/Python/mitkPythonService.cpp +++ b/Modules/Python/mitkPythonService.cpp @@ -1,150 +1,192 @@ /*=================================================================== 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 "mitkPythonService.h" #include #include #include #include +const QString mitk::PythonService::m_TmpImageName("temp_mitk_image"); + mitk::PythonService::PythonService() { m_PythonManager.initialize(); } mitk::PythonService::~PythonService() { } QVariant mitk::PythonService::Execute(const QString &pythonCommand, int commandType) { QVariant result; bool commandIssued = true; if(commandType == IPythonService::SINGLE_LINE_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::SingleInput ); else if(commandType == IPythonService::MULTI_LINE_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::FileInput ); else if(commandType == IPythonService::EVAL_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::EvalInput ); else commandIssued = false; if(commandIssued) this->NotifyObserver(pythonCommand); return result; } QList mitk::PythonService::GetVariableStack() const { QList list; PyObject* dict = PyImport_GetModuleDict(); PyObject* object = PyDict_GetItemString(dict, "__main__"); PyObject* dirMain = PyObject_Dir(object); PyObject* tempObject; if(dirMain) { QString attr, attrValue, attrType; for(int i = 0; iob_type->tp_name; if(PyUnicode_Check(tempObject) || PyString_Check(tempObject)) attrValue = PyString_AsString(tempObject); else attrValue = ""; mitk::PythonVariable var; var.m_Name = attr; var.m_Value = attrValue; var.m_Type = attrType; list.append(var); } } return list; } void mitk::PythonService::AddPythonCommandObserver(mitk::PythonCommandObserver *observer) { if(m_Observer.contains(observer)) m_Observer.append(observer); } void mitk::PythonService::RemovePythonCommandObserver(mitk::PythonCommandObserver *observer) { m_Observer.removeOne(observer); } void mitk::PythonService::NotifyObserver(const QString &command) { foreach(mitk::PythonCommandObserver* observer, m_Observer) { observer->CommandExecuted(command); } } +QString mitk::PythonService::GetTempImageName(const QString& ext) const +{ + QString tmpFolder = QDir::tempPath(); + QString fileName = tmpFolder + QDir::separator() + m_TmpImageName + ext; + return fileName; +} + bool mitk::PythonService::CopyToPythonAsItkImage(mitk::Image *image, const QString &varName) { // save image - QString tmpFolder = QDir::tempPath(); - QString fileName = tmpFolder + QDir::separator() + varName + ".nrrd"; + QString fileName = this->GetTempImageName( QString::fromStdString(mitk::IOUtil::DEFAULTIMAGEEXTENSION) ); - MITK_DEBUG << "Saving temporary file " << fileName.toStdString(); + MITK_DEBUG("PythonService") << "Saving temporary file " << fileName.toStdString(); if( !mitk::IOUtil::SaveImage(image, fileName.toStdString()) ) { MITK_ERROR << "Temporary file could not be created."; } else { - // TODO CORRECT TYPE SETUP, MAKE MITK_DEBUG MITK_DEBUG + // TODO CORRECT TYPE SETUP, MAKE MITK_DEBUG("PythonService") MITK_DEBUG("PythonService") int dim = 3; QString type = "US"; QString command; - command.append( "import itk\n" ); - command.append( "try:\n" ); - command.append( " mitkImages" ); - command.append( "except NameError:\n" ); - command.append( " mitkImages = {}\n" ); - //command.append( QString("mitkImages['%1_dim''] = %2\n").arg( varName ).arg(dim) ); - //command.append( QString("mitkImages['%1_pixelType'] = itk.%2\n").arg( varName ).argtype( type ) ); - command.append( QString("mitkImages['%1_imageType'] = itk.Image[%2, %3]\n").arg( varName ).arg( type ).arg( dim ) ); - command.append( QString("readerType = itk.ImageFileReader[mitkImages['%1_imageType']]\n").arg( varName ) ); - command.append( "reader = readerType.New()\n" ); - command.append( QString("reader.SetFileName( \"%1\" )\n").arg(fileName) ); - command.append( "reader.Update()\n" ); - command.append( QString("mitkImages['%1'] = reader.GetOutput()\n").arg( varName )); - MITK_DEBUG << "Issuing python command " << command.toStdString(); - this->Execute(command, IPythonService::SINGLE_LINE_COMMAND ); + + command.append( QString("import itk\n") ); + command.append( QString("imageType = itk.Image[%1, %2]\n") .arg( type ).arg( dim ) ); + + command.append( QString("readerType = itk.ImageFileReader[imageType]\n") ); + command.append( QString("reader = readerType.New()\n") ); + command.append( QString("reader.SetFileName( \"%1\" )\n") .arg(fileName) ); + command.append( QString("reader.Update()\n") ); + command.append( QString("%1 = reader.GetOutput()\n").arg( varName ) ); + + MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); + this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); QFile file(fileName); - MITK_DEBUG << "Removing file " << fileName.toStdString(); + MITK_DEBUG("PythonService") << "Removing file " << fileName.toStdString(); file.remove(); return true; } return false; } mitk::Image::Pointer mitk::PythonService::CopyItkImageFromPython(const QString &varName) { - return 0; + mitk::Image::Pointer mitkImage; + QString command; + QString fileName = GetTempImageName( QString::fromStdString( mitk::IOUtil::DEFAULTIMAGEEXTENSION ) ); + + MITK_DEBUG("PythonService") << "Saving temporary file with python itk code " << fileName.toStdString(); + command.append( QString("import itk\n") ); + + command.append( QString( "writer = itk.ImageFileWriter[ %1 ].New()\n").arg( varName ) ); + command.append( QString( "writer.SetFileName( \"%1\" )\n").arg(fileName) ); + command.append( QString( "writer.SetInput( %1 )\n").arg(varName) ); + command.append( QString( "writer.Update()\n" ) ); + + MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); + this->Execute(command, IPythonService::MULTI_LINE_COMMAND ); + + try + { + MITK_DEBUG("PythonService") << "Loading temporary file " << fileName.toStdString() << " as MITK image"; + mitkImage = mitk::IOUtil::LoadImage( fileName.toStdString() ); + } + catch(std::exception& e) + { + MITK_ERROR << e.what(); + } + + QFile file(fileName); + if( file.exists() ) + { + MITK_DEBUG("PythonService") << "Removing temporary file " << fileName.toStdString(); + file.remove(); + } + + return mitkImage; +} + +ctkAbstractPythonManager *mitk::PythonService::GetPythonManager() +{ + return &m_PythonManager; } diff --git a/Modules/Python/mitkPythonService.h b/Modules/Python/mitkPythonService.h index d0c2c4215f..ba21f76595 100644 --- a/Modules/Python/mitkPythonService.h +++ b/Modules/Python/mitkPythonService.h @@ -1,45 +1,49 @@ /*=================================================================== 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 mitkPythonService_h #define mitkPythonService_h #include "mitkIPythonService.h" #include #include namespace mitk { class PythonService: public itk::LightObject, public mitk::IPythonService { public: PythonService(); ~PythonService(); // leer in mitkIPythonService.cpp implementieren QVariant Execute( const QString& pythonCommand, int commandType = SINGLE_LINE_COMMAND ); QList GetVariableStack() const; void AddPythonCommandObserver( PythonCommandObserver* observer ); void RemovePythonCommandObserver( PythonCommandObserver* observer ); void NotifyObserver( const QString& command ); bool CopyToPythonAsItkImage( mitk::Image* image, const QString& varName ); mitk::Image::Pointer CopyItkImageFromPython( const QString& varName ); + ctkAbstractPythonManager* GetPythonManager(); + protected: + QString GetTempImageName(const QString &ext) const; private: QList m_Observer; ctkAbstractPythonManager m_PythonManager; + static const QString m_TmpImageName; }; } #endif diff --git a/Plugins/org.mitk.gui.qt.python/CMakeLists.txt b/Plugins/org.mitk.gui.qt.python/CMakeLists.txt index 9d894df5de..04847ce61c 100644 --- a/Plugins/org.mitk.gui.qt.python/CMakeLists.txt +++ b/Plugins/org.mitk.gui.qt.python/CMakeLists.txt @@ -1,9 +1,6 @@ project(org_mitk_gui_qt_python) MACRO_CREATE_MITK_CTK_PLUGIN( EXPORT_DIRECTIVE org_mitk_gui_qt_python_EXPORT EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDENCIES QmitkExt CTK) - -configure_file(PythonPath.h.in - "${CMAKE_CURRENT_BINARY_DIR}/PythonPath.h" @ONLY) + MODULE_DEPENDENCIES QmitkExt mitkPython) diff --git a/Plugins/org.mitk.gui.qt.python/PythonPath.h.in b/Plugins/org.mitk.gui.qt.python/PythonPath.h.in deleted file mode 100644 index 945904a8c3..0000000000 --- a/Plugins/org.mitk.gui.qt.python/PythonPath.h.in +++ /dev/null @@ -1,2 +0,0 @@ -#define PYTHONPATH_ITK_LIBRARY_DIRS "@ITK_LIBRARY_DIRS@" -#define PYTHONPATH_WRAP_ITK_DIR "@ITK_DIR@/Wrapping/WrapITK/Python" diff --git a/Plugins/org.mitk.gui.qt.python/files.cmake b/Plugins/org.mitk.gui.qt.python/files.cmake index 9e80499580..d2d693e932 100644 --- a/Plugins/org.mitk.gui.qt.python/files.cmake +++ b/Plugins/org.mitk.gui.qt.python/files.cmake @@ -1,35 +1,31 @@ set(SRC_CPP_FILES ) set(INTERNAL_CPP_FILES mitkPluginActivator.cpp QmitkPythonView.cpp - QmitkCtkPythonShell.cpp - QmitkPythonVariableStackTableModel.cpp ) set(MOC_H_FILES src/internal/QmitkPythonView.h - src/internal/QmitkCtkPythonShell.h src/internal/mitkPluginActivator.h - src/internal/QmitkPythonVariableStackTableModel.h ) set(CPP_FILES ) set(CACHED_RESOURCE_FILES plugin.xml resources/Python.png ) set(QRC_FILES resources/Python.qrc ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonVariableStackTableModel.cpp b/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonVariableStackTableModel.cpp deleted file mode 100755 index b12c04353a..0000000000 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonVariableStackTableModel.cpp +++ /dev/null @@ -1,370 +0,0 @@ -/*=================================================================== - -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 "QmitkPythonVariableStackTableModel.h" -#include -#include -#include -#include -#include -#include -#include -#include "mitkPluginActivator.h" -#include - - -QmitkPythonVariableStackTableModel::QmitkPythonVariableStackTableModel(QObject *parent) - :QAbstractTableModel(parent) -{ -} - -QmitkPythonVariableStackTableModel::~QmitkPythonVariableStackTableModel() -{ -} - -bool QmitkPythonVariableStackTableModel::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")) - { - MITK_INFO << "dropped MITK DataNode"; - 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); - mitk::Image* mitkImage = dynamic_cast(node->GetData()); - - // save image - QString tmpFolder = QDir::tempPath(); - QString nodeName = QString::fromStdString(node->GetName()); - QString fileName = tmpFolder + QDir::separator() + nodeName + ".nrrd"; - - MITK_INFO << "Saving temporary file " << fileName.toStdString(); - if( !mitk::IOUtil::SaveImage(mitkImage, fileName.toStdString()) ) - { - MITK_ERROR << "Temporary file could not be created."; - } - - QString command; - command.append("import itk\n"); - command.append( QString("dim_%1 = 3\n").arg( nodeName ) ); - command.append( QString("pixelType_%1 = itk.US\n").arg( nodeName ) ); - command.append( QString("imageType_%1 = itk.Image[pixelType_%2, dim_%3]\n").arg( nodeName ).arg( nodeName ).arg( nodeName ) ); - command.append( QString("readerType = itk.ImageFileReader[imageType_%1]\n").arg( nodeName ) ); - command.append( "reader = readerType.New()\n" ); - command.append( QString("reader.SetFileName( \"%1\" )\n").arg(fileName) ); - command.append("reader.Update()\n"); - command.append( QString("image_%1 = reader.GetOutput()\n").arg( nodeName ).arg( nodeName ) ); - MITK_INFO << "Issuing python command " << command.toStdString(); - mitk::PluginActivator::GetPythonManager()->executeString(command, ctkAbstractPythonManager::FileInput ); - this->Update(); - - QFile file(fileName); - MITK_INFO << "Removing file " << fileName.toStdString(); - file.remove(); - - /* - if( mitkImage ) - { - MITK_INFO << "found MITK image"; - switch(mitkImage->GetDimension()) - { - case 2: - { - AccessFixedDimensionByItk( mitkImage, ItkImageProcessing, 2 ); break; - } - case 3: - { - AccessFixedDimensionByItk( mitkImage, ItkImageProcessing, 3 ); break; - } - case 4: - { - AccessFixedDimensionByItk( mitkImage, ItkImageProcessing, 4 ); break; - } - default: break; - } - } - 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(this->getAttributeList()); - } - */ - } - } - return returnValue; -} - -QVariant QmitkPythonVariableStackTableModel::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 QmitkPythonVariableStackTableModel::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 QmitkPythonVariableStackTableModel::rowCount(const QModelIndex &) const -{ - return m_VariableStack.size(); -} - -int QmitkPythonVariableStackTableModel::columnCount(const QModelIndex &) const -{ - return 3; -} - -QVariant QmitkPythonVariableStackTableModel::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 QmitkPythonVariableStackTableModel::clear() -{ - m_VariableStack.clear(); - QAbstractTableModel::reset(); -} - -void QmitkPythonVariableStackTableModel::setVariableStack(QList varStack) -{ - m_VariableStack = varStack; - QAbstractTableModel::reset(); -} - -QList QmitkPythonVariableStackTableModel::getVariableStack() -{ - return m_VariableStack; -} - -/* -QMimeData * QmitkPythonVariableStackTableModel::mimeData(const QModelIndexList & indexes) const -{ - QMimeData * ret = new QMimeData; - - QString command; - QString tmpFolder = QDir::tempPath(); - for (int indexesCounter = 0; indexesCounter < indexes.size(); indexesCounter++) - { - QString name = m_VariableStack[indexes.at(indexesCounter).row()][0]; - QString fileName = tmpFolder + QDir::separator() + name + ".nrrd"; - - MITK_INFO << "Saving temporary file with python itk code " << fileName.toStdString(); - command.append("import itk\n"); - command.append("writer = itk.ImageFileWriter[ image ].New()\n"); - command.append( QString( "reader.SetFileName( \"%1\" )\n").arg(fileName) ); - command.append( QString( "writer.SetInput( \"%1\" )\n").arg(fileName) ); - command.append("writer.Update()\n"); - - MITK_INFO << "Loading temporary file " << fileName.toStdString() << " as MITK image"; - mitk::Image::Pointer mitkImage = mitk::IOUtil::LoadImage( fileName.toStdString() ); - - if( mitkImage.IsNotNull() ) - { - } - else - { - MITK_ERROR << "Temporary image could not be written or was invalid."; - } - } - - return ret; - - /* - 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 = this->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 QmitkPythonVariableStackTableModel::mimeTypes() const -{ - return QAbstractTableModel::mimeTypes(); - QStringList types; - types << "application/x-mitk-datanodes"; - types << "application/x-qabstractitemmodeldatalist"; - return types; -} - -Qt::DropActions QmitkPythonVariableStackTableModel::supportedDropActions() const -{ - return Qt::CopyAction | Qt::MoveAction; -} - - -void QmitkPythonVariableStackTableModel::Update() -{ -// std::cout << "QmitkPythonVariableStackTableModel::update()" << std::endl; - this->setVariableStack(this->getAttributeList()); -} - -QList QmitkPythonVariableStackTableModel::getAttributeList() -{ - PyObject* dict = PyImport_GetModuleDict(); - PyObject* object = PyDict_GetItemString(dict, "__main__"); - PyObject* dirMain = PyObject_Dir(object); - PyObject* tempObject; - QList 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 * QmitkPythonVariableStackTableModel::getPyObject(PyObject * object) -{ - PyObject* dict = PyImport_GetModuleDict(); - PyObject* main = PyDict_GetItemString(dict, "__main__"); - return PyObject_GetAttr(main, object); -} - -PyObject * QmitkPythonVariableStackTableModel::getPyObjectString(const QString &objectName) -{ - PyObject* dict = PyImport_GetModuleDict(); - PyObject* main = PyDict_GetItemString(dict, "__main__"); - return PyObject_GetAttrString(main, objectName.toLocal8Bit().data()); -} diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp b/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp index 4bc00f3b04..310f56ea69 100644 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp +++ b/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp @@ -1,131 +1,67 @@ /*=================================================================== 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 "QmitkPythonView.h" #include #include "QmitkCtkPythonShell.h" #include "mitkPluginActivator.h" -#include "QmitkPythonVariableStackTableModel.h" -#include -#include +#include "QmitkPythonVariableStackTableView.h" const std::string QmitkPythonView::VIEW_ID = "org.mitk.views.python"; struct QmitkPythonViewData { // widget - QmitkPythonVariableStackTableModel* m_VariableStackTableModel; + QmitkPythonVariableStackTableView* m_PythonVariableStackTableView; QmitkCtkPythonShell* m_PythonShell; }; QmitkPythonView::QmitkPythonView() : d( new QmitkPythonViewData ) { + d->m_PythonVariableStackTableView = 0; d->m_PythonShell = 0; } QmitkPythonView::~QmitkPythonView() { delete d; } -void QmitkPythonView::OnVariableStackDoubleClicked(const QModelIndex &index) -{ - QString command; - QString tmpFolder = QDir::tempPath(); - - QString name = d->m_VariableStackTableModel->getVariableStack().at(index.row())[0]; - QString fileName = tmpFolder + QDir::separator() + name + ".nrrd"; - - MITK_INFO << "Saving temporary file with python itk code " << fileName.toStdString(); - command.append("import itk\n"); - command.append( QString( "writer = itk.ImageFileWriter[ %1 ].New()\n").arg( name ) ); - command.append( QString( "writer.SetFileName( \"%1\" )\n").arg(fileName) ); - command.append( QString( "writer.SetInput( %1 )\n").arg(name) ); - command.append("writer.Update()\n"); - mitk::PluginActivator::GetPythonManager()->executeString(command, ctkAbstractPythonManager::FileInput ); - d->m_VariableStackTableModel->Update(); - - mitk::Image::Pointer mitkImage; - try - { - MITK_INFO << "Loading temporary file " << fileName.toStdString() << " as MITK image"; - mitkImage = mitk::IOUtil::LoadImage( fileName.toStdString() ); - } - catch(std::exception& e) - { - MITK_ERROR << e.what(); - } - - QFile file(fileName); - if( file.exists() ) - { - MITK_INFO << "Removing temporary file " << fileName.toStdString(); - file.remove(); - } - - if( mitkImage.IsNotNull() ) - { - QString nodeName = name.replace("image_", ""); - mitk::DataNode::Pointer node = this->GetDataStorage()->GetNamedNode( nodeName.toStdString().c_str() ); - if( node.IsNull() ) - { - node = mitk::DataNode::New(); - this->GetDataStorage()->Add(node); - } - - node->SetData( mitkImage ); - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); - } -} - void QmitkPythonView::CreateQtPartControl(QWidget* parent) { - d->m_VariableStackTableModel = new QmitkPythonVariableStackTableModel(parent); - d->m_VariableStackTableModel->Update(); - - QTableView* variableStackView = new QTableView; - variableStackView->setSelectionBehavior( QAbstractItemView::SelectRows ); - variableStackView->setAlternatingRowColors(true); - //variableStackView->setDragEnabled(true); - variableStackView->setDropIndicatorShown(true); - variableStackView->setAcceptDrops(true); - variableStackView->setModel( d->m_VariableStackTableModel ); + d->m_PythonVariableStackTableView = new QmitkPythonVariableStackTableView; + d->m_PythonVariableStackTableView->SetDataStorage(this->GetDataStorage()); d->m_PythonShell = new QmitkCtkPythonShell; - d->m_PythonShell->SetPythonManager( mitk::PluginActivator::GetPythonManager() ); QList sizes; sizes << 1 << 3; QSplitter* splitter = new QSplitter; - splitter->addWidget(variableStackView); + splitter->addWidget(d->m_PythonVariableStackTableView); splitter->addWidget(d->m_PythonShell); splitter->setStretchFactor ( 0, 1 ); splitter->setStretchFactor ( 1, 3 ); QGridLayout* layout = new QGridLayout; layout->addWidget( splitter, 0, 0 ); parent->setLayout(layout); - - connect( d->m_PythonShell, SIGNAL(newCommandExecuted()), d->m_VariableStackTableModel, SLOT(Update()) ); - connect( variableStackView, SIGNAL(doubleClicked ( const QModelIndex& )), this, SLOT( OnVariableStackDoubleClicked(const QModelIndex&) ) ); } void QmitkPythonView::SetFocus() { d->m_PythonShell->setFocus(); } diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.h b/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.h index 5d781cd98b..41b4bee47a 100644 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.h +++ b/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.h @@ -1,70 +1,64 @@ /*=================================================================== 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 QmitkPythonView_H_ #define QmitkPythonView_H_ /// Qmitk #include /// /// d pointer forward declaration /// struct QmitkPythonViewData; /// /// \brief New python view (CONSOLE) /// class QmitkPythonView : public QmitkAbstractView { Q_OBJECT public: static const std::string VIEW_ID; // = "org.mitk.extapp.defaultperspective" /// /// \brief Standard ctor. /// QmitkPythonView(); /// /// \brief Standard dtor. /// virtual ~QmitkPythonView(); - /// - /// \brief Standard dtor. - /// -public slots: - void OnVariableStackDoubleClicked( const QModelIndex & index ); - protected: /// /// \brief Create the view here. /// virtual void CreateQtPartControl(QWidget* parent); /// /// focus on load image /// void SetFocus(); private: QmitkPythonViewData* d; }; #endif /*QmitkPythonView_H_*/ diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.cpp index 7d5bca5dd3..c9ce4149a5 100644 --- a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.cpp @@ -1,67 +1,35 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include #include "QmitkPythonView.h" -#include "PythonPath.h" -#include namespace mitk { void PluginActivator::start(ctkPluginContext* context) { - MITK_DEBUG << "registering python paths"; - - QString itkLibDirs(PYTHONPATH_ITK_LIBRARY_DIRS); - MITK_DEBUG << "itkLibDirs" << itkLibDirs.toStdString(); - QString itkWrapItkDir(PYTHONPATH_WRAP_ITK_DIR); - MITK_DEBUG << "itkWrapItkDir" << itkWrapItkDir.toStdString(); - - QString basecommand = "sys.path.append('%1');"; - QString pythonCommand; - if( ! itkWrapItkDir.isEmpty() ) - { - pythonCommand = basecommand.arg(itkLibDirs); - MITK_DEBUG << "issuing command " << pythonCommand.toStdString(); - GetPythonManager()->executeString(pythonCommand, ctkAbstractPythonManager::SingleInput ); - - pythonCommand = basecommand.arg(itkWrapItkDir); - MITK_DEBUG << "issuing command " << pythonCommand.toStdString(); - GetPythonManager()->executeString(pythonCommand, ctkAbstractPythonManager::SingleInput ); - } - else - { - MITK_WARN << "No wrapping directory set for WrapITK. ITK Python Wrapping not available!"; - } - BERRY_REGISTER_EXTENSION_CLASS(QmitkPythonView, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } - ctkAbstractPythonManager *PluginActivator::GetPythonManager() - { - static ctkAbstractPythonManager PythonManager; - return &PythonManager; - } - } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_python, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h index e9fa608c85..eb6cd768f0 100644 --- a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h @@ -1,41 +1,38 @@ /*=================================================================== 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 #include -class ctkAbstractPythonManager; namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: - static ctkAbstractPythonManager* GetPythonManager(); - void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } #endif // MITKPLUGINACTIVATOR_H