ctkAbstractPythonManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QDir>
  16. #include <QDebug>
  17. // CTK includes
  18. #include "ctkAbstractPythonManager.h"
  19. #include "ctkScriptingPythonCoreConfigure.h"
  20. // PythonQT includes
  21. #include <PythonQt.h>
  22. #include <PythonQt_QtBindings.h>
  23. // STD includes
  24. #include <csignal>
  25. #ifdef __GNUC__
  26. // Disable warnings related to signal() function
  27. // See http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
  28. // Note: Ideally the incriminated functions and macros should be fixed upstream ...
  29. #pragma GCC diagnostic ignored "-Wold-style-cast"
  30. #endif
  31. //-----------------------------------------------------------------------------
  32. class ctkAbstractPythonManagerPrivate
  33. {
  34. Q_DECLARE_PUBLIC(ctkAbstractPythonManager);
  35. protected:
  36. ctkAbstractPythonManager* q_ptr;
  37. public:
  38. ctkAbstractPythonManagerPrivate(ctkAbstractPythonManager& object);
  39. virtual ~ctkAbstractPythonManagerPrivate();
  40. void (*InitFunction)();
  41. int PythonQtInitializationFlags;
  42. };
  43. //-----------------------------------------------------------------------------
  44. // ctkAbstractPythonManagerPrivate methods
  45. //-----------------------------------------------------------------------------
  46. ctkAbstractPythonManagerPrivate::ctkAbstractPythonManagerPrivate(ctkAbstractPythonManager &object) :
  47. q_ptr(&object)
  48. {
  49. this->InitFunction = 0;
  50. this->PythonQtInitializationFlags = PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut;
  51. }
  52. //-----------------------------------------------------------------------------
  53. ctkAbstractPythonManagerPrivate::~ctkAbstractPythonManagerPrivate()
  54. {
  55. }
  56. //-----------------------------------------------------------------------------
  57. // ctkAbstractPythonManager methods
  58. //-----------------------------------------------------------------------------
  59. ctkAbstractPythonManager::ctkAbstractPythonManager(QObject* _parent) : Superclass(_parent),
  60. d_ptr(new ctkAbstractPythonManagerPrivate(*this))
  61. {
  62. }
  63. //-----------------------------------------------------------------------------
  64. ctkAbstractPythonManager::~ctkAbstractPythonManager()
  65. {
  66. if (Py_IsInitialized())
  67. {
  68. Py_Finalize();
  69. }
  70. PythonQt::cleanup();
  71. }
  72. //-----------------------------------------------------------------------------
  73. void ctkAbstractPythonManager::setInitializationFlags(int flags)
  74. {
  75. Q_D(ctkAbstractPythonManager);
  76. if (PythonQt::self())
  77. {
  78. return;
  79. }
  80. d->PythonQtInitializationFlags = flags;
  81. }
  82. //-----------------------------------------------------------------------------
  83. int ctkAbstractPythonManager::initializationFlags()const
  84. {
  85. Q_D(const ctkAbstractPythonManager);
  86. return d->PythonQtInitializationFlags;
  87. }
  88. //-----------------------------------------------------------------------------
  89. bool ctkAbstractPythonManager::initialize()
  90. {
  91. Q_D(ctkAbstractPythonManager);
  92. if (!PythonQt::self())
  93. {
  94. this->initPythonQt(d->PythonQtInitializationFlags);
  95. }
  96. return this->isPythonInitialized();
  97. }
  98. //-----------------------------------------------------------------------------
  99. PythonQtObjectPtr ctkAbstractPythonManager::mainContext()
  100. {
  101. bool initalized = this->initialize();
  102. if (initalized)
  103. {
  104. return PythonQt::self()->getMainModule();
  105. }
  106. return PythonQtObjectPtr();
  107. }
  108. //-----------------------------------------------------------------------------
  109. void ctkAbstractPythonManager::initPythonQt(int flags)
  110. {
  111. Q_D(ctkAbstractPythonManager);
  112. PythonQt::init(flags);
  113. // Python maps SIGINT (control-c) to its own handler. We will remap it
  114. // to the default so that control-c works.
  115. #ifdef SIGINT
  116. signal(SIGINT, SIG_DFL);
  117. #endif
  118. PythonQtObjectPtr _mainContext = PythonQt::self()->getMainModule();
  119. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(QString)),
  120. SLOT(printStdout(QString)));
  121. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(QString)),
  122. SLOT(printStderr(QString)));
  123. PythonQt_init_QtBindings();
  124. QStringList initCode;
  125. // Update 'sys.path'
  126. initCode << "import sys";
  127. foreach (const QString& path, this->pythonPaths())
  128. {
  129. initCode << QString("sys.path.append('%1')").arg(QDir::fromNativeSeparators(path));
  130. }
  131. _mainContext.evalScript(initCode.join("\n"));
  132. this->preInitialization();
  133. if (d->InitFunction)
  134. {
  135. (*d->InitFunction)();
  136. }
  137. emit this->pythonPreInitialized();
  138. this->executeInitializationScripts();
  139. emit this->pythonInitialized();
  140. }
  141. //-----------------------------------------------------------------------------
  142. bool ctkAbstractPythonManager::isPythonInitialized()const
  143. {
  144. return PythonQt::self() != 0;
  145. }
  146. //-----------------------------------------------------------------------------
  147. bool ctkAbstractPythonManager::pythonErrorOccured()const
  148. {
  149. return PythonQt::self()->errorOccured();
  150. }
  151. //-----------------------------------------------------------------------------
  152. QStringList ctkAbstractPythonManager::pythonPaths()
  153. {
  154. return QStringList();
  155. }
  156. //-----------------------------------------------------------------------------
  157. void ctkAbstractPythonManager::preInitialization()
  158. {
  159. }
  160. //-----------------------------------------------------------------------------
  161. void ctkAbstractPythonManager::executeInitializationScripts()
  162. {
  163. }
  164. //-----------------------------------------------------------------------------
  165. void ctkAbstractPythonManager::registerPythonQtDecorator(QObject* decorator)
  166. {
  167. PythonQt::self()->addDecorators(decorator);
  168. }
  169. //-----------------------------------------------------------------------------
  170. void ctkAbstractPythonManager::registerClassForPythonQt(const QMetaObject* metaobject)
  171. {
  172. PythonQt::self()->registerClass(metaobject);
  173. }
  174. //-----------------------------------------------------------------------------
  175. void ctkAbstractPythonManager::registerCPPClassForPythonQt(const char* name)
  176. {
  177. PythonQt::self()->registerCPPClass(name);
  178. }
  179. //-----------------------------------------------------------------------------
  180. QVariant ctkAbstractPythonManager::executeString(const QString& code,
  181. ctkAbstractPythonManager::ExecuteStringMode mode)
  182. {
  183. int start = -1;
  184. switch(mode)
  185. {
  186. case ctkAbstractPythonManager::FileInput: start = Py_file_input; break;
  187. case ctkAbstractPythonManager::SingleInput: start = Py_single_input; break;
  188. case ctkAbstractPythonManager::EvalInput:
  189. default: start = Py_eval_input; break;
  190. }
  191. QVariant ret;
  192. PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  193. if (main)
  194. {
  195. ret = main.evalScript(code, start);
  196. }
  197. return ret;
  198. }
  199. //-----------------------------------------------------------------------------
  200. void ctkAbstractPythonManager::executeFile(const QString& filename)
  201. {
  202. PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  203. if (main)
  204. {
  205. QString path = QFileInfo(filename).absolutePath();
  206. this->executeString(QString("import sys\nsys.path.insert(0, '%1')").arg(path));
  207. this->executeString(QString("execfile('%1')").arg(filename));
  208. this->executeString(QString("import sys\nif sys.path[0] == '%1': sys.path.pop(0)").arg(path));
  209. }
  210. }
  211. //-----------------------------------------------------------------------------
  212. void ctkAbstractPythonManager::setInitializationFunction(void (*initFunction)())
  213. {
  214. Q_D(ctkAbstractPythonManager);
  215. d->InitFunction = initFunction;
  216. }
  217. //----------------------------------------------------------------------------
  218. QStringList ctkAbstractPythonManager::pythonAttributes(const QString& pythonVariableName,
  219. const QString& module,
  220. bool appendParenthesis) const
  221. {
  222. Q_ASSERT(PyThreadState_GET()->interp);
  223. PyObject* dict = PyImport_GetModuleDict();
  224. // Split module by '.' and retrieve the object associated if the last module
  225. PyObject* object = 0;
  226. PyObject* prevObject = 0;
  227. QStringList moduleList = module.split(".", QString::SkipEmptyParts);
  228. foreach(const QString& module, moduleList)
  229. {
  230. object = PyDict_GetItemString(dict, module.toAscii().data());
  231. if (prevObject) { Py_DECREF(prevObject); }
  232. if (!object)
  233. {
  234. break;
  235. }
  236. Py_INCREF(object);
  237. dict = PyModule_GetDict(object);
  238. prevObject = object;
  239. }
  240. if (!object)
  241. {
  242. return QStringList();
  243. }
  244. // PyObject* object = PyDict_GetItemString(dict, module.toAscii().data());
  245. // if (!object)
  246. // {
  247. // return QStringList();
  248. // }
  249. // Py_INCREF(object);
  250. if (!pythonVariableName.isEmpty())
  251. {
  252. QStringList tmpNames = pythonVariableName.split('.');
  253. for (int i = 0; i < tmpNames.size() && object; ++i)
  254. {
  255. QByteArray tmpName = tmpNames.at(i).toLatin1();
  256. PyObject* prevObj = object;
  257. if (PyDict_Check(object))
  258. {
  259. object = PyDict_GetItemString(object, tmpName.data());
  260. Py_XINCREF(object);
  261. }
  262. else
  263. {
  264. object = PyObject_GetAttrString(object, tmpName.data());
  265. }
  266. Py_DECREF(prevObj);
  267. }
  268. PyErr_Clear();
  269. }
  270. QStringList results;
  271. if (object)
  272. {
  273. PyObject* keys = PyObject_Dir(object);
  274. if (keys)
  275. {
  276. PyObject* key;
  277. PyObject* value;
  278. int nKeys = PyList_Size(keys);
  279. for (int i = 0; i < nKeys; ++i)
  280. {
  281. key = PyList_GetItem(keys, i);
  282. value = PyObject_GetAttr(object, key);
  283. if (!value)
  284. {
  285. continue;
  286. }
  287. QString key_str(PyString_AsString(key));
  288. // Append "()" if the associated object is a function
  289. if (appendParenthesis && PyCallable_Check(value))
  290. {
  291. key_str.append("()");
  292. }
  293. results << key_str;
  294. Py_DECREF(value);
  295. }
  296. Py_DECREF(keys);
  297. }
  298. Py_DECREF(object);
  299. }
  300. return results;
  301. }
  302. //-----------------------------------------------------------------------------
  303. void ctkAbstractPythonManager::addObjectToPythonMain(const QString& name, QObject* obj)
  304. {
  305. PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  306. if (main && obj)
  307. {
  308. main.addObject(name, obj);
  309. }
  310. }
  311. //-----------------------------------------------------------------------------
  312. void ctkAbstractPythonManager::addWrapperFactory(PythonQtForeignWrapperFactory* factory)
  313. {
  314. PythonQt::self()->addWrapperFactory(factory);
  315. }
  316. //-----------------------------------------------------------------------------
  317. QVariant ctkAbstractPythonManager::getVariable(const QString& name)
  318. {
  319. PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  320. if (main)
  321. {
  322. return PythonQt::self()->getVariable(main, name);
  323. }
  324. return QVariant();
  325. }
  326. //-----------------------------------------------------------------------------
  327. void ctkAbstractPythonManager::printStdout(const QString& text)
  328. {
  329. std::cout << qPrintable(text);
  330. }
  331. //-----------------------------------------------------------------------------
  332. void ctkAbstractPythonManager::printStderr(const QString& text)
  333. {
  334. std::cout << qPrintable(text);
  335. }