ctkConsole.cpp 31 KB

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