ctkPythonConsole.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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.apache.org/licenses/LICENSE-2.0.txt
  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. Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
  17. All rights reserved.
  18. ParaView is a free software; you can redistribute it and/or modify it
  19. under the terms of the ParaView license version 1.2.
  20. See http://www.paraview.org/paraview/project/license.html for the full ParaView license.
  21. A copy of this license can be obtained by contacting
  22. Kitware Inc.
  23. 28 Corporate Drive
  24. Clifton Park, NY 12065
  25. USA
  26. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  27. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  28. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  29. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
  30. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  31. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  32. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  33. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  34. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  35. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  36. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. =========================================================================*/
  38. // Qt includes
  39. #include <QCoreApplication>
  40. #include <QResizeEvent>
  41. #include <QScrollBar>
  42. #include <QStringListModel>
  43. #include <QTextCharFormat>
  44. #include <QVBoxLayout>
  45. // PythonQt includes
  46. #include <PythonQt.h>
  47. #include <PythonQtObjectPtr.h>
  48. // CTK includes
  49. #include <ctkConsole.h>
  50. #include <ctkConsole_p.h>
  51. #include <ctkAbstractPythonManager.h>
  52. #include "ctkPythonConsole.h"
  53. #ifdef __GNUC__
  54. // Disable warnings related to Python macros and functions
  55. // See http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
  56. // Note: Ideally the incriminated functions and macros should be fixed upstream ...
  57. #pragma GCC diagnostic ignored "-Wold-style-cast"
  58. #endif
  59. //----------------------------------------------------------------------------
  60. // ctkPythonConsoleCompleter
  61. //----------------------------------------------------------------------------
  62. class ctkPythonConsoleCompleter : public ctkConsoleCompleter
  63. {
  64. public:
  65. ctkPythonConsoleCompleter(ctkAbstractPythonManager& pythonManager)
  66. : PythonManager(pythonManager)
  67. {
  68. this->setParent(&pythonManager);
  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. bool appendParenthesis = true;
  107. attrs = this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__"), appendParenthesis);
  108. attrs << this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__.__builtins__"),
  109. appendParenthesis);
  110. attrs.removeDuplicates();
  111. }
  112. // Initialize the completion model
  113. if (!attrs.isEmpty())
  114. {
  115. this->setCompletionMode(QCompleter::PopupCompletion);
  116. this->setModel(new QStringListModel(attrs, this));
  117. this->setCaseSensitivity(Qt::CaseInsensitive);
  118. this->setCompletionPrefix(compareText.toLower());
  119. //qDebug() << "completion" << completion;
  120. // If a dot as been entered and if an item of possible
  121. // choices matches one of the preference list, it will be selected.
  122. QModelIndex preferredIndex = this->completionModel()->index(0, 0);
  123. int dotCount = completion.count('.');
  124. if (dotCount == 0 || completion.at(completion.count() - 1) == '.')
  125. {
  126. foreach(const QString& pref, this->AutocompletePreferenceList)
  127. {
  128. //qDebug() << "pref" << pref;
  129. int dotPref = pref.count('.');
  130. // Skip if there are dots in pref and if the completion has already more dots
  131. // than the pref
  132. if ((dotPref != 0) && (dotCount > dotPref))
  133. {
  134. continue;
  135. }
  136. // Extract string before the last dot
  137. int lastDot = pref.lastIndexOf('.');
  138. QString prefBeforeLastDot;
  139. if (lastDot != -1)
  140. {
  141. prefBeforeLastDot = pref.left(lastDot);
  142. }
  143. //qDebug() << "prefBeforeLastDot" << prefBeforeLastDot;
  144. if (!prefBeforeLastDot.isEmpty() && QString::compare(prefBeforeLastDot, lookup) != 0)
  145. {
  146. continue;
  147. }
  148. QString prefAfterLastDot = pref;
  149. if (lastDot != -1 )
  150. {
  151. prefAfterLastDot = pref.right(pref.size() - lastDot - 1);
  152. }
  153. //qDebug() << "prefAfterLastDot" << prefAfterLastDot;
  154. QModelIndexList list = this->completionModel()->match(
  155. this->completionModel()->index(0, 0), Qt::DisplayRole, QVariant(prefAfterLastDot));
  156. if (list.count() > 0)
  157. {
  158. preferredIndex = list.first();
  159. break;
  160. }
  161. }
  162. }
  163. this->popup()->setCurrentIndex(preferredIndex);
  164. }
  165. }
  166. ctkAbstractPythonManager& PythonManager;
  167. };
  168. //----------------------------------------------------------------------------
  169. // ctkPythonConsolePrivate
  170. //----------------------------------------------------------------------------
  171. class ctkPythonConsolePrivate : public ctkConsolePrivate
  172. {
  173. Q_DECLARE_PUBLIC(ctkPythonConsole);
  174. public:
  175. ctkPythonConsolePrivate(ctkPythonConsole& object);
  176. ~ctkPythonConsolePrivate();
  177. void initializeInteractiveConsole();
  178. bool push(const QString& code);
  179. /// Reset the input buffer of the interactive console
  180. // void resetInputBuffer();
  181. void printWelcomeMessage();
  182. ctkAbstractPythonManager* PythonManager;
  183. PyObject* InteractiveConsole;
  184. };
  185. //----------------------------------------------------------------------------
  186. // ctkPythonConsolePrivate methods
  187. //----------------------------------------------------------------------------
  188. ctkPythonConsolePrivate::ctkPythonConsolePrivate(ctkPythonConsole& object)
  189. : ctkConsolePrivate(object), PythonManager(0), InteractiveConsole(0)
  190. {
  191. }
  192. //----------------------------------------------------------------------------
  193. ctkPythonConsolePrivate::~ctkPythonConsolePrivate()
  194. {
  195. }
  196. //----------------------------------------------------------------------------
  197. void ctkPythonConsolePrivate::initializeInteractiveConsole()
  198. {
  199. Q_ASSERT(this->PythonManager);
  200. // set up the code.InteractiveConsole instance that we'll use.
  201. const char* code =
  202. "import code\n"
  203. "__ctkConsole = code.InteractiveConsole(locals())\n";
  204. PyRun_SimpleString(code);
  205. // Now get the reference to __ctkConsole and save the pointer.
  206. PyObject* main_module = PyImport_AddModule("__main__");
  207. PyObject* global_dict = PyModule_GetDict(main_module);
  208. this->InteractiveConsole = PyDict_GetItemString(
  209. global_dict, "__ctkConsole");
  210. if (!this->InteractiveConsole)
  211. {
  212. qCritical("Failed to locate the InteractiveConsole object.");
  213. }
  214. }
  215. //----------------------------------------------------------------------------
  216. bool ctkPythonConsolePrivate::push(const QString& code)
  217. {
  218. Q_ASSERT(this->PythonManager);
  219. bool ret_value = false;
  220. QString buffer = code;
  221. // The embedded python interpreter cannot handle DOS line-endings, see
  222. // http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
  223. buffer.remove('\r');
  224. PyObject *res = PyObject_CallMethod(this->InteractiveConsole,
  225. const_cast<char*>("push"),
  226. const_cast<char*>("z"),
  227. buffer.toAscii().data());
  228. if (res)
  229. {
  230. int status = 0;
  231. if (PyArg_Parse(res, "i", &status))
  232. {
  233. ret_value = (status > 0);
  234. }
  235. Py_DECREF(res);
  236. }
  237. return ret_value;
  238. }
  239. ////----------------------------------------------------------------------------
  240. //void ctkPythonConsolePrivate::resetInputBuffer()
  241. //{
  242. // if (this->InteractiveConsole)
  243. // {
  244. // //this->MakeCurrent();
  245. // const char* code = "__ctkConsole.resetbuffer()\n";
  246. // PyRun_SimpleString(code);
  247. // //this->ReleaseControl();
  248. // }
  249. //}
  250. //----------------------------------------------------------------------------
  251. void ctkPythonConsolePrivate::printWelcomeMessage()
  252. {
  253. Q_Q(ctkPythonConsole);
  254. q->printMessage(
  255. QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()),
  256. q->welcomeTextColor());
  257. }
  258. //----------------------------------------------------------------------------
  259. // ctkPythonConsole methods
  260. //----------------------------------------------------------------------------
  261. ctkPythonConsole::ctkPythonConsole(QWidget* parentObject):
  262. Superclass(new ctkPythonConsolePrivate(*this), parentObject)
  263. {
  264. this->setObjectName("pythonConsole");
  265. // Disable RemoveTrailingSpaces and AutomaticIndentation
  266. this->setEditorHints(this->editorHints() ^ (RemoveTrailingSpaces | AutomaticIndentation));
  267. // Enable SplitCopiedTextByLine
  268. this->setEditorHints(this->editorHints() | SplitCopiedTextByLine);
  269. this->setDisabled(true);
  270. }
  271. //----------------------------------------------------------------------------
  272. ctkPythonConsole::~ctkPythonConsole()
  273. {
  274. }
  275. ////----------------------------------------------------------------------------
  276. void ctkPythonConsole::initialize(ctkAbstractPythonManager* newPythonManager)
  277. {
  278. Q_D(ctkPythonConsole);
  279. if (d->PythonManager)
  280. {
  281. qWarning() << "ctkPythonConsole already initialized !";
  282. return;
  283. }
  284. // The call to mainContext() ensures that python has been initialized.
  285. Q_ASSERT(newPythonManager);
  286. newPythonManager->mainContext();
  287. Q_ASSERT(PythonQt::self()); // PythonQt should be initialized
  288. ctkPythonConsoleCompleter* completer = new ctkPythonConsoleCompleter(*newPythonManager);
  289. this->setCompleter(completer);
  290. d->PythonManager = newPythonManager;
  291. d->initializeInteractiveConsole();
  292. this->connect(PythonQt::self(), SIGNAL(pythonStdOut(QString)),
  293. d, SLOT(printOutputMessage(QString)));
  294. this->connect(PythonQt::self(), SIGNAL(pythonStdErr(QString)),
  295. d, SLOT(printErrorMessage(QString)));
  296. PythonQt::self()->setRedirectStdInCallBack(
  297. ctkConsole::stdInRedirectCallBack, reinterpret_cast<void*>(this));
  298. // Set primary and secondary prompt
  299. this->setPs1(">>> ");
  300. this->setPs2("... ");
  301. this->reset();
  302. // Expose help() function
  303. QStringList helpImportCode;
  304. helpImportCode << "from pydoc import help";
  305. d->PythonManager->executeString(helpImportCode.join("\n"));
  306. this->setDisabled(false);
  307. }
  308. ////----------------------------------------------------------------------------
  309. //void ctkPythonConsole::executeScript(const QString& script)
  310. //{
  311. // Q_D(ctkPythonConsole);
  312. // Q_UNUSED(script);
  313. // d->printOutputMessage("\n");
  314. // emit this->executing(true);
  315. //// d->Interpreter->RunSimpleString(
  316. //// script.toAscii().data());
  317. // emit this->executing(false);
  318. // d->promptForInput();
  319. //}
  320. //----------------------------------------------------------------------------
  321. QString ctkPythonConsole::ps1() const
  322. {
  323. PyObject * ps1 = PySys_GetObject(const_cast<char*>("ps1"));
  324. const char * ps1_str = PyString_AsString(ps1);
  325. return QLatin1String(ps1_str);
  326. }
  327. //----------------------------------------------------------------------------
  328. void ctkPythonConsole::setPs1(const QString& newPs1)
  329. {
  330. PySys_SetObject(const_cast<char*>("ps1"), PyString_FromString(newPs1.toAscii().data()));
  331. }
  332. //----------------------------------------------------------------------------
  333. QString ctkPythonConsole::ps2() const
  334. {
  335. PyObject * ps2 = PySys_GetObject(const_cast<char*>("ps2"));
  336. const char * ps2_str = PyString_AsString(ps2);
  337. return QLatin1String(ps2_str);
  338. }
  339. //----------------------------------------------------------------------------
  340. void ctkPythonConsole::setPs2(const QString& newPs2)
  341. {
  342. PySys_SetObject(const_cast<char*>("ps2"), PyString_FromString(newPs2.toAscii().data()));
  343. }
  344. //----------------------------------------------------------------------------
  345. void ctkPythonConsole::executeCommand(const QString& command)
  346. {
  347. Q_D(ctkPythonConsole);
  348. d->MultilineStatement = d->push(command);
  349. }
  350. //----------------------------------------------------------------------------
  351. void ctkPythonConsole::reset()
  352. {
  353. // Set primary and secondary prompt
  354. this->setPs1(">>> ");
  355. this->setPs2("... ");
  356. this->Superclass::reset();
  357. }