ctkConsole.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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 <QAbstractItemView>
  40. #include <QAction>
  41. #include <QApplication>
  42. #include <QClipboard>
  43. #include <QCompleter>
  44. #include <QFile>
  45. #include <QFileDialog>
  46. #include <QKeyEvent>
  47. #include <QMimeData>
  48. #include <QPointer>
  49. #include <QPushButton>
  50. #include <QTextBlock>
  51. #include <QTextCursor>
  52. #include <QVBoxLayout>
  53. #include <QScrollBar>
  54. #include <QDebug>
  55. // CTK includes
  56. #include "ctkConsole.h"
  57. #include "ctkConsole_p.h"
  58. #include "ctkPimpl.h"
  59. //-----------------------------------------------------------------------------
  60. // ctkConsoleCompleter methods
  61. //-----------------------------------------------------------------------------
  62. QStringList ctkConsoleCompleter::autocompletePreferenceList()
  63. {
  64. return this->AutocompletePreferenceList;
  65. }
  66. //-----------------------------------------------------------------------------
  67. void ctkConsoleCompleter::setAutocompletePreferenceList(const QStringList& list)
  68. {
  69. this->AutocompletePreferenceList = list;
  70. }
  71. //-----------------------------------------------------------------------------
  72. // ctkConsolePrivate methods
  73. //-----------------------------------------------------------------------------
  74. ctkConsolePrivate::ctkConsolePrivate(ctkConsole& object) :
  75. Superclass(0),
  76. q_ptr(&object),
  77. InteractivePosition(documentEnd()),
  78. MessageOutputSize(0),
  79. MultilineStatement(false), Ps1("$ "), Ps2("> "),
  80. EditorHints(ctkConsole::AutomaticIndentation | ctkConsole::RemoveTrailingSpaces),
  81. ScrollbarAtBottom(false),
  82. CompleterShortcuts(QList<QKeySequence>() << Qt::Key_Tab),
  83. RunFileOptions(ctkConsole::RunFileShortcut),
  84. RunFileButton(NULL),
  85. RunFileAction(NULL)
  86. {
  87. }
  88. //-----------------------------------------------------------------------------
  89. void ctkConsolePrivate::init()
  90. {
  91. Q_Q(ctkConsole);
  92. this->setParent(q);
  93. this->setTabChangesFocus(false);
  94. this->setAcceptDrops(false);
  95. this->setAcceptRichText(false);
  96. this->setUndoRedoEnabled(false);
  97. this->PromptColor = QColor(0, 0, 0); // Black
  98. this->OutputTextColor = QColor(0, 150, 0); // Green
  99. this->MessageOutputColor = QColor(Qt::gray); // Gray
  100. this->ErrorTextColor = QColor(255, 0, 0); // Red
  101. this->StdinTextColor = QColor(Qt::darkGray);
  102. this->CommandTextColor = QColor(0, 0, 150); // Blue
  103. this->WelcomeTextColor = QColor(0, 0, 255); // Dark Blue
  104. QFont shellFont;
  105. shellFont.setFamily("Courier");
  106. shellFont.setStyleHint(QFont::TypeWriter);
  107. shellFont.setFixedPitch(true);
  108. QTextCharFormat format;
  109. format.setFont(shellFont);
  110. format.setForeground(this->OutputTextColor);
  111. this->setCurrentCharFormat(format);
  112. this->CommandHistory.append("");
  113. this->CommandPosition = 0;
  114. this->RunFileAction = new QAction(q->tr("&Run file"), q);
  115. this->RunFileAction->setShortcut(q->tr("Ctrl+r"));
  116. connect(this->RunFileAction, SIGNAL(triggered()), q, SLOT(runFile()));
  117. q->addAction(this->RunFileAction);
  118. QAction* printHelpAction = new QAction(q->tr("Print &help"),q);
  119. printHelpAction->setShortcut(q->tr("Ctrl+h"));
  120. connect(printHelpAction, SIGNAL(triggered()), q, SLOT(printHelp()));
  121. q->addAction(printHelpAction);
  122. this->RunFileButton = new QPushButton(q);
  123. this->RunFileButton->setText(q->tr("&Run script from file"));
  124. this->RunFileButton->setVisible(false);
  125. QVBoxLayout * layout = new QVBoxLayout(q);
  126. layout->setMargin(0);
  127. layout->setSpacing(0);
  128. layout->addWidget(this);
  129. layout->addWidget(this->RunFileButton);
  130. connect(this->verticalScrollBar(), SIGNAL(valueChanged(int)),
  131. SLOT(onScrollBarValueChanged(int)));
  132. connect(this, SIGNAL(textChanged()), SLOT(onTextChanged()));
  133. connect(this->RunFileButton, SIGNAL(clicked()), q, SLOT(runFile()));
  134. connect(this, SIGNAL(cursorPositionChanged()),
  135. q, SIGNAL(cursorPositionChanged()));
  136. }
  137. //-----------------------------------------------------------------------------
  138. bool ctkConsolePrivate::isMoveLeftWithinLine(QKeyEvent* e, QTextCursor::MoveOperation &moveOperation, QTextCursor::MoveMode &moveMode)
  139. {
  140. if (e == QKeySequence::MoveToPreviousChar)
  141. {
  142. moveOperation = QTextCursor::Left;
  143. moveMode = QTextCursor::MoveAnchor;
  144. return true;
  145. }
  146. else if (e == QKeySequence::SelectPreviousChar)
  147. {
  148. moveOperation = QTextCursor::Left;
  149. moveMode = QTextCursor::KeepAnchor;
  150. return true;
  151. }
  152. else if (e == QKeySequence::MoveToPreviousWord)
  153. {
  154. moveOperation = QTextCursor::WordLeft;
  155. moveMode = QTextCursor::MoveAnchor;
  156. return true;
  157. }
  158. else if (e == QKeySequence::SelectPreviousWord)
  159. {
  160. moveOperation = QTextCursor::WordLeft;
  161. moveMode = QTextCursor::KeepAnchor;
  162. return true;
  163. }
  164. else if (e == QKeySequence::MoveToStartOfLine)
  165. {
  166. moveOperation = QTextCursor::StartOfLine;
  167. moveMode = QTextCursor::MoveAnchor;
  168. return true;
  169. }
  170. else if (e == QKeySequence::SelectStartOfLine)
  171. {
  172. moveOperation = QTextCursor::StartOfLine;
  173. moveMode = QTextCursor::KeepAnchor;
  174. return true;
  175. }
  176. else if (e == QKeySequence::MoveToStartOfBlock)
  177. {
  178. moveOperation = QTextCursor::StartOfLine;
  179. moveMode = QTextCursor::MoveAnchor;
  180. return true;
  181. }
  182. else if (e == QKeySequence::SelectStartOfBlock)
  183. {
  184. moveOperation = QTextCursor::StartOfLine;
  185. moveMode = QTextCursor::KeepAnchor;
  186. return true;
  187. }
  188. else if (e == QKeySequence::MoveToStartOfDocument)
  189. {
  190. moveOperation = QTextCursor::StartOfLine;
  191. moveMode = QTextCursor::MoveAnchor;
  192. return true;
  193. }
  194. else if (e == QKeySequence::SelectStartOfDocument)
  195. {
  196. moveOperation = QTextCursor::StartOfLine;
  197. moveMode = QTextCursor::KeepAnchor;
  198. return true;
  199. }
  200. else
  201. {
  202. return false;
  203. }
  204. }
  205. //-----------------------------------------------------------------------------
  206. bool ctkConsolePrivate::isMoveRighttWithinLine(QKeyEvent* e, QTextCursor::MoveOperation &moveOperation, QTextCursor::MoveMode &moveMode)
  207. {
  208. if (e == QKeySequence::MoveToNextChar)
  209. {
  210. moveOperation = QTextCursor::Right;
  211. moveMode = QTextCursor::MoveAnchor;
  212. return true;
  213. }
  214. else if (e == QKeySequence::SelectNextChar)
  215. {
  216. moveOperation = QTextCursor::Right;
  217. moveMode = QTextCursor::KeepAnchor;
  218. return true;
  219. }
  220. else if (e == QKeySequence::MoveToNextWord)
  221. {
  222. moveOperation = QTextCursor::WordRight;
  223. moveMode = QTextCursor::MoveAnchor;
  224. return true;
  225. }
  226. else if (e == QKeySequence::SelectNextWord)
  227. {
  228. moveOperation = QTextCursor::WordRight;
  229. moveMode = QTextCursor::KeepAnchor;
  230. return true;
  231. }
  232. else if (e == QKeySequence::MoveToEndOfLine)
  233. {
  234. moveOperation = QTextCursor::EndOfLine;
  235. moveMode = QTextCursor::MoveAnchor;
  236. return true;
  237. }
  238. else if (e == QKeySequence::SelectEndOfLine)
  239. {
  240. moveOperation = QTextCursor::EndOfLine;
  241. moveMode = QTextCursor::KeepAnchor;
  242. return true;
  243. }
  244. else if (e == QKeySequence::MoveToEndOfBlock)
  245. {
  246. moveOperation = QTextCursor::EndOfLine;
  247. moveMode = QTextCursor::MoveAnchor;
  248. return true;
  249. }
  250. else if (e == QKeySequence::SelectEndOfBlock)
  251. {
  252. moveOperation = QTextCursor::EndOfLine;
  253. moveMode = QTextCursor::KeepAnchor;
  254. return true;
  255. }
  256. else if (e == QKeySequence::MoveToEndOfDocument)
  257. {
  258. moveOperation = QTextCursor::EndOfLine;
  259. moveMode = QTextCursor::MoveAnchor;
  260. return true;
  261. }
  262. else if (e == QKeySequence::SelectEndOfDocument)
  263. {
  264. moveOperation = QTextCursor::EndOfLine;
  265. moveMode = QTextCursor::KeepAnchor;
  266. return true;
  267. }
  268. else
  269. {
  270. return false;
  271. }
  272. }
  273. //-----------------------------------------------------------------------------
  274. void ctkConsolePrivate::keyPressEvent(QKeyEvent* e)
  275. {
  276. if (this->Completer && this->Completer->popup()->isVisible())
  277. {
  278. // The following keys are forwarded by the completer to the widget
  279. switch (e->key())
  280. {
  281. case Qt::Key_Enter:
  282. case Qt::Key_Return:
  283. case Qt::Key_Escape:
  284. case Qt::Key_Tab:
  285. case Qt::Key_Backtab:
  286. e->ignore();
  287. return; // let the completer do default behavior
  288. default:
  289. break;
  290. }
  291. }
  292. QTextCursor text_cursor = this->textCursor();
  293. // Set to true if there's a current selection
  294. const bool selection = text_cursor.anchor() != text_cursor.position();
  295. // Set to true if the cursor overlaps the history area
  296. const bool history_area = this->isCursorInHistoryArea();
  297. // The message output area is defined just under the command line
  298. // and it can display all messages catch during we autocomplete, etc.
  299. // Set to true if the cursor overlaps the message output area
  300. const bool message_output_area = this->isCursorInMessageOutputArea();
  301. // Allow copying anywhere in the console ...
  302. if(e == QKeySequence::Copy)
  303. {
  304. if(selection)
  305. {
  306. this->copy();
  307. }
  308. e->accept();
  309. return;
  310. }
  311. // Allow cut only if the selection is limited to the interactive area ...
  312. if(e == QKeySequence::Cut)
  313. {
  314. if(selection && !history_area && !message_output_area)
  315. {
  316. this->cut();
  317. }
  318. e->accept();
  319. return;
  320. }
  321. // Paste to the end of commandLine if in the history area or in message output area
  322. if(e == QKeySequence::Paste)
  323. {
  324. if(history_area || message_output_area)
  325. {
  326. text_cursor.setPosition(this->commandEnd());
  327. this->setTextCursor(text_cursor);
  328. }
  329. this->paste();
  330. e->accept();
  331. return;
  332. }
  333. // Allow vertical scrolling using page up/down
  334. if (e == QKeySequence::MoveToPreviousPage || e == QKeySequence::SelectPreviousPage
  335. || e == QKeySequence::MoveToNextPage || e == QKeySequence::SelectNextPage)
  336. {
  337. if (e == QKeySequence::SelectPreviousPage || e == QKeySequence::SelectNextPage)
  338. {
  339. // ignore
  340. e->accept();
  341. }
  342. else
  343. {
  344. this->Superclass::keyPressEvent(e);
  345. this->updateCommandBuffer();
  346. }
  347. return;
  348. }
  349. // Force the cursor back to the interactive area if anything else than copy/paste or page up/down is done
  350. // but only when a "real" key is pressed, not just a modifier (otherwise we could not press Control-c in the
  351. // history area because the cursor would jump to the interactive area immediately when Control is pressed)
  352. // Update: message_output_area is like the history_area: we can't modify it
  353. if( (history_area
  354. || message_output_area)
  355. && e->key() != Qt::Key_Control
  356. && e->key() != Qt::Key_Meta
  357. && e->key() != Qt::Key_Alt
  358. && e->key() != Qt::Key_Shift)
  359. {
  360. text_cursor.setPosition(this->commandEnd());
  361. this->setTextCursor(text_cursor);
  362. }
  363. // Start of line should be the start of interactive area
  364. QTextCursor::MoveOperation moveOperation = QTextCursor::NoMove;
  365. QTextCursor::MoveMode moveMode = QTextCursor::MoveAnchor;
  366. if(isMoveLeftWithinLine(e, moveOperation, moveMode))
  367. {
  368. text_cursor.movePosition(moveOperation, moveMode);
  369. if (text_cursor.position() >= this->InteractivePosition)
  370. {
  371. this->Superclass::keyPressEvent(e);
  372. }
  373. else
  374. {
  375. text_cursor.setPosition(this->InteractivePosition, moveMode);
  376. this->setTextCursor(text_cursor);
  377. e->accept();
  378. }
  379. this->updateCompleterIfVisible();
  380. return;
  381. }
  382. // End of line should be the end of interactive area
  383. moveOperation = QTextCursor::NoMove;
  384. moveMode = QTextCursor::MoveAnchor;
  385. if(isMoveRighttWithinLine(e, moveOperation, moveMode))
  386. {
  387. text_cursor.movePosition(moveOperation, moveMode);
  388. if (text_cursor.position() <= this->commandEnd())
  389. {
  390. this->Superclass::keyPressEvent(e);
  391. }
  392. else
  393. {
  394. text_cursor.setPosition(this->commandEnd(), moveMode);
  395. this->setTextCursor(text_cursor);
  396. e->accept();
  397. }
  398. this->updateCompleterIfVisible();
  399. return;
  400. }
  401. if (e == QKeySequence::Delete)
  402. {
  403. e->accept();
  404. // Can delete only if we are not at the end of the command line.
  405. // There is an exception if something (in the interactive area only) is selected,
  406. // because it will erase the text selected instead.
  407. if (text_cursor.position() < this->commandEnd()
  408. || (text_cursor.position() <= this->commandEnd()
  409. && selection && !message_output_area && !history_area))
  410. {
  411. this->Superclass::keyPressEvent(e);
  412. this->updateCommandBuffer();
  413. }
  414. return;
  415. }
  416. // There seems to be no QKeySequence for backspace, therefore the key
  417. // has to be recognized directly (the same way as it is done in the parent class)
  418. if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~Qt::ShiftModifier))
  419. {
  420. e->accept();
  421. // Can delete with backspace only if the cursor is after the InteractivePosition.
  422. // There is an exception if something (in the interactive area only) is selected,
  423. // because it will erase the text selected instead.
  424. if (text_cursor.position() > this->InteractivePosition
  425. || (text_cursor.position() >= this->InteractivePosition
  426. && selection && !message_output_area && !history_area))
  427. {
  428. this->Superclass::keyPressEvent(e);
  429. this->updateCommandBuffer();
  430. this->updateCompleterIfVisible();
  431. }
  432. return;
  433. }
  434. if (e == QKeySequence::DeleteStartOfWord)
  435. {
  436. e->accept();
  437. if (text_cursor.position() > this->InteractivePosition)
  438. {
  439. this->Superclass::keyPressEvent(e);
  440. this->updateCommandBuffer();
  441. this->updateCompleterIfVisible();
  442. }
  443. return;
  444. }
  445. if (e == QKeySequence::MoveToPreviousLine || e == QKeySequence::SelectPreviousLine)
  446. {
  447. e->accept();
  448. if (this->CommandPosition > 0)
  449. {
  450. this->replaceCommandBuffer(this->CommandHistory[--this->CommandPosition]);
  451. }
  452. return;
  453. }
  454. if (e == QKeySequence::MoveToNextLine || e == QKeySequence::SelectNextLine)
  455. {
  456. e->accept();
  457. if (this->CommandPosition < this->CommandHistory.size() - 2)
  458. {
  459. this->replaceCommandBuffer(this->CommandHistory[++this->CommandPosition]);
  460. }
  461. else
  462. {
  463. this->CommandPosition = this->CommandHistory.size()-1;
  464. this->replaceCommandBuffer("");
  465. }
  466. return;
  467. }
  468. if (e == QKeySequence::InsertParagraphSeparator)
  469. {
  470. e->accept();
  471. text_cursor.setPosition(this->documentEnd());
  472. this->setTextCursor(text_cursor);
  473. if (this->InputEventLoop.isNull())
  474. {
  475. this->internalExecuteCommand();
  476. }
  477. else
  478. {
  479. this->processInput();
  480. }
  481. return;
  482. }
  483. if (this->CompleterShortcuts.contains(e->key() + e->modifiers()))
  484. {
  485. e->accept();
  486. this->updateCompleter();
  487. this->selectCompletion();
  488. return;
  489. }
  490. e->accept();
  491. this->switchToUserInputTextColor();
  492. this->Superclass::keyPressEvent(e);
  493. this->updateCommandBuffer();
  494. this->updateCompleterIfVisible();
  495. }
  496. //-----------------------------------------------------------------------------
  497. void ctkConsolePrivate::switchToUserInputTextColor(QTextCursor* textCursorToUpdate)
  498. {
  499. QColor color = this->CommandTextColor;
  500. if (!this->InputEventLoop.isNull())
  501. {
  502. color = this->StdinTextColor;
  503. }
  504. QTextCharFormat currentFormat = this->currentCharFormat();
  505. // Do not trigger a finishEdit for no reason. onTextChanged() would be called.
  506. if (currentFormat.foreground() != color)
  507. {
  508. currentFormat.setForeground(color);
  509. this->setCurrentCharFormat(currentFormat);
  510. }
  511. if (textCursorToUpdate)
  512. {
  513. QTextCharFormat textCursorFormat = textCursorToUpdate->charFormat();
  514. if (textCursorFormat.foreground() != color)
  515. {
  516. textCursorFormat.setForeground(color);
  517. textCursorToUpdate->setCharFormat(textCursorFormat);
  518. }
  519. }
  520. }
  521. //-----------------------------------------------------------------------------
  522. int ctkConsolePrivate::documentEnd() const
  523. {
  524. QTextCursor c(this->document());
  525. c.movePosition(QTextCursor::End);
  526. return c.position();
  527. }
  528. //-----------------------------------------------------------------------------
  529. int ctkConsolePrivate::commandEnd() const
  530. {
  531. QTextCursor c(this->document());
  532. c.setPosition(this->documentEnd()-this->MessageOutputSize);
  533. return c.position();
  534. }
  535. //-----------------------------------------------------------------------------
  536. void ctkConsolePrivate::focusOutEvent(QFocusEvent *e)
  537. {
  538. this->Superclass::focusOutEvent(e);
  539. // For some reason the QCompleter tries to set the focus policy to
  540. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  541. this->setFocusPolicy(Qt::WheelFocus);
  542. }
  543. //-----------------------------------------------------------------------------
  544. void ctkConsolePrivate::resizeEvent(QResizeEvent * e)
  545. {
  546. this->Superclass::resizeEvent(e);
  547. if (this->ScrollbarAtBottom)
  548. {
  549. this->moveCursor(QTextCursor::End);
  550. this->scrollToBottom();
  551. }
  552. }
  553. //-----------------------------------------------------------------------------
  554. void ctkConsolePrivate::scrollToBottom()
  555. {
  556. this->verticalScrollBar()->setValue(this->verticalScrollBar()->maximum());
  557. }
  558. //-----------------------------------------------------------------------------
  559. void ctkConsolePrivate::updateCompleterIfVisible()
  560. {
  561. if (this->Completer && this->Completer->popup()->isVisible())
  562. {
  563. this->updateCompleter();
  564. }
  565. }
  566. //-----------------------------------------------------------------------------
  567. void ctkConsolePrivate::selectCompletion()
  568. {
  569. if (this->Completer && this->Completer->completionCount() == 1)
  570. {
  571. this->insertCompletion(this->Completer->currentCompletion());
  572. this->Completer->popup()->hide();
  573. }
  574. }
  575. //-----------------------------------------------------------------------------
  576. void ctkConsolePrivate::setCompleter(ctkConsoleCompleter* completer)
  577. {
  578. if (this->Completer)
  579. {
  580. this->Completer->setWidget(0);
  581. disconnect(this->Completer, SIGNAL(activated(QString)),
  582. this, SLOT(insertCompletion(QString)));
  583. }
  584. this->Completer = completer;
  585. if (this->Completer)
  586. {
  587. this->Completer->setWidget(this);
  588. connect(this->Completer, SIGNAL(activated(QString)),
  589. this, SLOT(insertCompletion(QString)));
  590. }
  591. }
  592. //-----------------------------------------------------------------------------
  593. void ctkConsolePrivate::updateCompleter()
  594. {
  595. if (this->Completer)
  596. {
  597. // Get the text between the current cursor position
  598. // and the start of the line
  599. QTextCursor text_cursor = this->textCursor();
  600. text_cursor.setPosition(this->InteractivePosition, QTextCursor::KeepAnchor);
  601. QString commandText = text_cursor.selectedText();
  602. // Save current positions: Since some implementation of
  603. // updateCompletionModel (e.g python) can display messages
  604. // while building the completion model, it is important to save
  605. // and restore the positions.
  606. int savedInteractivePosition = this->InteractivePosition;
  607. int savedCursorPosition = this->textCursor().position();
  608. //move the cursor at the end in case of a message displayed
  609. QTextCursor tc = this->textCursor();
  610. tc.setPosition(this->documentEnd());
  611. this->setTextCursor(tc);
  612. // Save color of displayed message
  613. QColor savedOutputTextColor = this->OutputTextColor;
  614. QColor savedErrorTextColor = this->ErrorTextColor;
  615. // Change color of displayed message in message_output_area
  616. this->OutputTextColor = this->MessageOutputColor;
  617. this->ErrorTextColor = this->MessageOutputColor;
  618. // Call the completer to update the completion model
  619. this->Completer->updateCompletionModel(commandText);
  620. // Restore Color
  621. this->OutputTextColor = savedOutputTextColor;
  622. this->ErrorTextColor = savedErrorTextColor;
  623. // Restore positions
  624. this->InteractivePosition = savedInteractivePosition;
  625. QTextCursor textCursor = this->textCursor();
  626. textCursor.setPosition(savedCursorPosition);
  627. this->setTextCursor(textCursor);
  628. // Place and show the completer if there are available completions
  629. if (this->Completer->completionCount())
  630. {
  631. // Get a QRect for the cursor at the start of the
  632. // current word and then translate it down 8 pixels.
  633. text_cursor = this->textCursor();
  634. text_cursor.movePosition(QTextCursor::StartOfWord);
  635. QRect cr = this->cursorRect(text_cursor);
  636. cr.translate(0,8);
  637. cr.setWidth(this->Completer->popup()->sizeHintForColumn(0)
  638. + this->Completer->popup()->verticalScrollBar()->sizeHint().width());
  639. this->Completer->complete(cr);
  640. }
  641. else
  642. {
  643. this->Completer->popup()->hide();
  644. }
  645. }
  646. }
  647. //-----------------------------------------------------------------------------
  648. void ctkConsolePrivate::updateCommandBuffer(int commandLength)
  649. {
  650. if (commandLength == -1)
  651. {
  652. commandLength =
  653. this->commandEnd() - this->InteractivePosition;
  654. }
  655. this->commandBuffer() =
  656. this->toPlainText().mid(this->InteractivePosition, commandLength);
  657. }
  658. //-----------------------------------------------------------------------------
  659. void ctkConsolePrivate::replaceCommandBuffer(const QString& text)
  660. {
  661. this->commandBuffer() = text;
  662. QTextCursor c(this->document());
  663. c.setPosition(this->InteractivePosition);
  664. c.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
  665. c.removeSelectedText();
  666. // all text removed, we need then to re-init our tracker on the message output area
  667. this->MessageOutputSize = 0;
  668. this->switchToUserInputTextColor(&c);
  669. c.insertText(text);
  670. }
  671. //-----------------------------------------------------------------------------
  672. QString& ctkConsolePrivate::commandBuffer()
  673. {
  674. return this->CommandHistory.back();
  675. }
  676. //-----------------------------------------------------------------------------
  677. void ctkConsolePrivate::internalExecuteCommand()
  678. {
  679. Q_Q(ctkConsole);
  680. QString command = this->commandBuffer();
  681. if (this->EditorHints & ctkConsole::RemoveTrailingSpaces)
  682. {
  683. command.replace(QRegExp("\\s*$"), ""); // Remove trailing spaces
  684. this->commandBuffer() = command; // Update buffer
  685. }
  686. // First update the history cache. It's essential to update the
  687. // this->CommandPosition before calling internalExecuteCommand() since that
  688. // can result in a clearing of the current command (BUG #8765).
  689. if (!command.isEmpty()) // Don't store empty commands in the history
  690. {
  691. this->CommandHistory.push_back("");
  692. this->CommandPosition = this->CommandHistory.size() - 1;
  693. }
  694. QTextCursor c(this->document());
  695. c.movePosition(QTextCursor::End);
  696. c.insertText("\n");
  697. this->InteractivePosition = this->documentEnd();
  698. emit q->aboutToExecute(command);
  699. q->executeCommand(command);
  700. emit q->executed(command);
  701. // Find the indent for the command.
  702. QString indent;
  703. if (this->EditorHints & ctkConsole::AutomaticIndentation)
  704. {
  705. QRegExp regExp("^(\\s+)");
  706. if (regExp.indexIn(command) != -1)
  707. {
  708. indent = regExp.cap(1);
  709. }
  710. }
  711. this->promptForInput(indent);
  712. this->MessageOutputSize = 0;
  713. }
  714. //-----------------------------------------------------------------------------
  715. void ctkConsolePrivate::processInput()
  716. {
  717. QString command = this->commandBuffer();
  718. if (this->EditorHints & ctkConsole::RemoveTrailingSpaces)
  719. {
  720. command.replace(QRegExp("\\s*$"), ""); // Remove trailing spaces
  721. this->commandBuffer() = command; // Update buffer
  722. }
  723. QTextCursor c(this->document());
  724. c.movePosition(QTextCursor::End);
  725. c.insertText("\n");
  726. this->InteractivePosition = this->documentEnd();
  727. this->InputEventLoop->exit();
  728. }
  729. //-----------------------------------------------------------------------------
  730. void ctkConsolePrivate::printString(const QString& text)
  731. {
  732. this->textCursor().movePosition(QTextCursor::End);
  733. this->textCursor().insertText(text);
  734. this->InteractivePosition = this->documentEnd();
  735. }
  736. //----------------------------------------------------------------------------
  737. void ctkConsolePrivate::printOutputMessage(const QString& text)
  738. {
  739. Q_Q(ctkConsole);
  740. QString textToPrint = text;
  741. if (this->MessageOutputSize == 0)
  742. {
  743. textToPrint.prepend("\n");
  744. }
  745. this->MessageOutputSize += textToPrint.size();
  746. q->printMessage(textToPrint, q->outputTextColor());
  747. }
  748. //----------------------------------------------------------------------------
  749. void ctkConsolePrivate::printErrorMessage(const QString& text)
  750. {
  751. Q_Q(ctkConsole);
  752. QString textToPrint = text;
  753. if (this->MessageOutputSize == 0)
  754. {
  755. textToPrint.prepend("\n");
  756. }
  757. this->MessageOutputSize += textToPrint.size();
  758. q->printMessage(textToPrint, q->errorTextColor());
  759. }
  760. //-----------------------------------------------------------------------------
  761. void ctkConsolePrivate::printCommand(const QString& cmd)
  762. {
  763. this->textCursor().insertText(cmd);
  764. this->updateCommandBuffer();
  765. }
  766. //----------------------------------------------------------------------------
  767. void ctkConsolePrivate::promptForInput(const QString& indent)
  768. {
  769. Q_Q(ctkConsole);
  770. QTextCharFormat format = q->getFormat();
  771. format.setForeground(q->promptColor());
  772. q->setFormat(format);
  773. if(!this->MultilineStatement)
  774. {
  775. this->prompt(q->ps1());
  776. this->MessageOutputSize=0;
  777. }
  778. else
  779. {
  780. this->prompt(q->ps2());
  781. }
  782. this->printCommand(indent);
  783. }
  784. //-----------------------------------------------------------------------------
  785. void ctkConsolePrivate::prompt(const QString& text)
  786. {
  787. QTextCursor text_cursor = this->textCursor();
  788. // If the cursor is currently on a clean line, do nothing, otherwise we move
  789. // the cursor to a new line before showing the prompt.
  790. text_cursor.movePosition(QTextCursor::StartOfLine);
  791. int startpos = text_cursor.position();
  792. text_cursor.movePosition(QTextCursor::EndOfLine);
  793. int endpos = text_cursor.position();
  794. if (endpos != startpos)
  795. {
  796. this->textCursor().insertText("\n");
  797. }
  798. this->textCursor().insertText(text);
  799. this->InteractivePosition = this->documentEnd();
  800. }
  801. //----------------------------------------------------------------------------
  802. void ctkConsolePrivate::printWelcomeMessage()
  803. {
  804. Q_Q(ctkConsole);
  805. q->printMessage(
  806. QLatin1String("CTK Console"),
  807. q->welcomeTextColor());
  808. }
  809. //-----------------------------------------------------------------------------
  810. void ctkConsolePrivate::insertCompletion(const QString& completion)
  811. {
  812. Q_Q(ctkConsole);
  813. QTextCursor tc = this->textCursor();
  814. // save the initial cursor position
  815. QTextCursor endOfCompletion = this->textCursor();
  816. endOfCompletion.setPosition(tc.position());
  817. // Select the previous charactere
  818. tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
  819. if (tc.selectedText()==".")
  820. {
  821. tc.insertText(QString(".") + completion);
  822. }
  823. else
  824. {
  825. //can't more autocomplete when cursor right after '(' or ')'
  826. if (tc.selectedText()==")" || tc.selectedText()=="(")
  827. {
  828. return;
  829. }
  830. tc.clearSelection();
  831. tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
  832. tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
  833. tc.insertText(completion);
  834. endOfCompletion.setPosition(tc.position());
  835. this->setTextCursor(tc);
  836. }
  837. // Get back the whole command line to apply a cursor offset
  838. // (moving cursor between parenthsesis if the completion is
  839. // a callable object with more than the self argument)
  840. // StartOfBlock don't catch the whole command line if multi-line statement
  841. tc.movePosition(QTextCursor::StartOfBlock,QTextCursor::KeepAnchor);
  842. QString shellLine = tc.selectedText();
  843. shellLine.replace(q->ps1(), "");
  844. shellLine.replace(q->ps2(), "");
  845. tc.setPosition(endOfCompletion.position());
  846. this->setTextCursor(tc);
  847. int cursorOffset = this->Completer->cursorOffset(shellLine);
  848. tc.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, cursorOffset);
  849. this->setTextCursor(tc);
  850. this->updateCommandBuffer();
  851. }
  852. //-----------------------------------------------------------------------------
  853. void ctkConsolePrivate::onScrollBarValueChanged(int value)
  854. {
  855. this->ScrollbarAtBottom = (this->verticalScrollBar()->maximum() == value);
  856. }
  857. //-----------------------------------------------------------------------------
  858. void ctkConsolePrivate::onTextChanged()
  859. {
  860. this->scrollToBottom();
  861. this->ensureCursorVisible();
  862. }
  863. //-----------------------------------------------------------------------------
  864. bool ctkConsolePrivate::isCursorInHistoryArea()const
  865. {
  866. return this->textCursor().anchor() < this->InteractivePosition
  867. || this->textCursor().position() < this->InteractivePosition;
  868. }
  869. //-----------------------------------------------------------------------------
  870. bool ctkConsolePrivate::isCursorInMessageOutputArea()const
  871. {
  872. return this->textCursor().anchor() > this->commandEnd()
  873. || this->textCursor().position() > this->commandEnd();
  874. }
  875. //-----------------------------------------------------------------------------
  876. void ctkConsolePrivate::insertFromMimeData(const QMimeData* source)
  877. {
  878. if (this->isCursorInHistoryArea())
  879. {
  880. QTextCursor textCursor = this->textCursor();
  881. textCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
  882. this->setTextCursor(textCursor);
  883. }
  884. const QString text = source->text();
  885. if (!text.isEmpty())
  886. {
  887. this->pasteText(text);
  888. }
  889. else
  890. {
  891. this->Superclass::insertFromMimeData(source);
  892. }
  893. }
  894. //-----------------------------------------------------------------------------
  895. void ctkConsolePrivate::pasteText(const QString& text)
  896. {
  897. if(text.isNull())
  898. {
  899. return;
  900. }
  901. QTextCursor textCursor = this->textCursor();
  902. if (this->EditorHints & ctkConsole::SplitCopiedTextByLine)
  903. {
  904. QStringList lines = text.split(QRegExp("(?:\r\n|\r|\n)"));
  905. for(int i=0; i < lines.count(); ++i)
  906. {
  907. this->switchToUserInputTextColor(&textCursor);
  908. textCursor.insertText(lines.at(i));
  909. this->updateCommandBuffer();
  910. if (i < lines.count() - 1)
  911. {
  912. this->internalExecuteCommand();
  913. }
  914. }
  915. }
  916. else
  917. {
  918. this->switchToUserInputTextColor(&textCursor);
  919. textCursor.insertText(text);
  920. this->updateCommandBuffer();
  921. }
  922. }
  923. //-----------------------------------------------------------------------------
  924. // ctkConsole methods
  925. //-----------------------------------------------------------------------------
  926. ctkConsole::ctkConsole(QWidget* parentObject) :
  927. Superclass(parentObject),
  928. d_ptr(new ctkConsolePrivate(*this))
  929. {
  930. Q_D(ctkConsole);
  931. d->init();
  932. }
  933. //-----------------------------------------------------------------------------
  934. ctkConsole::ctkConsole(ctkConsolePrivate * pimpl, QWidget* parentObject) :
  935. QWidget(parentObject), d_ptr(pimpl)
  936. {
  937. Q_D(ctkConsole);
  938. d->init();
  939. }
  940. //-----------------------------------------------------------------------------
  941. ctkConsole::~ctkConsole()
  942. {
  943. }
  944. //-----------------------------------------------------------------------------
  945. QTextCharFormat ctkConsole::getFormat() const
  946. {
  947. Q_D(const ctkConsole);
  948. return d->currentCharFormat();
  949. }
  950. //-----------------------------------------------------------------------------
  951. void ctkConsole::setFormat(const QTextCharFormat& Format)
  952. {
  953. Q_D(ctkConsole);
  954. d->setCurrentCharFormat(Format);
  955. }
  956. //-----------------------------------------------------------------------------
  957. QFont ctkConsole::shellFont() const
  958. {
  959. Q_D(const ctkConsole);
  960. return d->currentFont();
  961. }
  962. //-----------------------------------------------------------------------------
  963. void ctkConsole::setShellFont(const QFont& font)
  964. {
  965. Q_D(ctkConsole);
  966. int savedPosition = d->textCursor().position();
  967. d->selectAll();
  968. d->setCurrentFont(font);
  969. QTextCursor tc = d->textCursor();
  970. tc.clearSelection();
  971. tc.setPosition(savedPosition);
  972. d->setTextCursor(tc);
  973. }
  974. //-----------------------------------------------------------------------------
  975. CTK_GET_CPP(ctkConsole, ctkConsoleCompleter*, completer, Completer);
  976. //-----------------------------------------------------------------------------
  977. void ctkConsole::setCompleter(ctkConsoleCompleter* completer)
  978. {
  979. Q_D(ctkConsole);
  980. d->setCompleter(completer);
  981. }
  982. //-----------------------------------------------------------------------------
  983. CTK_GET_CPP(ctkConsole, QColor, promptColor, PromptColor);
  984. CTK_SET_CPP(ctkConsole, const QColor&, setPromptColor, PromptColor);
  985. //-----------------------------------------------------------------------------
  986. CTK_GET_CPP(ctkConsole, QColor, outputTextColor, OutputTextColor);
  987. CTK_SET_CPP(ctkConsole, const QColor&, setOutputTextColor, OutputTextColor);
  988. //-----------------------------------------------------------------------------
  989. CTK_GET_CPP(ctkConsole, QColor, errorTextColor, ErrorTextColor);
  990. CTK_SET_CPP(ctkConsole, const QColor&, setErrorTextColor, ErrorTextColor);
  991. //-----------------------------------------------------------------------------
  992. CTK_GET_CPP(ctkConsole, QColor, stdinTextColor, StdinTextColor);
  993. CTK_SET_CPP(ctkConsole, const QColor&, setStdinTextColor, StdinTextColor);
  994. //-----------------------------------------------------------------------------
  995. CTK_GET_CPP(ctkConsole, QColor, commandTextColor, CommandTextColor);
  996. CTK_SET_CPP(ctkConsole, const QColor&, setCommandTextColor, CommandTextColor);
  997. //-----------------------------------------------------------------------------
  998. CTK_GET_CPP(ctkConsole, QColor, welcomeTextColor, WelcomeTextColor);
  999. CTK_SET_CPP(ctkConsole, const QColor&, setWelcomeTextColor, WelcomeTextColor);
  1000. //-----------------------------------------------------------------------------
  1001. QColor ctkConsole::backgroundColor()const
  1002. {
  1003. Q_D(const ctkConsole);
  1004. QPalette pal = d->palette();
  1005. return pal.color(QPalette::Base);
  1006. }
  1007. //-----------------------------------------------------------------------------
  1008. void ctkConsole::setBackgroundColor(const QColor& newColor)
  1009. {
  1010. Q_D(ctkConsole);
  1011. if (this->backgroundColor() == newColor)
  1012. {
  1013. return;
  1014. }
  1015. QPalette pal = this->palette();
  1016. pal.setColor(QPalette::Base, newColor);
  1017. d->setPalette(pal);
  1018. }
  1019. //-----------------------------------------------------------------------------
  1020. CTK_GET_CPP(ctkConsole, QString, ps1, Ps1);
  1021. CTK_SET_CPP(ctkConsole, const QString&, setPs1, Ps1);
  1022. //-----------------------------------------------------------------------------
  1023. CTK_GET_CPP(ctkConsole, QString, ps2, Ps2);
  1024. CTK_SET_CPP(ctkConsole, const QString&, setPs2, Ps2);
  1025. //-----------------------------------------------------------------------------
  1026. CTK_GET_CPP(ctkConsole, ctkConsole::EditorHints, editorHints, EditorHints);
  1027. CTK_SET_CPP(ctkConsole, const ctkConsole::EditorHints&, setEditorHints, EditorHints);
  1028. //-----------------------------------------------------------------------------
  1029. int ctkConsole::cursorPosition() const
  1030. {
  1031. Q_D(const ctkConsole);
  1032. return d->textCursor().position();
  1033. }
  1034. //-----------------------------------------------------------------------------
  1035. int ctkConsole::cursorColumn() const
  1036. {
  1037. Q_D(const ctkConsole);
  1038. QTextCursor cursor = d->textCursor();
  1039. cursor.movePosition(QTextCursor::StartOfLine);
  1040. return d->textCursor().position() - cursor.position();
  1041. }
  1042. //-----------------------------------------------------------------------------
  1043. int ctkConsole::cursorLine() const
  1044. {
  1045. Q_D(const ctkConsole);
  1046. QTextCursor cursor = d->textCursor();
  1047. cursor.movePosition(QTextCursor::StartOfLine);
  1048. int lines = 1;
  1049. QTextBlock block = cursor.block().previous();
  1050. while(block.isValid())
  1051. {
  1052. lines += block.lineCount();
  1053. block = block.previous();
  1054. }
  1055. return lines;
  1056. }
  1057. //-----------------------------------------------------------------------------
  1058. Qt::ScrollBarPolicy ctkConsole::scrollBarPolicy()const
  1059. {
  1060. Q_D(const ctkConsole);
  1061. return d->verticalScrollBarPolicy();
  1062. }
  1063. //-----------------------------------------------------------------------------
  1064. void ctkConsole::setScrollBarPolicy(const Qt::ScrollBarPolicy& newScrollBarPolicy)
  1065. {
  1066. Q_D(ctkConsole);
  1067. d->setVerticalScrollBarPolicy(newScrollBarPolicy);
  1068. }
  1069. //-----------------------------------------------------------------------------
  1070. CTK_GET_CPP(ctkConsole, QList<QKeySequence>, completerShortcuts, CompleterShortcuts);
  1071. //-----------------------------------------------------------------------------
  1072. void ctkConsole::setCompleterShortcuts(const QList<QKeySequence>& keys)
  1073. {
  1074. Q_D(ctkConsole);
  1075. d->CompleterShortcuts = keys;
  1076. }
  1077. //-----------------------------------------------------------------------------
  1078. void ctkConsole::addCompleterShortcut(const QKeySequence& key)
  1079. {
  1080. Q_D(ctkConsole);
  1081. if (!d->CompleterShortcuts.contains(key))
  1082. {
  1083. d->CompleterShortcuts.append(key);
  1084. }
  1085. }
  1086. //-----------------------------------------------------------------------------
  1087. CTK_GET_CPP(ctkConsole, ctkConsole::RunFileOptions, runFileOptions, RunFileOptions);
  1088. //-----------------------------------------------------------------------------
  1089. void ctkConsole::setRunFileOptions(const RunFileOptions& newOptions)
  1090. {
  1091. Q_D(ctkConsole);
  1092. d->RunFileButton->setVisible(newOptions.testFlag(ctkConsole::RunFileButton));
  1093. d->RunFileAction->setEnabled(newOptions.testFlag(ctkConsole::RunFileShortcut));
  1094. }
  1095. //-----------------------------------------------------------------------------
  1096. void ctkConsole::exec(const QString& command)
  1097. {
  1098. Q_D(ctkConsole);
  1099. d->replaceCommandBuffer(command);
  1100. d->internalExecuteCommand();
  1101. }
  1102. //-----------------------------------------------------------------------------
  1103. void ctkConsole::runFile(const QString& filePath)
  1104. {
  1105. QFile file(filePath);
  1106. if (!file.open(QIODevice::ReadOnly))
  1107. {
  1108. qWarning() << tr( "File '%1' can't be read.").arg(filePath);
  1109. return;
  1110. }
  1111. for (QTextStream fileStream(&file); !fileStream.atEnd();)
  1112. {
  1113. QString line = fileStream.readLine();
  1114. this->exec(line);
  1115. }
  1116. }
  1117. //-----------------------------------------------------------------------------
  1118. void ctkConsole::runFile()
  1119. {
  1120. QString filePath =
  1121. QFileDialog::getOpenFileName(this, tr("Select a script file to run"));
  1122. if (!filePath.isEmpty())
  1123. {
  1124. this->runFile(filePath);
  1125. }
  1126. }
  1127. //-----------------------------------------------------------------------------
  1128. void ctkConsole::printHelp()
  1129. {
  1130. this->printMessage("\n", Qt::gray);
  1131. this->printMessage(tr("CTRL+h: Print this help message\n"), Qt::gray);
  1132. this->printMessage(tr("CTRL+r: Open a file dialog to select a file to run\n"), Qt::gray);
  1133. }
  1134. //-----------------------------------------------------------------------------
  1135. void ctkConsole::executeCommand(const QString& command)
  1136. {
  1137. qWarning() << "ctkConsole::executeCommand not implemented !";
  1138. qWarning() << "command:" << command;
  1139. }
  1140. //----------------------------------------------------------------------------
  1141. void ctkConsole::printMessage(const QString& message, const QColor& color)
  1142. {
  1143. Q_D(ctkConsole);
  1144. QTextCharFormat format = this->getFormat();
  1145. format.setForeground(color);
  1146. this->setFormat(format);
  1147. d->printString(message);
  1148. }
  1149. //-----------------------------------------------------------------------------
  1150. void ctkConsole::clear()
  1151. {
  1152. Q_D(ctkConsole);
  1153. d->clear();
  1154. // For some reason the QCompleter tries to set the focus policy to
  1155. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  1156. d->setFocusPolicy(Qt::WheelFocus);
  1157. d->promptForInput();
  1158. }
  1159. //-----------------------------------------------------------------------------
  1160. void ctkConsole::reset()
  1161. {
  1162. Q_D(ctkConsole);
  1163. d->clear();
  1164. // For some reason the QCompleter tries to set the focus policy to
  1165. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  1166. d->setFocusPolicy(Qt::WheelFocus);
  1167. d->printWelcomeMessage();
  1168. d->promptForInput();
  1169. }
  1170. //-----------------------------------------------------------------------------
  1171. QString ctkConsole::stdInRedirectCallBack(void * callData)
  1172. {
  1173. ctkConsole * self = reinterpret_cast<ctkConsole*>(callData);
  1174. Q_ASSERT(self);
  1175. if (!self)
  1176. {
  1177. return QLatin1String("");
  1178. }
  1179. return self->readInputLine();
  1180. }
  1181. namespace
  1182. {
  1183. class InputEventLoop : public QEventLoop
  1184. {
  1185. public:
  1186. InputEventLoop(QApplication * app, QObject * parentObject = 0) :
  1187. QEventLoop(parentObject), App(app){}
  1188. virtual bool processEvents(ProcessEventsFlags flags = AllEvents)
  1189. {
  1190. this->App->processEvents(flags);
  1191. return true;
  1192. }
  1193. QApplication * App;
  1194. };
  1195. }
  1196. //-----------------------------------------------------------------------------
  1197. QString ctkConsole::readInputLine()
  1198. {
  1199. Q_D(ctkConsole);
  1200. d->moveCursor(QTextCursor::End);
  1201. QScopedPointer<InputEventLoop> eventLoop(new InputEventLoop(qApp));
  1202. d->InputEventLoop = QPointer<QEventLoop>(eventLoop.data());
  1203. eventLoop->exec();
  1204. return d->commandBuffer();
  1205. }