ctkPythonShell.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. //----------------------------------------------------------------------------
  55. class ctkPythonShellCompleter : public ctkConsoleWidgetCompleter
  56. {
  57. public:
  58. ctkPythonShellCompleter(ctkPythonShell& p) : Parent(p)
  59. {
  60. this->setParent(&p);
  61. }
  62. virtual void updateCompletionModel(const QString& completion)
  63. {
  64. // Start by clearing the model
  65. this->setModel(0);
  66. // Don't try to complete the empty string
  67. if (completion.isEmpty())
  68. {
  69. return;
  70. }
  71. // Search backward through the string for usable characters
  72. QString textToComplete;
  73. for (int i = completion.length()-1; i >= 0; --i)
  74. {
  75. QChar c = completion.at(i);
  76. if (c.isLetterOrNumber() || c == '.' || c == '_')
  77. {
  78. textToComplete.prepend(c);
  79. }
  80. else
  81. {
  82. break;
  83. }
  84. }
  85. // Split the string at the last dot, if one exists
  86. QString lookup;
  87. QString compareText = textToComplete;
  88. int dot = compareText.lastIndexOf('.');
  89. if (dot != -1)
  90. {
  91. lookup = compareText.mid(0, dot);
  92. compareText = compareText.mid(dot+1);
  93. }
  94. // Lookup python names
  95. QStringList attrs;
  96. if (!lookup.isEmpty() || !compareText.isEmpty())
  97. {
  98. attrs = Parent.getPythonAttributes(lookup);
  99. }
  100. // Initialize the completion model
  101. if (!attrs.isEmpty())
  102. {
  103. this->setCompletionMode(QCompleter::PopupCompletion);
  104. this->setModel(new QStringListModel(attrs, this));
  105. this->setCaseSensitivity(Qt::CaseInsensitive);
  106. this->setCompletionPrefix(compareText.toLower());
  107. this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));
  108. }
  109. }
  110. ctkPythonShell& Parent;
  111. };
  112. /////////////////////////////////////////////////////////////////////////
  113. // ctkPythonShell::pqImplementation
  114. struct ctkPythonShell::pqImplementation
  115. {
  116. pqImplementation(QWidget* _parent, ctkAbstractPythonManager* pythonManager)
  117. : Console(_parent), PythonManager(pythonManager)
  118. {
  119. }
  120. //----------------------------------------------------------------------------
  121. // void initialize(int argc, char* argv[])
  122. // {
  123. // // Setup Python's interactive prompts
  124. // PyObject* ps1 = PySys_GetObject(const_cast<char*>("ps1"));
  125. // if(!ps1)
  126. // {
  127. // PySys_SetObject(const_cast<char*>("ps1"), ps1 = PyString_FromString(">>> "));
  128. // Py_XDECREF(ps1);
  129. // }
  130. //
  131. // PyObject* ps2 = PySys_GetObject(const_cast<char*>("ps2"));
  132. // if(!ps2)
  133. // {
  134. // PySys_SetObject(const_cast<char*>("ps2"), ps2 = PyString_FromString("... "));
  135. // Py_XDECREF(ps2);
  136. // }
  137. // this->MultilineStatement = false;
  138. // }
  139. //----------------------------------------------------------------------------
  140. ~pqImplementation()
  141. {
  142. // this->destroyInterpretor();
  143. }
  144. //----------------------------------------------------------------------------
  145. // void destroyInterpretor()
  146. // {
  147. // if (this->Interpreter)
  148. // {
  149. // QTextCharFormat format = this->Console.getFormat();
  150. // format.setForeground(QColor(255, 0, 0));
  151. // this->Console.setFormat(format);
  152. // this->Console.printString("\n... restarting ...\n");
  153. // format.setForeground(QColor(0, 0, 0));
  154. // this->Console.setFormat(format);
  155. //
  156. // this->Interpreter->MakeCurrent();
  157. //
  158. // // Restore Python's original stdout and stderr
  159. // PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));
  160. // PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));
  161. // this->Interpreter->ReleaseControl();
  162. // this->Interpreter->Delete();
  163. // }
  164. // this->Interpreter = 0;
  165. // }
  166. //----------------------------------------------------------------------------
  167. void executeCommand(const QString& command)
  168. {
  169. // this->MultilineStatement =
  170. // this->Interpreter->Push(Command.toAscii().data());
  171. if (command.length())
  172. {
  173. Q_ASSERT(this->PythonManager);
  174. this->PythonManager->executeString(command);
  175. }
  176. }
  177. //----------------------------------------------------------------------------
  178. void promptForInput(const QString& indent=QString())
  179. {
  180. QTextCharFormat format = this->Console.getFormat();
  181. format.setForeground(QColor(0, 0, 0));
  182. this->Console.setFormat(format);
  183. // this->Interpreter->MakeCurrent();
  184. if(!this->MultilineStatement)
  185. {
  186. this->Console.prompt(">>> ");
  187. //this->Console.prompt(
  188. // PyString_AsString(PySys_GetObject(const_cast<char*>("ps1"))));
  189. }
  190. else
  191. {
  192. this->Console.prompt("... ");
  193. //this->Console.prompt(
  194. // PyString_AsString(PySys_GetObject(const_cast<char*>("ps2"))));
  195. }
  196. this->Console.printCommand(indent);
  197. // this->Interpreter->ReleaseControl();
  198. }
  199. /// Provides a console for gathering user input and displaying
  200. /// Python output
  201. ctkConsoleWidget Console;
  202. ctkAbstractPythonManager* PythonManager;
  203. /// Indicates if the last statement processes was incomplete.
  204. bool MultilineStatement;
  205. };
  206. /////////////////////////////////////////////////////////////////////////
  207. // ctkPythonShell
  208. //----------------------------------------------------------------------------
  209. ctkPythonShell::ctkPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent):
  210. Superclass(_parent),
  211. Implementation(new pqImplementation(this, pythonManager))
  212. {
  213. // Layout UI
  214. QVBoxLayout* const boxLayout = new QVBoxLayout(this);
  215. boxLayout->setMargin(0);
  216. boxLayout->addWidget(&this->Implementation->Console);
  217. this->setObjectName("pythonShell");
  218. ctkPythonShellCompleter* completer = new ctkPythonShellCompleter(*this);
  219. this->Implementation->Console.setCompleter(completer);
  220. QObject::connect(
  221. &this->Implementation->Console, SIGNAL(executeCommand(const QString&)),
  222. this, SLOT(onExecuteCommand(const QString&)));
  223. // The call to mainContext() ensures that python has been initialized.
  224. Q_ASSERT(this->Implementation->PythonManager);
  225. this->Implementation->PythonManager->mainContext();
  226. QTextCharFormat format = this->Implementation->Console.getFormat();
  227. format.setForeground(QColor(0, 0, 255));
  228. this->Implementation->Console.setFormat(format);
  229. this->Implementation->Console.printString(
  230. QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()));
  231. this->promptForInput();
  232. Q_ASSERT(PythonQt::self());
  233. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
  234. SLOT(printStdout(const QString&)));
  235. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
  236. SLOT(printStderr(const QString&)));
  237. }
  238. //----------------------------------------------------------------------------
  239. ctkPythonShell::~ctkPythonShell()
  240. {
  241. delete this->Implementation;
  242. }
  243. //----------------------------------------------------------------------------
  244. void ctkPythonShell::clear()
  245. {
  246. this->Implementation->Console.clear();
  247. this->Implementation->promptForInput();
  248. }
  249. // //----------------------------------------------------------------------------
  250. // void ctkPythonShell::makeCurrent()
  251. // {
  252. // this->Implementation->Interpreter->MakeCurrent();
  253. // }
  254. //
  255. // //----------------------------------------------------------------------------
  256. // void ctkPythonShell::releaseControl()
  257. // {
  258. // this->Implementation->Interpreter->ReleaseControl();
  259. // }
  260. //----------------------------------------------------------------------------
  261. void ctkPythonShell::executeScript(const QString& script)
  262. {
  263. Q_UNUSED(script);
  264. this->printStdout("\n");
  265. emit this->executing(true);
  266. // this->Implementation->Interpreter->RunSimpleString(
  267. // script.toAscii().data());
  268. emit this->executing(false);
  269. this->Implementation->promptForInput();
  270. }
  271. //----------------------------------------------------------------------------
  272. QStringList ctkPythonShell::getPythonAttributes(const QString& pythonVariableName)
  273. {
  274. // this->makeCurrent();
  275. Q_ASSERT(PyThreadState_GET()->interp);
  276. PyObject* dict = PyImport_GetModuleDict();
  277. PyObject* object = PyDict_GetItemString(dict, "__main__");
  278. Py_INCREF(object);
  279. if (!pythonVariableName.isEmpty())
  280. {
  281. QStringList tmpNames = pythonVariableName.split('.');
  282. for (int i = 0; i < tmpNames.size() && object; ++i)
  283. {
  284. QByteArray tmpName = tmpNames.at(i).toLatin1();
  285. PyObject* prevObj = object;
  286. if (PyDict_Check(object))
  287. {
  288. object = PyDict_GetItemString(object, tmpName.data());
  289. Py_XINCREF(object);
  290. }
  291. else
  292. {
  293. object = PyObject_GetAttrString(object, tmpName.data());
  294. }
  295. Py_DECREF(prevObj);
  296. }
  297. PyErr_Clear();
  298. }
  299. QStringList results;
  300. if (object)
  301. {
  302. PyObject* keys = PyObject_Dir(object);
  303. if (keys)
  304. {
  305. PyObject* key;
  306. PyObject* value;
  307. QString keystr;
  308. int nKeys = PyList_Size(keys);
  309. for (int i = 0; i < nKeys; ++i)
  310. {
  311. key = PyList_GetItem(keys, i);
  312. value = PyObject_GetAttr(object, key);
  313. if (!value)
  314. {
  315. continue;
  316. }
  317. results << PyString_AsString(key);
  318. Py_DECREF(value);
  319. }
  320. Py_DECREF(keys);
  321. }
  322. Py_DECREF(object);
  323. }
  324. // this->releaseControl();
  325. return results;
  326. }
  327. //----------------------------------------------------------------------------
  328. void ctkPythonShell::printStdout(const QString& text)
  329. {
  330. QTextCharFormat format = this->Implementation->Console.getFormat();
  331. format.setForeground(QColor(0, 150, 0));
  332. this->Implementation->Console.setFormat(format);
  333. this->Implementation->Console.printString(text);
  334. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  335. }
  336. //----------------------------------------------------------------------------
  337. void ctkPythonShell::printMessage(const QString& text)
  338. {
  339. QTextCharFormat format = this->Implementation->Console.getFormat();
  340. format.setForeground(QColor(0, 0, 150));
  341. this->Implementation->Console.setFormat(format);
  342. this->Implementation->Console.printString(text);
  343. }
  344. //----------------------------------------------------------------------------
  345. void ctkPythonShell::printStderr(const QString& text)
  346. {
  347. QTextCharFormat format = this->Implementation->Console.getFormat();
  348. format.setForeground(QColor(255, 0, 0));
  349. this->Implementation->Console.setFormat(format);
  350. this->Implementation->Console.printString(text);
  351. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  352. }
  353. //----------------------------------------------------------------------------
  354. void ctkPythonShell::onExecuteCommand(const QString& Command)
  355. {
  356. QString command = Command;
  357. command.replace(QRegExp("\\s*$"), "");
  358. this->internalExecuteCommand(command);
  359. // Find the indent for the command.
  360. QRegExp regExp("^(\\s+)");
  361. QString indent;
  362. if (regExp.indexIn(command) != -1)
  363. {
  364. indent = regExp.cap(1);
  365. }
  366. this->Implementation->promptForInput(indent);
  367. }
  368. //----------------------------------------------------------------------------
  369. void ctkPythonShell::promptForInput()
  370. {
  371. this->Implementation->promptForInput();
  372. }
  373. //----------------------------------------------------------------------------
  374. void ctkPythonShell::internalExecuteCommand(const QString& command)
  375. {
  376. emit this->executing(true);
  377. this->Implementation->executeCommand(command);
  378. emit this->executing(false);
  379. }