diff --git a/Modules/ModuleList.cmake b/Modules/ModuleList.cmake index cb8587cb34..3cc77ea99a 100644 --- a/Modules/ModuleList.cmake +++ b/Modules/ModuleList.cmake @@ -1,88 +1,86 @@ # The entries in the mitk_modules list must be # ordered according to their dependencies. set(MITK_MODULES Core CommandLine CoreCmdApps AppUtil LegacyIO DataTypesExt Annotation LegacyGL AlgorithmsExt MapperExt DICOM DICOMQI DICOMTesting SceneSerializationBase PlanarFigure ImageDenoising ImageExtraction SceneSerialization Gizmo GraphAlgorithms Multilabel Chart ImageStatistics ContourModel SurfaceInterpolation Segmentation QtWidgets QtWidgetsExt ImageStatisticsUI SegmentationUI MatchPointRegistration MatchPointRegistrationUI Classification OpenIGTLink IGTBase IGT CameraCalibration OpenCL OpenCVVideoSupport QtOverlays ToFHardware ToFProcessing ToFUI PhotoacousticsHardware PhotoacousticsAlgorithms PhotoacousticsLib US USUI DICOMUI Remeshing Python - QtPython PythonService - QtPythonService Persistence OpenIGTLinkUI IGTUI RT RTUI IOExt XNAT TubeGraph BiophotonicsHardware BoundingShape RenderWindowManager RenderWindowManagerUI SemanticRelations SemanticRelationsUI CEST BasicImageProcessing ModelFit ModelFitUI Pharmacokinetics PharmacokineticsUI DICOMPM REST RESTService DICOMweb DeepLearningSegmentation ) if(MITK_ENABLE_PIC_READER) list(APPEND MITK_MODULES IpPicSupportIO) endif() diff --git a/Modules/Python/test/files.cmake b/Modules/Python/test/files.cmake index 0fc8d40dcb..853d512ad2 100644 --- a/Modules/Python/test/files.cmake +++ b/Modules/Python/test/files.cmake @@ -1,11 +1,10 @@ set(MODULE_TESTS mitkPythonTest.cpp - mitkQtPythonTest.cpp ) SET(CPP_FILES mitkPythonObserverMock.cpp ) SET(H_FILES mitkPythonObserverMock.h ) \ No newline at end of file diff --git a/Modules/Python/test/mitkQtPythonTest.cpp b/Modules/Python/test/mitkQtPythonTest.cpp deleted file mode 100644 index a0a4492555..0000000000 --- a/Modules/Python/test/mitkQtPythonTest.cpp +++ /dev/null @@ -1,404 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//#include - -class mitkQtPythonTestSuite : public mitk::TestFixture -{ - CPPUNIT_TEST_SUITE(mitkQtPythonTestSuite); - MITK_TEST(TestEvaluateOperationWithResult); - MITK_TEST(TestExecuteStatement); - MITK_TEST(TestSettingVariable); - MITK_TEST(TestSettingVariableAndUseIt); - MITK_TEST(TestRunningScript); - MITK_TEST(TestGetVariableStack); - MITK_TEST(TestGetVariable); - MITK_TEST(TestDoesVariableExist_True); - MITK_TEST(TestDoesVariableExist_False); - MITK_TEST(TestAddObserver); - MITK_TEST(TestRemoveObserver); - MITK_TEST(TestNotifyObserver); - MITK_TEST(TestCopyImageToPython); - MITK_TEST(TestCopyImageFromPython); - CPPUNIT_TEST_SUITE_END(); - -public: - - void setUp() - { - mitk::IPythonService::ForceLoadModule(); - } - - void TestEvaluateOperationWithResult() - { - std::string result = ""; - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - result = m_PythonService->Execute("5+5", mitk::IPythonService::EVAL_COMMAND); - try - { - std::string result = m_PythonService->Execute("5+5", mitk::IPythonService::EVAL_COMMAND); - CPPUNIT_ASSERT_MESSAGE("Testing if running python code 5+5 results in 10", result == "10"); - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in Python Execution"); - } - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestExecuteStatement() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - try - { - std::string result = m_PythonService->Execute("print('Hello')"); - // std::string result = "None"; - CPPUNIT_ASSERT_MESSAGE("Testing if executing a statement works", result == ""); - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in Python Execution"); - } - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestSettingVariable() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - try - { - std::string result = m_PythonService->Execute("number = 5"); - CPPUNIT_ASSERT_MESSAGE("Testing if initializing a variable works", result == ""); - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in Python Execution"); - } - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestSettingVariableAndUseIt() - { - std::string result = ""; - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - try - { - result = m_PythonService->Execute("number = 5"); - result = m_PythonService->Execute("number+5", mitk::IPythonService::EVAL_COMMAND); - CPPUNIT_ASSERT_MESSAGE("Testing if initializing a variable and using it works", result == "10"); - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in Python Execution"); - } - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestRunningScript() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - try - { - std::string pythonFileName = "hello.py"; - std::string fileName = mitk::StandardFileLocations::GetInstance()->FindFile( - pythonFileName.c_str(), "Modules/Python/test/hello_world_project"); - m_PythonService->ExecuteScript(fileName); - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in Python Execution for Script"); - return; - } - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestGetVariableStack() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - try - { - auto list = m_PythonService->GetVariableStack(); - if (!(list.size() > 0)) - { - CPPUNIT_FAIL("Failed to get variable stack"); - } - //for (mitk::PythonVariable var : list) - //{ - // MITK_INFO << var.m_Name << ", " << var.m_Value << ", " << var.m_Type; - //} - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in getting variable stack"); - return; - } - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestGetVariable() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - m_PythonService->Execute("variable_to_get ='Get this variable'"); - - std::string variableToGet = m_PythonService->GetVariable("variable_to_get"); - CPPUNIT_ASSERT_MESSAGE("Testing if getting a variable as string representation works", variableToGet == "Get this variable"); - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestDoesVariableExist_True() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - m_PythonService->Execute("existingVariable ='This variable exists'"); - - bool variableExists = m_PythonService->DoesVariableExist("existingVariable"); - CPPUNIT_ASSERT_MESSAGE("Testing if an existing variable is recognized", variableExists == true); - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestDoesVariableExist_False() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - bool variableExists = m_PythonService->DoesVariableExist("nonExistingVariable"); - CPPUNIT_ASSERT_MESSAGE("Testing if an not existing variable is not recognized", variableExists == false); - } - else - { - CPPUNIT_FAIL("No Service Reference found"); - } - } - - void TestAddObserver() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - int numberBeforeAdding = m_PythonService->GetNumberOfObserver(); - auto observer = new PythonObserverMock; - m_PythonService->AddPythonCommandObserver(observer); - int numberAfterAdding = m_PythonService->GetNumberOfObserver(); - CPPUNIT_ASSERT_MESSAGE("Testing if a new command observer can be added", - numberAfterAdding == numberBeforeAdding + 1); - } - } - - void TestRemoveObserver() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - int numberBeforeAdding = m_PythonService->GetNumberOfObserver(); - auto observer = new PythonObserverMock; - m_PythonService->AddPythonCommandObserver(observer); - int numberAfterAdding = m_PythonService->GetNumberOfObserver(); - CPPUNIT_ASSERT_MESSAGE("Testing if a new command observer can be added", - numberAfterAdding == numberBeforeAdding + 1); - - m_PythonService->RemovePythonCommandObserver(observer); - int numberAfterRemoving = m_PythonService->GetNumberOfObserver(); - CPPUNIT_ASSERT_MESSAGE("Testing if a command observer can be removed", - numberAfterRemoving == numberBeforeAdding); - } - } - - void TestNotifyObserver() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - - auto observer = new PythonObserverMock; - m_PythonService->AddPythonCommandObserver(observer); - std::string command = "number = 5"; - try - { - m_PythonService->Execute(command); - } - catch (const mitk::Exception &e) - { - MITK_ERROR << e.GetDescription(); - CPPUNIT_FAIL("Error in Python Execution"); - } - m_PythonService->NotifyObserver(command); - CPPUNIT_ASSERT_MESSAGE("Testing if a command observer is notified", observer->m_Updated == true); - } - } - - void TestCopyImageToPython() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - mitk::Image::Pointer img = mitk::IOUtil::Load(GetTestDataFilePath("Pic3D.nrrd")); - m_PythonService->CopyToPythonAsSimpleItkImage(img, "input"); - } - } - - void TestCopyImageFromPython() - { - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(filter); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = - dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - std::string imgPath = GetTestDataFilePath("Pic3D.nrrd"); - std::string pythonCommand = "image_nrrd = sitk.ReadImage('" + imgPath + "')"; - m_PythonService->Execute(pythonCommand); - mitk::Image::Pointer img = m_PythonService->CopySimpleItkImageFromPython("image_nrrd"); - } - } -}; - -MITK_TEST_SUITE_REGISTRATION(mitkQtPython) diff --git a/Modules/QtPython/CMakeLists.txt b/Modules/QtPython/CMakeLists.txt deleted file mode 100644 index d497d472ef..0000000000 --- a/Modules/QtPython/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -if(MITK_USE_Python3) - mitkFunctionCheckCompilerFlags("/wd4273" CMAKE_CXX_FLAGS) - - set(OpenCV_DEP ) - if(MITK_USE_OpenCV) - set(OpenCV_DEP OpenCV) - endif() - - mitk_create_module( - DEPENDS MitkCore MitkQtWidgets MitkPython - PACKAGE_DEPENDS - PUBLIC Qt5|Widgets CTK|CTKScriptingPythonCore+CTKScriptingPythonWidgets - ) - - if(BUILD_TESTING) - add_subdirectory(Testing) - endif() -endif() diff --git a/Modules/QtPython/QmitkCtkPythonShell.cpp b/Modules/QtPython/QmitkCtkPythonShell.cpp deleted file mode 100644 index 18ac980cc4..0000000000 --- a/Modules/QtPython/QmitkCtkPythonShell.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkCtkPythonShell.h" - -#include -#include -#include -#include -#include -#include "mitkIPythonService.h" -#include -#include -#include - -struct QmitkCtkPythonShellData -{ - mitk::IPythonService* m_PythonService; - us::ServiceReference m_PythonServiceRef; -}; - -QmitkCtkPythonShell::QmitkCtkPythonShell(QWidget* parent) - : ctkPythonConsole(parent), d( new QmitkCtkPythonShellData ) -{ - this->setWelcomeTextColor(Qt::green); - this->setPromptColor(Qt::gray); - this->setStdinTextColor(Qt::white); - this->setCommandTextColor(Qt::white); - this->setOutputTextColor(Qt::white); - - MITK_DEBUG("QmitkCtkPythonShell") << "retrieving IPythonService"; - us::ModuleContext* context = us::GetModuleContext(); - d->m_PythonServiceRef = context->GetServiceReference(); - d->m_PythonService = dynamic_cast ( context->GetService(d->m_PythonServiceRef) ); - - MITK_DEBUG("QmitkCtkPythonShell") << "checking IPythonService"; - Q_ASSERT( d->m_PythonService ); - - MITK_DEBUG("QmitkCtkPythonShell") << "initialize m_PythonService"; - //this->initialize( d->m_PythonService->GetPythonManager() ); - - MITK_DEBUG("QmitkCtkPythonShell") << "m_PythonService initialized"; - mitk::IPythonService::ForceLoadModule(); -} - -QmitkCtkPythonShell::~QmitkCtkPythonShell() -{ - us::ModuleContext* context = us::GetModuleContext(); - context->UngetService( d->m_PythonServiceRef ); - delete d; -} - -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_PythonService->Execute( urls[i].toString().toStdString(), mitk::IPythonService::SINGLE_LINE_COMMAND ); - } -} - -bool QmitkCtkPythonShell::canInsertFromMimeData(const QMimeData *) const -{ - return true; -} - -void QmitkCtkPythonShell::executeCommand(const QString& command) -{ - MITK_DEBUG("QmitkCtkPythonShell") << "executing command " << command.toStdString(); - d->m_PythonService->Execute(command.toStdString(),mitk::IPythonService::MULTI_LINE_COMMAND); - d->m_PythonService->NotifyObserver(command.toStdString()); -} - -void QmitkCtkPythonShell::Paste(const QString &command) -{ - if( this->isVisible() ) - { - this->exec( command ); - //this->executeCommand( command ); - } -} diff --git a/Modules/QtPython/QmitkCtkPythonShell.h b/Modules/QtPython/QmitkCtkPythonShell.h deleted file mode 100644 index 10c507a63d..0000000000 --- a/Modules/QtPython/QmitkCtkPythonShell.h +++ /dev/null @@ -1,56 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkCtkPythonShell_h -#define QmitkCtkPythonShell_h - -#include -#include -#include - -/// -/// 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 MITKQTPYTHON_EXPORT QmitkCtkPythonShell : public ctkPythonConsole -{ - Q_OBJECT - -public: - QmitkCtkPythonShell(QWidget* parent = nullptr); - ~QmitkCtkPythonShell() override; -public slots: - void Paste( const QString& command ); -protected: - void dragEnterEvent(QDragEnterEvent *event) override; - void dropEvent(QDropEvent *event) override; - bool canInsertFromMimeData( const QMimeData *source ) const; - void executeCommand(const QString& command) override; - -private: - QmitkCtkPythonShellData* d; -}; - - - - -#endif // QmitkCtkPythonShell_h - diff --git a/Modules/QtPython/QmitkPythonScriptEditorHighlighter.cpp b/Modules/QtPython/QmitkPythonScriptEditorHighlighter.cpp deleted file mode 100644 index 09356d6569..0000000000 --- a/Modules/QtPython/QmitkPythonScriptEditorHighlighter.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "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 &) -{ -} - diff --git a/Modules/QtPython/QmitkPythonScriptEditorHighlighter.h b/Modules/QtPython/QmitkPythonScriptEditorHighlighter.h deleted file mode 100644 index a628b3ef5e..0000000000 --- a/Modules/QtPython/QmitkPythonScriptEditorHighlighter.h +++ /dev/null @@ -1,36 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkPythonScriptEditorHighlighter_h -#define QmitkPythonScriptEditorHighlighter_h - -#include -#include - -/// -/// A script highlighter for Python Scripts -class MITKQTPYTHON_EXPORT QmitkPythonScriptEditorHighlighter : public QSyntaxHighlighter -{ - Q_OBJECT - -public: - QmitkPythonScriptEditorHighlighter(QTextDocument *parent); - ~QmitkPythonScriptEditorHighlighter() override; - -protected: - void highlightBlock(const QString &text) override; - void highlightComments(const QString &text); - -private: -}; - -#endif // QmitkPythonScriptEditorHighlighter_h diff --git a/Modules/QtPython/QmitkPythonSnippets.cpp b/Modules/QtPython/QmitkPythonSnippets.cpp deleted file mode 100644 index 460ae115dd..0000000000 --- a/Modules/QtPython/QmitkPythonSnippets.cpp +++ /dev/null @@ -1,491 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkPythonSnippets.h" -#include "QmitkPythonScriptEditorHighlighter.h" -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct QmitkPythonSnippetsData -{ - QString m_AutoSaveFileName; - QString m_SaveFileName; - - QAction* m_PasteSnippet; - QAction* m_RemoveSnippet; - QAction* m_RenameSnippet; - QAction* m_AddSnippet; - QAction* m_RestoreDefaultSnippets; - QAction* m_LoadSnippets; - QAction* m_SaveSnippets; - - QToolBar* m_Toolbar; - - QComboBox* m_Name; - - QTextEdit* m_Content; - - QGridLayout* m_Layout; - - QmitkPythonSnippets::QStringMap m_Snippets; -}; - -const QString QmitkPythonSnippets::DEFAULT_SNIPPET_FILE( ":/mitkPython/PythonSnippets.xml" ); -const QString QmitkPythonSnippets::SNIPPETS_ROOT_XML_ELEMENT_NAME( "PythonSnippets" ); -const QString QmitkPythonSnippets::SNIPPETS_XML_ELEMENT_NAME( "PythonSnippet" ); - -QmitkPythonSnippets::QmitkPythonSnippets( const QString& _AutoSaveFileName, QWidget* parent ) -: QWidget(parent), d(new QmitkPythonSnippetsData) -{ - d->m_SaveFileName = QDir::currentPath(); - d->m_AutoSaveFileName = _AutoSaveFileName; - - if( !QmitkPythonSnippets::LoadStringMap( d->m_AutoSaveFileName, d->m_Snippets ) ) - { - QmitkPythonSnippets::LoadStringMap( DEFAULT_SNIPPET_FILE, d->m_Snippets ); - } - - d->m_PasteSnippet = new QAction(this); - d->m_PasteSnippet->setObjectName(QString::fromUtf8("PasteSnippet")); - QIcon icon; - icon.addFile(QString::fromUtf8(":/mitkPython/edit-paste.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_PasteSnippet->setIcon(icon); - d->m_PasteSnippet->setToolTip("Paste snippet!"); - d->m_PasteSnippet->setEnabled(false); - - d->m_RemoveSnippet = new QAction(this); - d->m_RemoveSnippet->setObjectName(QString::fromUtf8("RemoveSnippet")); - QIcon icon1; - icon1.addFile(QString::fromUtf8(":/mitkPython/edit-delete.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_RemoveSnippet->setIcon(icon1); - d->m_RemoveSnippet->setToolTip("Remove snippet."); - d->m_RemoveSnippet->setEnabled(false); - - d->m_RenameSnippet = new QAction(this); - d->m_RenameSnippet->setObjectName(QString::fromUtf8("RenameSnippet")); - QIcon icon2; - icon2.addFile(QString::fromUtf8(":/mitkPython/edit-find-replace.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_RenameSnippet->setIcon(icon2); - d->m_RenameSnippet->setToolTip("Rename snippet."); - d->m_RenameSnippet->setEnabled(false); - - d->m_AddSnippet = new QAction(this); - d->m_AddSnippet->setObjectName(QString::fromUtf8("AddSnippet")); - QIcon icon3; - icon3.addFile(QString::fromUtf8(":/mitkPython/document-new.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_AddSnippet->setIcon(icon3); - d->m_AddSnippet->setToolTip("Add snippet."); - - d->m_RestoreDefaultSnippets = new QAction(this); - d->m_RestoreDefaultSnippets->setObjectName(QString::fromUtf8("RestoreDefaultSnippets")); - QIcon icon4; - icon4.addFile(QString::fromUtf8(":/mitkPython/edit-clear.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_RestoreDefaultSnippets->setIcon(icon4); - d->m_RestoreDefaultSnippets->setToolTip("Restore default snippets"); - - d->m_LoadSnippets = new QAction(this); - d->m_LoadSnippets->setToolTip("Load Snippets from disk."); - d->m_LoadSnippets->setObjectName(QString::fromUtf8("LoadSnippets")); - QIcon icon5; - icon5.addFile(QString::fromUtf8(":/mitkPython/document-open.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_LoadSnippets->setIcon(icon5); - - d->m_SaveSnippets = new QAction(this); - d->m_SaveSnippets->setToolTip("Save Snippets to disk."); - d->m_SaveSnippets->setObjectName(QString::fromUtf8("SaveSnippets")); - QIcon icon6; - icon6.addFile(QString::fromUtf8(":/mitkPython/document-save.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_SaveSnippets->setIcon(icon6); - d->m_SaveSnippets->setEnabled(false); - - d->m_Toolbar = new QToolBar; - d->m_Toolbar->addAction( d->m_PasteSnippet ); - d->m_Toolbar->addAction( d->m_AddSnippet ); - d->m_Toolbar->addAction( d->m_RemoveSnippet ); - d->m_Toolbar->addAction( d->m_RenameSnippet ); - d->m_Toolbar->addAction( d->m_RestoreDefaultSnippets ); - d->m_Toolbar->addAction( d->m_SaveSnippets ); - d->m_Toolbar->addAction( d->m_LoadSnippets ); - - d->m_Name = new QComboBox; - d->m_Name->setObjectName(QString::fromUtf8("Name")); - - d->m_Content = new QTextEdit(this); - d->m_Content->setObjectName(QString::fromUtf8("Content")); - d->m_Content->setEnabled(false); - - new QmitkPythonScriptEditorHighlighter( d->m_Content->document() ); - - d->m_Layout = new QGridLayout; - d->m_Layout->addWidget( d->m_Toolbar, 0, 0, 1, 1 ); - d->m_Layout->addWidget( d->m_Name, 1, 0, 1, 1 ); - d->m_Layout->addWidget( d->m_Content, 2, 0, 1, 1 ); - d->m_Layout->setContentsMargins(2,2,2,2); - - this->setLayout(d->m_Layout); - QMetaObject::connectSlotsByName(this); - - this->Update(); -} - -QmitkPythonSnippets::~QmitkPythonSnippets() -{ - delete d; -} - -void QmitkPythonSnippets::on_PasteSnippet_triggered( bool ) -{ - emit PasteCommandRequested( d->m_Content->toPlainText() ); -} - -void QmitkPythonSnippets::on_RenameSnippet_triggered(bool) -{ - QString oldname = d->m_Name->currentText(); - QString name = oldname; - bool ok = false; - while( true ) - { - name = QInputDialog::getText(this, - tr("Add new snippet"), - tr("Name of snippet:"), - QLineEdit::Normal, - name, - &ok); - - if (ok) - { - if ( d->m_Snippets.contains(name) ) - { - QMessageBox::warning(this, - tr("Duplicate name."), - tr("The entered name already exists. Enter another one or cancel the operation."), - QMessageBox::Ok, - QMessageBox::Ok ); - } - else - { - QString tmpSnippet = d->m_Snippets[oldname]; - d->m_Snippets.remove(oldname); - d->m_Snippets[name] = tmpSnippet; - this->Update(name); - this->SaveStringMap( d->m_AutoSaveFileName, d->m_Snippets ); - break; - } - } - else - { - break; - } - } -} - -void QmitkPythonSnippets::on_AddSnippet_triggered(bool) -{ - bool ok; - QString name = QInputDialog::getText(this, - tr("Add new snippet"), - tr("Name of snippet:"), - QLineEdit::Normal, - "newSnippet", - &ok); - if (ok && !name.isEmpty()) - { - MITK_DEBUG("QmitkPythonSnippets") << "creating unique name for " << name.toStdString(); - name = this->CreateUniqueName(name); - - MITK_DEBUG("QmitkPythonSnippets") << "creating snippet " << name.toStdString(); - d->m_Snippets[name] = ""; - this->Update(name); - this->SaveStringMap( d->m_AutoSaveFileName, d->m_Snippets ); - } -} - -QString QmitkPythonSnippets::CreateUniqueName( const QString& name ) const -{ - QString newName = name; - size_t i = 2; - while( d->m_Snippets.contains(name) ) - { - newName = name + QString("_%1").arg(i); - ++i; - } - - return newName; -} - -void QmitkPythonSnippets::on_RemoveSnippet_triggered(bool) -{ - QString name = d->m_Name->currentText(); - QString question = QString("Really remove Snippet %1?").arg(name); - int remove = QMessageBox::question( this, - QString("Confirm removal"), - question, - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No ); - - if( remove == QMessageBox::Yes || remove == QMessageBox::Ok ) - { - d->m_Snippets.remove(name); - this->Update(); - this->SaveStringMap( d->m_AutoSaveFileName, d->m_Snippets ); - } -} - -void QmitkPythonSnippets::on_RestoreDefaultSnippets_triggered(bool) -{ - QString question = QString("Really restore default Snippets?"); - int remove = QMessageBox::question( this, - QString("Confirm restoring"), - question, - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No ); - if( remove == QMessageBox::Yes || remove == QMessageBox::Ok ) - { - QmitkPythonSnippets::LoadStringMap( DEFAULT_SNIPPET_FILE, d->m_Snippets ); - this->Update(); - this->SaveStringMap( d->m_AutoSaveFileName, d->m_Snippets ); - } -} - -void QmitkPythonSnippets::on_Name_currentIndexChanged(int i) -{ - bool validSelection = i >= 0 ; - - d->m_PasteSnippet->setEnabled(validSelection); - d->m_RemoveSnippet->setEnabled(validSelection); - d->m_RenameSnippet->setEnabled(validSelection); - d->m_Content->setEnabled(validSelection); - d->m_SaveSnippets->setEnabled(validSelection); - - if( validSelection ) - { - QString name = d->m_Name->currentText(); - MITK_DEBUG("QmitkPythonSnippets") << "selected snippet " << name.toStdString(); - d->m_Content->setText( d->m_Snippets[name] ); - MITK_DEBUG("QmitkPythonSnippets") << "selected snippet content " << d->m_Snippets[name].toStdString(); - } -} - -void QmitkPythonSnippets::SaveStringMap(const QString &filename, const QmitkPythonSnippets::QStringMap &) const -{ - MITK_DEBUG("QmitkPythonSnippets") << "saving to xml file " << filename.toStdString(); - - if( filename.isEmpty() ) - { - MITK_WARN("QmitkPythonSnippets") << "empty auto save file path given. quit."; - return; - } - - QFile file(filename); - file.open(QIODevice::WriteOnly); - if( !file.isOpen() ) - { - MITK_WARN("QmitkPythonSnippets") << "could not open file " << filename.toStdString() << " for writing"; - return; - } - QXmlStreamWriter xmlWriter(&file); - - xmlWriter.setAutoFormatting(true); - xmlWriter.writeStartDocument(); - xmlWriter.writeStartElement(SNIPPETS_ROOT_XML_ELEMENT_NAME); - - QStringMap::const_iterator it = d->m_Snippets.begin(); - while( it != d->m_Snippets.end() ) - { - - { - MITK_DEBUG("QmitkPythonSnippets") << "SNIPPETS_XML_ELEMENT_NAME " << SNIPPETS_XML_ELEMENT_NAME.toStdString(); - MITK_DEBUG("QmitkPythonSnippets") << "writing item " << it.key().toStdString(); - } - - xmlWriter.writeStartElement(SNIPPETS_XML_ELEMENT_NAME); - - xmlWriter.writeAttribute( "key", it.key() ); - xmlWriter.writeAttribute( "value", it.value() ); - - xmlWriter.writeEndElement(); - - ++it; - } - - xmlWriter.writeEndDocument(); - if( file.isOpen() ) - file.close(); - - { - MITK_DEBUG("QmitkPythonSnippets") << "SaveStringMap successful "; - } - -} - -bool QmitkPythonSnippets::LoadStringMap( const QString& filename, QmitkPythonSnippets::QStringMap& oldMap ) -{ - MITK_DEBUG("QmitkPythonSnippets") << "loading from xml file " << filename.toStdString(); - QStringMap map; - - QXmlStreamReader xmlReader; - QFile file; - QByteArray data; - // resource file - if( filename.startsWith(":") ) - { - QResource res( filename ); - data = QByteArray( reinterpret_cast< const char* >( res.data() ), res.size() ); - xmlReader.addData( data ); - } - else - { - file.setFileName( filename ); - if (!file.open(QFile::ReadOnly | QFile::Text)) - { - MITK_ERROR << "Error: Cannot read file " << qPrintable(filename) - << ": " << qPrintable(file.errorString()); - return false; - } - xmlReader.setDevice(&file); - } - - xmlReader.readNext(); - - while(!xmlReader.atEnd()) - { - xmlReader.readNext(); - - if(xmlReader.name() == SNIPPETS_XML_ELEMENT_NAME) - { - QXmlStreamAttributes attributes = xmlReader.attributes(); - QString key; - QString value; - if(attributes.hasAttribute("key")) - { - key = attributes.value("key").toString(); - } - - if(attributes.hasAttribute("value")) - { - value = attributes.value("value").toString(); - } - - if( !key.isEmpty() ) - { - MITK_DEBUG("QmitkPythonSnippets") << "loaded snippet " << key.toStdString(); - MITK_DEBUG("QmitkPythonSnippets") << "value " << value.toStdString(); - map[key] = value; - } - } - } - - if (xmlReader.hasError()) - { - MITK_ERROR << "Error: Failed to parse file " - << qPrintable(filename) << ": " - << qPrintable(xmlReader.errorString()); - return false; - } - else if (file.error() != QFile::NoError) - { - MITK_ERROR << "Error: Cannot read file " << qPrintable(filename) - << ": " << qPrintable(file.errorString()); - return false; - } - - if( file.isOpen() ) - file.close(); - - oldMap = map; - return true; -} - -void QmitkPythonSnippets::Update(const QString &name) -{ - d->m_Name->clear(); - d->m_Content->clear(); - - MITK_DEBUG("QmitkPythonSnippets") << "size of snippets " << d->m_Snippets.size(); - QStringMap::const_iterator it = d->m_Snippets.begin(); - - while( it != d->m_Snippets.end() ) - { - MITK_DEBUG("QmitkPythonSnippets") << "adding item " << it.key().toStdString(); - d->m_Name->addItem( it.key() ); - ++it; - } - - int index = d->m_Name->findText( name ); - if( index >= 0 ) - { - MITK_DEBUG("QmitkPythonSnippets") << "selecting index " << index; - d->m_Name->setCurrentIndex(index); - } - -} - -void QmitkPythonSnippets::on_Content_textChanged() -{ - if( d->m_Content->isEnabled() ) - { - QString name = d->m_Name->currentText(); - QString snippet = d->m_Content->toPlainText(); - d->m_Snippets[name] = snippet; - - this->SaveStringMap( d->m_AutoSaveFileName, d->m_Snippets ); - MITK_DEBUG("QmitkPythonSnippets") << "SaveStringMap successful"; - } -} - -void QmitkPythonSnippets::on_SaveSnippets_triggered(bool) -{ - QString fileName = QFileDialog::getSaveFileName(this, "Save snippets", d->m_SaveFileName, "XML files (*.xml)"); - if( !fileName.isEmpty() ) - { - d->m_SaveFileName = fileName; - this->SaveStringMap( d->m_SaveFileName, d->m_Snippets ); - } -} - -void QmitkPythonSnippets::on_LoadSnippets_triggered(bool) -{ - QString fileName = QFileDialog::getOpenFileName(this, "Load snippets", d->m_SaveFileName, "XML files (*.xml)"); - - if( !fileName.isEmpty() ) - { - d->m_SaveFileName = fileName; - QString question = QString("Your current snippets will be overwritten. Proceed?"); - int overwrite = QMessageBox::warning(this, - QString("Confirm overwrite"), - question, - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No ); - - if( overwrite == QMessageBox::Yes ) - { - this->LoadStringMap( d->m_SaveFileName, d->m_Snippets ); - this->Update( d->m_Name->currentText() ); - this->SaveStringMap( d->m_AutoSaveFileName, d->m_Snippets ); - } - } - -} diff --git a/Modules/QtPython/QmitkPythonSnippets.h b/Modules/QtPython/QmitkPythonSnippets.h deleted file mode 100644 index abec155fc2..0000000000 --- a/Modules/QtPython/QmitkPythonSnippets.h +++ /dev/null @@ -1,101 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef _QmitkPythonSnippets_H -#define _QmitkPythonSnippets_H - -#include -#include -#include -struct QmitkPythonSnippetsData; - -/// -/// a widget that holds snippets and serializes the snippets to a certain places -class MITKQTPYTHON_EXPORT QmitkPythonSnippets: public QWidget -{ - Q_OBJECT - - public: - static const QString DEFAULT_SNIPPET_FILE; - static const QString SNIPPETS_ROOT_XML_ELEMENT_NAME; - static const QString SNIPPETS_XML_ELEMENT_NAME; - /// - /// typedef for string map - typedef QMap QStringMap; - /// - /// build ui here - /// the snippets will be loaded from _AutoSaveFileName if not empty and readable - /// otherwise the default snippets will be loaded - QmitkPythonSnippets( const QString& _AutoSaveFileName="", QWidget* parent=nullptr ); - /// - /// delete d pointer - ~QmitkPythonSnippets() override; - /// - /// read string map from xml file - static bool LoadStringMap( const QString& filename, QStringMap& oldMap ); - -signals: - /// - /// this class whishes to paste sth command - void PasteCommandRequested(const QString& command); - - protected slots: - /// - /// emits PasteCommandRequested signal - void on_PasteSnippet_triggered( bool checked = false ); - /// - /// ask for name as long as it exists, call update() - void on_RenameSnippet_triggered( bool checked = false ); - /// - /// ask for name, create snippet, call update() - void on_AddSnippet_triggered( bool checked = false ); - /// - /// remove the current snippet, call update() - void on_RemoveSnippet_triggered( bool checked = false ); - /// - /// call LoadStringMap with d->m_DefaultSnippetsAutoSaveFileName - void on_RestoreDefaultSnippets_triggered( bool checked = false ); - /// - /// update action state (enable/disable), update text box - void on_Name_currentIndexChanged( int i ); - /// - /// save changed snippet - void on_Content_textChanged(); - /// - /// ask for file, save snippets - void on_SaveSnippets_triggered( bool checked = false ); - /// - /// ask for file, load snippets (do not replace) - void on_LoadSnippets_triggered( bool checked = false ); - - protected: - /// - /// write string map to xml file - void SaveStringMap( const QString& filename, const QStringMap& map ) const; - /// - /// creates a name which does not exist in the list - QString CreateUniqueName(const QString &name) const; - /// - /// update combo box - /// if name is passed, the according element will be selected - void Update(const QString &name = ""); - private: - /// - /// d pointer declaration (holds members) - QmitkPythonSnippetsData* d; -}; - - - - -#endif // _QmitkPythonSnippets_H_INCLUDED - diff --git a/Modules/QtPython/QmitkPythonSnippets.ui b/Modules/QtPython/QmitkPythonSnippets.ui deleted file mode 100644 index f7bc574d07..0000000000 --- a/Modules/QtPython/QmitkPythonSnippets.ui +++ /dev/null @@ -1,116 +0,0 @@ - - - QmitkPythonSnippets - - - - 0 - 0 - 613 - 436 - - - - - 0 - 0 - - - - true - - - QmitkTemplate - - - - - - Name: - - - - - - - true - - - - - - - Content: - - - - - - - - - - - :/mitkPython/edit-paste.png:/mitkPython/edit-paste.png - - - Paste snippet! - - - Push button to paste the snippet into the console or the editor. Or double click on the snippet text window. - - - - - - :/mitkPython/edit-delete.png:/mitkPython/edit-delete.png - - - Remove snippet - - - Remove the selected snippet. - - - - - - :/mitkPython/edit-find-replace.png:/mitkPython/edit-find-replace.png - - - Rename snippet - - - Rename the selected snippet. - - - - - - :/mitkPython/document-new.png:/mitkPython/document-new.png - - - Add snippet - - - Add a new snippet to the list. - - - - - - :/mitkPython/edit-clear.png:/mitkPython/edit-clear.png - - - Restore default snippets - - - Clear and restore the default snippets. - - - - - - - - diff --git a/Modules/QtPython/QmitkPythonTextEditor.cpp b/Modules/QtPython/QmitkPythonTextEditor.cpp deleted file mode 100644 index 29de17ca46..0000000000 --- a/Modules/QtPython/QmitkPythonTextEditor.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkPythonTextEditor.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include "QmitkPythonScriptEditorHighlighter.h" - -struct QmitkPythonTextEditorData -{ - QString m_FilePath; - - QAction* m_LoadScript; - QAction* m_SaveScript; - QAction* m_RunScript; - QToolBar* m_Toolbar; - - QTextEdit* m_Content; - - QGridLayout* m_Layout; - mitk::IPythonService* m_PythonService; - us::ServiceReference m_PythonServiceRef; - - QString m_FileName; -}; - -QmitkPythonTextEditor::QmitkPythonTextEditor(QWidget *parent) - :QWidget(parent), d(new QmitkPythonTextEditorData) -{ - us::ModuleContext* context = us::GetModuleContext(); - d->m_PythonServiceRef = context->GetServiceReference(); - d->m_PythonService = context->GetService( d->m_PythonServiceRef ); - - d->m_LoadScript = new QAction(this); - d->m_LoadScript->setToolTip("Load script from disk."); - d->m_LoadScript->setObjectName(QString::fromUtf8("LoadScript")); - QIcon icon2; - icon2.addFile(QString::fromUtf8(":/mitkPython/document-open.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_LoadScript->setIcon(icon2); - - d->m_SaveScript = new QAction(this); - d->m_SaveScript->setToolTip("Save script to disk."); - d->m_SaveScript->setObjectName(QString::fromUtf8("SaveScript")); - QIcon icon3; - icon3.addFile(QString::fromUtf8(":/mitkPython/document-save.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_SaveScript->setIcon(icon3); - - d->m_RunScript = new QAction(this); - d->m_RunScript->setToolTip("Run the current script."); - d->m_RunScript->setObjectName(QString::fromUtf8("RunScript")); - QIcon icon4; - icon4.addFile(QString::fromUtf8(":/mitkPython/media-playback-start.png"), QSize(), QIcon::Normal, QIcon::Off); - d->m_RunScript->setIcon(icon4); - - d->m_Toolbar = new QToolBar; - d->m_Toolbar->addAction( d->m_LoadScript ); - d->m_Toolbar->addAction( d->m_SaveScript ); - d->m_Toolbar->addAction( d->m_RunScript ); - - d->m_Content = new QTextEdit(this); - d->m_Content->setObjectName(QString::fromUtf8("Content")); - - new QmitkPythonScriptEditorHighlighter(d->m_Content->document()); - - d->m_Layout = new QGridLayout; - d->m_Layout->addWidget( d->m_Toolbar, 0, 0, 1, 1 ); - d->m_Layout->addWidget( d->m_Content, 1, 0, 1, 1 ); - d->m_Layout->setContentsMargins(2,2,2,2); - - this->setLayout(d->m_Layout); - QMetaObject::connectSlotsByName(this); -} - -QmitkPythonTextEditor::~QmitkPythonTextEditor() -{ - us::ModuleContext* context = us::GetModuleContext(); - context->UngetService( d->m_PythonServiceRef ); - - delete d; -} - -void QmitkPythonTextEditor::dragEnterEvent(QDragEnterEvent *event) -{ - event->accept(); -} - -void QmitkPythonTextEditor::dropEvent(QDropEvent *event) -{ - QList urls = event->mimeData()->urls(); - for(int i = 0; i < urls.size(); i++) - { - this->Paste( urls[i].toString() ); - } -} -/* -bool QmitkPythonTextEditor::canInsertFromMimeData( const QMimeData * ) const -{ - return true; -} -*/ - -void QmitkPythonTextEditor::Paste(const QString &command) -{ - if( this->isVisible() ) - { - d->m_Content->insertPlainText(command + "\n"); - } -} - - -QString QmitkPythonTextEditor::ReadFile(const QString& filename) -{ - QFile file(filename); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - { - MITK_ERROR << "Could not open file " << filename.toStdString(); - return nullptr; - } - - QByteArray total; - QByteArray line; - while (!file.atEnd()) - { - line = file.read(1024); - total.append(line); - } - - return QString(total); -} - -void QmitkPythonTextEditor::on_SaveScript_triggered( bool ) -{ - d->m_FileName = QFileDialog::getSaveFileName(this,tr("Save File"), d->m_FileName,tr("*.py")); - if( d->m_FileName.compare("") != 0) - { - std::ofstream myfile; - myfile.open(d->m_FileName.toLocal8Bit().data()); - myfile << d->m_Content->toPlainText().toLocal8Bit().data(); - myfile.close(); - } -} - -void QmitkPythonTextEditor::on_LoadScript_triggered( bool ) -{ - d->m_FileName = QFileDialog::getOpenFileName( this, "Load Script", d->m_FileName, tr("*.py")); - if( !d->m_FileName.isEmpty() ) - { - QString contents = this->ReadFile( d->m_FileName ); - d->m_Content->setText(contents); - } -} - -void QmitkPythonTextEditor::on_RunScript_triggered( bool ) -{ - if( !d->m_PythonService ) - { - MITK_ERROR << "Python service not available."; - return; - } - - d->m_PythonService->Execute( d->m_Content->toPlainText().toStdString(), mitk::IPythonService::MULTI_LINE_COMMAND ); -} diff --git a/Modules/QtPython/QmitkPythonTextEditor.h b/Modules/QtPython/QmitkPythonTextEditor.h deleted file mode 100644 index 2c34734200..0000000000 --- a/Modules/QtPython/QmitkPythonTextEditor.h +++ /dev/null @@ -1,49 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QMITKPYTHONTEXTEDITOR_H_ -#define QMITKPYTHONTEXTEDITOR_H_ - -#include -#include -#include -#include -struct QmitkPythonTextEditorData; - -/// -/// this is a python text editor with syntax highlightning -class MITKQTPYTHON_EXPORT QmitkPythonTextEditor : public QWidget -{ - Q_OBJECT - -public: - QmitkPythonTextEditor(QWidget *parent = nullptr); - ~QmitkPythonTextEditor() override; -public slots: - void Paste(const QString& command); - -protected slots: - void on_SaveScript_triggered(bool checked=false); - void on_LoadScript_triggered(bool checked=false); - void on_RunScript_triggered(bool checked=false); - -protected: - void dragEnterEvent(QDragEnterEvent *event) override; - void dropEvent(QDropEvent *event) override; - //bool canInsertFromMimeData( const QMimeData *source ) const; - QString ReadFile(const QString &filename); - -private: - QmitkPythonTextEditorData* d; -}; - -#endif diff --git a/Modules/QtPython/QmitkPythonVariableStackTableModel.cpp b/Modules/QtPython/QmitkPythonVariableStackTableModel.cpp deleted file mode 100755 index 399903ff84..0000000000 --- a/Modules/QtPython/QmitkPythonVariableStackTableModel.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkPythonVariableStackTableModel.h" -#include -#include -#include -#include -#include -#include -#include "QmitkMimeTypes.h" - -const QString QmitkPythonVariableStackTableModel::MITK_IMAGE_VAR_NAME = "mitkImage"; -const QString QmitkPythonVariableStackTableModel::MITK_SURFACE_VAR_NAME = "mitkSurface"; - -QmitkPythonVariableStackTableModel::QmitkPythonVariableStackTableModel(QObject *parent) - :QAbstractTableModel(parent) -{ - us::ModuleContext* context = us::GetModuleContext(); - m_PythonServiceRef = context->GetServiceReference(); - m_PythonService = context->GetService(m_PythonServiceRef); - m_PythonService->AddPythonCommandObserver( this ); -} - -QmitkPythonVariableStackTableModel::~QmitkPythonVariableStackTableModel() -{ - us::ModuleContext* context = us::GetModuleContext(); - context->UngetService( m_PythonServiceRef ); - m_PythonService->RemovePythonCommandObserver( this ); -} - -bool QmitkPythonVariableStackTableModel::dropMimeData(const QMimeData * data, Qt::DropAction action, int, int, const QModelIndex &) -{ - // 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(QmitkMimeTypes::DataNodePtrs)) - { - MITK_DEBUG("QmitkPythonVariableStackTableModel") << "dropped MITK DataNode"; - returnValue = true; - - int i = 0; - QList dataNodeList = QmitkMimeTypes::ToDataNodePtrList(data); - mitk::DataNode* node = nullptr; - foreach(node, dataNodeList) - { - mitk::Image* mitkImage = dynamic_cast(node->GetData()); - MITK_DEBUG("QmitkPythonVariableStackTableModel") << "mitkImage is not null " << (mitkImage != nullptr? "true": "false"); - - QRegExp rx("^\\d"); - QString varName(node->GetName().c_str()); - // regex replace every character that is not allowed in a python variable - varName = varName.replace(QRegExp("[.\\+\\-*\\s\\/\\n\\t\\r]"),QString("_")); - - if( mitkImage ) - { - if ( varName.isEmpty() ) - varName = MITK_IMAGE_VAR_NAME; - if ( rx.indexIn(varName) == 0) - varName.prepend("_").prepend(MITK_IMAGE_VAR_NAME); - - if( i > 0 ) - varName = QString("%1%2").arg(varName).arg(i); - MITK_DEBUG("QmitkPythonVariableStackTableModel") << "varName" << varName.toStdString(); - - bool exportAsCvImage = mitkImage->GetDimension() == 2 && m_PythonService->IsOpenCvPythonWrappingAvailable(); - - if( exportAsCvImage ) - { - int ret = QMessageBox::question(nullptr, "Export option", - "2D image detected. Export as OpenCV image to Python instead of an SimpleITK image?", - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - exportAsCvImage = ret == QMessageBox::Yes; - if(exportAsCvImage) - { - m_PythonService->CopyToPythonAsCvImage( mitkImage, varName.toStdString() ); - ++i; - } - } - if( !exportAsCvImage ) - { - if( m_PythonService->IsSimpleItkPythonWrappingAvailable() ) - { - m_PythonService->CopyToPythonAsSimpleItkImage( mitkImage, varName.toStdString() ); - ++i; - } - else - { - MITK_ERROR << "SimpleITK Python wrapping not available. Skipping export for image " << node->GetName(); - } - } - } - else - { - mitk::Surface* surface = dynamic_cast(node->GetData()); - MITK_DEBUG("QmitkPythonVariableStackTableModel") << "found surface"; - - if( surface ) - { - if (varName.isEmpty() ) - varName = MITK_SURFACE_VAR_NAME; - if ( rx.indexIn(varName) == 0) - varName.prepend("_").prepend(MITK_SURFACE_VAR_NAME); - - MITK_DEBUG("QmitkPythonVariableStackTableModel") << "varName" << varName; - - if( m_PythonService->IsVtkPythonWrappingAvailable() ) - { - m_PythonService->CopyToPythonAsVtkPolyData( surface, varName.toStdString() ); - } - else - { - MITK_ERROR << "VTK Python wrapping not available. Skipping export for surface " << node->GetName(); - } - } - } - } - } - 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 = "Type"; - else if(section == 2) - headerData = "Value"; - } - } - - 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 QString::fromStdString(item.m_Name); - if(index.column() == 1) - return QString::fromStdString(item.m_Type); - if(index.column() == 2) - return QString::fromStdString(item.m_Value); - } - } - 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 std::string& pythonCommand) -{ - MITK_DEBUG("QmitkPythonVariableStackTableModel") << "command was executed " << pythonCommand; - m_VariableStack = m_PythonService->GetVariableStack(); - QAbstractTableModel::beginResetModel(); - QAbstractTableModel::endResetModel(); -} - -std::vector QmitkPythonVariableStackTableModel::GetVariableStack() const -{ - return m_VariableStack; -} diff --git a/Modules/QtPython/QmitkPythonVariableStackTableModel.h b/Modules/QtPython/QmitkPythonVariableStackTableModel.h deleted file mode 100755 index a9e8ac748f..0000000000 --- a/Modules/QtPython/QmitkPythonVariableStackTableModel.h +++ /dev/null @@ -1,59 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkPythonVariableStackTableModel_h -#define QmitkPythonVariableStackTableModel_h - -#include -#include -#include -#include "mitkIPythonService.h" -#include -#include - -/// -/// 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 MITKQTPYTHON_EXPORT QmitkPythonVariableStackTableModel : public QAbstractTableModel, public mitk::PythonCommandObserver -{ - Q_OBJECT - -public: - static const QString MITK_IMAGE_VAR_NAME; - static const QString MITK_SURFACE_VAR_NAME; - - QmitkPythonVariableStackTableModel(QObject *parent = nullptr); - ~QmitkPythonVariableStackTableModel() override; - - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - Qt::ItemFlags flags( const QModelIndex& index ) const override; - QVariant headerData(int section, Qt::Orientation orientation, - int role) const override; - - QStringList mimeTypes() const override; - bool dropMimeData ( const QMimeData *, Qt::DropAction, int, int, const QModelIndex & ) override; - Qt::DropActions supportedDropActions() const override; - //Qt::DropActions supportedDragActions() const; - - void CommandExecuted(const std::string& pythonCommand) override; - - std::vector GetVariableStack() const; -private: - std::vector m_VariableStack; - mitk::IPythonService* m_PythonService; - us::ServiceReference m_PythonServiceRef; -}; - -#endif // QmitkPythonVariableStackTableModel_h diff --git a/Modules/QtPython/QmitkPythonVariableStackTableView.cpp b/Modules/QtPython/QmitkPythonVariableStackTableView.cpp deleted file mode 100755 index 4d3ddc392a..0000000000 --- a/Modules/QtPython/QmitkPythonVariableStackTableView.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkPythonVariableStackTableView.h" -#include -#include -#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 ); - - us::ModuleContext* context = us::GetModuleContext(); - us::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 == nullptr ) - { - MITK_ERROR << "QmitkPythonVariableStackTableView not configured correctly. Quit"; - return; - } - - int row = index.row(); - std::vector variableStack = m_TableModel->GetVariableStack(); - { - MITK_DEBUG("QmitkPythonVariableStackTableView") << "row " << row; - MITK_DEBUG("QmitkPythonVariableStackTableView") << "variableStack.size(): " << variableStack.size(); - } - - QString varName = QString::fromStdString( variableStack.at(row).m_Name ); - QString type = QString::fromStdString( variableStack.at(row).m_Type ); - QString value = QString::fromStdString( variableStack.at(row).m_Value ); - - { - MITK_DEBUG("QmitkPythonVariableStackTableView") << "varName: " << varName.toStdString(); - MITK_DEBUG("QmitkPythonVariableStackTableView") << "type: " << type.toStdString(); - } - - mitk::Image::Pointer mitkImage; - mitk::Surface::Pointer mitkSurface; - - if( type.startsWith("Image") ) - { - mitkImage = m_PythonService->CopySimpleItkImageFromPython(varName.toStdString()); - } - else if( type.startsWith("numpy.ndarray") ) - { - mitkImage = m_PythonService->CopyCvImageFromPython(varName.toStdString()); - } - else if( value.startsWith("(vtkCommonDataModelPython.vtkPolyData)") ) - { - mitkSurface = m_PythonService->CopyVtkPolyDataFromPython(varName.toStdString()); - } - - std::string nodeName = varName.toStdString(); - mitk::DataNode::Pointer node = m_DataStorage->GetNamedNode(nodeName); - - // only create data node if it does not exist - if ( node.IsNull() ) - { - node = mitk::DataNode::New(); - node->SetName ( nodeName ); - m_DataStorage->Add(node); - } - - if( mitkImage.IsNotNull() ) - { - node->SetData( mitkImage ); - } - else if( mitkSurface.IsNotNull() ) - { - node->SetData( mitkSurface ); - // init renderwindow geometry - mitk::RenderingManager::GetInstance()->InitializeViews(mitkSurface->GetGeometry()); - } - - mitk::RenderingManager::GetInstance()->RequestUpdateAll(); -} diff --git a/Modules/QtPython/QmitkPythonVariableStackTableView.h b/Modules/QtPython/QmitkPythonVariableStackTableView.h deleted file mode 100755 index 3754279bbf..0000000000 --- a/Modules/QtPython/QmitkPythonVariableStackTableView.h +++ /dev/null @@ -1,46 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef QmitkPythonVariableStackTableView_h -#define QmitkPythonVariableStackTableView_h - -#include -#include -#include "QmitkPythonVariableStackTableModel.h" -#include -#include - -/// -/// 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 MITKQTPYTHON_EXPORT QmitkPythonVariableStackTableView : public QTableView -{ - Q_OBJECT - -public: - QmitkPythonVariableStackTableView(QWidget *parent = nullptr); - ~QmitkPythonVariableStackTableView() override; - - 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/QtPython/Testing/CMakeLists.txt b/Modules/QtPython/Testing/CMakeLists.txt deleted file mode 100644 index bca7958889..0000000000 --- a/Modules/QtPython/Testing/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -set(package_deps PACKAGE_DEPENDS PRIVATE) - -MITK_CREATE_MODULE_TESTS(${package_deps}) - -if(UNIX AND NOT APPLE) - #[[ The PythonQt library (dependency of MitkQtPython module) depends on Qt - libraries without absolute paths. Use LD_LIBRARY_PATH as workaround. - See T26955. ]] - if(TARGET ${TESTDRIVER}) - get_target_property(ld_library_path Qt5::Core IMPORTED_LOCATION_RELEASE) - get_filename_component(ld_library_path "${ld_library_path}" DIRECTORY) - - add_test( - NAME mitkPythonTest - COMMAND ${CMAKE_COMMAND} -E env "LD_LIBRARY_PATH=${ld_library_path}" - ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkPythonConsoleTest - ) - endif() -endif() diff --git a/Modules/QtPython/Testing/files.cmake b/Modules/QtPython/Testing/files.cmake deleted file mode 100644 index 9f32bcc809..0000000000 --- a/Modules/QtPython/Testing/files.cmake +++ /dev/null @@ -1,10 +0,0 @@ -if(UNIX AND NOT APPLE) - # See T26955. - set(MODULE_CUSTOM_TESTS - mitkPythonConsoleTest.cpp - ) -else() - set(MODULE_TESTS - mitkPythonConsoleTest.cpp - ) -endif() diff --git a/Modules/QtPython/Testing/mitkPythonConsoleTest.cpp b/Modules/QtPython/Testing/mitkPythonConsoleTest.cpp deleted file mode 100644 index c92ea15d72..0000000000 --- a/Modules/QtPython/Testing/mitkPythonConsoleTest.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class mitkPythonConsoleTestSuite : public mitk::TestFixture -{ - CPPUNIT_TEST_SUITE(mitkPythonConsoleTestSuite); - MITK_TEST(TestPython); - CPPUNIT_TEST_SUITE_END(); - -public: - - void TestPython() - { - us::ModuleContext* context = us::GetModuleContext(); - us::ServiceReference m_PythonServiceRef = context->GetServiceReference(); - mitk::IPythonService* m_PythonService = dynamic_cast ( context->GetService(m_PythonServiceRef) ); - mitk::IPythonService::ForceLoadModule(); - - std::string result = m_PythonService->Execute( "5+5", mitk::IPythonService::EVAL_COMMAND ); - MITK_TEST_CONDITION( result == "10", "Testing if running python code 5+5 results in 10" ); - } -}; - -MITK_TEST_SUITE_REGISTRATION(mitkPythonConsole) diff --git a/Modules/QtPython/files.cmake b/Modules/QtPython/files.cmake deleted file mode 100644 index b2aa0226dc..0000000000 --- a/Modules/QtPython/files.cmake +++ /dev/null @@ -1,25 +0,0 @@ -SET(CPP_FILES - QmitkCtkPythonShell.cpp - QmitkPythonVariableStackTableModel.cpp - QmitkPythonVariableStackTableView.cpp - QmitkPythonScriptEditorHighlighter.cpp - QmitkPythonTextEditor.cpp - QmitkPythonSnippets.cpp -) - -#SET(UI_FILES -# QmitkPythonSnippets.ui -#) - -SET(MOC_H_FILES - QmitkCtkPythonShell.h - QmitkPythonVariableStackTableModel.h - QmitkPythonVariableStackTableView.h - QmitkPythonScriptEditorHighlighter.h - QmitkPythonTextEditor.h - QmitkPythonSnippets.h -) - -set(QRC_FILES - resources/mitkPython.qrc -) diff --git a/Modules/QtPython/resources/PythonSnippets.xml b/Modules/QtPython/resources/PythonSnippets.xml deleted file mode 100644 index 7e8a1bcb5d..0000000000 --- a/Modules/QtPython/resources/PythonSnippets.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/Modules/QtPython/resources/document-new.png b/Modules/QtPython/resources/document-new.png deleted file mode 100644 index fe0808b96a..0000000000 Binary files a/Modules/QtPython/resources/document-new.png and /dev/null differ diff --git a/Modules/QtPython/resources/document-open.png b/Modules/QtPython/resources/document-open.png deleted file mode 100644 index d07347689e..0000000000 Binary files a/Modules/QtPython/resources/document-open.png and /dev/null differ diff --git a/Modules/QtPython/resources/document-save.png b/Modules/QtPython/resources/document-save.png deleted file mode 100644 index 26f6689e44..0000000000 Binary files a/Modules/QtPython/resources/document-save.png and /dev/null differ diff --git a/Modules/QtPython/resources/edit-clear.png b/Modules/QtPython/resources/edit-clear.png deleted file mode 100644 index a316e45b08..0000000000 Binary files a/Modules/QtPython/resources/edit-clear.png and /dev/null differ diff --git a/Modules/QtPython/resources/edit-delete.png b/Modules/QtPython/resources/edit-delete.png deleted file mode 100644 index 3c09637cd2..0000000000 Binary files a/Modules/QtPython/resources/edit-delete.png and /dev/null differ diff --git a/Modules/QtPython/resources/edit-find-replace.png b/Modules/QtPython/resources/edit-find-replace.png deleted file mode 100644 index 575e6feac9..0000000000 Binary files a/Modules/QtPython/resources/edit-find-replace.png and /dev/null differ diff --git a/Modules/QtPython/resources/edit-paste.png b/Modules/QtPython/resources/edit-paste.png deleted file mode 100644 index 911ed85b5a..0000000000 Binary files a/Modules/QtPython/resources/edit-paste.png and /dev/null differ diff --git a/Modules/QtPython/resources/media-playback-start.png b/Modules/QtPython/resources/media-playback-start.png deleted file mode 100644 index fbe68ea24f..0000000000 Binary files a/Modules/QtPython/resources/media-playback-start.png and /dev/null differ diff --git a/Modules/QtPython/resources/mitkPython.qrc b/Modules/QtPython/resources/mitkPython.qrc deleted file mode 100644 index 55d4c94e13..0000000000 --- a/Modules/QtPython/resources/mitkPython.qrc +++ /dev/null @@ -1,13 +0,0 @@ - - - document-new.png - document-open.png - document-save.png - edit-delete.png - edit-paste.png - edit-find-replace.png - edit-clear.png - media-playback-start.png - PythonSnippets.xml - - diff --git a/Modules/QtPythonService/CMakeLists.txt b/Modules/QtPythonService/CMakeLists.txt deleted file mode 100644 index bf9eed9014..0000000000 --- a/Modules/QtPythonService/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -mitkFunctionCheckCompilerFlags("-Wno-cpp" CMAKE_CXX_FLAGS) - -mitk_create_module(QtPythonService - INCLUDE_DIRS - PRIVATE src/QtPythonService - DEPENDS PUBLIC MitkPython - PACKAGE_DEPENDS - PUBLIC Qt5|Widgets CTK|CTKScriptingPythonCore+CTKScriptingPythonWidgets - AUTOLOAD_WITH MitkPython -) - -if(TARGET ${MODULE_TARGET}) - target_link_libraries(${MODULE_TARGET} PUBLIC Python3::NumPy) - configure_file(PythonPath.h.in "${CMAKE_CURRENT_BINARY_DIR}/PythonPath.h" @ONLY) -endif() \ No newline at end of file diff --git a/Modules/QtPythonService/PythonPath.h.in b/Modules/QtPythonService/PythonPath.h.in deleted file mode 100644 index 28581baec4..0000000000 --- a/Modules/QtPythonService/PythonPath.h.in +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef _DEBUG -#define PYTHON_PATH_BUILD_TYPE "/Debug" -#else -#define PYTHON_PATH_BUILD_TYPE "/Release" -#endif - -#define PYTHON_LIBRARY "@PYTHON_LIBRARY@" - -#ifdef WIN32 -//Todo: windows system python -#define EXTERNAL_SITE_PACKAGES "@MITK_EXTERNAL_PROJECT_PREFIX@/lib/python@PYTHON_VERSION_MAJOR@.@PYTHON_VERSION_MINOR@/site-packages" -#define EXTERNAL_DIST_PACKAGES "@MITK_EXTERNAL_PROJECT_PREFIX@/lib/python@PYTHON_VERSION_MAJOR@.@PYTHON_VERSION_MINOR@/dist-packages" -#else -#define EXTERNAL_SITE_PACKAGES "@MITK_EXTERNAL_PROJECT_PREFIX@/lib/python@PYTHON_VERSION_MAJOR@.@PYTHON_VERSION_MINOR@/site-packages" -#define EXTERNAL_DIST_PACKAGES "@MITK_EXTERNAL_PROJECT_PREFIX@/lib/python@PYTHON_VERSION_MAJOR@.@PYTHON_VERSION_MINOR@/dist-packages" -#endif diff --git a/Modules/QtPythonService/files.cmake b/Modules/QtPythonService/files.cmake deleted file mode 100644 index 66e7471410..0000000000 --- a/Modules/QtPythonService/files.cmake +++ /dev/null @@ -1,4 +0,0 @@ -set(CPP_FILES - mitkQtPythonService.cpp - mitkQtPythonActivator.cpp -) diff --git a/Modules/QtPythonService/mitkQtPythonActivator.cpp b/Modules/QtPythonService/mitkQtPythonActivator.cpp deleted file mode 100644 index 84bd97a9b4..0000000000 --- a/Modules/QtPythonService/mitkQtPythonActivator.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef mitkQtPythonActivator_h -#define mitkQtPythonActivator_h - -// Microservices -#include -#include "usModuleContext.h" -#include "mitkQtPythonService.h" -#include - -namespace mitk -{ - /// - /// installs the PythonService - /// runs all initial commands (setting env paths etc) - /// - class QtPythonActivator : public us::ModuleActivator - { - public: - - void Load(us::ModuleContext* context) override - { - MITK_DEBUG << "QtPythonActivator::Load"; - //Registering QtPythonService as MicroService - m_PythonService = itk::SmartPointer(new QtPythonService()); - - us::ServiceProperties _PythonServiceProps; - _PythonServiceProps["Name"] = std::string("QtPythonService"); - _PythonServiceProps["service.ranking"] = int(1); - - m_PythonServiceRegistration = context->RegisterService(m_PythonService.GetPointer(), _PythonServiceProps); - } - - void Unload(us::ModuleContext*) override - { - MITK_DEBUG("QtPythonActivator") << "QtPythonActivator::Unload"; - MITK_DEBUG("QtPythonActivator") << "m_PythonService GetReferenceCount " << m_PythonService->GetReferenceCount(); - m_PythonServiceRegistration.Unregister(); - m_PythonService->Delete(); - MITK_DEBUG("QtPythonActivator") << "m_PythonService GetReferenceCount " << m_PythonService->GetReferenceCount(); - } - - ~QtPythonActivator() override - { - } - - private: - itk::SmartPointer m_PythonService; - us::ServiceRegistration m_PythonServiceRegistration; - }; -} - -US_EXPORT_MODULE_ACTIVATOR(mitk::QtPythonActivator) -#endif diff --git a/Modules/QtPythonService/mitkQtPythonService.cpp b/Modules/QtPythonService/mitkQtPythonService.cpp deleted file mode 100644 index 30bbc08488..0000000000 --- a/Modules/QtPythonService/mitkQtPythonService.cpp +++ /dev/null @@ -1,943 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "mitkQtPythonService.h" -#include -#include -#include -#include - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 5208) -#endif - -#include - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -#include "PythonPath.h" -#include -#include -#include -#include -#include -#include -#include - -#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION -#include - -#include - -#ifndef WIN32 -#include -#endif - -typedef itksys::SystemTools ist; - -mitk::QtPythonService::QtPythonService() - : m_ItkWrappingAvailable( true ) - , m_OpenCVWrappingAvailable( true ) - , m_VtkWrappingAvailable( true ) - , m_ErrorOccured( false ) -{ - m_PythonManager = new ctkAbstractPythonManager(); - bool pythonInitialized = static_cast( Py_IsInitialized() ); //m_PythonManager.isPythonInitialized() ); - - // due to strange static var behaviour on windows Py_IsInitialized() returns correct value while - // m_PythonManager.isPythonInitialized() does not because it has been constructed and destructed again - if( !pythonInitialized ) - { - MITK_INFO << "Initializing python service"; - //TODO a better way to do this -#ifndef WIN32 - dlerror(); - if(dlopen(PYTHON_LIBRARY, RTLD_NOW | RTLD_GLOBAL) == nullptr ) - { - mitkThrow() << "Python runtime could not be loaded: " << dlerror(); - } -#endif - - std::string programPath = QCoreApplication::applicationDirPath().toStdString() + "/"; - QString pythonCommand; - pythonCommand.append( QString("import site, sys\n") ); - pythonCommand.append( QString("import SimpleITK as sitk\n") ); - pythonCommand.append( QString("import SimpleITK._SimpleITK as _SimpleITK\n") ); - pythonCommand.append( QString("import numpy\n") ); - - pythonCommand.append( QString("sys.path.append('')\n") ); - pythonCommand.append( QString("sys.path.append('%1')\n").arg(programPath.c_str()) ); - pythonCommand.append( QString("sys.path.append('%1')\n").arg(EXTERNAL_DIST_PACKAGES) ); - pythonCommand.append( QString("\nsite.addsitedir('%1')").arg(EXTERNAL_SITE_PACKAGES) ); - - //if( pythonInitialized ) - // m_PythonManager->setInitializationFlags(PythonQt::RedirectStdOut|PythonQt::PythonAlreadyInitialized); - //else - // m_PythonManager->setInitializationFlags(PythonQt::RedirectStdOut); - - if (pythonInitialized) - m_PythonManager->setInitializationFlags(PythonQt::PythonAlreadyInitialized); - - m_PythonManager->initialize(); - - m_PythonManager->executeString( pythonCommand, ctkAbstractPythonManager::FileInput ); - } - std::string programPath = QCoreApplication::applicationDirPath().toStdString() + "/"; - MITK_INFO << programPath; -} - -mitk::QtPythonService::~QtPythonService() -{ - MITK_DEBUG("mitk::QtPythonService") << "destructing QtPythonService"; -} - -void mitk::QtPythonService::AddRelativeSearchDirs(std::vector< std::string > dirs) -{ - std::string programPath = QCoreApplication::applicationDirPath().toStdString() + "/"; - std::string cwd = ist::GetCurrentWorkingDirectory() + "/"; - - for (auto dir : dirs) - { - m_PythonManager->executeString(QString("sys.path.append('%1')").arg((programPath + dir).c_str()), ctkAbstractPythonManager::SingleInput ); - m_PythonManager->executeString(QString("sys.path.append('%1')").arg((cwd + dir).c_str()), ctkAbstractPythonManager::SingleInput ); - } -} - -void mitk::QtPythonService::AddAbsoluteSearchDirs(std::vector< std::string > dirs) -{ - for (auto dir : dirs) - { - m_PythonManager->executeString(QString("sys.path.append('%1')").arg(dir.c_str()), ctkAbstractPythonManager::SingleInput ); - } -} - -std::string mitk::QtPythonService::Execute(const std::string &stdpythonCommand, - int commandType) -{ - QString pythonCommand = QString::fromStdString(stdpythonCommand); - QVariant result; - PyGILState_STATE gState = PyGILState_Ensure(); - 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.toStdString()); - m_ErrorOccured = PythonQt::self()->hadError(); - } - - return result.toString().toStdString(); -} - -void mitk::QtPythonService::ExecuteScript(const std::string &pythonScript) -{ - std::ifstream t(pythonScript.c_str()); - std::string str((std::istreambuf_iterator(t)), - std::istreambuf_iterator()); - t.close(); - - m_PythonManager->executeString(QString::fromStdString(str)); -} - -std::vector mitk::QtPythonService::GetVariableStack() -{ - std::vector list; - - PyObject* dict = PyImport_GetModuleDict(); - PyObject* object = PyDict_GetItemString(dict, "__main__"); - PyObject* dirMain = PyObject_Dir(object); - PyObject* tempObject = nullptr; - //PyObject* strTempObject = 0; - - if(dirMain) - { - std::string name, attrValue, attrType; - - for(int i = 0; iob_type->tp_name; - - if(tempObject && ( PyUnicode_Check(tempObject) || PyString_Check(tempObject) ) ) - attrValue = PyString_AsString(tempObject); - else - attrValue = ""; - - mitk::PythonVariable var; - var.m_Name = name; - var.m_Value = attrValue; - var.m_Type = attrType; - list.push_back(var); - } - } - - return list; -} - -std::string mitk::QtPythonService::GetVariable(const std::string& name) -{ - std::vector allVars = this->GetVariableStack(); - for(unsigned int i = 0; i< allVars.size(); i++) - { - if( allVars.at(i).m_Name == name ) - return allVars.at(i).m_Value; - } - - return ""; -} - -bool mitk::QtPythonService::DoesVariableExist(const std::string& name) -{ - bool varExists = false; - - std::vector allVars = this->GetVariableStack(); - for(unsigned int i = 0; i< allVars.size(); i++) - { - if( allVars.at(i).m_Name == name ) - { - varExists = true; - break; - } - } - - return varExists; -} - -void mitk::QtPythonService::AddPythonCommandObserver(mitk::PythonCommandObserver *observer) -{ - if(!m_Observer.contains(observer)) - m_Observer.append(observer); -} - -void mitk::QtPythonService::RemovePythonCommandObserver(mitk::PythonCommandObserver *observer) -{ - m_Observer.removeOne(observer); -} - -void mitk::QtPythonService::NotifyObserver(const std::string &command) -{ - MITK_DEBUG("mitk::QtPythonService") << "number of observer " << m_Observer.size(); - for( int i=0; i< m_Observer.size(); ++i ) - { - m_Observer.at(i)->CommandExecuted(command); - } -} - -int mitk::QtPythonService::GetNumberOfObserver() -{ - return m_Observer.size(); -} - -bool mitk::QtPythonService::CopyToPythonAsSimpleItkImage(mitk::Image::Pointer image, const std::string &stdvarName) -{ - QString varName = QString::fromStdString( stdvarName ); - QString command; - unsigned int* imgDim = image->GetDimensions(); - int npy_nd = 1; - - // access python module - PyObject *pyMod = PyImport_AddModule("__main__"); - // global dictionary - PyObject *pyDict = PyModule_GetDict(pyMod); - const mitk::Vector3D spacing = image->GetGeometry()->GetSpacing(); - const mitk::Point3D origin = image->GetGeometry()->GetOrigin(); - mitk::PixelType pixelType = image->GetPixelType(); - itk::ImageIOBase::IOPixelType ioPixelType = image->GetPixelType().GetPixelType(); - PyObject* npyArray = nullptr; - mitk::ImageReadAccessor racc(image); - void* array = const_cast(racc.GetData()); - - mitk::Vector3D xDirection; - mitk::Vector3D yDirection; - mitk::Vector3D zDirection; - const vnl_matrix_fixed &transform = - image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); - - mitk::Vector3D s = image->GetGeometry()->GetSpacing(); - - // ToDo: Check if this is a collumn or row vector from the matrix. - // right now it works but not sure for rotated geometries - mitk::FillVector3D(xDirection, transform[0][0]/s[0], transform[0][1]/s[1], transform[0][2]/s[2]); - mitk::FillVector3D(yDirection, transform[1][0]/s[0], transform[1][1]/s[1], transform[1][2]/s[2]); - mitk::FillVector3D(zDirection, transform[2][0]/s[0], transform[2][1]/s[1], transform[2][2]/s[2]); - - // save the total number of elements here (since the numpy array is one dimensional) - npy_intp* npy_dims = new npy_intp[1]; - npy_dims[0] = imgDim[0]; - - /** - * Build a string in the format [1024,1028,1] - * to describe the dimensionality. This is needed for simple itk - * to know the dimensions of the image - */ - QString dimensionString; - dimensionString.append(QString("[")); - dimensionString.append(QString::number(imgDim[0])); - for (unsigned i = 1; i < 3; ++i) - // always three because otherwise the 3d-geometry gets destroyed - // (relevant for backtransformation of simple itk image to mitk. - { - dimensionString.append(QString(",")); - dimensionString.append(QString::number(imgDim[i])); - npy_dims[0] *= imgDim[i]; - } - dimensionString.append("]"); - - - // the next line is necessary for vectorimages - npy_dims[0] *= pixelType.GetNumberOfComponents(); - - // default pixeltype: unsigned short - NPY_TYPES npy_type = NPY_USHORT; - std::string sitk_type = "sitkUInt8"; - if( ioPixelType == itk::ImageIOBase::SCALAR ) - { - if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { - npy_type = NPY_DOUBLE; - sitk_type = "sitkFloat64"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { - npy_type = NPY_FLOAT; - sitk_type = "sitkFloat32"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { - npy_type = NPY_SHORT; - sitk_type = "sitkInt16"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { - npy_type = NPY_BYTE; - sitk_type = "sitkInt8"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { - npy_type = NPY_INT; - sitk_type = "sitkInt32"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { - npy_type = NPY_LONG; - sitk_type = "sitkInt64"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { - npy_type = NPY_UBYTE; - sitk_type = "sitkUInt8"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { - npy_type = NPY_UINT; - sitk_type = "sitkUInt32"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { - npy_type = NPY_LONG; - sitk_type = "sitkUInt64"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { - npy_type = NPY_USHORT; - sitk_type = "sitkUInt16"; - } - } - else if ( ioPixelType == itk::ImageIOBase::VECTOR || - ioPixelType == itk::ImageIOBase::RGB || - ioPixelType == itk::ImageIOBase::RGBA - ) - { - if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { - npy_type = NPY_DOUBLE; - sitk_type = "sitkVectorFloat64"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { - npy_type = NPY_FLOAT; - sitk_type = "sitkVectorFloat32"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { - npy_type = NPY_SHORT; - sitk_type = "sitkVectorInt16"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { - npy_type = NPY_BYTE; - sitk_type = "sitkVectorInt8"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { - npy_type = NPY_INT; - sitk_type = "sitkVectorInt32"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { - npy_type = NPY_LONG; - sitk_type = "sitkVectorInt64"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { - npy_type = NPY_UBYTE; - sitk_type = "sitkVectorUInt8"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { - npy_type = NPY_UINT; - sitk_type = "sitkVectorUInt32"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { - npy_type = NPY_LONG; - sitk_type = "sitkVectorUInt64"; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { - npy_type = NPY_USHORT; - sitk_type = "sitkVectorUInt16"; - } - } - else { - MITK_WARN << "not a recognized pixeltype"; - return false; - } - - // creating numpy array - import_array1 (true); - npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); - - // add temp array it to the python dictionary to access it in python code - const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") - .arg(varName).toStdString().c_str(), - npyArray ); - - - // sanity check - if ( status != 0 ) - return false; - - - command.append( QString("%1 = sitk.Image(%2,sitk.%3,%4)\n").arg(varName) - .arg(dimensionString) - .arg(QString(sitk_type.c_str())).arg(QString::number(pixelType.GetNumberOfComponents())) ); - command.append( QString("%1.SetSpacing([%2,%3,%4])\n").arg(varName) - .arg(QString::number(spacing[0])) - .arg(QString::number(spacing[1])) - .arg(QString::number(spacing[2])) ); - command.append( QString("%1.SetOrigin([%2,%3,%4])\n").arg(varName) - .arg(QString::number(origin[0])) - .arg(QString::number(origin[1])) - .arg(QString::number(origin[2])) ); - command.append( QString("%1.SetDirection([%2,%3,%4,%5,%6,%7,%8,%9,%10])\n").arg(varName) - .arg(QString::number(xDirection[0])) - .arg(QString::number(xDirection[1])) - .arg(QString::number(xDirection[2])) - .arg(QString::number(yDirection[0])) - .arg(QString::number(yDirection[1])) - .arg(QString::number(yDirection[2])) - .arg(QString::number(zDirection[0])) - .arg(QString::number(zDirection[1])) - .arg(QString::number(zDirection[2])) - ); - // directly access the cpp api from the lib - command.append( QString("_SimpleITK._SetImageFromArray(%1_numpy_array,%1)\n").arg(varName) ); - command.append( QString("del %1_numpy_array").arg(varName) ); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - - - this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - return true; -} - - -mitk::PixelType DeterminePixelType(const std::string& pythonPixeltype, unsigned long nrComponents, int dimensions) -{ - typedef itk::RGBPixel< unsigned char > UCRGBPixelType; - typedef itk::RGBPixel< unsigned short > USRGBPixelType; - typedef itk::RGBPixel< float > FloatRGBPixelType; - typedef itk::RGBPixel< double > DoubleRGBPixelType; - typedef itk::Image< UCRGBPixelType > UCRGBImageType; - typedef itk::Image< USRGBPixelType > USRGBImageType; - typedef itk::Image< FloatRGBPixelType > FloatRGBImageType; - typedef itk::Image< DoubleRGBPixelType > DoubleRGBImageType; - typedef itk::RGBAPixel< unsigned char > UCRGBAPixelType; - typedef itk::RGBAPixel< unsigned short > USRGBAPixelType; - typedef itk::RGBAPixel< float > FloatRGBAPixelType; - typedef itk::RGBAPixel< double > DoubleRGBAPixelType; - typedef itk::Image< UCRGBAPixelType > UCRGBAImageType; - typedef itk::Image< USRGBAPixelType > USRGBAImageType; - typedef itk::Image< FloatRGBAPixelType > FloatRGBAImageType; - typedef itk::Image< DoubleRGBAPixelType > DoubleRGBAImageType; - - auto pixelType = mitk::MakePixelType(nrComponents); - - if (nrComponents == 1) - { - if( pythonPixeltype.compare("float64") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("float32") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("int16") == 0) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("int8") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("int32") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("int64") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("uint8") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("uint32") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("uint64") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } else if( pythonPixeltype.compare("uint16") == 0 ) { - pixelType = mitk::MakePixelType(nrComponents); - } - else - { - mitkThrow()<< "unknown scalar PixelType"; - } - } else if(nrComponents == 3 && dimensions == 2) { - if( pythonPixeltype.compare("float64") == 0 ) { - pixelType = mitk::MakePixelType(); - } else if( pythonPixeltype.compare("float32") == 0 ) { - pixelType = mitk::MakePixelType(); - } else if( pythonPixeltype.compare("uint8") == 0 ) { - pixelType = mitk::MakePixelType(); - } else if( pythonPixeltype.compare("uint16") == 0 ) { - pixelType = mitk::MakePixelType(); - } - } else if( (nrComponents == 4) && dimensions == 2 ) { - if( pythonPixeltype.compare("float64") == 0 ) { - pixelType = mitk::MakePixelType(); - } else if( pythonPixeltype.compare("float32") == 0 ) { - pixelType = mitk::MakePixelType(); - } else if( pythonPixeltype.compare("uint8") == 0 ) { - pixelType = mitk::MakePixelType(); - } else if( pythonPixeltype.compare("uint16") == 0 ) { - pixelType = mitk::MakePixelType(); - } - } - else { - if( pythonPixeltype.compare("float64") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("float32") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("int16") == 0) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("int8") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("int32") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("int64") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("uint8") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("uint16") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("uint32") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else if( pythonPixeltype.compare("uint64") == 0 ) { - pixelType = mitk::MakePixelType >(nrComponents); - } else { - mitkThrow()<< "unknown vectorial PixelType"; - } - } - - return pixelType; -} - -mitk::Image::Pointer mitk::QtPythonService::CopySimpleItkImageFromPython(const std::string &stdvarName) -{ - double*ds = nullptr; - // access python module - PyObject *pyMod = PyImport_AddModule("__main__"); - // global dictionarry - PyObject *pyDict = PyModule_GetDict(pyMod); - mitk::Image::Pointer mitkImage = mitk::Image::New(); - mitk::Vector3D spacing; - mitk::Point3D origin; - QString command; - QString varName = QString::fromStdString( stdvarName ); - - command.append( QString("%1_numpy_array = sitk.GetArrayFromImage(%1)\n").arg(varName) ); - command.append( QString("%1_spacing = numpy.asarray(%1.GetSpacing())\n").arg(varName) ); - command.append( QString("%1_origin = numpy.asarray(%1.GetOrigin())\n").arg(varName) ); - command.append( QString("%1_dtype = %1_numpy_array.dtype.name\n").arg(varName) ); - command.append( QString("%1_direction = numpy.asarray(%1.GetDirection())\n").arg(varName) ); - command.append( QString("%1_nrComponents = numpy.asarray(%1.GetNumberOfComponentsPerPixel())\n").arg(varName)); - command.append( QString("%1_dtype = %1_numpy_array.dtype.name\n").arg(varName) ); - - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - PyObject* py_dtype = PyDict_GetItemString(pyDict,QString("%1_dtype").arg(varName).toStdString().c_str() ); - std::string dtype = PyString_AsString(py_dtype); - PyArrayObject* py_data = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_numpy_array").arg(varName).toStdString().c_str() ); - PyArrayObject* py_spacing = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_spacing").arg(varName).toStdString().c_str() ); - PyArrayObject* py_origin = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_origin").arg(varName).toStdString().c_str() ); - PyArrayObject* py_direction = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_direction").arg(varName).toStdString().c_str() ); - - PyArrayObject* py_nrComponents = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_nrComponents").arg(varName).toStdString().c_str() ); - - unsigned int nr_Components = *(reinterpret_cast(PyArray_DATA(py_nrComponents))); - - unsigned int nr_dimensions = PyArray_NDIM(py_data); - if (nr_Components > 1) // for VectorImages the last dimension in the numpy array are the vector components. - { - --nr_dimensions; - } - - mitk::PixelType pixelType = DeterminePixelType(dtype, nr_Components, nr_dimensions); - - unsigned int* dimensions = new unsigned int[nr_dimensions]; - // fill backwards , nd data saves dimensions in opposite direction - for( unsigned i = 0; i < nr_dimensions; ++i ) - { - dimensions[i] = PyArray_DIMS(py_data)[nr_dimensions - 1 - i]; - } - - mitkImage->Initialize(pixelType, nr_dimensions, dimensions); - - - mitkImage->SetChannel(PyArray_DATA(py_data)); - - - ds = reinterpret_cast(PyArray_DATA(py_spacing)); - spacing[0] = ds[0]; - spacing[1] = ds[1]; - spacing[2] = ds[2]; - - mitkImage->GetGeometry()->SetSpacing(spacing); - - - ds = reinterpret_cast(PyArray_DATA(py_origin)); - origin[0] = ds[0]; - origin[1] = ds[1]; - origin[2] = ds[2]; - mitkImage->GetGeometry()->SetOrigin(origin); - - - itk::Matrix py_transform; - - ds = reinterpret_cast(PyArray_DATA(py_direction)); - py_transform[0][0] = ds[0]; - py_transform[0][1] = ds[1]; - py_transform[0][2] = ds[2]; - - py_transform[1][0] = ds[3]; - py_transform[1][1] = ds[4]; - py_transform[1][2] = ds[5]; - - py_transform[2][0] = ds[6]; - py_transform[2][1] = ds[7]; - py_transform[2][2] = ds[8]; - - mitk::AffineTransform3D::Pointer affineTransform = mitkImage->GetGeometry()->GetIndexToWorldTransform(); - - itk::Matrix transform = py_transform * affineTransform->GetMatrix(); - - affineTransform->SetMatrix(transform); - - mitkImage->GetGeometry()->SetIndexToWorldTransform(affineTransform); - - // mitk::AffineTransform3D::New(); - //mitkImage->GetGeometry()->SetIndexToWorldTransform(); - - // cleanup - command.clear(); - command.append( QString("del %1_numpy_array\n").arg(varName) ); - command.append( QString("del %1_dtype\n").arg(varName) ); - command.append( QString("del %1_spacing\n").arg(varName) ); - command.append( QString("del %1_origin\n").arg(varName) ); - command.append( QString("del %1_direction\n").arg(varName) ); - command.append( QString("del %1_nrComponents\n").arg(varName) ); - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - delete[] dimensions; - - - return mitkImage; -} - -bool mitk::QtPythonService::CopyMITKImageToPython(mitk::Image::Pointer &image, const std::string &varName) -{ - mitkThrow() << "This function is not implemented"; -} - -mitk::Image::Pointer mitk::QtPythonService::CopyMITKImageFromPython(const std::string &varName) -{ - mitkThrow() << "This function is not implemented"; -} - -std::vector mitk::QtPythonService::CopyListOfMITKImagesFromPython(const std::string &listVarName) -{ - mitkThrow() << "This function is not implemented"; -} - -bool mitk::QtPythonService::CopyToPythonAsCvImage( mitk::Image* image, const std::string& stdvarName ) -{ - QString varName = QString::fromStdString( stdvarName ); - QString command; - unsigned int* imgDim = image->GetDimensions(); - int npy_nd = 1; - - // access python module - PyObject *pyMod = PyImport_AddModule((char*)"__main__"); - // global dictionary - PyObject *pyDict = PyModule_GetDict(pyMod); - mitk::PixelType pixelType = image->GetPixelType(); - PyObject* npyArray = nullptr; - mitk::ImageReadAccessor racc(image); - void* array = (void*) racc.GetData(); - - // save the total number of elements here (since the numpy array is one dimensional) - npy_intp* npy_dims = new npy_intp[1]; - npy_dims[0] = imgDim[0]; - - /** - * Build a string in the format [1024,1028,1] - * to describe the dimensionality. This is needed for simple itk - * to know the dimensions of the image - */ - QString dimensionString; - dimensionString.append(QString("[")); - dimensionString.append(QString::number(imgDim[0])); - // ToDo: check if we need this - for (unsigned i = 1; i < 3; ++i) - // always three because otherwise the 3d-geometry gets destroyed - // (relevant for backtransformation of simple itk image to mitk. - { - dimensionString.append(QString(",")); - dimensionString.append(QString::number(imgDim[i])); - npy_dims[0] *= imgDim[i]; - } - dimensionString.append("]"); - - - // the next line is necessary for vectorimages - npy_dims[0] *= pixelType.GetNumberOfComponents(); - - // default pixeltype: unsigned short - NPY_TYPES npy_type = NPY_USHORT; - if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { - npy_type = NPY_DOUBLE; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { - npy_type = NPY_FLOAT; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { - npy_type = NPY_SHORT; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { - npy_type = NPY_BYTE; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { - npy_type = NPY_INT; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { - npy_type = NPY_LONG; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { - npy_type = NPY_UBYTE; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { - npy_type = NPY_UINT; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { - npy_type = NPY_LONG; - } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { - npy_type = NPY_USHORT; - } - else { - MITK_WARN << "not a recognized pixeltype"; - return false; - } - - // creating numpy array - import_array1 (true); - npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); - - // add temp array it to the python dictionary to access it in python code - const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") - .arg(varName).toStdString().c_str(), - npyArray ); - // sanity check - if ( status != 0 ) - return false; - - command.append( QString("import numpy as np\n")); - //command.append( QString("if '%1' in globals():\n").arg(varName)); - //command.append( QString(" del %1\n").arg(varName)); - command.append( QString("%1_array_tmp=%1_numpy_array.copy()\n").arg(varName)); - command.append( QString("%1_array_tmp=%1_array_tmp.reshape(%2,%3,%4)\n").arg( varName, - QString::number(imgDim[1]), - QString::number(imgDim[0]), - QString::number(pixelType.GetNumberOfComponents()))); - - command.append( QString("%1 = %1_array_tmp[:,...,::-1]\n").arg(varName)); - command.append( QString("del %1_numpy_array\n").arg(varName) ); - command.append( QString("del %1_array_tmp").arg(varName) ); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - - this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - return true; -} - - -mitk::Image::Pointer mitk::QtPythonService::CopyCvImageFromPython( const std::string& stdvarName ) -{ - - // access python module - PyObject *pyMod = PyImport_AddModule((char*)"__main__"); - // global dictionarry - PyObject *pyDict = PyModule_GetDict(pyMod); - mitk::Image::Pointer mitkImage = mitk::Image::New(); - QString command; - QString varName = QString::fromStdString( stdvarName ); - - command.append( QString("import numpy as np\n")); - command.append( QString("%1_dtype=%1.dtype.name\n").arg(varName) ); - command.append( QString("%1_shape=np.asarray(%1.shape)\n").arg(varName) ); - command.append( QString("%1_np_array=%1[:,...,::-1]\n").arg(varName)); - command.append( QString("%1_np_array=np.reshape(%1_np_array,%1.shape[0] * %1.shape[1] * %1.shape[2])").arg(varName) ); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - PyObject* py_dtype = PyDict_GetItemString(pyDict,QString("%1_dtype").arg(varName).toStdString().c_str() ); - std::string dtype = PyString_AsString(py_dtype); - PyArrayObject* py_data = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_np_array").arg(varName).toStdString().c_str() ); - PyArrayObject* shape = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_shape").arg(varName).toStdString().c_str() ); - - size_t* d = reinterpret_cast(PyArray_DATA(shape)); - - unsigned int dimensions[3]; - dimensions[0] = d[1]; - dimensions[1] = d[0]; - dimensions[2] = d[2]; - - unsigned int nr_dimensions = 2; - - // get number of components - unsigned int nr_Components = (unsigned int) d[2]; - - auto pixelType = DeterminePixelType(dtype, nr_Components, nr_dimensions); - - mitkImage->Initialize(pixelType, nr_dimensions, dimensions); - //mitkImage->SetChannel(py_data->data); - - { - mitk::ImageWriteAccessor ra(mitkImage); - char* data = (char*)(ra.GetData()); - memcpy(data, PyArray_DATA(py_data), dimensions[0] * dimensions[1] * pixelType.GetSize()); - } - - command.clear(); - - command.append( QString("del %1_shape\n").arg(varName) ); - command.append( QString("del %1_dtype\n").arg(varName) ); - command.append( QString("del %1_np_array").arg(varName)); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - return mitkImage; -} - -ctkAbstractPythonManager *mitk::QtPythonService::GetPythonManager() -{ - return m_PythonManager; -} - -mitk::Surface::Pointer mitk::QtPythonService::CopyVtkPolyDataFromPython( const std::string& stdvarName ) -{ - // access python module - PyObject *pyMod = PyImport_AddModule((char*)"__main__"); - // global dictionarry - PyObject *pyDict = PyModule_GetDict(pyMod); - // python memory address - PyObject *pyAddr = nullptr; - // cpp address - size_t addr = 0; - mitk::Surface::Pointer surface = mitk::Surface::New(); - QString command; - QString varName = QString::fromStdString( stdvarName ); - - command.append( QString("%1_addr_str = %1.GetAddressAsString(\"vtkPolyData\")\n").arg(varName) ); - // remove 0x from the address - command.append( QString("%1_addr = int(%1_addr_str[5:],16)").arg(varName) ); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - // get address of the object - pyAddr = PyDict_GetItemString(pyDict,QString("%1_addr").arg(varName).toStdString().c_str()); - - // convert to long - addr = PyInt_AsLong(pyAddr); - - MITK_DEBUG << "Python object address: " << addr; - - // get the object - vtkPolyData* poly = (vtkPolyData*)((void*)addr); - surface->SetVtkPolyData(poly); - - // delete helper variables from python stack - command = ""; - command.append( QString("del %1_addr_str\n").arg(varName) ); - command.append( QString("del %1_addr").arg(varName) ); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - return surface; -} - -bool mitk::QtPythonService::CopyToPythonAsVtkPolyData( mitk::Surface* surface, const std::string& stdvarName ) -{ - QString varName = QString::fromStdString( stdvarName ); - std::ostringstream oss; - std::string addr = ""; - QString command; - QString address; - - oss << (void*) ( surface->GetVtkPolyData() ); - - // get the address - addr = oss.str(); - - // remove "0x" - address = QString::fromStdString(addr.substr(2)); - - command.append( QString("%1 = vtk.vtkPolyData(\"%2\")\n").arg(varName).arg(address) ); - - MITK_DEBUG("QtPythonService") << "Issuing python command " << command.toStdString(); - this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); - - return true; -} - -bool mitk::QtPythonService::IsSimpleItkPythonWrappingAvailable() -{ - this->Execute( "import SimpleITK as sitk\n", IPythonService::SINGLE_LINE_COMMAND ); - // directly access cpp lib - this->Execute( "import SimpleITK._SimpleITK as _SimpleITK\n", IPythonService::SINGLE_LINE_COMMAND ); - m_ItkWrappingAvailable = !this->PythonErrorOccured(); - - // check for numpy - this->Execute( "import numpy\n", IPythonService::SINGLE_LINE_COMMAND ); - - if ( this->PythonErrorOccured() ) - MITK_ERROR << "Numpy not found."; - - m_ItkWrappingAvailable = !this->PythonErrorOccured(); - - return m_ItkWrappingAvailable; -} - -bool mitk::QtPythonService::IsOpenCvPythonWrappingAvailable() -{ - this->Execute( "import cv2\n", IPythonService::SINGLE_LINE_COMMAND ); - m_OpenCVWrappingAvailable = !this->PythonErrorOccured(); - - return m_OpenCVWrappingAvailable; -} - -bool mitk::QtPythonService::IsVtkPythonWrappingAvailable() -{ - this->Execute( "import vtk", IPythonService::SINGLE_LINE_COMMAND ); - //this->Execute( "print \"Using VTK version \" + vtk.vtkVersion.GetVTKVersion()\n", IPythonService::SINGLE_LINE_COMMAND ); - m_VtkWrappingAvailable = !this->PythonErrorOccured(); - - return m_VtkWrappingAvailable; -} - -bool mitk::QtPythonService::PythonErrorOccured() const -{ - return m_ErrorOccured; -} diff --git a/Modules/QtPythonService/mitkQtPythonService.h b/Modules/QtPythonService/mitkQtPythonService.h deleted file mode 100644 index 09feb38cd2..0000000000 --- a/Modules/QtPythonService/mitkQtPythonService.h +++ /dev/null @@ -1,122 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef mitkQtPythonService_h -#define mitkQtPythonService_h - -#include -#include "mitkIPythonService.h" -#include -#include "mitkSurface.h" - -namespace mitk -{ - /// - /// implementation of the IPythonService using ctkabstractpythonmanager - /// \see IPythonService - class QtPythonService: public itk::LightObject, public mitk::IPythonService - { - public: - /// instantiate python manager here - QtPythonService(); - /// - /// empty implementation... - ~QtPythonService() override; - /// - /// \see IPythonService::Execute() - std::string Execute( const std::string& pythonCommand, int commandType = SINGLE_LINE_COMMAND) override; - /// - /// \see IPythonService::ExecuteScript() - void ExecuteScript(const std::string &pathToPythonScript) override; - /// - /// \see IPythonService::PythonErrorOccured() - bool PythonErrorOccured() const override; - /// - /// \see IPythonService::GetVariableStack() - std::vector GetVariableStack() override; - /// - /// \see IPythonService::DoesVariableExist() - bool DoesVariableExist(const std::string& name) override; - /// - /// \see IPythonService::GetVariable() - std::string GetVariable(const std::string& name) override; - /// - /// \see IPythonService::AddPythonCommandObserver() - void AddPythonCommandObserver( PythonCommandObserver* observer ) override; - /// - /// \see IPythonService::RemovePythonCommandObserver() - void RemovePythonCommandObserver( PythonCommandObserver* observer ) override; - /// - /// \see IPythonService::NotifyObserver() - void NotifyObserver( const std::string& command ) override; - /// - /// \see IPythonService::GetNumberOfObserver() - int GetNumberOfObserver() override; - /// - /// \see IPythonService::IsItkPythonWrappingAvailable() - bool IsSimpleItkPythonWrappingAvailable() override; - /// - /// \see IPythonService::CopyToPythonAsItkImage() - bool CopyToPythonAsSimpleItkImage( mitk::Image::Pointer image, const std::string& varName ) override; - /// - /// \see IPythonService::CopyItkImageFromPython() - mitk::Image::Pointer CopySimpleItkImageFromPython( const std::string& varName ) override; - /// - /// \see IPythonService::CopyMITKImageToPython() - /// \throws MITK exception since this function is not implemented (only implementation in mitkPythonService) - bool CopyMITKImageToPython(mitk::Image::Pointer &image, const std::string &varName) override; - /// - /// \see IPythonService::CopyMITKImageFromPython() - /// \throws MITK exception since this function is not implemented (only implementation in mitkPythonService) - mitk::Image::Pointer CopyMITKImageFromPython(const std::string &varName) override; - /// - /// \see IPythonService::CopyListOfMITKImagesFromPython() - /// \throws MITK exception since this function is not implemented (only implementation in mitkPythonService) - std::vector CopyListOfMITKImagesFromPython(const std::string &listVarName) override; - /// - /// \see IPythonService::IsOpenCvPythonWrappingAvailable() - bool IsOpenCvPythonWrappingAvailable() override; - /// - /// \see IPythonService::CopyToPythonAsCvImage() - bool CopyToPythonAsCvImage( mitk::Image* image, const std::string& varName ) override; - /// - /// \see IPythonService::CopyCvImageFromPython() - mitk::Image::Pointer CopyCvImageFromPython( const std::string& varName ) override; - /// - /// \see IPythonService::IsVtkPythonWrappingAvailable() - bool IsVtkPythonWrappingAvailable() override; - /// - /// \see IPythonService::CopyToPythonAsVtkPolyData() - bool CopyToPythonAsVtkPolyData( mitk::Surface* surface, const std::string& varName ) override; - /// - /// \see IPythonService::CopyVtkPolyDataFromPython() - mitk::Surface::Pointer CopyVtkPolyDataFromPython( const std::string& varName ) override; - /// - /// \return the ctk abstract python manager instance - ctkAbstractPythonManager* GetPythonManager() /*override*/; - - void AddRelativeSearchDirs(std::vector< std::string > dirs) override; - - void AddAbsoluteSearchDirs(std::vector< std::string > dirs) override; - - - protected: - - private: - QList m_Observer; - ctkAbstractPythonManager* m_PythonManager; - bool m_ItkWrappingAvailable; - bool m_OpenCVWrappingAvailable; - bool m_VtkWrappingAvailable; - bool m_ErrorOccured; - }; -} -#endif diff --git a/Modules/QtPythonService/test/CMakeLists.txt b/Modules/QtPythonService/test/CMakeLists.txt deleted file mode 100644 index 153cd81e2e..0000000000 --- a/Modules/QtPythonService/test/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -MITK_CREATE_MODULE_TESTS() diff --git a/Modules/QtPythonService/test/files.cmake b/Modules/QtPythonService/test/files.cmake deleted file mode 100644 index 36a44ec352..0000000000 --- a/Modules/QtPythonService/test/files.cmake +++ /dev/null @@ -1,3 +0,0 @@ -set(MODULE_TESTS - mitkQtPythonTest.cpp -) \ No newline at end of file diff --git a/Modules/QtPythonService/test/mitkQtPythonTest.cpp b/Modules/QtPythonService/test/mitkQtPythonTest.cpp deleted file mode 100644 index 7d54ae267e..0000000000 --- a/Modules/QtPythonService/test/mitkQtPythonTest.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include -#include -#include -#include -#include -#include -#include - -class mitkQtPythonTestSuite : public mitk::TestFixture -{ - CPPUNIT_TEST_SUITE(mitkQtPythonTestSuite); - MITK_TEST(TestPython); - CPPUNIT_TEST_SUITE_END(); - -public: - - void TestPython() - { - std::string result = ""; - us::ModuleContext *context = us::GetModuleContext(); - std::string filter = "(Name=QtPythonService)"; - auto m_PythonServiceRefs = context->GetServiceReferences(/*filter*/); - - if (!m_PythonServiceRefs.empty()) - { - mitk::IPythonService *m_PythonService = dynamic_cast(context->GetService(m_PythonServiceRefs.front())); - mitk::IPythonService::ForceLoadModule(); - - result = m_PythonService->Execute("5+5", mitk::IPythonService::EVAL_COMMAND); - } - - MITK_TEST_CONDITION(result == "10", "Testing if running python code 5+5 results in 10"); - } -}; - -MITK_TEST_SUITE_REGISTRATION(mitkQtPython) diff --git a/Plugins/PluginList.cmake b/Plugins/PluginList.cmake index 70f68ac508..1cd85f9248 100644 --- a/Plugins/PluginList.cmake +++ b/Plugins/PluginList.cmake @@ -1,98 +1,97 @@ # Plug-ins must be ordered according to their dependencies set(MITK_PLUGINS org.blueberry.core.runtime:ON org.blueberry.core.expressions:OFF org.blueberry.core.commands:OFF org.blueberry.core.jobs:OFF org.blueberry.ui.qt:OFF org.blueberry.ui.qt.help:ON org.blueberry.ui.qt.log:ON org.blueberry.ui.qt.objectinspector:OFF org.mitk.core.services:ON org.mitk.gui.common:ON org.mitk.planarfigure:ON org.mitk.core.ext:OFF org.mitk.core.jobs:OFF org.mitk.gui.qt.application:ON org.mitk.gui.qt.ext:OFF org.mitk.gui.qt.extapplication:OFF org.mitk.gui.qt.mitkworkbench.intro:OFF org.mitk.gui.qt.common:ON org.mitk.gui.qt.stdmultiwidgeteditor:ON org.mitk.gui.qt.mxnmultiwidgeteditor:OFF org.mitk.gui.qt.common.legacy:OFF org.mitk.gui.qt.cmdlinemodules:OFF org.mitk.gui.qt.chartExample:OFF org.mitk.gui.qt.datamanager:ON org.mitk.gui.qt.datamanagerlight:OFF org.mitk.gui.qt.datastorageviewertest:OFF org.mitk.gui.qt.properties:ON org.mitk.gui.qt.basicimageprocessing:OFF org.mitk.gui.qt.dicombrowser:OFF org.mitk.gui.qt.dicominspector:OFF org.mitk.gui.qt.dosevisualization:OFF org.mitk.gui.qt.geometrytools:OFF org.mitk.gui.qt.igtexamples:OFF org.mitk.gui.qt.igttracking:OFF org.mitk.gui.qt.lasercontrol:OFF org.mitk.gui.qt.openigtlink:OFF org.mitk.gui.qt.imagecropper:OFF org.mitk.gui.qt.imagenavigator:ON org.mitk.gui.qt.viewnavigator:OFF org.mitk.gui.qt.materialeditor:OFF org.mitk.gui.qt.measurementtoolbox:OFF org.mitk.gui.qt.moviemaker:OFF org.mitk.gui.qt.pointsetinteraction:OFF org.mitk.gui.qt.pointsetinteractionmultispectrum:OFF - org.mitk.gui.qt.python:OFF org.mitk.gui.qt.remeshing:OFF org.mitk.gui.qt.segmentation:OFF org.mitk.gui.qt.deformableclippingplane:OFF org.mitk.gui.qt.aicpregistration:OFF org.mitk.gui.qt.renderwindowmanager:OFF org.mitk.gui.qt.semanticrelations:OFF org.mitk.gui.qt.toftutorial:OFF org.mitk.gui.qt.tofutil:OFF org.mitk.gui.qt.tubegraph:OFF org.mitk.gui.qt.ugvisualization:OFF org.mitk.gui.qt.photoacoustics.pausviewer:OFF org.mitk.gui.qt.photoacoustics.pausmotioncompensation:OFF org.mitk.gui.qt.photoacoustics.imageprocessing:OFF org.mitk.gui.qt.photoacoustics.simulation:OFF org.mitk.gui.qt.photoacoustics.spectralunmixing:OFF org.mitk.gui.qt.ultrasound:OFF org.mitk.gui.qt.volumevisualization:OFF org.mitk.gui.qt.eventrecorder:OFF org.mitk.gui.qt.xnat:OFF org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation:OFF org.mitk.gui.qt.spectrocamrecorder:OFF org.mitk.gui.qt.classificationsegmentation:OFF org.mitk.gui.qt.overlaymanager:OFF org.mitk.gui.qt.igt.app.hummelprotocolmeasurements:OFF org.mitk.gui.qt.multilabelsegmentation:OFF org.mitk.matchpoint.core.helper:OFF org.mitk.gui.qt.matchpoint.algorithm.browser:OFF org.mitk.gui.qt.matchpoint.algorithm.control:OFF org.mitk.gui.qt.matchpoint.mapper:OFF org.mitk.gui.qt.matchpoint.framereg:OFF org.mitk.gui.qt.matchpoint.visualizer:OFF org.mitk.gui.qt.matchpoint.evaluator:OFF org.mitk.gui.qt.matchpoint.manipulator:OFF org.mitk.gui.qt.preprocessing.resampling:OFF org.mitk.gui.qt.radiomics:OFF org.mitk.gui.qt.cest:OFF org.mitk.gui.qt.fit.demo:OFF org.mitk.gui.qt.fit.inspector:OFF org.mitk.gui.qt.fit.genericfitting:OFF org.mitk.gui.qt.pharmacokinetics.mri:OFF org.mitk.gui.qt.pharmacokinetics.pet:OFF org.mitk.gui.qt.pharmacokinetics.simulation:OFF org.mitk.gui.qt.pharmacokinetics.curvedescriptor:OFF org.mitk.gui.qt.pharmacokinetics.concentration.mri:OFF org.mitk.gui.qt.flowapplication:OFF org.mitk.gui.qt.flow.segmentation:OFF org.mitk.gui.qt.deeplearningsegmentation:ON ) diff --git a/Plugins/org.mitk.gui.qt.python/CMakeLists.txt b/Plugins/org.mitk.gui.qt.python/CMakeLists.txt deleted file mode 100644 index fb55d48c06..0000000000 --- a/Plugins/org.mitk.gui.qt.python/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -if(MITK_USE_Python3) - -project(org_mitk_gui_qt_python) - -mitk_create_plugin( - EXPORT_DIRECTIVE org_mitk_gui_qt_python_EXPORT - EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS MitkQtWidgetsExt MitkPython MitkQtPython) - -endif() diff --git a/Plugins/org.mitk.gui.qt.python/documentation/UserManual/MitkPythonPluginView.png b/Plugins/org.mitk.gui.qt.python/documentation/UserManual/MitkPythonPluginView.png deleted file mode 100644 index 44c8d928b0..0000000000 Binary files a/Plugins/org.mitk.gui.qt.python/documentation/UserManual/MitkPythonPluginView.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.python/documentation/UserManual/QmitkPython.dox b/Plugins/org.mitk.gui.qt.python/documentation/UserManual/QmitkPython.dox deleted file mode 100644 index 73d1ecb6af..0000000000 --- a/Plugins/org.mitk.gui.qt.python/documentation/UserManual/QmitkPython.dox +++ /dev/null @@ -1,33 +0,0 @@ -/** -\page org_mitk_views_python The Python Plugin - -Available sections: - - \ref org_mitk_views_pythonOverview - - \ref org_mitk_views_pythonUsage - - \ref org_mitk_views_pythonConsole - - \ref org_mitk_views_pythonSnippets - -\section org_mitk_views_pythonOverview Overview -The Python view provides the graphical front end to run Python code through the mitkPython module. Furthermore the SimpleITK/VTK/OpenCV Python wrapping can be used. -Images and surfaces in the DataManager can be transferred via a drag & drop mechanism into the MITK Python Console. - -\section org_mitk_views_pythonUsage Transfer data -Images and surfaces can be tranferred from the data manger into the python console. To transfer an image or -surface simply drag it from the data manager into the Variable Stack view, as shown in Figure. -A new entry will appear in the Variable Stack, as soon as the data is transferred. As soon as the -entry is available the object can be accessed and modified in the python console. Three dimensional -images will be copied in-memory to python via numpy and a SimpleITK image object is created with the -same properties. When a two dimensional image is transferred the user can choose to transfer it as an OpenCV -image object. Surfaces are fully memory mapped as a vtkPolyData object. To transfer an image or surface -from the python runtime to the data manager just double click on the corresponding entry in the Variable Stack View. - -\imageMacro{MitkPythonPluginView.png,"Screenshot of the MITK Python Plugin",6} - -\section org_mitk_views_pythonConsole Console -The Python console can be used for interactive programming. All items in the data storage can be accessed -in the python console. The console can also be used to load python scripts and run them. - -\section org_mitk_views_pythonSnippets Snippets -The python plugin contains some code snippets of SimpleITK/VTK/OpenCV that can be run in the python console. -Snippets can be modified and saved by the user. -*/ diff --git a/Plugins/org.mitk.gui.qt.python/files.cmake b/Plugins/org.mitk.gui.qt.python/files.cmake deleted file mode 100644 index d2d693e932..0000000000 --- a/Plugins/org.mitk.gui.qt.python/files.cmake +++ /dev/null @@ -1,31 +0,0 @@ -set(SRC_CPP_FILES -) - -set(INTERNAL_CPP_FILES - mitkPluginActivator.cpp - QmitkPythonView.cpp -) - -set(MOC_H_FILES - src/internal/QmitkPythonView.h - src/internal/mitkPluginActivator.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/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.python/manifest_headers.cmake deleted file mode 100644 index 3c21bc8d85..0000000000 --- a/Plugins/org.mitk.gui.qt.python/manifest_headers.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(Plugin-Name "MITK Python") -set(Plugin-Version "1.0.0") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.mitk.gui.qt.common) diff --git a/Plugins/org.mitk.gui.qt.python/plugin.xml b/Plugins/org.mitk.gui.qt.python/plugin.xml deleted file mode 100644 index 9629c07384..0000000000 --- a/Plugins/org.mitk.gui.qt.python/plugin.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - Allow the acces of python from MITK - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.python/resources/Python.png b/Plugins/org.mitk.gui.qt.python/resources/Python.png deleted file mode 100644 index 813e4d1b5c..0000000000 Binary files a/Plugins/org.mitk.gui.qt.python/resources/Python.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.python/resources/Python.qrc b/Plugins/org.mitk.gui.qt.python/resources/Python.qrc deleted file mode 100644 index 5b36d01dbf..0000000000 --- a/Plugins/org.mitk.gui.qt.python/resources/Python.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - Python.png - - diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp b/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp deleted file mode 100644 index 2f00d0aa01..0000000000 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "QmitkPythonView.h" -#include -#include "mitkPluginActivator.h" -#include -#include -#include - -#include -#include -#include - -const std::string QmitkPythonView::VIEW_ID = "org.mitk.views.python"; - -struct QmitkPythonViewData -{ - // widget - QmitkPythonVariableStackTableView* m_PythonVariableStackTableView; - QmitkPythonSnippets* m_PythonSnippets; - - QmitkCtkPythonShell* m_PythonShell; - QmitkPythonTextEditor* m_TextEditor; -}; - -QmitkPythonView::QmitkPythonView() - : d( new QmitkPythonViewData ) -{ - d->m_PythonVariableStackTableView = nullptr; - d->m_PythonShell = nullptr; -} - -QmitkPythonView::~QmitkPythonView() -{ - delete d; -} - -void QmitkPythonView::CreateQtPartControl(QWidget* parent) -{ - d->m_PythonVariableStackTableView = new QmitkPythonVariableStackTableView; - d->m_PythonVariableStackTableView->SetDataStorage(this->GetDataStorage()); - //d->m_PythonVariableStackTableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive); - - QString snippetsFilePath = mitk::PluginActivator::m_XmlFilePath; - MITK_DEBUG("QmitkPythonView") << "got snippetsFilePath " << snippetsFilePath.toStdString(); - - d->m_PythonSnippets = new QmitkPythonSnippets(snippetsFilePath); - - MITK_DEBUG("QmitkPythonView") << "initializing varStackSnippetsTab"; - QTabWidget* varStackSnippetsTab = new QTabWidget; - varStackSnippetsTab->addTab( d->m_PythonVariableStackTableView, "Variable Stack" ); - varStackSnippetsTab->addTab( d->m_PythonSnippets, "Snippets" ); - varStackSnippetsTab->setTabPosition( QTabWidget::South ); - - MITK_DEBUG("QmitkPythonView") << "initializing m_PythonShell"; - d->m_PythonShell = new QmitkCtkPythonShell; - - MITK_DEBUG("QmitkPythonView") << "initializing m_TextEditor"; - d->m_TextEditor = new QmitkPythonTextEditor; - - MITK_DEBUG("QmitkPythonView") << "initializing tabWidgetConsoleEditor"; - QTabWidget* tabWidgetConsoleEditor = new QTabWidget; - tabWidgetConsoleEditor->addTab( d->m_PythonShell, "Console" ); - tabWidgetConsoleEditor->addTab( d->m_TextEditor, "Text Editor" ); - tabWidgetConsoleEditor->setTabPosition( QTabWidget::South ); - - QList sizes; - sizes << 1 << 3; - QSplitter* splitter = new QSplitter; - splitter->addWidget(varStackSnippetsTab); - splitter->addWidget(tabWidgetConsoleEditor); - splitter->setStretchFactor ( 0, 1 ); - splitter->setStretchFactor ( 1, 3 ); - - QGridLayout* layout = new QGridLayout; - layout->addWidget( splitter, 0, 0 ); - parent->setLayout(layout); - - MITK_DEBUG("QmitkPythonView") << "creating connections for m_PythonSnippets"; - connect( d->m_PythonSnippets, SIGNAL(PasteCommandRequested(QString)), d->m_PythonShell, SLOT(Paste(QString)) ); - connect( d->m_PythonSnippets, SIGNAL(PasteCommandRequested(QString)), d->m_TextEditor, SLOT(Paste(QString)) ); -} - -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 deleted file mode 100644 index 577e1f275e..0000000000 --- a/Plugins/org.mitk.gui.qt.python/src/internal/QmitkPythonView.h +++ /dev/null @@ -1,60 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#ifndef 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. - /// - ~QmitkPythonView() override; - -protected: - - /// - /// \brief Create the view here. - /// - void CreateQtPartControl(QWidget* parent) override; - - /// - /// focus on load image - /// - void SetFocus() override; - -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 deleted file mode 100644 index 0249049b5b..0000000000 --- a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -#include "mitkPluginActivator.h" -#include "QmitkPythonView.h" - -namespace mitk -{ - QString PluginActivator::m_XmlFilePath; - - void PluginActivator::start(ctkPluginContext* context) - { - m_XmlFilePath = context->getDataFile("PythonSnippets.xml").absoluteFilePath(); - - BERRY_REGISTER_EXTENSION_CLASS(QmitkPythonView, context) - } - - void PluginActivator::stop(ctkPluginContext* context) - { - Q_UNUSED(context) - } -} diff --git a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h deleted file mode 100644 index 5f499ce5c3..0000000000 --- a/Plugins/org.mitk.gui.qt.python/src/internal/mitkPluginActivator.h +++ /dev/null @@ -1,35 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#ifndef MITKPLUGINACTIVATOR_H -#define MITKPLUGINACTIVATOR_H - -#include - -namespace mitk { - -class PluginActivator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_python") - Q_INTERFACES(ctkPluginActivator) - -public: - void start(ctkPluginContext* context) override; - void stop(ctkPluginContext* context) override; - - static QString m_XmlFilePath; -}; // PluginActivator - -} - -#endif // MITKPLUGINACTIVATOR_H