ctkConsole.cpp 44 KB

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