ctkConsole.cpp 28 KB

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