ctkPythonShell.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) 2010 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.commontk.org/LICENSE
  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. /*=========================================================================
  15. Program: ParaView
  16. Module: $RCSfile$
  17. Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
  18. All rights reserved.
  19. ParaView is a free software; you can redistribute it and/or modify it
  20. under the terms of the ParaView license version 1.2.
  21. See License_v1.2.txt for the full ParaView license.
  22. A copy of this license can be obtained by contacting
  23. Kitware Inc.
  24. 28 Corporate Drive
  25. Clifton Park, NY 12065
  26. USA
  27. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  30. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
  31. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  32. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  34. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  35. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  36. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  37. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. =========================================================================*/
  39. //#include <vtkPython.h> // python first
  40. // Qt includes
  41. #include <QCoreApplication>
  42. #include <QResizeEvent>
  43. #include <QScrollBar>
  44. #include <QStringListModel>
  45. #include <QTextCharFormat>
  46. #include <QVBoxLayout>
  47. // PythonQt includes
  48. #include <PythonQt.h>
  49. #include <PythonQtObjectPtr.h>
  50. // CTK includes
  51. #include <ctkConsoleWidget.h>
  52. #include <ctkAbstractPythonManager.h>
  53. #include "ctkPythonShell.h"
  54. #ifdef __GNUC__
  55. // Disable warnings related to Python macros and functions
  56. // See http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
  57. // Note: Ideally the incriminated functions and macros should be fixed upstream ...
  58. #pragma GCC diagnostic ignored "-Wold-style-cast"
  59. #endif
  60. //----------------------------------------------------------------------------
  61. class ctkPythonShellCompleter : public ctkConsoleWidgetCompleter
  62. {
  63. public:
  64. ctkPythonShellCompleter(ctkPythonShell& p) : Parent(p)
  65. {
  66. this->setParent(&p);
  67. }
  68. virtual void updateCompletionModel(const QString& completion)
  69. {
  70. // Start by clearing the model
  71. this->setModel(0);
  72. // Don't try to complete the empty string
  73. if (completion.isEmpty())
  74. {
  75. return;
  76. }
  77. // Search backward through the string for usable characters
  78. QString textToComplete;
  79. for (int i = completion.length()-1; i >= 0; --i)
  80. {
  81. QChar c = completion.at(i);
  82. if (c.isLetterOrNumber() || c == '.' || c == '_')
  83. {
  84. textToComplete.prepend(c);
  85. }
  86. else
  87. {
  88. break;
  89. }
  90. }
  91. // Split the string at the last dot, if one exists
  92. QString lookup;
  93. QString compareText = textToComplete;
  94. int dot = compareText.lastIndexOf('.');
  95. if (dot != -1)
  96. {
  97. lookup = compareText.mid(0, dot);
  98. compareText = compareText.mid(dot+1);
  99. }
  100. // Lookup python names
  101. QStringList attrs;
  102. if (!lookup.isEmpty() || !compareText.isEmpty())
  103. {
  104. attrs = Parent.getPythonAttributes(lookup);
  105. }
  106. // Initialize the completion model
  107. if (!attrs.isEmpty())
  108. {
  109. this->setCompletionMode(QCompleter::PopupCompletion);
  110. this->setModel(new QStringListModel(attrs, this));
  111. this->setCaseSensitivity(Qt::CaseInsensitive);
  112. this->setCompletionPrefix(compareText.toLower());
  113. this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));
  114. }
  115. }
  116. ctkPythonShell& Parent;
  117. };
  118. /////////////////////////////////////////////////////////////////////////
  119. // ctkPythonShell::pqImplementation
  120. struct ctkPythonShell::pqImplementation
  121. {
  122. pqImplementation(QWidget* _parent, ctkAbstractPythonManager* pythonManager)
  123. : Console(_parent), PythonManager(pythonManager), MultilineStatement(false),
  124. InteractiveConsole(0)
  125. {
  126. }
  127. //----------------------------------------------------------------------------
  128. // void initialize(int argc, char* argv[])
  129. // {
  130. // // Setup Python's interactive prompts
  131. // PyObject* ps1 = PySys_GetObject(const_cast<char*>("ps1"));
  132. // if(!ps1)
  133. // {
  134. // PySys_SetObject(const_cast<char*>("ps1"), ps1 = PyString_FromString(">>> "));
  135. // Py_XDECREF(ps1);
  136. // }
  137. //
  138. // PyObject* ps2 = PySys_GetObject(const_cast<char*>("ps2"));
  139. // if(!ps2)
  140. // {
  141. // PySys_SetObject(const_cast<char*>("ps2"), ps2 = PyString_FromString("... "));
  142. // Py_XDECREF(ps2);
  143. // }
  144. // this->MultilineStatement = false;
  145. // }
  146. //----------------------------------------------------------------------------
  147. ~pqImplementation()
  148. {
  149. // this->destroyInterpretor();
  150. }
  151. //----------------------------------------------------------------------------
  152. // void destroyInterpretor()
  153. // {
  154. // if (this->Interpreter)
  155. // {
  156. // QTextCharFormat format = this->Console.getFormat();
  157. // format.setForeground(QColor(255, 0, 0));
  158. // this->Console.setFormat(format);
  159. // this->Console.printString("\n... restarting ...\n");
  160. // format.setForeground(QColor(0, 0, 0));
  161. // this->Console.setFormat(format);
  162. //
  163. // this->Interpreter->MakeCurrent();
  164. //
  165. // // Restore Python's original stdout and stderr
  166. // PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));
  167. // PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));
  168. // this->Interpreter->ReleaseControl();
  169. // this->Interpreter->Delete();
  170. // }
  171. // this->Interpreter = 0;
  172. // }
  173. //----------------------------------------------------------------------------
  174. void initializeInteractiveConsole()
  175. {
  176. qDebug() << "initializeInteractiveConsole";
  177. // set up the code.InteractiveConsole instance that we'll use.
  178. const char* code =
  179. "import code\n"
  180. "__ctkConsole=code.InteractiveConsole(locals())\n";
  181. PyRun_SimpleString(code);
  182. // Now get the reference to __ctkConsole and save the pointer.
  183. PyObject* main_module = PyImport_AddModule("__main__");
  184. PyObject* global_dict = PyModule_GetDict(main_module);
  185. this->InteractiveConsole = PyDict_GetItemString(
  186. global_dict, "__ctkConsole");
  187. if (!this->InteractiveConsole)
  188. {
  189. qCritical("Failed to locate the InteractiveConsole object.");
  190. }
  191. }
  192. //----------------------------------------------------------------------------
  193. bool push(const QString& code)
  194. {
  195. bool ret_value = false;
  196. QString buffer = code;
  197. // The embedded python interpreter cannot handle DOS line-endings, see
  198. // http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
  199. buffer.remove('\r');
  200. PyObject *res = PyObject_CallMethod(this->InteractiveConsole,
  201. const_cast<char*>("push"),
  202. const_cast<char*>("z"),
  203. buffer.toAscii().data());
  204. if (res)
  205. {
  206. int status = 0;
  207. if (PyArg_Parse(res, "i", &status))
  208. {
  209. ret_value = (status > 0);
  210. }
  211. Py_DECREF(res);
  212. }
  213. return ret_value;
  214. }
  215. //----------------------------------------------------------------------------
  216. void resetBuffer()
  217. {
  218. if (this->InteractiveConsole)
  219. {
  220. //this->MakeCurrent();
  221. const char* code = "__ctkConsole.resetbuffer()\n";
  222. PyRun_SimpleString(code);
  223. //this->ReleaseControl();
  224. }
  225. }
  226. //----------------------------------------------------------------------------
  227. void executeCommand(const QString& command)
  228. {
  229. this->MultilineStatement = this->push(command);
  230. // if (command.length())
  231. // {
  232. // Q_ASSERT(this->PythonManager);
  233. // this->PythonManager->executeString(command);
  234. // }
  235. }
  236. //----------------------------------------------------------------------------
  237. void promptForInput(const QString& indent=QString())
  238. {
  239. QTextCharFormat format = this->Console.getFormat();
  240. format.setForeground(QColor(0, 0, 0));
  241. this->Console.setFormat(format);
  242. // this->Interpreter->MakeCurrent();
  243. if(!this->MultilineStatement)
  244. {
  245. this->Console.prompt(">>> ");
  246. //this->Console.prompt(
  247. // PyString_AsString(PySys_GetObject(const_cast<char*>("ps1"))));
  248. }
  249. else
  250. {
  251. this->Console.prompt("... ");
  252. //this->Console.prompt(
  253. // PyString_AsString(PySys_GetObject(const_cast<char*>("ps2"))));
  254. }
  255. this->Console.printCommand(indent);
  256. // this->Interpreter->ReleaseControl();
  257. }
  258. /// Provides a console for gathering user input and displaying
  259. /// Python output
  260. ctkConsoleWidget Console;
  261. ctkAbstractPythonManager* PythonManager;
  262. /// Indicates if the last statement processes was incomplete.
  263. bool MultilineStatement;
  264. PyObject* InteractiveConsole;
  265. };
  266. /////////////////////////////////////////////////////////////////////////
  267. // ctkPythonShell
  268. //----------------------------------------------------------------------------
  269. ctkPythonShell::ctkPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent):
  270. Superclass(_parent),
  271. Implementation(new pqImplementation(this, pythonManager))
  272. {
  273. // Layout UI
  274. QVBoxLayout* const boxLayout = new QVBoxLayout(this);
  275. boxLayout->setMargin(0);
  276. boxLayout->addWidget(&this->Implementation->Console);
  277. this->setObjectName("pythonShell");
  278. this->setFocusProxy(&this->Implementation->Console);
  279. ctkPythonShellCompleter* completer = new ctkPythonShellCompleter(*this);
  280. this->Implementation->Console.setCompleter(completer);
  281. QObject::connect(
  282. &this->Implementation->Console, SIGNAL(executeCommand(const QString&)),
  283. this, SLOT(onExecuteCommand(const QString&)));
  284. // The call to mainContext() ensures that python has been initialized.
  285. Q_ASSERT(this->Implementation->PythonManager);
  286. this->Implementation->PythonManager->mainContext();
  287. this->Implementation->initializeInteractiveConsole();
  288. QTextCharFormat format = this->Implementation->Console.getFormat();
  289. format.setForeground(QColor(0, 0, 255));
  290. this->Implementation->Console.setFormat(format);
  291. this->Implementation->Console.printString(
  292. QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()));
  293. this->promptForInput();
  294. Q_ASSERT(PythonQt::self());
  295. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
  296. SLOT(printStdout(const QString&)));
  297. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
  298. SLOT(printStderr(const QString&)));
  299. }
  300. //----------------------------------------------------------------------------
  301. ctkPythonShell::~ctkPythonShell()
  302. {
  303. delete this->Implementation;
  304. }
  305. //----------------------------------------------------------------------------
  306. void ctkPythonShell::clear()
  307. {
  308. this->Implementation->Console.clear();
  309. this->Implementation->promptForInput();
  310. }
  311. //----------------------------------------------------------------------------
  312. void ctkPythonShell::executeScript(const QString& script)
  313. {
  314. Q_UNUSED(script);
  315. this->printStdout("\n");
  316. emit this->executing(true);
  317. // this->Implementation->Interpreter->RunSimpleString(
  318. // script.toAscii().data());
  319. emit this->executing(false);
  320. this->Implementation->promptForInput();
  321. }
  322. //----------------------------------------------------------------------------
  323. QStringList ctkPythonShell::getPythonAttributes(const QString& pythonVariableName)
  324. {
  325. // this->makeCurrent();
  326. Q_ASSERT(PyThreadState_GET()->interp);
  327. PyObject* dict = PyImport_GetModuleDict();
  328. PyObject* object = PyDict_GetItemString(dict, "__main__");
  329. Py_INCREF(object);
  330. if (!pythonVariableName.isEmpty())
  331. {
  332. QStringList tmpNames = pythonVariableName.split('.');
  333. for (int i = 0; i < tmpNames.size() && object; ++i)
  334. {
  335. QByteArray tmpName = tmpNames.at(i).toLatin1();
  336. PyObject* prevObj = object;
  337. if (PyDict_Check(object))
  338. {
  339. object = PyDict_GetItemString(object, tmpName.data());
  340. Py_XINCREF(object);
  341. }
  342. else
  343. {
  344. object = PyObject_GetAttrString(object, tmpName.data());
  345. }
  346. Py_DECREF(prevObj);
  347. }
  348. PyErr_Clear();
  349. }
  350. QStringList results;
  351. if (object)
  352. {
  353. PyObject* keys = PyObject_Dir(object);
  354. if (keys)
  355. {
  356. PyObject* key;
  357. PyObject* value;
  358. QString keystr;
  359. int nKeys = PyList_Size(keys);
  360. for (int i = 0; i < nKeys; ++i)
  361. {
  362. key = PyList_GetItem(keys, i);
  363. value = PyObject_GetAttr(object, key);
  364. if (!value)
  365. {
  366. continue;
  367. }
  368. results << PyString_AsString(key);
  369. Py_DECREF(value);
  370. }
  371. Py_DECREF(keys);
  372. }
  373. Py_DECREF(object);
  374. }
  375. // this->releaseControl();
  376. return results;
  377. }
  378. //----------------------------------------------------------------------------
  379. void ctkPythonShell::printStdout(const QString& text)
  380. {
  381. QTextCharFormat format = this->Implementation->Console.getFormat();
  382. format.setForeground(QColor(0, 150, 0));
  383. this->Implementation->Console.setFormat(format);
  384. this->Implementation->Console.printString(text);
  385. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  386. }
  387. //----------------------------------------------------------------------------
  388. void ctkPythonShell::printMessage(const QString& text)
  389. {
  390. QTextCharFormat format = this->Implementation->Console.getFormat();
  391. format.setForeground(QColor(0, 0, 150));
  392. this->Implementation->Console.setFormat(format);
  393. this->Implementation->Console.printString(text);
  394. }
  395. //----------------------------------------------------------------------------
  396. void ctkPythonShell::printStderr(const QString& text)
  397. {
  398. QTextCharFormat format = this->Implementation->Console.getFormat();
  399. format.setForeground(QColor(255, 0, 0));
  400. this->Implementation->Console.setFormat(format);
  401. this->Implementation->Console.printString(text);
  402. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  403. }
  404. //----------------------------------------------------------------------------
  405. void ctkPythonShell::onExecuteCommand(const QString& Command)
  406. {
  407. QString command = Command;
  408. command.replace(QRegExp("\\s*$"), "");
  409. this->internalExecuteCommand(command);
  410. // Find the indent for the command.
  411. QRegExp regExp("^(\\s+)");
  412. QString indent;
  413. if (regExp.indexIn(command) != -1)
  414. {
  415. indent = regExp.cap(1);
  416. }
  417. this->Implementation->promptForInput(indent);
  418. }
  419. //----------------------------------------------------------------------------
  420. void ctkPythonShell::promptForInput()
  421. {
  422. this->Implementation->promptForInput();
  423. }
  424. //----------------------------------------------------------------------------
  425. void ctkPythonShell::internalExecuteCommand(const QString& command)
  426. {
  427. emit this->executing(true);
  428. this->Implementation->executeCommand(command);
  429. emit this->executing(false);
  430. }