ctkConsole.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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 <QTextCursor>
  50. #include <QVBoxLayout>
  51. #include <QScrollBar>
  52. #include <QDebug>
  53. // CTK includes
  54. #include "ctkConsole.h"
  55. #include "ctkConsole_p.h"
  56. #include "ctkPimpl.h"
  57. //-----------------------------------------------------------------------------
  58. // ctkConsoleCompleter methods
  59. //-----------------------------------------------------------------------------
  60. QStringList ctkConsoleCompleter::autocompletePreferenceList()
  61. {
  62. return this->AutocompletePreferenceList;
  63. }
  64. //-----------------------------------------------------------------------------
  65. void ctkConsoleCompleter::setAutocompletePreferenceList(const QStringList& list)
  66. {
  67. this->AutocompletePreferenceList = list;
  68. }
  69. //-----------------------------------------------------------------------------
  70. // ctkConsolePrivate methods
  71. //-----------------------------------------------------------------------------
  72. ctkConsolePrivate::ctkConsolePrivate(ctkConsole& object) :
  73. Superclass(0),
  74. q_ptr(&object),
  75. InteractivePosition(documentEnd()),
  76. MultilineStatement(false), Ps1("$ "), Ps2("> "),
  77. EditorHints(ctkConsole::AutomaticIndentation | ctkConsole::RemoveTrailingSpaces),
  78. ScrollbarAtBottom(false),
  79. CompleterShortcuts(QList<QKeySequence>() << Qt::Key_Tab)
  80. {
  81. }
  82. //-----------------------------------------------------------------------------
  83. void ctkConsolePrivate::init()
  84. {
  85. Q_Q(ctkConsole);
  86. this->setParent(q);
  87. this->setTabChangesFocus(false);
  88. this->setAcceptDrops(false);
  89. this->setAcceptRichText(false);
  90. this->setUndoRedoEnabled(false);
  91. this->PromptColor = QColor(0, 0, 0); // Black
  92. this->OutputTextColor = QColor(0, 150, 0); // Green
  93. this->ErrorTextColor = QColor(255, 0, 0); // Red
  94. this->StdinTextColor = QColor(Qt::darkGray);
  95. this->CommandTextColor = QColor(0, 0, 150); // Blue
  96. this->WelcomeTextColor = QColor(0, 0, 255); // Dark Blue
  97. QFont shellFont;
  98. shellFont.setFamily("Courier");
  99. shellFont.setStyleHint(QFont::TypeWriter);
  100. shellFont.setFixedPitch(true);
  101. QTextCharFormat format;
  102. format.setFont(shellFont);
  103. format.setForeground(this->OutputTextColor);
  104. this->setCurrentCharFormat(format);
  105. this->CommandHistory.append("");
  106. this->CommandPosition = 0;
  107. QAction* runFileAction = new QAction(q->tr("&Run file"),q);
  108. runFileAction->setShortcut(q->tr("Ctrl+r"));
  109. connect(runFileAction, SIGNAL(triggered()), q, SLOT(runFile()));
  110. q->addAction(runFileAction);
  111. QAction* printHelpAction = new QAction(q->tr("Print &help"),q);
  112. printHelpAction->setShortcut(q->tr("Ctrl+h"));
  113. connect(printHelpAction, SIGNAL(triggered()), q, SLOT(printHelp()));
  114. q->addAction(printHelpAction);
  115. QVBoxLayout * layout = new QVBoxLayout(q);
  116. layout->setMargin(0);
  117. layout->addWidget(this);
  118. connect(this->verticalScrollBar(), SIGNAL(valueChanged(int)),
  119. SLOT(onScrollBarValueChanged(int)));
  120. connect(this, SIGNAL(textChanged()), SLOT(onTextChanged()));
  121. }
  122. //-----------------------------------------------------------------------------
  123. bool ctkConsolePrivate::isMoveLeftWithinLine(QKeyEvent* e, QTextCursor::MoveOperation &moveOperation, QTextCursor::MoveMode &moveMode)
  124. {
  125. if (e == QKeySequence::MoveToPreviousChar)
  126. {
  127. moveOperation = QTextCursor::Left;
  128. moveMode = QTextCursor::MoveAnchor;
  129. return true;
  130. }
  131. else if (e == QKeySequence::SelectPreviousChar)
  132. {
  133. moveOperation = QTextCursor::Left;
  134. moveMode = QTextCursor::KeepAnchor;
  135. return true;
  136. }
  137. else if (e == QKeySequence::MoveToPreviousWord)
  138. {
  139. moveOperation = QTextCursor::WordLeft;
  140. moveMode = QTextCursor::MoveAnchor;
  141. return true;
  142. }
  143. else if (e == QKeySequence::SelectPreviousWord)
  144. {
  145. moveOperation = QTextCursor::WordLeft;
  146. moveMode = QTextCursor::KeepAnchor;
  147. return true;
  148. }
  149. else if (e == QKeySequence::MoveToStartOfLine)
  150. {
  151. moveOperation = QTextCursor::StartOfLine;
  152. moveMode = QTextCursor::MoveAnchor;
  153. return true;
  154. }
  155. else if (e == QKeySequence::SelectStartOfLine)
  156. {
  157. moveOperation = QTextCursor::StartOfLine;
  158. moveMode = QTextCursor::KeepAnchor;
  159. return true;
  160. }
  161. else if (e == QKeySequence::MoveToStartOfBlock)
  162. {
  163. moveOperation = QTextCursor::StartOfLine;
  164. moveMode = QTextCursor::MoveAnchor;
  165. return true;
  166. }
  167. else if (e == QKeySequence::SelectStartOfBlock)
  168. {
  169. moveOperation = QTextCursor::StartOfLine;
  170. moveMode = QTextCursor::KeepAnchor;
  171. return true;
  172. }
  173. else if (e == QKeySequence::MoveToStartOfDocument)
  174. {
  175. moveOperation = QTextCursor::StartOfLine;
  176. moveMode = QTextCursor::MoveAnchor;
  177. return true;
  178. }
  179. else if (e == QKeySequence::SelectStartOfDocument)
  180. {
  181. moveOperation = QTextCursor::StartOfLine;
  182. moveMode = QTextCursor::KeepAnchor;
  183. return true;
  184. }
  185. else
  186. {
  187. return false;
  188. }
  189. }
  190. //-----------------------------------------------------------------------------
  191. void ctkConsolePrivate::keyPressEvent(QKeyEvent* e)
  192. {
  193. if (this->Completer && this->Completer->popup()->isVisible())
  194. {
  195. // The following keys are forwarded by the completer to the widget
  196. switch (e->key())
  197. {
  198. case Qt::Key_Enter:
  199. case Qt::Key_Return:
  200. case Qt::Key_Escape:
  201. case Qt::Key_Tab:
  202. case Qt::Key_Backtab:
  203. e->ignore();
  204. return; // let the completer do default behavior
  205. default:
  206. break;
  207. }
  208. }
  209. QTextCursor text_cursor = this->textCursor();
  210. // Set to true if there's a current selection
  211. const bool selection = text_cursor.anchor() != text_cursor.position();
  212. // Set to true if the cursor overlaps the history area
  213. const bool history_area = this->isCursorInHistoryArea();
  214. // Allow copying anywhere in the console ...
  215. if(e == QKeySequence::Copy)
  216. {
  217. if(selection)
  218. {
  219. this->copy();
  220. }
  221. e->accept();
  222. return;
  223. }
  224. // Allow cut only if the selection is limited to the interactive area ...
  225. if(e == QKeySequence::Cut)
  226. {
  227. if(selection && !history_area)
  228. {
  229. this->cut();
  230. }
  231. e->accept();
  232. return;
  233. }
  234. // Paste to the end of document if in the history area
  235. if(e == QKeySequence::Paste)
  236. {
  237. if(history_area)
  238. {
  239. text_cursor.setPosition(this->documentEnd());
  240. this->setTextCursor(text_cursor);
  241. }
  242. this->paste();
  243. e->accept();
  244. return;
  245. }
  246. // Allow vertical scrolling using page up/down
  247. if (e == QKeySequence::MoveToPreviousPage || e == QKeySequence::SelectPreviousPage
  248. || e == QKeySequence::MoveToNextPage || e == QKeySequence::SelectNextPage)
  249. {
  250. if (e == QKeySequence::SelectPreviousPage || e == QKeySequence::SelectNextPage)
  251. {
  252. // ignore
  253. e->accept();
  254. }
  255. else
  256. {
  257. this->Superclass::keyPressEvent(e);
  258. this->updateCommandBuffer();
  259. }
  260. return;
  261. }
  262. // Force the cursor back to the interactive area if anything else than copy/paste or page up/down is done
  263. // but only when a "real" key is pressed, not just a modifier (otherwise we could not press Control-c in the
  264. // history area because the cursor would jump to the interactive area immediately when Control is pressed)
  265. if(history_area
  266. && e->key() != Qt::Key_Control
  267. && e->key() != Qt::Key_Meta
  268. && e->key() != Qt::Key_Alt
  269. && e->key() != Qt::Key_Shift)
  270. {
  271. text_cursor.setPosition(this->documentEnd());
  272. this->setTextCursor(text_cursor);
  273. }
  274. // Start of line should be the start of interactive area
  275. QTextCursor::MoveOperation moveOperation = QTextCursor::NoMove;
  276. QTextCursor::MoveMode moveMode = QTextCursor::MoveAnchor;
  277. if(isMoveLeftWithinLine(e, moveOperation, moveMode))
  278. {
  279. text_cursor.movePosition(moveOperation, moveMode);
  280. if (text_cursor.position() > this->InteractivePosition)
  281. {
  282. this->Superclass::keyPressEvent(e);
  283. }
  284. else
  285. {
  286. text_cursor.setPosition(this->InteractivePosition, moveMode);
  287. this->setTextCursor(text_cursor);
  288. e->accept();
  289. }
  290. return;
  291. }
  292. if (e == QKeySequence::Delete)
  293. {
  294. e->accept();
  295. this->Superclass::keyPressEvent(e);
  296. this->updateCommandBuffer();
  297. return;
  298. }
  299. // There seems to be no QKeySequence for backspace, therefore the key
  300. // has to be recognized directly (the same way as it is done in the parent class)
  301. if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~Qt::ShiftModifier))
  302. {
  303. e->accept();
  304. if(text_cursor.position() > this->InteractivePosition)
  305. {
  306. this->Superclass::keyPressEvent(e);
  307. this->updateCommandBuffer();
  308. this->updateCompleterIfVisible();
  309. }
  310. return;
  311. }
  312. if (e == QKeySequence::DeleteStartOfWord)
  313. {
  314. e->accept();
  315. if(text_cursor.position() > this->InteractivePosition)
  316. {
  317. this->Superclass::keyPressEvent(e);
  318. this->updateCommandBuffer();
  319. this->updateCompleterIfVisible();
  320. }
  321. return;
  322. }
  323. if (e == QKeySequence::MoveToPreviousLine || e == QKeySequence::SelectPreviousLine)
  324. {
  325. e->accept();
  326. if (this->CommandPosition > 0)
  327. {
  328. this->replaceCommandBuffer(this->CommandHistory[--this->CommandPosition]);
  329. }
  330. return;
  331. }
  332. if (e == QKeySequence::MoveToNextLine || e == QKeySequence::SelectNextLine)
  333. {
  334. e->accept();
  335. if (this->CommandPosition < this->CommandHistory.size() - 2)
  336. {
  337. this->replaceCommandBuffer(this->CommandHistory[++this->CommandPosition]);
  338. }
  339. else
  340. {
  341. this->CommandPosition = this->CommandHistory.size()-1;
  342. this->replaceCommandBuffer("");
  343. }
  344. return;
  345. }
  346. if (e == QKeySequence::InsertParagraphSeparator)
  347. {
  348. e->accept();
  349. text_cursor.setPosition(this->documentEnd());
  350. this->setTextCursor(text_cursor);
  351. if (this->InputEventLoop.isNull())
  352. {
  353. this->internalExecuteCommand();
  354. }
  355. else
  356. {
  357. this->processInput();
  358. }
  359. return;
  360. }
  361. if (this->CompleterShortcuts.contains(e->key() + e->modifiers()))
  362. {
  363. e->accept();
  364. this->updateCompleter();
  365. this->selectCompletion();
  366. return;
  367. }
  368. e->accept();
  369. this->switchToUserInputTextColor();
  370. this->Superclass::keyPressEvent(e);
  371. this->updateCommandBuffer();
  372. this->updateCompleterIfVisible();
  373. }
  374. //-----------------------------------------------------------------------------
  375. void ctkConsolePrivate::switchToUserInputTextColor(QTextCursor* textCursorToUpdate)
  376. {
  377. QColor color = this->CommandTextColor;
  378. if (!this->InputEventLoop.isNull())
  379. {
  380. color = this->StdinTextColor;
  381. }
  382. QTextCharFormat currentFormat = this->currentCharFormat();
  383. // Do not trigger a finishEdit for no reason. onTextChanged() would be called.
  384. if (currentFormat.foreground() != color)
  385. {
  386. currentFormat.setForeground(color);
  387. this->setCurrentCharFormat(currentFormat);
  388. }
  389. if (textCursorToUpdate)
  390. {
  391. QTextCharFormat textCursorFormat = textCursorToUpdate->charFormat();
  392. if (textCursorFormat.foreground() != color)
  393. {
  394. textCursorFormat.setForeground(color);
  395. textCursorToUpdate->setCharFormat(textCursorFormat);
  396. }
  397. }
  398. }
  399. //-----------------------------------------------------------------------------
  400. int ctkConsolePrivate::documentEnd() const
  401. {
  402. QTextCursor c(this->document());
  403. c.movePosition(QTextCursor::End);
  404. return c.position();
  405. }
  406. //-----------------------------------------------------------------------------
  407. void ctkConsolePrivate::focusOutEvent(QFocusEvent *e)
  408. {
  409. this->Superclass::focusOutEvent(e);
  410. // For some reason the QCompleter tries to set the focus policy to
  411. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  412. this->setFocusPolicy(Qt::WheelFocus);
  413. }
  414. //-----------------------------------------------------------------------------
  415. void ctkConsolePrivate::resizeEvent(QResizeEvent * e)
  416. {
  417. this->Superclass::resizeEvent(e);
  418. if (this->ScrollbarAtBottom)
  419. {
  420. this->moveCursor(QTextCursor::End);
  421. this->scrollToBottom();
  422. }
  423. }
  424. //-----------------------------------------------------------------------------
  425. void ctkConsolePrivate::scrollToBottom()
  426. {
  427. this->verticalScrollBar()->setValue(this->verticalScrollBar()->maximum());
  428. }
  429. //-----------------------------------------------------------------------------
  430. void ctkConsolePrivate::updateCompleterIfVisible()
  431. {
  432. if (this->Completer && this->Completer->popup()->isVisible())
  433. {
  434. this->updateCompleter();
  435. }
  436. }
  437. //-----------------------------------------------------------------------------
  438. void ctkConsolePrivate::selectCompletion()
  439. {
  440. if (this->Completer && this->Completer->completionCount() == 1)
  441. {
  442. this->insertCompletion(this->Completer->currentCompletion());
  443. this->Completer->popup()->hide();
  444. }
  445. }
  446. //-----------------------------------------------------------------------------
  447. void ctkConsolePrivate::setCompleter(ctkConsoleCompleter* completer)
  448. {
  449. if (this->Completer)
  450. {
  451. this->Completer->setWidget(0);
  452. disconnect(this->Completer, SIGNAL(activated(QString)),
  453. this, SLOT(insertCompletion(QString)));
  454. }
  455. this->Completer = completer;
  456. if (this->Completer)
  457. {
  458. this->Completer->setWidget(this);
  459. connect(this->Completer, SIGNAL(activated(QString)),
  460. this, SLOT(insertCompletion(QString)));
  461. }
  462. }
  463. //-----------------------------------------------------------------------------
  464. void ctkConsolePrivate::updateCompleter()
  465. {
  466. if (this->Completer)
  467. {
  468. // Get the text between the current cursor position
  469. // and the start of the line
  470. QTextCursor text_cursor = this->textCursor();
  471. text_cursor.setPosition(this->InteractivePosition, QTextCursor::KeepAnchor);
  472. QString commandText = text_cursor.selectedText();
  473. // Call the completer to update the completion model
  474. this->Completer->updateCompletionModel(commandText);
  475. // Place and show the completer if there are available completions
  476. if (this->Completer->completionCount())
  477. {
  478. // Get a QRect for the cursor at the start of the
  479. // current word and then translate it down 8 pixels.
  480. text_cursor = this->textCursor();
  481. text_cursor.movePosition(QTextCursor::StartOfWord);
  482. QRect cr = this->cursorRect(text_cursor);
  483. cr.translate(0,8);
  484. cr.setWidth(this->Completer->popup()->sizeHintForColumn(0)
  485. + this->Completer->popup()->verticalScrollBar()->sizeHint().width());
  486. this->Completer->complete(cr);
  487. }
  488. else
  489. {
  490. this->Completer->popup()->hide();
  491. }
  492. }
  493. }
  494. //-----------------------------------------------------------------------------
  495. void ctkConsolePrivate::updateCommandBuffer()
  496. {
  497. this->commandBuffer() = this->toPlainText().mid(this->InteractivePosition);
  498. }
  499. //-----------------------------------------------------------------------------
  500. void ctkConsolePrivate::replaceCommandBuffer(const QString& text)
  501. {
  502. this->commandBuffer() = text;
  503. QTextCursor c(this->document());
  504. c.setPosition(this->InteractivePosition);
  505. c.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
  506. c.removeSelectedText();
  507. this->switchToUserInputTextColor(&c);
  508. c.insertText(text);
  509. }
  510. //-----------------------------------------------------------------------------
  511. QString& ctkConsolePrivate::commandBuffer()
  512. {
  513. return this->CommandHistory.back();
  514. }
  515. //-----------------------------------------------------------------------------
  516. void ctkConsolePrivate::internalExecuteCommand()
  517. {
  518. Q_Q(ctkConsole);
  519. QString command = this->commandBuffer();
  520. if (this->EditorHints & ctkConsole::RemoveTrailingSpaces)
  521. {
  522. command.replace(QRegExp("\\s*$"), ""); // Remove trailing spaces
  523. this->commandBuffer() = command; // Update buffer
  524. }
  525. // First update the history cache. It's essential to update the
  526. // this->CommandPosition before calling internalExecuteCommand() since that
  527. // can result in a clearing of the current command (BUG #8765).
  528. if (!command.isEmpty()) // Don't store empty commands in the history
  529. {
  530. this->CommandHistory.push_back("");
  531. this->CommandPosition = this->CommandHistory.size() - 1;
  532. }
  533. QTextCursor c(this->document());
  534. c.movePosition(QTextCursor::End);
  535. c.insertText("\n");
  536. this->InteractivePosition = this->documentEnd();
  537. emit q->aboutToExecute(command);
  538. q->executeCommand(command);
  539. emit q->executed(command);
  540. // Find the indent for the command.
  541. QString indent;
  542. if (this->EditorHints & ctkConsole::AutomaticIndentation)
  543. {
  544. QRegExp regExp("^(\\s+)");
  545. if (regExp.indexIn(command) != -1)
  546. {
  547. indent = regExp.cap(1);
  548. }
  549. }
  550. this->promptForInput(indent);
  551. }
  552. //-----------------------------------------------------------------------------
  553. void ctkConsolePrivate::processInput()
  554. {
  555. QString command = this->commandBuffer();
  556. if (this->EditorHints & ctkConsole::RemoveTrailingSpaces)
  557. {
  558. command.replace(QRegExp("\\s*$"), ""); // Remove trailing spaces
  559. this->commandBuffer() = command; // Update buffer
  560. }
  561. QTextCursor c(this->document());
  562. c.movePosition(QTextCursor::End);
  563. c.insertText("\n");
  564. this->InteractivePosition = this->documentEnd();
  565. this->InputEventLoop->exit();
  566. }
  567. //-----------------------------------------------------------------------------
  568. void ctkConsolePrivate::printString(const QString& text)
  569. {
  570. this->textCursor().movePosition(QTextCursor::End);
  571. this->textCursor().insertText(text);
  572. this->InteractivePosition = this->documentEnd();
  573. }
  574. //----------------------------------------------------------------------------
  575. void ctkConsolePrivate::printOutputMessage(const QString& text)
  576. {
  577. Q_Q(ctkConsole);
  578. q->printMessage(text, q->outputTextColor());
  579. }
  580. //----------------------------------------------------------------------------
  581. void ctkConsolePrivate::printErrorMessage(const QString& text)
  582. {
  583. Q_Q(ctkConsole);
  584. q->printMessage(text, q->errorTextColor());
  585. }
  586. //-----------------------------------------------------------------------------
  587. void ctkConsolePrivate::printCommand(const QString& cmd)
  588. {
  589. this->textCursor().insertText(cmd);
  590. this->updateCommandBuffer();
  591. }
  592. //----------------------------------------------------------------------------
  593. void ctkConsolePrivate::promptForInput(const QString& indent)
  594. {
  595. Q_Q(ctkConsole);
  596. QTextCharFormat format = q->getFormat();
  597. format.setForeground(q->promptColor());
  598. q->setFormat(format);
  599. if(!this->MultilineStatement)
  600. {
  601. this->prompt(q->ps1());
  602. }
  603. else
  604. {
  605. this->prompt(q->ps2());
  606. }
  607. this->printCommand(indent);
  608. }
  609. //-----------------------------------------------------------------------------
  610. void ctkConsolePrivate::prompt(const QString& text)
  611. {
  612. QTextCursor text_cursor = this->textCursor();
  613. // If the cursor is currently on a clean line, do nothing, otherwise we move
  614. // the cursor to a new line before showing the prompt.
  615. text_cursor.movePosition(QTextCursor::StartOfLine);
  616. int startpos = text_cursor.position();
  617. text_cursor.movePosition(QTextCursor::EndOfLine);
  618. int endpos = text_cursor.position();
  619. if (endpos != startpos)
  620. {
  621. this->textCursor().insertText("\n");
  622. }
  623. this->textCursor().insertText(text);
  624. this->InteractivePosition = this->documentEnd();
  625. }
  626. //----------------------------------------------------------------------------
  627. void ctkConsolePrivate::printWelcomeMessage()
  628. {
  629. Q_Q(ctkConsole);
  630. q->printMessage(
  631. QLatin1String("CTK Console"),
  632. q->welcomeTextColor());
  633. }
  634. //-----------------------------------------------------------------------------
  635. void ctkConsolePrivate::insertCompletion(const QString& completion)
  636. {
  637. QTextCursor tc = this->textCursor();
  638. tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
  639. if (tc.selectedText()==".")
  640. {
  641. tc.insertText(QString(".") + completion);
  642. }
  643. else
  644. {
  645. tc = this->textCursor();
  646. tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
  647. tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
  648. tc.insertText(completion);
  649. this->setTextCursor(tc);
  650. }
  651. this->updateCommandBuffer();
  652. }
  653. //-----------------------------------------------------------------------------
  654. void ctkConsolePrivate::onScrollBarValueChanged(int value)
  655. {
  656. this->ScrollbarAtBottom = (this->verticalScrollBar()->maximum() == value);
  657. }
  658. //-----------------------------------------------------------------------------
  659. void ctkConsolePrivate::onTextChanged()
  660. {
  661. this->scrollToBottom();
  662. this->ensureCursorVisible();
  663. }
  664. //-----------------------------------------------------------------------------
  665. bool ctkConsolePrivate::isCursorInHistoryArea()const
  666. {
  667. return this->textCursor().anchor() < this->InteractivePosition
  668. || this->textCursor().position() < this->InteractivePosition;
  669. }
  670. //-----------------------------------------------------------------------------
  671. void ctkConsolePrivate::insertFromMimeData(const QMimeData* source)
  672. {
  673. if (this->isCursorInHistoryArea())
  674. {
  675. QTextCursor textCursor = this->textCursor();
  676. textCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
  677. this->setTextCursor(textCursor);
  678. }
  679. const QString text = source->text();
  680. if (!text.isEmpty())
  681. {
  682. this->pasteText(text);
  683. }
  684. else
  685. {
  686. this->Superclass::insertFromMimeData(source);
  687. }
  688. }
  689. //-----------------------------------------------------------------------------
  690. void ctkConsolePrivate::pasteText(const QString& text)
  691. {
  692. if(text.isNull())
  693. {
  694. return;
  695. }
  696. QTextCursor textCursor = this->textCursor();
  697. if (this->EditorHints & ctkConsole::SplitCopiedTextByLine)
  698. {
  699. QStringList lines = text.split(QRegExp("(?:\r\n|\r|\n)"));
  700. for(int i=0; i < lines.count(); ++i)
  701. {
  702. this->switchToUserInputTextColor(&textCursor);
  703. textCursor.insertText(lines.at(i));
  704. this->updateCommandBuffer();
  705. if (i < lines.count() - 1)
  706. {
  707. this->internalExecuteCommand();
  708. }
  709. }
  710. }
  711. else
  712. {
  713. this->switchToUserInputTextColor(&textCursor);
  714. textCursor.insertText(text);
  715. this->updateCommandBuffer();
  716. }
  717. }
  718. //-----------------------------------------------------------------------------
  719. // ctkConsole methods
  720. //-----------------------------------------------------------------------------
  721. ctkConsole::ctkConsole(QWidget* parentObject) :
  722. Superclass(parentObject),
  723. d_ptr(new ctkConsolePrivate(*this))
  724. {
  725. Q_D(ctkConsole);
  726. d->init();
  727. }
  728. //-----------------------------------------------------------------------------
  729. ctkConsole::ctkConsole(ctkConsolePrivate * pimpl, QWidget* parentObject) :
  730. QWidget(parentObject), d_ptr(pimpl)
  731. {
  732. Q_D(ctkConsole);
  733. d->init();
  734. }
  735. //-----------------------------------------------------------------------------
  736. ctkConsole::~ctkConsole()
  737. {
  738. }
  739. //-----------------------------------------------------------------------------
  740. QTextCharFormat ctkConsole::getFormat() const
  741. {
  742. Q_D(const ctkConsole);
  743. return d->currentCharFormat();
  744. }
  745. //-----------------------------------------------------------------------------
  746. void ctkConsole::setFormat(const QTextCharFormat& Format)
  747. {
  748. Q_D(ctkConsole);
  749. d->setCurrentCharFormat(Format);
  750. }
  751. //-----------------------------------------------------------------------------
  752. QFont ctkConsole::shellFont() const
  753. {
  754. Q_D(const ctkConsole);
  755. return d->currentFont();
  756. }
  757. //-----------------------------------------------------------------------------
  758. void ctkConsole::setShellFont(const QFont& font)
  759. {
  760. Q_D(ctkConsole);
  761. int savedPosition = d->textCursor().position();
  762. d->selectAll();
  763. d->setCurrentFont(font);
  764. QTextCursor tc = d->textCursor();
  765. tc.clearSelection();
  766. tc.setPosition(savedPosition);
  767. d->setTextCursor(tc);
  768. }
  769. //-----------------------------------------------------------------------------
  770. CTK_GET_CPP(ctkConsole, ctkConsoleCompleter*, completer, Completer);
  771. //-----------------------------------------------------------------------------
  772. void ctkConsole::setCompleter(ctkConsoleCompleter* completer)
  773. {
  774. Q_D(ctkConsole);
  775. d->setCompleter(completer);
  776. }
  777. //-----------------------------------------------------------------------------
  778. CTK_GET_CPP(ctkConsole, QColor, promptColor, PromptColor);
  779. CTK_SET_CPP(ctkConsole, const QColor&, setPromptColor, PromptColor);
  780. //-----------------------------------------------------------------------------
  781. CTK_GET_CPP(ctkConsole, QColor, outputTextColor, OutputTextColor);
  782. CTK_SET_CPP(ctkConsole, const QColor&, setOutputTextColor, OutputTextColor);
  783. //-----------------------------------------------------------------------------
  784. CTK_GET_CPP(ctkConsole, QColor, errorTextColor, ErrorTextColor);
  785. CTK_SET_CPP(ctkConsole, const QColor&, setErrorTextColor, ErrorTextColor);
  786. //-----------------------------------------------------------------------------
  787. CTK_GET_CPP(ctkConsole, QColor, stdinTextColor, StdinTextColor);
  788. CTK_SET_CPP(ctkConsole, const QColor&, setStdinTextColor, StdinTextColor);
  789. //-----------------------------------------------------------------------------
  790. CTK_GET_CPP(ctkConsole, QColor, commandTextColor, CommandTextColor);
  791. CTK_SET_CPP(ctkConsole, const QColor&, setCommandTextColor, CommandTextColor);
  792. //-----------------------------------------------------------------------------
  793. CTK_GET_CPP(ctkConsole, QColor, welcomeTextColor, WelcomeTextColor);
  794. CTK_SET_CPP(ctkConsole, const QColor&, setWelcomeTextColor, WelcomeTextColor);
  795. //-----------------------------------------------------------------------------
  796. QColor ctkConsole::backgroundColor()const
  797. {
  798. Q_D(const ctkConsole);
  799. QPalette pal = d->palette();
  800. return pal.color(QPalette::Base);
  801. }
  802. //-----------------------------------------------------------------------------
  803. void ctkConsole::setBackgroundColor(const QColor& newColor)
  804. {
  805. Q_D(ctkConsole);
  806. if (this->backgroundColor() == newColor)
  807. {
  808. return;
  809. }
  810. QPalette pal = this->palette();
  811. pal.setColor(QPalette::Base, newColor);
  812. d->setPalette(pal);
  813. }
  814. //-----------------------------------------------------------------------------
  815. CTK_GET_CPP(ctkConsole, QString, ps1, Ps1);
  816. CTK_SET_CPP(ctkConsole, const QString&, setPs1, Ps1);
  817. //-----------------------------------------------------------------------------
  818. CTK_GET_CPP(ctkConsole, QString, ps2, Ps2);
  819. CTK_SET_CPP(ctkConsole, const QString&, setPs2, Ps2);
  820. //-----------------------------------------------------------------------------
  821. CTK_GET_CPP(ctkConsole, ctkConsole::EditorHints, editorHints, EditorHints);
  822. CTK_SET_CPP(ctkConsole, const ctkConsole::EditorHints&, setEditorHints, EditorHints);
  823. //-----------------------------------------------------------------------------
  824. Qt::ScrollBarPolicy ctkConsole::scrollBarPolicy()const
  825. {
  826. Q_D(const ctkConsole);
  827. return d->verticalScrollBarPolicy();
  828. }
  829. //-----------------------------------------------------------------------------
  830. void ctkConsole::setScrollBarPolicy(const Qt::ScrollBarPolicy& newScrollBarPolicy)
  831. {
  832. Q_D(ctkConsole);
  833. d->setVerticalScrollBarPolicy(newScrollBarPolicy);
  834. }
  835. //-----------------------------------------------------------------------------
  836. CTK_GET_CPP(ctkConsole, QList<QKeySequence>, completerShortcuts, CompleterShortcuts);
  837. //-----------------------------------------------------------------------------
  838. void ctkConsole::setCompleterShortcuts(const QList<QKeySequence>& keys)
  839. {
  840. Q_D(ctkConsole);
  841. d->CompleterShortcuts = keys;
  842. }
  843. //-----------------------------------------------------------------------------
  844. void ctkConsole::addCompleterShortcut(const QKeySequence& key)
  845. {
  846. Q_D(ctkConsole);
  847. if (!d->CompleterShortcuts.contains(key))
  848. {
  849. d->CompleterShortcuts.append(key);
  850. }
  851. }
  852. //-----------------------------------------------------------------------------
  853. void ctkConsole::exec(const QString& command)
  854. {
  855. Q_D(ctkConsole);
  856. d->replaceCommandBuffer(command);
  857. d->internalExecuteCommand();
  858. }
  859. //-----------------------------------------------------------------------------
  860. void ctkConsole::runFile(const QString& filePath)
  861. {
  862. QFile file(filePath);
  863. if (!file.open(QIODevice::ReadOnly))
  864. {
  865. qWarning() << tr( "File '%1' can't be read.").arg(filePath);
  866. return;
  867. }
  868. for (QTextStream fileStream(&file); !fileStream.atEnd();)
  869. {
  870. QString line = fileStream.readLine();
  871. this->exec(line);
  872. }
  873. }
  874. //-----------------------------------------------------------------------------
  875. void ctkConsole::runFile()
  876. {
  877. QString filePath =
  878. QFileDialog::getOpenFileName(this, tr("Select a script file to run"));
  879. if (!filePath.isEmpty())
  880. {
  881. this->runFile(filePath);
  882. }
  883. }
  884. //-----------------------------------------------------------------------------
  885. void ctkConsole::printHelp()
  886. {
  887. this->printMessage("\n", Qt::gray);
  888. this->printMessage(tr("CTRL+h: Print this help message\n"), Qt::gray);
  889. this->printMessage(tr("CTRL+r: Open a file dialog to select a file to run\n"), Qt::gray);
  890. }
  891. //-----------------------------------------------------------------------------
  892. void ctkConsole::executeCommand(const QString& command)
  893. {
  894. qWarning() << "ctkConsole::executeCommand not implemented !";
  895. qWarning() << "command:" << command;
  896. }
  897. //----------------------------------------------------------------------------
  898. void ctkConsole::printMessage(const QString& message, const QColor& color)
  899. {
  900. Q_D(ctkConsole);
  901. QTextCharFormat format = this->getFormat();
  902. format.setForeground(color);
  903. this->setFormat(format);
  904. d->printString(message);
  905. }
  906. //-----------------------------------------------------------------------------
  907. void ctkConsole::clear()
  908. {
  909. Q_D(ctkConsole);
  910. d->clear();
  911. // For some reason the QCompleter tries to set the focus policy to
  912. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  913. d->setFocusPolicy(Qt::WheelFocus);
  914. d->promptForInput();
  915. }
  916. //-----------------------------------------------------------------------------
  917. void ctkConsole::reset()
  918. {
  919. Q_D(ctkConsole);
  920. d->clear();
  921. // For some reason the QCompleter tries to set the focus policy to
  922. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  923. d->setFocusPolicy(Qt::WheelFocus);
  924. d->printWelcomeMessage();
  925. d->promptForInput();
  926. }
  927. //-----------------------------------------------------------------------------
  928. QString ctkConsole::stdInRedirectCallBack(void * callData)
  929. {
  930. ctkConsole * self = reinterpret_cast<ctkConsole*>(callData);
  931. Q_ASSERT(self);
  932. if (!self)
  933. {
  934. return QLatin1String("");
  935. }
  936. return self->readInputLine();
  937. }
  938. namespace
  939. {
  940. class InputEventLoop : public QEventLoop
  941. {
  942. public:
  943. InputEventLoop(QApplication * app, QObject * parentObject = 0) :
  944. QEventLoop(parentObject), App(app){}
  945. virtual bool processEvents(ProcessEventsFlags flags = AllEvents)
  946. {
  947. this->App->processEvents(flags);
  948. return true;
  949. }
  950. QApplication * App;
  951. };
  952. }
  953. //-----------------------------------------------------------------------------
  954. QString ctkConsole::readInputLine()
  955. {
  956. Q_D(ctkConsole);
  957. d->moveCursor(QTextCursor::End);
  958. QScopedPointer<InputEventLoop> eventLoop(new InputEventLoop(qApp));
  959. d->InputEventLoop = QPointer<QEventLoop>(eventLoop.data());
  960. eventLoop->exec();
  961. return d->commandBuffer();
  962. }