ctkConsole.cpp 43 KB

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