ctkPythonConsole.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. // Qt includes
  40. #include <QCoreApplication>
  41. #include <QResizeEvent>
  42. #include <QScrollBar>
  43. #include <QStringListModel>
  44. #include <QTextCharFormat>
  45. #include <QVBoxLayout>
  46. // PythonQt includes
  47. #include <PythonQt.h>
  48. #include <PythonQtObjectPtr.h>
  49. // CTK includes
  50. #include <ctkConsole.h>
  51. #include <ctkConsole_p.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(ctkAbstractPythonManager& pythonManager)
  67. : PythonManager(pythonManager)
  68. {
  69. this->setParent(&pythonManager);
  70. }
  71. virtual void updateCompletionModel(const QString& completion)
  72. {
  73. // Start by clearing the model
  74. this->setModel(0);
  75. // Don't try to complete the empty string
  76. if (completion.isEmpty())
  77. {
  78. return;
  79. }
  80. // Search backward through the string for usable characters
  81. QString textToComplete;
  82. for (int i = completion.length()-1; i >= 0; --i)
  83. {
  84. QChar c = completion.at(i);
  85. if (c.isLetterOrNumber() || c == '.' || c == '_')
  86. {
  87. textToComplete.prepend(c);
  88. }
  89. else
  90. {
  91. break;
  92. }
  93. }
  94. // Split the string at the last dot, if one exists
  95. QString lookup;
  96. QString compareText = textToComplete;
  97. int dot = compareText.lastIndexOf('.');
  98. if (dot != -1)
  99. {
  100. lookup = compareText.mid(0, dot);
  101. compareText = compareText.mid(dot+1);
  102. }
  103. // Lookup python names
  104. QStringList attrs;
  105. if (!lookup.isEmpty() || !compareText.isEmpty())
  106. {
  107. attrs = this->PythonManager.pythonAttributes(lookup);
  108. }
  109. // Initialize the completion model
  110. if (!attrs.isEmpty())
  111. {
  112. this->setCompletionMode(QCompleter::PopupCompletion);
  113. this->setModel(new QStringListModel(attrs, this));
  114. this->setCaseSensitivity(Qt::CaseInsensitive);
  115. this->setCompletionPrefix(compareText.toLower());
  116. this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));
  117. }
  118. }
  119. ctkAbstractPythonManager& PythonManager;
  120. };
  121. //----------------------------------------------------------------------------
  122. // ctkPythonConsolePrivate
  123. //----------------------------------------------------------------------------
  124. class ctkPythonConsolePrivate : public ctkConsolePrivate
  125. {
  126. Q_DECLARE_PUBLIC(ctkPythonConsole);
  127. public:
  128. ctkPythonConsolePrivate(ctkPythonConsole& object);
  129. ~ctkPythonConsolePrivate();
  130. void initializeInteractiveConsole();
  131. bool push(const QString& code);
  132. /// Reset the input buffer of the interactive console
  133. // void resetInputBuffer();
  134. void printWelcomeMessage();
  135. ctkAbstractPythonManager* PythonManager;
  136. PyObject* InteractiveConsole;
  137. };
  138. //----------------------------------------------------------------------------
  139. // ctkPythonConsolePrivate methods
  140. //----------------------------------------------------------------------------
  141. ctkPythonConsolePrivate::ctkPythonConsolePrivate(ctkPythonConsole& object)
  142. : ctkConsolePrivate(object), PythonManager(0), InteractiveConsole(0)
  143. {
  144. }
  145. //----------------------------------------------------------------------------
  146. ctkPythonConsolePrivate::~ctkPythonConsolePrivate()
  147. {
  148. }
  149. //----------------------------------------------------------------------------
  150. void ctkPythonConsolePrivate::initializeInteractiveConsole()
  151. {
  152. Q_ASSERT(this->PythonManager);
  153. // set up the code.InteractiveConsole instance that we'll use.
  154. const char* code =
  155. "import code\n"
  156. "__ctkConsole = code.InteractiveConsole(locals())\n";
  157. PyRun_SimpleString(code);
  158. // Now get the reference to __ctkConsole and save the pointer.
  159. PyObject* main_module = PyImport_AddModule("__main__");
  160. PyObject* global_dict = PyModule_GetDict(main_module);
  161. this->InteractiveConsole = PyDict_GetItemString(
  162. global_dict, "__ctkConsole");
  163. if (!this->InteractiveConsole)
  164. {
  165. qCritical("Failed to locate the InteractiveConsole object.");
  166. }
  167. }
  168. //----------------------------------------------------------------------------
  169. bool ctkPythonConsolePrivate::push(const QString& code)
  170. {
  171. Q_ASSERT(this->PythonManager);
  172. bool ret_value = false;
  173. QString buffer = code;
  174. // The embedded python interpreter cannot handle DOS line-endings, see
  175. // http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
  176. buffer.remove('\r');
  177. PyObject *res = PyObject_CallMethod(this->InteractiveConsole,
  178. const_cast<char*>("push"),
  179. const_cast<char*>("z"),
  180. buffer.toAscii().data());
  181. if (res)
  182. {
  183. int status = 0;
  184. if (PyArg_Parse(res, "i", &status))
  185. {
  186. ret_value = (status > 0);
  187. }
  188. Py_DECREF(res);
  189. }
  190. return ret_value;
  191. }
  192. ////----------------------------------------------------------------------------
  193. //void ctkPythonConsolePrivate::resetInputBuffer()
  194. //{
  195. // if (this->InteractiveConsole)
  196. // {
  197. // //this->MakeCurrent();
  198. // const char* code = "__ctkConsole.resetbuffer()\n";
  199. // PyRun_SimpleString(code);
  200. // //this->ReleaseControl();
  201. // }
  202. //}
  203. //----------------------------------------------------------------------------
  204. void ctkPythonConsolePrivate::printWelcomeMessage()
  205. {
  206. Q_Q(ctkPythonConsole);
  207. q->printMessage(
  208. QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()),
  209. q->welcomeTextColor());
  210. }
  211. //----------------------------------------------------------------------------
  212. // ctkPythonConsole methods
  213. //----------------------------------------------------------------------------
  214. ctkPythonConsole::ctkPythonConsole(QWidget* parentObject):
  215. Superclass(new ctkPythonConsolePrivate(*this), parentObject)
  216. {
  217. this->setObjectName("pythonConsole");
  218. // Disable RemoveTrailingSpaces and AutomaticIndentation
  219. this->setEditorHints(this->editorHints() ^ (RemoveTrailingSpaces | AutomaticIndentation));
  220. // Enable SplitCopiedTextByLine
  221. this->setEditorHints(this->editorHints() | SplitCopiedTextByLine);
  222. this->setDisabled(true);
  223. }
  224. //----------------------------------------------------------------------------
  225. ctkPythonConsole::~ctkPythonConsole()
  226. {
  227. }
  228. ////----------------------------------------------------------------------------
  229. void ctkPythonConsole::initialize(ctkAbstractPythonManager* newPythonManager)
  230. {
  231. Q_D(ctkPythonConsole);
  232. if (d->PythonManager)
  233. {
  234. qWarning() << "ctkPythonConsole already initialized !";
  235. return;
  236. }
  237. // The call to mainContext() ensures that python has been initialized.
  238. Q_ASSERT(newPythonManager);
  239. newPythonManager->mainContext();
  240. Q_ASSERT(PythonQt::self()); // PythonQt should be initialized
  241. ctkPythonConsoleCompleter* completer = new ctkPythonConsoleCompleter(*newPythonManager);
  242. this->setCompleter(completer);
  243. d->PythonManager = newPythonManager;
  244. d->initializeInteractiveConsole();
  245. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
  246. d, SLOT(printOutputMessage(const QString&)));
  247. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
  248. d, SLOT(printErrorMessage(const QString&)));
  249. // Set primary and secondary prompt
  250. this->setPs1(">>> ");
  251. this->setPs2("... ");
  252. this->reset();
  253. // Expose help() function
  254. QStringList helpImportCode;
  255. helpImportCode << "import pydoc";
  256. helpImportCode << "help = pydoc.help.help";
  257. helpImportCode << "del pydoc";
  258. d->PythonManager->executeString(helpImportCode.join("\n"));
  259. this->setDisabled(false);
  260. }
  261. ////----------------------------------------------------------------------------
  262. //void ctkPythonConsole::executeScript(const QString& script)
  263. //{
  264. // Q_D(ctkPythonConsole);
  265. // Q_UNUSED(script);
  266. // d->printOutputMessage("\n");
  267. // emit this->executing(true);
  268. //// d->Interpreter->RunSimpleString(
  269. //// script.toAscii().data());
  270. // emit this->executing(false);
  271. // d->promptForInput();
  272. //}
  273. //----------------------------------------------------------------------------
  274. QString ctkPythonConsole::ps1() const
  275. {
  276. PyObject * ps1 = PySys_GetObject(const_cast<char*>("ps1"));
  277. const char * ps1_str = PyString_AsString(ps1);
  278. return QLatin1String(ps1_str);
  279. }
  280. //----------------------------------------------------------------------------
  281. void ctkPythonConsole::setPs1(const QString& newPs1)
  282. {
  283. PySys_SetObject(const_cast<char*>("ps1"), PyString_FromString(newPs1.toAscii().data()));
  284. }
  285. //----------------------------------------------------------------------------
  286. QString ctkPythonConsole::ps2() const
  287. {
  288. PyObject * ps2 = PySys_GetObject(const_cast<char*>("ps2"));
  289. const char * ps2_str = PyString_AsString(ps2);
  290. return QLatin1String(ps2_str);
  291. }
  292. //----------------------------------------------------------------------------
  293. void ctkPythonConsole::setPs2(const QString& newPs2)
  294. {
  295. PySys_SetObject(const_cast<char*>("ps2"), PyString_FromString(newPs2.toAscii().data()));
  296. }
  297. //----------------------------------------------------------------------------
  298. void ctkPythonConsole::executeCommand(const QString& command)
  299. {
  300. Q_D(ctkPythonConsole);
  301. d->MultilineStatement = d->push(command);
  302. }
  303. //----------------------------------------------------------------------------
  304. void ctkPythonConsole::reset()
  305. {
  306. // Set primary and secondary prompt
  307. this->setPs1(">>> ");
  308. this->setPs2("... ");
  309. this->Superclass::reset();
  310. }