ctkConsole.cpp 33 KB

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