ctkConsole.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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. void ctkConsolePrivate::keyPressEvent(QKeyEvent* e)
  207. {
  208. if (this->Completer && this->Completer->popup()->isVisible())
  209. {
  210. // The following keys are forwarded by the completer to the widget
  211. switch (e->key())
  212. {
  213. case Qt::Key_Enter:
  214. case Qt::Key_Return:
  215. case Qt::Key_Escape:
  216. case Qt::Key_Tab:
  217. case Qt::Key_Backtab:
  218. e->ignore();
  219. return; // let the completer do default behavior
  220. default:
  221. break;
  222. }
  223. }
  224. QTextCursor text_cursor = this->textCursor();
  225. // Set to true if there's a current selection
  226. const bool selection = text_cursor.anchor() != text_cursor.position();
  227. // Set to true if the cursor overlaps the history area
  228. const bool history_area = this->isCursorInHistoryArea();
  229. // Allow copying anywhere in the console ...
  230. if(e == QKeySequence::Copy)
  231. {
  232. if(selection)
  233. {
  234. this->copy();
  235. }
  236. e->accept();
  237. return;
  238. }
  239. // Allow cut only if the selection is limited to the interactive area ...
  240. if(e == QKeySequence::Cut)
  241. {
  242. if(selection && !history_area)
  243. {
  244. this->cut();
  245. }
  246. e->accept();
  247. return;
  248. }
  249. // Paste to the end of document if in the history area
  250. if(e == QKeySequence::Paste)
  251. {
  252. if(history_area)
  253. {
  254. text_cursor.setPosition(this->documentEnd());
  255. this->setTextCursor(text_cursor);
  256. }
  257. this->paste();
  258. e->accept();
  259. return;
  260. }
  261. // Allow vertical scrolling using page up/down
  262. if (e == QKeySequence::MoveToPreviousPage || e == QKeySequence::SelectPreviousPage
  263. || e == QKeySequence::MoveToNextPage || e == QKeySequence::SelectNextPage)
  264. {
  265. if (e == QKeySequence::SelectPreviousPage || e == QKeySequence::SelectNextPage)
  266. {
  267. // ignore
  268. e->accept();
  269. }
  270. else
  271. {
  272. this->Superclass::keyPressEvent(e);
  273. this->updateCommandBuffer();
  274. }
  275. return;
  276. }
  277. // Force the cursor back to the interactive area if anything else than copy/paste or page up/down is done
  278. // but only when a "real" key is pressed, not just a modifier (otherwise we could not press Control-c in the
  279. // history area because the cursor would jump to the interactive area immediately when Control is pressed)
  280. if(history_area
  281. && e->key() != Qt::Key_Control
  282. && e->key() != Qt::Key_Meta
  283. && e->key() != Qt::Key_Alt
  284. && e->key() != Qt::Key_Shift)
  285. {
  286. text_cursor.setPosition(this->documentEnd());
  287. this->setTextCursor(text_cursor);
  288. }
  289. // Start of line should be the start of interactive area
  290. QTextCursor::MoveOperation moveOperation = QTextCursor::NoMove;
  291. QTextCursor::MoveMode moveMode = QTextCursor::MoveAnchor;
  292. if(isMoveLeftWithinLine(e, moveOperation, moveMode))
  293. {
  294. text_cursor.movePosition(moveOperation, moveMode);
  295. if (text_cursor.position() > this->InteractivePosition)
  296. {
  297. this->Superclass::keyPressEvent(e);
  298. }
  299. else
  300. {
  301. text_cursor.setPosition(this->InteractivePosition, moveMode);
  302. this->setTextCursor(text_cursor);
  303. e->accept();
  304. }
  305. return;
  306. }
  307. if (e == QKeySequence::Delete)
  308. {
  309. e->accept();
  310. this->Superclass::keyPressEvent(e);
  311. this->updateCommandBuffer();
  312. return;
  313. }
  314. // There seems to be no QKeySequence for backspace, therefore the key
  315. // has to be recognized directly (the same way as it is done in the parent class)
  316. if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~Qt::ShiftModifier))
  317. {
  318. e->accept();
  319. if(text_cursor.position() > this->InteractivePosition)
  320. {
  321. this->Superclass::keyPressEvent(e);
  322. this->updateCommandBuffer();
  323. this->updateCompleterIfVisible();
  324. }
  325. return;
  326. }
  327. if (e == QKeySequence::DeleteStartOfWord)
  328. {
  329. e->accept();
  330. if(text_cursor.position() > this->InteractivePosition)
  331. {
  332. this->Superclass::keyPressEvent(e);
  333. this->updateCommandBuffer();
  334. this->updateCompleterIfVisible();
  335. }
  336. return;
  337. }
  338. if (e == QKeySequence::MoveToPreviousLine || e == QKeySequence::SelectPreviousLine)
  339. {
  340. e->accept();
  341. if (this->CommandPosition > 0)
  342. {
  343. this->replaceCommandBuffer(this->CommandHistory[--this->CommandPosition]);
  344. }
  345. return;
  346. }
  347. if (e == QKeySequence::MoveToNextLine || e == QKeySequence::SelectNextLine)
  348. {
  349. e->accept();
  350. if (this->CommandPosition < this->CommandHistory.size() - 2)
  351. {
  352. this->replaceCommandBuffer(this->CommandHistory[++this->CommandPosition]);
  353. }
  354. else
  355. {
  356. this->CommandPosition = this->CommandHistory.size()-1;
  357. this->replaceCommandBuffer("");
  358. }
  359. return;
  360. }
  361. if (e == QKeySequence::InsertParagraphSeparator)
  362. {
  363. e->accept();
  364. text_cursor.setPosition(this->documentEnd());
  365. this->setTextCursor(text_cursor);
  366. if (this->InputEventLoop.isNull())
  367. {
  368. this->internalExecuteCommand();
  369. }
  370. else
  371. {
  372. this->processInput();
  373. }
  374. return;
  375. }
  376. if (this->CompleterShortcuts.contains(e->key() + e->modifiers()))
  377. {
  378. e->accept();
  379. this->updateCompleter();
  380. this->selectCompletion();
  381. return;
  382. }
  383. e->accept();
  384. this->switchToUserInputTextColor();
  385. this->Superclass::keyPressEvent(e);
  386. this->updateCommandBuffer();
  387. this->updateCompleterIfVisible();
  388. }
  389. //-----------------------------------------------------------------------------
  390. void ctkConsolePrivate::switchToUserInputTextColor(QTextCursor* textCursorToUpdate)
  391. {
  392. QColor color = this->CommandTextColor;
  393. if (!this->InputEventLoop.isNull())
  394. {
  395. color = this->StdinTextColor;
  396. }
  397. QTextCharFormat currentFormat = this->currentCharFormat();
  398. // Do not trigger a finishEdit for no reason. onTextChanged() would be called.
  399. if (currentFormat.foreground() != color)
  400. {
  401. currentFormat.setForeground(color);
  402. this->setCurrentCharFormat(currentFormat);
  403. }
  404. if (textCursorToUpdate)
  405. {
  406. QTextCharFormat textCursorFormat = textCursorToUpdate->charFormat();
  407. if (textCursorFormat.foreground() != color)
  408. {
  409. textCursorFormat.setForeground(color);
  410. textCursorToUpdate->setCharFormat(textCursorFormat);
  411. }
  412. }
  413. }
  414. //-----------------------------------------------------------------------------
  415. int ctkConsolePrivate::documentEnd() const
  416. {
  417. QTextCursor c(this->document());
  418. c.movePosition(QTextCursor::End);
  419. return c.position();
  420. }
  421. //-----------------------------------------------------------------------------
  422. int ctkConsolePrivate::commandEnd() const
  423. {
  424. QTextCursor c(this->document());
  425. c.setPosition(this->documentEnd()-this->MessageOutputSize);
  426. return c.position();
  427. }
  428. //-----------------------------------------------------------------------------
  429. void ctkConsolePrivate::focusOutEvent(QFocusEvent *e)
  430. {
  431. this->Superclass::focusOutEvent(e);
  432. // For some reason the QCompleter tries to set the focus policy to
  433. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  434. this->setFocusPolicy(Qt::WheelFocus);
  435. }
  436. //-----------------------------------------------------------------------------
  437. void ctkConsolePrivate::resizeEvent(QResizeEvent * e)
  438. {
  439. this->Superclass::resizeEvent(e);
  440. if (this->ScrollbarAtBottom)
  441. {
  442. this->moveCursor(QTextCursor::End);
  443. this->scrollToBottom();
  444. }
  445. }
  446. //-----------------------------------------------------------------------------
  447. void ctkConsolePrivate::scrollToBottom()
  448. {
  449. this->verticalScrollBar()->setValue(this->verticalScrollBar()->maximum());
  450. }
  451. //-----------------------------------------------------------------------------
  452. void ctkConsolePrivate::updateCompleterIfVisible()
  453. {
  454. if (this->Completer && this->Completer->popup()->isVisible())
  455. {
  456. this->updateCompleter();
  457. }
  458. }
  459. //-----------------------------------------------------------------------------
  460. void ctkConsolePrivate::selectCompletion()
  461. {
  462. if (this->Completer && this->Completer->completionCount() == 1)
  463. {
  464. this->insertCompletion(this->Completer->currentCompletion());
  465. this->Completer->popup()->hide();
  466. }
  467. }
  468. //-----------------------------------------------------------------------------
  469. void ctkConsolePrivate::setCompleter(ctkConsoleCompleter* completer)
  470. {
  471. if (this->Completer)
  472. {
  473. this->Completer->setWidget(0);
  474. disconnect(this->Completer, SIGNAL(activated(QString)),
  475. this, SLOT(insertCompletion(QString)));
  476. }
  477. this->Completer = completer;
  478. if (this->Completer)
  479. {
  480. this->Completer->setWidget(this);
  481. connect(this->Completer, SIGNAL(activated(QString)),
  482. this, SLOT(insertCompletion(QString)));
  483. }
  484. }
  485. //-----------------------------------------------------------------------------
  486. void ctkConsolePrivate::updateCompleter()
  487. {
  488. if (this->Completer)
  489. {
  490. // Get the text between the current cursor position
  491. // and the start of the line
  492. QTextCursor text_cursor = this->textCursor();
  493. text_cursor.setPosition(this->InteractivePosition, QTextCursor::KeepAnchor);
  494. QString commandText = text_cursor.selectedText();
  495. // Save current positions: Since some implementation of
  496. // updateCompletionModel (e.g python) can display messages
  497. // while building the completion model, it is important to save
  498. // and restore the positions.
  499. int savedInteractivePosition = this->InteractivePosition;
  500. int savedCursorPosition = this->textCursor().position();
  501. //move the cursor at the end in case of a message displayed
  502. QTextCursor tc = this->textCursor();
  503. tc.setPosition(this->documentEnd());
  504. this->setTextCursor(tc);
  505. // Save color of displayed message
  506. QColor savedOutputTextColor = this->OutputTextColor;
  507. QColor savedErrorTextColor = this->ErrorTextColor;
  508. // Change color of displayed message in message_output_area
  509. this->OutputTextColor = this->MessageOutputColor;
  510. this->ErrorTextColor = this->MessageOutputColor;
  511. // Call the completer to update the completion model
  512. this->Completer->updateCompletionModel(commandText);
  513. // Restore Color
  514. this->OutputTextColor = savedOutputTextColor;
  515. this->ErrorTextColor = savedErrorTextColor;
  516. // Restore positions
  517. this->InteractivePosition = savedInteractivePosition;
  518. QTextCursor textCursor = this->textCursor();
  519. textCursor.setPosition(savedCursorPosition);
  520. this->setTextCursor(textCursor);
  521. // Place and show the completer if there are available completions
  522. if (this->Completer->completionCount())
  523. {
  524. // Get a QRect for the cursor at the start of the
  525. // current word and then translate it down 8 pixels.
  526. text_cursor = this->textCursor();
  527. text_cursor.movePosition(QTextCursor::StartOfWord);
  528. QRect cr = this->cursorRect(text_cursor);
  529. cr.translate(0,8);
  530. cr.setWidth(this->Completer->popup()->sizeHintForColumn(0)
  531. + this->Completer->popup()->verticalScrollBar()->sizeHint().width());
  532. this->Completer->complete(cr);
  533. }
  534. else
  535. {
  536. this->Completer->popup()->hide();
  537. }
  538. }
  539. }
  540. //-----------------------------------------------------------------------------
  541. void ctkConsolePrivate::updateCommandBuffer(int commandLength)
  542. {
  543. if (commandLength == -1)
  544. {
  545. commandLength =
  546. this->commandEnd() - this->InteractivePosition;
  547. }
  548. this->commandBuffer() =
  549. this->toPlainText().mid(this->InteractivePosition, commandLength);
  550. }
  551. //-----------------------------------------------------------------------------
  552. void ctkConsolePrivate::replaceCommandBuffer(const QString& text)
  553. {
  554. this->commandBuffer() = text;
  555. QTextCursor c(this->document());
  556. c.setPosition(this->InteractivePosition);
  557. c.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
  558. c.removeSelectedText();
  559. // all text removed, we need then to re-init our tracker on the message output area
  560. this->MessageOutputSize = 0;
  561. this->switchToUserInputTextColor(&c);
  562. c.insertText(text);
  563. }
  564. //-----------------------------------------------------------------------------
  565. QString& ctkConsolePrivate::commandBuffer()
  566. {
  567. return this->CommandHistory.back();
  568. }
  569. //-----------------------------------------------------------------------------
  570. void ctkConsolePrivate::internalExecuteCommand()
  571. {
  572. Q_Q(ctkConsole);
  573. QString command = this->commandBuffer();
  574. if (this->EditorHints & ctkConsole::RemoveTrailingSpaces)
  575. {
  576. command.replace(QRegExp("\\s*$"), ""); // Remove trailing spaces
  577. this->commandBuffer() = command; // Update buffer
  578. }
  579. // First update the history cache. It's essential to update the
  580. // this->CommandPosition before calling internalExecuteCommand() since that
  581. // can result in a clearing of the current command (BUG #8765).
  582. if (!command.isEmpty()) // Don't store empty commands in the history
  583. {
  584. this->CommandHistory.push_back("");
  585. this->CommandPosition = this->CommandHistory.size() - 1;
  586. }
  587. QTextCursor c(this->document());
  588. c.movePosition(QTextCursor::End);
  589. c.insertText("\n");
  590. this->InteractivePosition = this->documentEnd();
  591. emit q->aboutToExecute(command);
  592. q->executeCommand(command);
  593. emit q->executed(command);
  594. // Find the indent for the command.
  595. QString indent;
  596. if (this->EditorHints & ctkConsole::AutomaticIndentation)
  597. {
  598. QRegExp regExp("^(\\s+)");
  599. if (regExp.indexIn(command) != -1)
  600. {
  601. indent = regExp.cap(1);
  602. }
  603. }
  604. this->promptForInput(indent);
  605. this->MessageOutputSize = 0;
  606. }
  607. //-----------------------------------------------------------------------------
  608. void ctkConsolePrivate::processInput()
  609. {
  610. QString command = this->commandBuffer();
  611. if (this->EditorHints & ctkConsole::RemoveTrailingSpaces)
  612. {
  613. command.replace(QRegExp("\\s*$"), ""); // Remove trailing spaces
  614. this->commandBuffer() = command; // Update buffer
  615. }
  616. QTextCursor c(this->document());
  617. c.movePosition(QTextCursor::End);
  618. c.insertText("\n");
  619. this->InteractivePosition = this->documentEnd();
  620. this->InputEventLoop->exit();
  621. }
  622. //-----------------------------------------------------------------------------
  623. void ctkConsolePrivate::printString(const QString& text)
  624. {
  625. this->textCursor().movePosition(QTextCursor::End);
  626. this->textCursor().insertText(text);
  627. this->InteractivePosition = this->documentEnd();
  628. }
  629. //----------------------------------------------------------------------------
  630. void ctkConsolePrivate::printOutputMessage(const QString& text)
  631. {
  632. Q_Q(ctkConsole);
  633. QString textToPrint = text;
  634. if (this->MessageOutputSize == 0)
  635. {
  636. textToPrint.prepend("\n");
  637. }
  638. this->MessageOutputSize += textToPrint.size();
  639. q->printMessage(textToPrint, q->outputTextColor());
  640. }
  641. //----------------------------------------------------------------------------
  642. void ctkConsolePrivate::printErrorMessage(const QString& text)
  643. {
  644. Q_Q(ctkConsole);
  645. QString textToPrint = text;
  646. if (this->MessageOutputSize == 0)
  647. {
  648. textToPrint.prepend("\n");
  649. }
  650. this->MessageOutputSize += textToPrint.size();
  651. q->printMessage(textToPrint, q->errorTextColor());
  652. }
  653. //-----------------------------------------------------------------------------
  654. void ctkConsolePrivate::printCommand(const QString& cmd)
  655. {
  656. this->textCursor().insertText(cmd);
  657. this->updateCommandBuffer();
  658. }
  659. //----------------------------------------------------------------------------
  660. void ctkConsolePrivate::promptForInput(const QString& indent)
  661. {
  662. Q_Q(ctkConsole);
  663. QTextCharFormat format = q->getFormat();
  664. format.setForeground(q->promptColor());
  665. q->setFormat(format);
  666. if(!this->MultilineStatement)
  667. {
  668. this->prompt(q->ps1());
  669. this->MessageOutputSize=0;
  670. }
  671. else
  672. {
  673. this->prompt(q->ps2());
  674. }
  675. this->printCommand(indent);
  676. }
  677. //-----------------------------------------------------------------------------
  678. void ctkConsolePrivate::prompt(const QString& text)
  679. {
  680. QTextCursor text_cursor = this->textCursor();
  681. // If the cursor is currently on a clean line, do nothing, otherwise we move
  682. // the cursor to a new line before showing the prompt.
  683. text_cursor.movePosition(QTextCursor::StartOfLine);
  684. int startpos = text_cursor.position();
  685. text_cursor.movePosition(QTextCursor::EndOfLine);
  686. int endpos = text_cursor.position();
  687. if (endpos != startpos)
  688. {
  689. this->textCursor().insertText("\n");
  690. }
  691. this->textCursor().insertText(text);
  692. this->InteractivePosition = this->documentEnd();
  693. }
  694. //----------------------------------------------------------------------------
  695. void ctkConsolePrivate::printWelcomeMessage()
  696. {
  697. Q_Q(ctkConsole);
  698. q->printMessage(
  699. QLatin1String("CTK Console"),
  700. q->welcomeTextColor());
  701. }
  702. //-----------------------------------------------------------------------------
  703. void ctkConsolePrivate::insertCompletion(const QString& completion)
  704. {
  705. Q_Q(ctkConsole);
  706. QTextCursor tc = this->textCursor();
  707. tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
  708. if (tc.selectedText()==".")
  709. {
  710. tc.insertText(QString(".") + completion);
  711. }
  712. else
  713. {
  714. tc = this->textCursor();
  715. tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
  716. tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
  717. tc.insertText(completion);
  718. this->setTextCursor(tc);
  719. }
  720. tc.movePosition(QTextCursor::StartOfBlock);
  721. tc.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
  722. QString shellLine = tc.selectedText();
  723. shellLine.replace(q->ps1(), "");
  724. shellLine.replace(q->ps2(), "");
  725. tc.movePosition(QTextCursor::EndOfLine, QTextCursor::MoveAnchor);
  726. this->setTextCursor(tc);
  727. int cursorOffset = this->Completer->cursorOffset(shellLine);
  728. tc.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, cursorOffset);
  729. this->setTextCursor(tc);
  730. this->updateCommandBuffer();
  731. }
  732. //-----------------------------------------------------------------------------
  733. void ctkConsolePrivate::onScrollBarValueChanged(int value)
  734. {
  735. this->ScrollbarAtBottom = (this->verticalScrollBar()->maximum() == value);
  736. }
  737. //-----------------------------------------------------------------------------
  738. void ctkConsolePrivate::onTextChanged()
  739. {
  740. this->scrollToBottom();
  741. this->ensureCursorVisible();
  742. }
  743. //-----------------------------------------------------------------------------
  744. bool ctkConsolePrivate::isCursorInHistoryArea()const
  745. {
  746. return this->textCursor().anchor() < this->InteractivePosition
  747. || this->textCursor().position() < this->InteractivePosition;
  748. }
  749. //-----------------------------------------------------------------------------
  750. bool ctkConsolePrivate::isCursorInMessageOutputArea()const
  751. {
  752. return this->textCursor().anchor() > this->commandEnd()
  753. || this->textCursor().position() > this->commandEnd();
  754. }
  755. //-----------------------------------------------------------------------------
  756. void ctkConsolePrivate::insertFromMimeData(const QMimeData* source)
  757. {
  758. if (this->isCursorInHistoryArea())
  759. {
  760. QTextCursor textCursor = this->textCursor();
  761. textCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
  762. this->setTextCursor(textCursor);
  763. }
  764. const QString text = source->text();
  765. if (!text.isEmpty())
  766. {
  767. this->pasteText(text);
  768. }
  769. else
  770. {
  771. this->Superclass::insertFromMimeData(source);
  772. }
  773. }
  774. //-----------------------------------------------------------------------------
  775. void ctkConsolePrivate::pasteText(const QString& text)
  776. {
  777. if(text.isNull())
  778. {
  779. return;
  780. }
  781. QTextCursor textCursor = this->textCursor();
  782. if (this->EditorHints & ctkConsole::SplitCopiedTextByLine)
  783. {
  784. QStringList lines = text.split(QRegExp("(?:\r\n|\r|\n)"));
  785. for(int i=0; i < lines.count(); ++i)
  786. {
  787. this->switchToUserInputTextColor(&textCursor);
  788. textCursor.insertText(lines.at(i));
  789. this->updateCommandBuffer();
  790. if (i < lines.count() - 1)
  791. {
  792. this->internalExecuteCommand();
  793. }
  794. }
  795. }
  796. else
  797. {
  798. this->switchToUserInputTextColor(&textCursor);
  799. textCursor.insertText(text);
  800. this->updateCommandBuffer();
  801. }
  802. }
  803. //-----------------------------------------------------------------------------
  804. // ctkConsole methods
  805. //-----------------------------------------------------------------------------
  806. ctkConsole::ctkConsole(QWidget* parentObject) :
  807. Superclass(parentObject),
  808. d_ptr(new ctkConsolePrivate(*this))
  809. {
  810. Q_D(ctkConsole);
  811. d->init();
  812. }
  813. //-----------------------------------------------------------------------------
  814. ctkConsole::ctkConsole(ctkConsolePrivate * pimpl, QWidget* parentObject) :
  815. QWidget(parentObject), d_ptr(pimpl)
  816. {
  817. Q_D(ctkConsole);
  818. d->init();
  819. }
  820. //-----------------------------------------------------------------------------
  821. ctkConsole::~ctkConsole()
  822. {
  823. }
  824. //-----------------------------------------------------------------------------
  825. QTextCharFormat ctkConsole::getFormat() const
  826. {
  827. Q_D(const ctkConsole);
  828. return d->currentCharFormat();
  829. }
  830. //-----------------------------------------------------------------------------
  831. void ctkConsole::setFormat(const QTextCharFormat& Format)
  832. {
  833. Q_D(ctkConsole);
  834. d->setCurrentCharFormat(Format);
  835. }
  836. //-----------------------------------------------------------------------------
  837. QFont ctkConsole::shellFont() const
  838. {
  839. Q_D(const ctkConsole);
  840. return d->currentFont();
  841. }
  842. //-----------------------------------------------------------------------------
  843. void ctkConsole::setShellFont(const QFont& font)
  844. {
  845. Q_D(ctkConsole);
  846. int savedPosition = d->textCursor().position();
  847. d->selectAll();
  848. d->setCurrentFont(font);
  849. QTextCursor tc = d->textCursor();
  850. tc.clearSelection();
  851. tc.setPosition(savedPosition);
  852. d->setTextCursor(tc);
  853. }
  854. //-----------------------------------------------------------------------------
  855. CTK_GET_CPP(ctkConsole, ctkConsoleCompleter*, completer, Completer);
  856. //-----------------------------------------------------------------------------
  857. void ctkConsole::setCompleter(ctkConsoleCompleter* completer)
  858. {
  859. Q_D(ctkConsole);
  860. d->setCompleter(completer);
  861. }
  862. //-----------------------------------------------------------------------------
  863. CTK_GET_CPP(ctkConsole, QColor, promptColor, PromptColor);
  864. CTK_SET_CPP(ctkConsole, const QColor&, setPromptColor, PromptColor);
  865. //-----------------------------------------------------------------------------
  866. CTK_GET_CPP(ctkConsole, QColor, outputTextColor, OutputTextColor);
  867. CTK_SET_CPP(ctkConsole, const QColor&, setOutputTextColor, OutputTextColor);
  868. //-----------------------------------------------------------------------------
  869. CTK_GET_CPP(ctkConsole, QColor, errorTextColor, ErrorTextColor);
  870. CTK_SET_CPP(ctkConsole, const QColor&, setErrorTextColor, ErrorTextColor);
  871. //-----------------------------------------------------------------------------
  872. CTK_GET_CPP(ctkConsole, QColor, stdinTextColor, StdinTextColor);
  873. CTK_SET_CPP(ctkConsole, const QColor&, setStdinTextColor, StdinTextColor);
  874. //-----------------------------------------------------------------------------
  875. CTK_GET_CPP(ctkConsole, QColor, commandTextColor, CommandTextColor);
  876. CTK_SET_CPP(ctkConsole, const QColor&, setCommandTextColor, CommandTextColor);
  877. //-----------------------------------------------------------------------------
  878. CTK_GET_CPP(ctkConsole, QColor, welcomeTextColor, WelcomeTextColor);
  879. CTK_SET_CPP(ctkConsole, const QColor&, setWelcomeTextColor, WelcomeTextColor);
  880. //-----------------------------------------------------------------------------
  881. QColor ctkConsole::backgroundColor()const
  882. {
  883. Q_D(const ctkConsole);
  884. QPalette pal = d->palette();
  885. return pal.color(QPalette::Base);
  886. }
  887. //-----------------------------------------------------------------------------
  888. void ctkConsole::setBackgroundColor(const QColor& newColor)
  889. {
  890. Q_D(ctkConsole);
  891. if (this->backgroundColor() == newColor)
  892. {
  893. return;
  894. }
  895. QPalette pal = this->palette();
  896. pal.setColor(QPalette::Base, newColor);
  897. d->setPalette(pal);
  898. }
  899. //-----------------------------------------------------------------------------
  900. CTK_GET_CPP(ctkConsole, QString, ps1, Ps1);
  901. CTK_SET_CPP(ctkConsole, const QString&, setPs1, Ps1);
  902. //-----------------------------------------------------------------------------
  903. CTK_GET_CPP(ctkConsole, QString, ps2, Ps2);
  904. CTK_SET_CPP(ctkConsole, const QString&, setPs2, Ps2);
  905. //-----------------------------------------------------------------------------
  906. CTK_GET_CPP(ctkConsole, ctkConsole::EditorHints, editorHints, EditorHints);
  907. CTK_SET_CPP(ctkConsole, const ctkConsole::EditorHints&, setEditorHints, EditorHints);
  908. //-----------------------------------------------------------------------------
  909. int ctkConsole::cursorPosition() const
  910. {
  911. Q_D(const ctkConsole);
  912. return d->textCursor().position();
  913. }
  914. //-----------------------------------------------------------------------------
  915. int ctkConsole::cursorColumn() const
  916. {
  917. Q_D(const ctkConsole);
  918. QTextCursor cursor = d->textCursor();
  919. cursor.movePosition(QTextCursor::StartOfLine);
  920. return d->textCursor().position() - cursor.position();
  921. }
  922. //-----------------------------------------------------------------------------
  923. int ctkConsole::cursorLine() const
  924. {
  925. Q_D(const ctkConsole);
  926. QTextCursor cursor = d->textCursor();
  927. cursor.movePosition(QTextCursor::StartOfLine);
  928. int lines = 1;
  929. QTextBlock block = cursor.block().previous();
  930. while(block.isValid())
  931. {
  932. lines += block.lineCount();
  933. block = block.previous();
  934. }
  935. return lines;
  936. }
  937. //-----------------------------------------------------------------------------
  938. Qt::ScrollBarPolicy ctkConsole::scrollBarPolicy()const
  939. {
  940. Q_D(const ctkConsole);
  941. return d->verticalScrollBarPolicy();
  942. }
  943. //-----------------------------------------------------------------------------
  944. void ctkConsole::setScrollBarPolicy(const Qt::ScrollBarPolicy& newScrollBarPolicy)
  945. {
  946. Q_D(ctkConsole);
  947. d->setVerticalScrollBarPolicy(newScrollBarPolicy);
  948. }
  949. //-----------------------------------------------------------------------------
  950. CTK_GET_CPP(ctkConsole, QList<QKeySequence>, completerShortcuts, CompleterShortcuts);
  951. //-----------------------------------------------------------------------------
  952. void ctkConsole::setCompleterShortcuts(const QList<QKeySequence>& keys)
  953. {
  954. Q_D(ctkConsole);
  955. d->CompleterShortcuts = keys;
  956. }
  957. //-----------------------------------------------------------------------------
  958. void ctkConsole::addCompleterShortcut(const QKeySequence& key)
  959. {
  960. Q_D(ctkConsole);
  961. if (!d->CompleterShortcuts.contains(key))
  962. {
  963. d->CompleterShortcuts.append(key);
  964. }
  965. }
  966. //-----------------------------------------------------------------------------
  967. CTK_GET_CPP(ctkConsole, ctkConsole::RunFileOptions, runFileOptions, RunFileOptions);
  968. //-----------------------------------------------------------------------------
  969. void ctkConsole::setRunFileOptions(const RunFileOptions& newOptions)
  970. {
  971. Q_D(ctkConsole);
  972. d->RunFileButton->setVisible(newOptions.testFlag(ctkConsole::RunFileButton));
  973. d->RunFileAction->setEnabled(newOptions.testFlag(ctkConsole::RunFileShortcut));
  974. }
  975. //-----------------------------------------------------------------------------
  976. void ctkConsole::exec(const QString& command)
  977. {
  978. Q_D(ctkConsole);
  979. d->replaceCommandBuffer(command);
  980. d->internalExecuteCommand();
  981. }
  982. //-----------------------------------------------------------------------------
  983. void ctkConsole::runFile(const QString& filePath)
  984. {
  985. QFile file(filePath);
  986. if (!file.open(QIODevice::ReadOnly))
  987. {
  988. qWarning() << tr( "File '%1' can't be read.").arg(filePath);
  989. return;
  990. }
  991. for (QTextStream fileStream(&file); !fileStream.atEnd();)
  992. {
  993. QString line = fileStream.readLine();
  994. this->exec(line);
  995. }
  996. }
  997. //-----------------------------------------------------------------------------
  998. void ctkConsole::runFile()
  999. {
  1000. QString filePath =
  1001. QFileDialog::getOpenFileName(this, tr("Select a script file to run"));
  1002. if (!filePath.isEmpty())
  1003. {
  1004. this->runFile(filePath);
  1005. }
  1006. }
  1007. //-----------------------------------------------------------------------------
  1008. void ctkConsole::printHelp()
  1009. {
  1010. this->printMessage("\n", Qt::gray);
  1011. this->printMessage(tr("CTRL+h: Print this help message\n"), Qt::gray);
  1012. this->printMessage(tr("CTRL+r: Open a file dialog to select a file to run\n"), Qt::gray);
  1013. }
  1014. //-----------------------------------------------------------------------------
  1015. void ctkConsole::executeCommand(const QString& command)
  1016. {
  1017. qWarning() << "ctkConsole::executeCommand not implemented !";
  1018. qWarning() << "command:" << command;
  1019. }
  1020. //----------------------------------------------------------------------------
  1021. void ctkConsole::printMessage(const QString& message, const QColor& color)
  1022. {
  1023. Q_D(ctkConsole);
  1024. QTextCharFormat format = this->getFormat();
  1025. format.setForeground(color);
  1026. this->setFormat(format);
  1027. d->printString(message);
  1028. }
  1029. //-----------------------------------------------------------------------------
  1030. void ctkConsole::clear()
  1031. {
  1032. Q_D(ctkConsole);
  1033. d->clear();
  1034. // For some reason the QCompleter tries to set the focus policy to
  1035. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  1036. d->setFocusPolicy(Qt::WheelFocus);
  1037. d->promptForInput();
  1038. }
  1039. //-----------------------------------------------------------------------------
  1040. void ctkConsole::reset()
  1041. {
  1042. Q_D(ctkConsole);
  1043. d->clear();
  1044. // For some reason the QCompleter tries to set the focus policy to
  1045. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  1046. d->setFocusPolicy(Qt::WheelFocus);
  1047. d->printWelcomeMessage();
  1048. d->promptForInput();
  1049. }
  1050. //-----------------------------------------------------------------------------
  1051. QString ctkConsole::stdInRedirectCallBack(void * callData)
  1052. {
  1053. ctkConsole * self = reinterpret_cast<ctkConsole*>(callData);
  1054. Q_ASSERT(self);
  1055. if (!self)
  1056. {
  1057. return QLatin1String("");
  1058. }
  1059. return self->readInputLine();
  1060. }
  1061. namespace
  1062. {
  1063. class InputEventLoop : public QEventLoop
  1064. {
  1065. public:
  1066. InputEventLoop(QApplication * app, QObject * parentObject = 0) :
  1067. QEventLoop(parentObject), App(app){}
  1068. virtual bool processEvents(ProcessEventsFlags flags = AllEvents)
  1069. {
  1070. this->App->processEvents(flags);
  1071. return true;
  1072. }
  1073. QApplication * App;
  1074. };
  1075. }
  1076. //-----------------------------------------------------------------------------
  1077. QString ctkConsole::readInputLine()
  1078. {
  1079. Q_D(ctkConsole);
  1080. d->moveCursor(QTextCursor::End);
  1081. QScopedPointer<InputEventLoop> eventLoop(new InputEventLoop(qApp));
  1082. d->InputEventLoop = QPointer<QEventLoop>(eventLoop.data());
  1083. eventLoop->exec();
  1084. return d->commandBuffer();
  1085. }