ctkConsole.cpp 36 KB

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