ctkPythonConsole.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. bool appendParenthesis = true;
  108. attrs = this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__"), appendParenthesis);
  109. attrs << this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__.__builtins__"),
  110. appendParenthesis);
  111. attrs.removeDuplicates();
  112. }
  113. // Initialize the completion model
  114. if (!attrs.isEmpty())
  115. {
  116. this->setCompletionMode(QCompleter::PopupCompletion);
  117. this->setModel(new QStringListModel(attrs, this));
  118. this->setCaseSensitivity(Qt::CaseInsensitive);
  119. this->setCompletionPrefix(compareText.toLower());
  120. //qDebug() << "completion" << completion;
  121. // If a dot as been entered and if an item of possible
  122. // choices matches one of the preference list, it will be selected.
  123. QModelIndex preferredIndex = this->completionModel()->index(0, 0);
  124. int dotCount = completion.count('.');
  125. if (dotCount == 0 || completion.at(completion.count() - 1) == '.')
  126. {
  127. foreach(const QString& pref, this->AutocompletePreferenceList)
  128. {
  129. //qDebug() << "pref" << pref;
  130. int dotPref = pref.count('.');
  131. // Skip if there are dots in pref and if the completion has already more dots
  132. // than the pref
  133. if ((dotPref != 0) && (dotCount > dotPref))
  134. {
  135. continue;
  136. }
  137. // Extract string before the last dot
  138. int lastDot = pref.lastIndexOf('.');
  139. QString prefBeforeLastDot;
  140. if (lastDot != -1)
  141. {
  142. prefBeforeLastDot = pref.left(lastDot);
  143. }
  144. //qDebug() << "prefBeforeLastDot" << prefBeforeLastDot;
  145. if (!prefBeforeLastDot.isEmpty() && QString::compare(prefBeforeLastDot, lookup) != 0)
  146. {
  147. continue;
  148. }
  149. QString prefAfterLastDot = pref;
  150. if (lastDot != -1 )
  151. {
  152. prefAfterLastDot = pref.right(pref.size() - lastDot - 1);
  153. }
  154. //qDebug() << "prefAfterLastDot" << prefAfterLastDot;
  155. QModelIndexList list = this->completionModel()->match(
  156. this->completionModel()->index(0, 0), Qt::DisplayRole, QVariant(prefAfterLastDot));
  157. if (list.count() > 0)
  158. {
  159. preferredIndex = list.first();
  160. break;
  161. }
  162. }
  163. }
  164. this->popup()->setCurrentIndex(preferredIndex);
  165. }
  166. }
  167. ctkAbstractPythonManager& PythonManager;
  168. };
  169. //----------------------------------------------------------------------------
  170. // ctkPythonConsolePrivate
  171. //----------------------------------------------------------------------------
  172. class ctkPythonConsolePrivate : public ctkConsolePrivate
  173. {
  174. Q_DECLARE_PUBLIC(ctkPythonConsole);
  175. public:
  176. ctkPythonConsolePrivate(ctkPythonConsole& object);
  177. ~ctkPythonConsolePrivate();
  178. void initializeInteractiveConsole();
  179. bool push(const QString& code);
  180. /// Reset the input buffer of the interactive console
  181. // void resetInputBuffer();
  182. void printWelcomeMessage();
  183. ctkAbstractPythonManager* PythonManager;
  184. PyObject* InteractiveConsole;
  185. };
  186. //----------------------------------------------------------------------------
  187. // ctkPythonConsolePrivate methods
  188. //----------------------------------------------------------------------------
  189. ctkPythonConsolePrivate::ctkPythonConsolePrivate(ctkPythonConsole& object)
  190. : ctkConsolePrivate(object), PythonManager(0), InteractiveConsole(0)
  191. {
  192. }
  193. //----------------------------------------------------------------------------
  194. ctkPythonConsolePrivate::~ctkPythonConsolePrivate()
  195. {
  196. }
  197. //----------------------------------------------------------------------------
  198. void ctkPythonConsolePrivate::initializeInteractiveConsole()
  199. {
  200. Q_ASSERT(this->PythonManager);
  201. // set up the code.InteractiveConsole instance that we'll use.
  202. const char* code =
  203. "import code\n"
  204. "__ctkConsole = code.InteractiveConsole(locals())\n";
  205. PyRun_SimpleString(code);
  206. // Now get the reference to __ctkConsole and save the pointer.
  207. PyObject* main_module = PyImport_AddModule("__main__");
  208. PyObject* global_dict = PyModule_GetDict(main_module);
  209. this->InteractiveConsole = PyDict_GetItemString(
  210. global_dict, "__ctkConsole");
  211. if (!this->InteractiveConsole)
  212. {
  213. qCritical("Failed to locate the InteractiveConsole object.");
  214. }
  215. }
  216. //----------------------------------------------------------------------------
  217. bool ctkPythonConsolePrivate::push(const QString& code)
  218. {
  219. Q_ASSERT(this->PythonManager);
  220. bool ret_value = false;
  221. QString buffer = code;
  222. // The embedded python interpreter cannot handle DOS line-endings, see
  223. // http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
  224. buffer.remove('\r');
  225. PyObject *res = PyObject_CallMethod(this->InteractiveConsole,
  226. const_cast<char*>("push"),
  227. const_cast<char*>("z"),
  228. buffer.toAscii().data());
  229. if (res)
  230. {
  231. int status = 0;
  232. if (PyArg_Parse(res, "i", &status))
  233. {
  234. ret_value = (status > 0);
  235. }
  236. Py_DECREF(res);
  237. }
  238. return ret_value;
  239. }
  240. ////----------------------------------------------------------------------------
  241. //void ctkPythonConsolePrivate::resetInputBuffer()
  242. //{
  243. // if (this->InteractiveConsole)
  244. // {
  245. // //this->MakeCurrent();
  246. // const char* code = "__ctkConsole.resetbuffer()\n";
  247. // PyRun_SimpleString(code);
  248. // //this->ReleaseControl();
  249. // }
  250. //}
  251. //----------------------------------------------------------------------------
  252. void ctkPythonConsolePrivate::printWelcomeMessage()
  253. {
  254. Q_Q(ctkPythonConsole);
  255. q->printMessage(
  256. QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()),
  257. q->welcomeTextColor());
  258. }
  259. //----------------------------------------------------------------------------
  260. // ctkPythonConsole methods
  261. //----------------------------------------------------------------------------
  262. ctkPythonConsole::ctkPythonConsole(QWidget* parentObject):
  263. Superclass(new ctkPythonConsolePrivate(*this), parentObject)
  264. {
  265. this->setObjectName("pythonConsole");
  266. // Disable RemoveTrailingSpaces and AutomaticIndentation
  267. this->setEditorHints(this->editorHints() ^ (RemoveTrailingSpaces | AutomaticIndentation));
  268. // Enable SplitCopiedTextByLine
  269. this->setEditorHints(this->editorHints() | SplitCopiedTextByLine);
  270. this->setDisabled(true);
  271. }
  272. //----------------------------------------------------------------------------
  273. ctkPythonConsole::~ctkPythonConsole()
  274. {
  275. }
  276. ////----------------------------------------------------------------------------
  277. void ctkPythonConsole::initialize(ctkAbstractPythonManager* newPythonManager)
  278. {
  279. Q_D(ctkPythonConsole);
  280. if (d->PythonManager)
  281. {
  282. qWarning() << "ctkPythonConsole already initialized !";
  283. return;
  284. }
  285. // The call to mainContext() ensures that python has been initialized.
  286. Q_ASSERT(newPythonManager);
  287. newPythonManager->mainContext();
  288. Q_ASSERT(PythonQt::self()); // PythonQt should be initialized
  289. ctkPythonConsoleCompleter* completer = new ctkPythonConsoleCompleter(*newPythonManager);
  290. this->setCompleter(completer);
  291. d->PythonManager = newPythonManager;
  292. d->initializeInteractiveConsole();
  293. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
  294. d, SLOT(printOutputMessage(const QString&)));
  295. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
  296. d, SLOT(printErrorMessage(const QString&)));
  297. PythonQt::self()->setRedirectStdInCallBack(
  298. ctkConsole::stdInRedirectCallBack, reinterpret_cast<void*>(this));
  299. // Set primary and secondary prompt
  300. this->setPs1(">>> ");
  301. this->setPs2("... ");
  302. this->reset();
  303. // Expose help() function
  304. QStringList helpImportCode;
  305. helpImportCode << "from pydoc import help";
  306. d->PythonManager->executeString(helpImportCode.join("\n"));
  307. this->setDisabled(false);
  308. }
  309. ////----------------------------------------------------------------------------
  310. //void ctkPythonConsole::executeScript(const QString& script)
  311. //{
  312. // Q_D(ctkPythonConsole);
  313. // Q_UNUSED(script);
  314. // d->printOutputMessage("\n");
  315. // emit this->executing(true);
  316. //// d->Interpreter->RunSimpleString(
  317. //// script.toAscii().data());
  318. // emit this->executing(false);
  319. // d->promptForInput();
  320. //}
  321. //----------------------------------------------------------------------------
  322. QString ctkPythonConsole::ps1() const
  323. {
  324. PyObject * ps1 = PySys_GetObject(const_cast<char*>("ps1"));
  325. const char * ps1_str = PyString_AsString(ps1);
  326. return QLatin1String(ps1_str);
  327. }
  328. //----------------------------------------------------------------------------
  329. void ctkPythonConsole::setPs1(const QString& newPs1)
  330. {
  331. PySys_SetObject(const_cast<char*>("ps1"), PyString_FromString(newPs1.toAscii().data()));
  332. }
  333. //----------------------------------------------------------------------------
  334. QString ctkPythonConsole::ps2() const
  335. {
  336. PyObject * ps2 = PySys_GetObject(const_cast<char*>("ps2"));
  337. const char * ps2_str = PyString_AsString(ps2);
  338. return QLatin1String(ps2_str);
  339. }
  340. //----------------------------------------------------------------------------
  341. void ctkPythonConsole::setPs2(const QString& newPs2)
  342. {
  343. PySys_SetObject(const_cast<char*>("ps2"), PyString_FromString(newPs2.toAscii().data()));
  344. }
  345. //----------------------------------------------------------------------------
  346. void ctkPythonConsole::executeCommand(const QString& command)
  347. {
  348. Q_D(ctkPythonConsole);
  349. d->MultilineStatement = d->push(command);
  350. }
  351. //----------------------------------------------------------------------------
  352. void ctkPythonConsole::reset()
  353. {
  354. // Set primary and secondary prompt
  355. this->setPs1(">>> ");
  356. this->setPs2("... ");
  357. this->Superclass::reset();
  358. }