ctkPythonConsole.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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.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 <ctkConsole.h>
  52. #include <ctkAbstractPythonManager.h>
  53. #include "ctkPythonConsole.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. // ctkPythonConsoleCompleter
  62. //----------------------------------------------------------------------------
  63. class ctkPythonConsoleCompleter : public ctkConsoleCompleter
  64. {
  65. public:
  66. ctkPythonConsoleCompleter(ctkPythonConsole& p) : Parent(p)
  67. {
  68. this->setParent(&p);
  69. }
  70. virtual void updateCompletionModel(const QString& completion)
  71. {
  72. // Start by clearing the model
  73. this->setModel(0);
  74. // Don't try to complete the empty string
  75. if (completion.isEmpty())
  76. {
  77. return;
  78. }
  79. // Search backward through the string for usable characters
  80. QString textToComplete;
  81. for (int i = completion.length()-1; i >= 0; --i)
  82. {
  83. QChar c = completion.at(i);
  84. if (c.isLetterOrNumber() || c == '.' || c == '_')
  85. {
  86. textToComplete.prepend(c);
  87. }
  88. else
  89. {
  90. break;
  91. }
  92. }
  93. // Split the string at the last dot, if one exists
  94. QString lookup;
  95. QString compareText = textToComplete;
  96. int dot = compareText.lastIndexOf('.');
  97. if (dot != -1)
  98. {
  99. lookup = compareText.mid(0, dot);
  100. compareText = compareText.mid(dot+1);
  101. }
  102. // Lookup python names
  103. QStringList attrs;
  104. if (!lookup.isEmpty() || !compareText.isEmpty())
  105. {
  106. attrs = this->Parent.pythonAttributes(lookup);
  107. }
  108. // Initialize the completion model
  109. if (!attrs.isEmpty())
  110. {
  111. this->setCompletionMode(QCompleter::PopupCompletion);
  112. this->setModel(new QStringListModel(attrs, this));
  113. this->setCaseSensitivity(Qt::CaseInsensitive);
  114. this->setCompletionPrefix(compareText.toLower());
  115. this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));
  116. }
  117. }
  118. ctkPythonConsole& Parent;
  119. };
  120. //----------------------------------------------------------------------------
  121. // ctkPythonConsolePrivate
  122. //----------------------------------------------------------------------------
  123. class ctkPythonConsolePrivate
  124. {
  125. Q_DECLARE_PUBLIC(ctkPythonConsole);
  126. protected:
  127. ctkPythonConsole* const q_ptr;
  128. public:
  129. ctkPythonConsolePrivate(ctkPythonConsole& object, ctkAbstractPythonManager* pythonManager);
  130. ~ctkPythonConsolePrivate();
  131. void initializeInteractiveConsole();
  132. bool push(const QString& code);
  133. void resetBuffer();
  134. void executeCommand(const QString& command);
  135. void promptForInput(const QString& indent = QString());
  136. /// Provides a console for gathering user input and displaying Python output
  137. ctkConsole Console;
  138. ctkAbstractPythonManager* PythonManager;
  139. /// Indicates if the last statement processes was incomplete.
  140. bool MultilineStatement;
  141. PyObject* InteractiveConsole;
  142. };
  143. //----------------------------------------------------------------------------
  144. // ctkPythonConsolePrivate methods
  145. //----------------------------------------------------------------------------
  146. ctkPythonConsolePrivate::ctkPythonConsolePrivate(
  147. ctkPythonConsole& object, ctkAbstractPythonManager* pythonManager)
  148. : q_ptr(&object), Console(&object), PythonManager(pythonManager), MultilineStatement(false),
  149. InteractiveConsole(0)
  150. {
  151. }
  152. //----------------------------------------------------------------------------
  153. ctkPythonConsolePrivate::~ctkPythonConsolePrivate()
  154. {
  155. }
  156. //----------------------------------------------------------------------------
  157. void ctkPythonConsolePrivate::initializeInteractiveConsole()
  158. {
  159. // set up the code.InteractiveConsole instance that we'll use.
  160. const char* code =
  161. "import code\n"
  162. "__ctkConsole=code.InteractiveConsole(locals())\n";
  163. PyRun_SimpleString(code);
  164. // Now get the reference to __ctkConsole and save the pointer.
  165. PyObject* main_module = PyImport_AddModule("__main__");
  166. PyObject* global_dict = PyModule_GetDict(main_module);
  167. this->InteractiveConsole = PyDict_GetItemString(
  168. global_dict, "__ctkConsole");
  169. if (!this->InteractiveConsole)
  170. {
  171. qCritical("Failed to locate the InteractiveConsole object.");
  172. }
  173. }
  174. //----------------------------------------------------------------------------
  175. bool ctkPythonConsolePrivate::push(const QString& code)
  176. {
  177. bool ret_value = false;
  178. QString buffer = code;
  179. // The embedded python interpreter cannot handle DOS line-endings, see
  180. // http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
  181. buffer.remove('\r');
  182. PyObject *res = PyObject_CallMethod(this->InteractiveConsole,
  183. const_cast<char*>("push"),
  184. const_cast<char*>("z"),
  185. buffer.toAscii().data());
  186. if (res)
  187. {
  188. int status = 0;
  189. if (PyArg_Parse(res, "i", &status))
  190. {
  191. ret_value = (status > 0);
  192. }
  193. Py_DECREF(res);
  194. }
  195. return ret_value;
  196. }
  197. //----------------------------------------------------------------------------
  198. void ctkPythonConsolePrivate::resetBuffer()
  199. {
  200. if (this->InteractiveConsole)
  201. {
  202. //this->MakeCurrent();
  203. const char* code = "__ctkConsole.resetbuffer()\n";
  204. PyRun_SimpleString(code);
  205. //this->ReleaseControl();
  206. }
  207. }
  208. //----------------------------------------------------------------------------
  209. void ctkPythonConsolePrivate::executeCommand(const QString& command)
  210. {
  211. this->MultilineStatement = this->push(command);
  212. // if (command.length())
  213. // {
  214. // Q_ASSERT(this->PythonManager);
  215. // this->PythonManager->executeString(command);
  216. // }
  217. }
  218. //----------------------------------------------------------------------------
  219. void ctkPythonConsolePrivate::promptForInput(const QString& indent)
  220. {
  221. QTextCharFormat format = this->Console.getFormat();
  222. format.setForeground(QColor(0, 0, 0));
  223. this->Console.setFormat(format);
  224. // this->Interpreter->MakeCurrent();
  225. if(!this->MultilineStatement)
  226. {
  227. this->Console.prompt(">>> ");
  228. //this->Console.prompt(
  229. // PyString_AsString(PySys_GetObject(const_cast<char*>("ps1"))));
  230. }
  231. else
  232. {
  233. this->Console.prompt("... ");
  234. //this->Console.prompt(
  235. // PyString_AsString(PySys_GetObject(const_cast<char*>("ps2"))));
  236. }
  237. this->Console.printCommand(indent);
  238. // this->Interpreter->ReleaseControl();
  239. }
  240. //----------------------------------------------------------------------------
  241. // ctkPythonConsole methods
  242. //----------------------------------------------------------------------------
  243. ctkPythonConsole::ctkPythonConsole(ctkAbstractPythonManager* pythonManager, QWidget* parentObject):
  244. Superclass(parentObject),
  245. d_ptr(new ctkPythonConsolePrivate(*this, pythonManager))
  246. {
  247. Q_D(ctkPythonConsole);
  248. // Layout UI
  249. QVBoxLayout* const boxLayout = new QVBoxLayout(this);
  250. boxLayout->setMargin(0);
  251. boxLayout->addWidget(&d->Console);
  252. this->setObjectName("pythonConsole");
  253. this->setFocusProxy(&d->Console);
  254. ctkPythonConsoleCompleter* completer = new ctkPythonConsoleCompleter(*this);
  255. d->Console.setCompleter(completer);
  256. QObject::connect(
  257. &d->Console, SIGNAL(executeCommand(const QString&)),
  258. this, SLOT(onExecuteCommand(const QString&)));
  259. // The call to mainContext() ensures that python has been initialized.
  260. Q_ASSERT(d->PythonManager);
  261. d->PythonManager->mainContext();
  262. d->initializeInteractiveConsole();
  263. QTextCharFormat format = d->Console.getFormat();
  264. format.setForeground(QColor(0, 0, 255));
  265. d->Console.setFormat(format);
  266. d->Console.printString(
  267. QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()));
  268. d->promptForInput();
  269. Q_ASSERT(PythonQt::self());
  270. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
  271. SLOT(printStdout(const QString&)));
  272. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
  273. SLOT(printStderr(const QString&)));
  274. }
  275. //----------------------------------------------------------------------------
  276. ctkPythonConsole::~ctkPythonConsole()
  277. {
  278. }
  279. //----------------------------------------------------------------------------
  280. void ctkPythonConsole::clear()
  281. {
  282. Q_D(ctkPythonConsole);
  283. d->Console.clear();
  284. d->promptForInput();
  285. }
  286. //----------------------------------------------------------------------------
  287. void ctkPythonConsole::executeScript(const QString& script)
  288. {
  289. Q_D(ctkPythonConsole);
  290. Q_UNUSED(script);
  291. this->printStdout("\n");
  292. emit this->executing(true);
  293. // d->Interpreter->RunSimpleString(
  294. // script.toAscii().data());
  295. emit this->executing(false);
  296. d->promptForInput();
  297. }
  298. //----------------------------------------------------------------------------
  299. QStringList ctkPythonConsole::pythonAttributes(const QString& pythonVariableName) const
  300. {
  301. // this->makeCurrent();
  302. Q_ASSERT(PyThreadState_GET()->interp);
  303. PyObject* dict = PyImport_GetModuleDict();
  304. PyObject* object = PyDict_GetItemString(dict, "__main__");
  305. Py_INCREF(object);
  306. if (!pythonVariableName.isEmpty())
  307. {
  308. QStringList tmpNames = pythonVariableName.split('.');
  309. for (int i = 0; i < tmpNames.size() && object; ++i)
  310. {
  311. QByteArray tmpName = tmpNames.at(i).toLatin1();
  312. PyObject* prevObj = object;
  313. if (PyDict_Check(object))
  314. {
  315. object = PyDict_GetItemString(object, tmpName.data());
  316. Py_XINCREF(object);
  317. }
  318. else
  319. {
  320. object = PyObject_GetAttrString(object, tmpName.data());
  321. }
  322. Py_DECREF(prevObj);
  323. }
  324. PyErr_Clear();
  325. }
  326. QStringList results;
  327. if (object)
  328. {
  329. PyObject* keys = PyObject_Dir(object);
  330. if (keys)
  331. {
  332. PyObject* key;
  333. PyObject* value;
  334. QString keystr;
  335. int nKeys = PyList_Size(keys);
  336. for (int i = 0; i < nKeys; ++i)
  337. {
  338. key = PyList_GetItem(keys, i);
  339. value = PyObject_GetAttr(object, key);
  340. if (!value)
  341. {
  342. continue;
  343. }
  344. results << PyString_AsString(key);
  345. Py_DECREF(value);
  346. }
  347. Py_DECREF(keys);
  348. }
  349. Py_DECREF(object);
  350. }
  351. // this->releaseControl();
  352. return results;
  353. }
  354. //----------------------------------------------------------------------------
  355. void ctkPythonConsole::printStdout(const QString& text)
  356. {
  357. Q_D(ctkPythonConsole);
  358. QTextCharFormat format = d->Console.getFormat();
  359. format.setForeground(QColor(0, 150, 0));
  360. d->Console.setFormat(format);
  361. d->Console.printString(text);
  362. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  363. }
  364. //----------------------------------------------------------------------------
  365. void ctkPythonConsole::printMessage(const QString& text)
  366. {
  367. Q_D(ctkPythonConsole);
  368. QTextCharFormat format = d->Console.getFormat();
  369. format.setForeground(QColor(0, 0, 150));
  370. d->Console.setFormat(format);
  371. d->Console.printString(text);
  372. }
  373. //----------------------------------------------------------------------------
  374. void ctkPythonConsole::printStderr(const QString& text)
  375. {
  376. Q_D(ctkPythonConsole);
  377. QTextCharFormat format = d->Console.getFormat();
  378. format.setForeground(QColor(255, 0, 0));
  379. d->Console.setFormat(format);
  380. d->Console.printString(text);
  381. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  382. }
  383. //----------------------------------------------------------------------------
  384. void ctkPythonConsole::onExecuteCommand(const QString& Command)
  385. {
  386. Q_D(ctkPythonConsole);
  387. QString command = Command;
  388. command.replace(QRegExp("\\s*$"), "");
  389. this->internalExecuteCommand(command);
  390. // Find the indent for the command.
  391. QRegExp regExp("^(\\s+)");
  392. QString indent;
  393. if (regExp.indexIn(command) != -1)
  394. {
  395. indent = regExp.cap(1);
  396. }
  397. d->promptForInput(indent);
  398. }
  399. //----------------------------------------------------------------------------
  400. void ctkPythonConsole::internalExecuteCommand(const QString& command)
  401. {
  402. Q_D(ctkPythonConsole);
  403. emit this->executing(true);
  404. d->executeCommand(command);
  405. emit this->executing(false);
  406. }