ctkConsoleWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. All rights reserved.
  5. Distributed under a BSD License. See LICENSE.txt file.
  6. This software is distributed "AS IS" WITHOUT ANY WARRANTY; without even
  7. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the above copyright notice for more information.
  9. =========================================================================*/
  10. /*=========================================================================
  11. Program: ParaView
  12. Module: $RCSfile$
  13. Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
  14. All rights reserved.
  15. ParaView is a free software; you can redistribute it and/or modify it
  16. under the terms of the ParaView license version 1.2.
  17. See License_v1.2.txt for the full ParaView license.
  18. A copy of this license can be obtained by contacting
  19. Kitware Inc.
  20. 28 Corporate Drive
  21. Clifton Park, NY 12065
  22. USA
  23. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
  27. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  28. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  29. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  30. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  31. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  32. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  33. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. =========================================================================*/
  35. // Qt includes
  36. #include <QAbstractItemView>
  37. #include <QApplication>
  38. #include <QClipboard>
  39. #include <QCompleter>
  40. #include <QKeyEvent>
  41. #include <QPointer>
  42. #include <QTextCursor>
  43. #include <QTextEdit>
  44. #include <QVBoxLayout>
  45. #include <QScrollBar>
  46. // CTK includes
  47. #include "ctkConsoleWidget.h"
  48. /////////////////////////////////////////////////////////////////////////
  49. // ctkConsoleWidget::pqImplementation
  50. class ctkConsoleWidget::pqImplementation :
  51. public QTextEdit
  52. {
  53. public:
  54. pqImplementation(ctkConsoleWidget& p) :
  55. QTextEdit(&p),
  56. Parent(p),
  57. InteractivePosition(documentEnd())
  58. {
  59. this->setTabChangesFocus(false);
  60. this->setAcceptDrops(false);
  61. this->setAcceptRichText(false);
  62. this->setUndoRedoEnabled(false);
  63. QFont f;
  64. f.setFamily("Courier");
  65. f.setStyleHint(QFont::TypeWriter);
  66. f.setFixedPitch(true);
  67. QTextCharFormat format;
  68. format.setFont(f);
  69. format.setForeground(QColor(0, 0, 0));
  70. this->setCurrentCharFormat(format);
  71. this->CommandHistory.append("");
  72. this->CommandPosition = 0;
  73. }
  74. void keyPressEvent(QKeyEvent* e)
  75. {
  76. if (this->Completer && this->Completer->popup()->isVisible())
  77. {
  78. // The following keys are forwarded by the completer to the widget
  79. switch (e->key())
  80. {
  81. case Qt::Key_Enter:
  82. case Qt::Key_Return:
  83. case Qt::Key_Escape:
  84. case Qt::Key_Tab:
  85. case Qt::Key_Backtab:
  86. e->ignore();
  87. return; // let the completer do default behavior
  88. default:
  89. break;
  90. }
  91. }
  92. QTextCursor text_cursor = this->textCursor();
  93. // Set to true if there's a current selection
  94. const bool selection = text_cursor.anchor() != text_cursor.position();
  95. // Set to true if the cursor overlaps the history area
  96. const bool history_area =
  97. text_cursor.anchor() < this->InteractivePosition
  98. || text_cursor.position() < this->InteractivePosition;
  99. // Allow copying anywhere in the console ...
  100. if(e->key() == Qt::Key_C && e->modifiers() == Qt::ControlModifier)
  101. {
  102. if(selection)
  103. {
  104. this->copy();
  105. }
  106. e->accept();
  107. return;
  108. }
  109. // Allow cut only if the selection is limited to the interactive area ...
  110. if(e->key() == Qt::Key_X && e->modifiers() == Qt::ControlModifier)
  111. {
  112. if(selection && !history_area)
  113. {
  114. this->cut();
  115. }
  116. e->accept();
  117. return;
  118. }
  119. // Allow paste only if the selection is in the interactive area ...
  120. if(e->key() == Qt::Key_V && e->modifiers() == Qt::ControlModifier)
  121. {
  122. if(!history_area)
  123. {
  124. const QMimeData* const clipboard = QApplication::clipboard()->mimeData();
  125. const QString text = clipboard->text();
  126. if(!text.isNull())
  127. {
  128. text_cursor.insertText(text);
  129. this->updateCommandBuffer();
  130. }
  131. }
  132. e->accept();
  133. return;
  134. }
  135. // Force the cursor back to the interactive area
  136. if(history_area && e->key() != Qt::Key_Control)
  137. {
  138. text_cursor.setPosition(this->documentEnd());
  139. this->setTextCursor(text_cursor);
  140. }
  141. switch(e->key())
  142. {
  143. case Qt::Key_Up:
  144. e->accept();
  145. if (this->CommandPosition > 0)
  146. {
  147. this->replaceCommandBuffer(this->CommandHistory[--this->CommandPosition]);
  148. }
  149. break;
  150. case Qt::Key_Down:
  151. e->accept();
  152. if (this->CommandPosition < this->CommandHistory.size() - 2)
  153. {
  154. this->replaceCommandBuffer(this->CommandHistory[++this->CommandPosition]);
  155. }
  156. else
  157. {
  158. this->CommandPosition = this->CommandHistory.size()-1;
  159. this->replaceCommandBuffer("");
  160. }
  161. break;
  162. case Qt::Key_Left:
  163. if (text_cursor.position() > this->InteractivePosition)
  164. {
  165. QTextEdit::keyPressEvent(e);
  166. }
  167. else
  168. {
  169. e->accept();
  170. }
  171. break;
  172. case Qt::Key_Delete:
  173. e->accept();
  174. QTextEdit::keyPressEvent(e);
  175. this->updateCommandBuffer();
  176. break;
  177. case Qt::Key_Backspace:
  178. e->accept();
  179. if(text_cursor.position() > this->InteractivePosition)
  180. {
  181. QTextEdit::keyPressEvent(e);
  182. this->updateCommandBuffer();
  183. this->updateCompleterIfVisible();
  184. }
  185. break;
  186. case Qt::Key_Tab:
  187. e->accept();
  188. this->updateCompleter();
  189. this->selectCompletion();
  190. break;
  191. case Qt::Key_Home:
  192. e->accept();
  193. text_cursor.setPosition(this->InteractivePosition);
  194. this->setTextCursor(text_cursor);
  195. break;
  196. case Qt::Key_Return:
  197. case Qt::Key_Enter:
  198. e->accept();
  199. text_cursor.setPosition(this->documentEnd());
  200. this->setTextCursor(text_cursor);
  201. this->internalExecuteCommand();
  202. break;
  203. default:
  204. e->accept();
  205. QTextEdit::keyPressEvent(e);
  206. this->updateCommandBuffer();
  207. this->updateCompleterIfVisible();
  208. break;
  209. }
  210. }
  211. /// Returns the end of the document
  212. /*const*/ int documentEnd()
  213. {
  214. QTextCursor c(this->document());
  215. c.movePosition(QTextCursor::End);
  216. return c.position();
  217. }
  218. void focusOutEvent(QFocusEvent *e)
  219. {
  220. QTextEdit::focusOutEvent(e);
  221. // For some reason the QCompleter tries to set the focus policy to
  222. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  223. this->setFocusPolicy(Qt::WheelFocus);
  224. }
  225. void updateCompleterIfVisible()
  226. {
  227. if (this->Completer && this->Completer->popup()->isVisible())
  228. {
  229. this->updateCompleter();
  230. }
  231. }
  232. /// If there is exactly 1 completion, insert it and hide the completer,
  233. /// else do nothing.
  234. void selectCompletion()
  235. {
  236. if (this->Completer && this->Completer->completionCount() == 1)
  237. {
  238. this->Parent.insertCompletion(this->Completer->currentCompletion());
  239. this->Completer->popup()->hide();
  240. }
  241. }
  242. void updateCompleter()
  243. {
  244. if (this->Completer)
  245. {
  246. // Get the text between the current cursor position
  247. // and the start of the line
  248. QTextCursor text_cursor = this->textCursor();
  249. text_cursor.setPosition(this->InteractivePosition, QTextCursor::KeepAnchor);
  250. QString commandText = text_cursor.selectedText();
  251. // Call the completer to update the completion model
  252. this->Completer->updateCompletionModel(commandText);
  253. // Place and show the completer if there are available completions
  254. if (this->Completer->completionCount())
  255. {
  256. // Get a QRect for the cursor at the start of the
  257. // current word and then translate it down 8 pixels.
  258. text_cursor = this->textCursor();
  259. text_cursor.movePosition(QTextCursor::StartOfWord);
  260. QRect cr = this->cursorRect(text_cursor);
  261. cr.translate(0,8);
  262. cr.setWidth(this->Completer->popup()->sizeHintForColumn(0)
  263. + this->Completer->popup()->verticalScrollBar()->sizeHint().width());
  264. this->Completer->complete(cr);
  265. }
  266. else
  267. {
  268. this->Completer->popup()->hide();
  269. }
  270. }
  271. }
  272. /// Update the contents of the command buffer from the contents of the widget
  273. void updateCommandBuffer()
  274. {
  275. this->commandBuffer() = this->toPlainText().mid(this->InteractivePosition);
  276. }
  277. /// Replace the contents of the command buffer, updating the display
  278. void replaceCommandBuffer(const QString& Text)
  279. {
  280. this->commandBuffer() = Text;
  281. QTextCursor c(this->document());
  282. c.setPosition(this->InteractivePosition);
  283. c.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
  284. c.removeSelectedText();
  285. c.insertText(Text);
  286. }
  287. /// References the buffer where the current un-executed command is stored
  288. QString& commandBuffer()
  289. {
  290. return this->CommandHistory.back();
  291. }
  292. /// Implements command-execution
  293. void internalExecuteCommand()
  294. {
  295. // First update the history cache. It's essential to update the
  296. // this->CommandPosition before calling internalExecuteCommand() since that
  297. // can result in a clearing of the current command (BUG #8765).
  298. QString command = this->commandBuffer();
  299. if (!command.isEmpty()) // Don't store empty commands in the history
  300. {
  301. this->CommandHistory.push_back("");
  302. this->CommandPosition = this->CommandHistory.size() - 1;
  303. }
  304. QTextCursor c(this->document());
  305. c.movePosition(QTextCursor::End);
  306. c.insertText("\n");
  307. this->InteractivePosition = this->documentEnd();
  308. this->Parent.internalExecuteCommand(command);
  309. }
  310. void setCompleter(ctkConsoleWidgetCompleter* completer)
  311. {
  312. if (this->Completer)
  313. {
  314. this->Completer->setWidget(0);
  315. QObject::disconnect(this->Completer, SIGNAL(activated(const QString&)),
  316. &this->Parent, SLOT(insertCompletion(const QString&)));
  317. }
  318. this->Completer = completer;
  319. if (this->Completer)
  320. {
  321. this->Completer->setWidget(this);
  322. QObject::connect(this->Completer, SIGNAL(activated(const QString&)),
  323. &this->Parent, SLOT(insertCompletion(const QString&)));
  324. }
  325. }
  326. /// Stores a back-reference to our owner
  327. ctkConsoleWidget& Parent;
  328. /// A custom completer
  329. QPointer<ctkConsoleWidgetCompleter> Completer;
  330. /** Stores the beginning of the area of interactive input, outside which
  331. changes can't be made to the text edit contents */
  332. int InteractivePosition;
  333. /// Stores command-history, plus the current command buffer
  334. QStringList CommandHistory;
  335. /// Stores the current position in the command-history
  336. int CommandPosition;
  337. };
  338. /////////////////////////////////////////////////////////////////////////
  339. // ctkConsoleWidget
  340. ctkConsoleWidget::ctkConsoleWidget(QWidget* Parent) :
  341. QWidget(Parent),
  342. Implementation(new pqImplementation(*this))
  343. {
  344. QVBoxLayout* const l = new QVBoxLayout(this);
  345. l->setMargin(0);
  346. l->addWidget(this->Implementation);
  347. }
  348. //-----------------------------------------------------------------------------
  349. ctkConsoleWidget::~ctkConsoleWidget()
  350. {
  351. delete this->Implementation;
  352. }
  353. //-----------------------------------------------------------------------------
  354. QTextCharFormat ctkConsoleWidget::getFormat()
  355. {
  356. return this->Implementation->currentCharFormat();
  357. }
  358. //-----------------------------------------------------------------------------
  359. void ctkConsoleWidget::setFormat(const QTextCharFormat& Format)
  360. {
  361. this->Implementation->setCurrentCharFormat(Format);
  362. }
  363. //-----------------------------------------------------------------------------
  364. void ctkConsoleWidget::setCompleter(ctkConsoleWidgetCompleter* completer)
  365. {
  366. this->Implementation->setCompleter(completer);
  367. }
  368. //-----------------------------------------------------------------------------
  369. void ctkConsoleWidget::insertCompletion(const QString& completion)
  370. {
  371. QTextCursor tc = this->Implementation->textCursor();
  372. tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
  373. if (tc.selectedText()==".")
  374. {
  375. tc.insertText(QString(".") + completion);
  376. }
  377. else
  378. {
  379. tc = this->Implementation->textCursor();
  380. tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
  381. tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
  382. tc.insertText(completion);
  383. this->Implementation->setTextCursor(tc);
  384. }
  385. this->Implementation->updateCommandBuffer();
  386. }
  387. //-----------------------------------------------------------------------------
  388. void ctkConsoleWidget::printString(const QString& Text)
  389. {
  390. this->Implementation->textCursor().movePosition(QTextCursor::End);
  391. this->Implementation->textCursor().insertText(Text);
  392. this->Implementation->InteractivePosition = this->Implementation->documentEnd();
  393. this->Implementation->ensureCursorVisible();
  394. }
  395. //-----------------------------------------------------------------------------
  396. void ctkConsoleWidget::printCommand(const QString& cmd)
  397. {
  398. this->Implementation->textCursor().insertText(cmd);
  399. this->Implementation->updateCommandBuffer();
  400. }
  401. //-----------------------------------------------------------------------------
  402. void ctkConsoleWidget::prompt(const QString& text)
  403. {
  404. QTextCursor text_cursor = this->Implementation->textCursor();
  405. // if the cursor is currently on a clean line, do nothing, otherwise we move
  406. // the cursor to a new line before showing the prompt.
  407. text_cursor.movePosition(QTextCursor::StartOfLine);
  408. int startpos = text_cursor.position();
  409. text_cursor.movePosition(QTextCursor::EndOfLine);
  410. int endpos = text_cursor.position();
  411. if (endpos != startpos)
  412. {
  413. this->Implementation->textCursor().insertText("\n");
  414. }
  415. this->Implementation->textCursor().insertText(text);
  416. this->Implementation->InteractivePosition = this->Implementation->documentEnd();
  417. this->Implementation->ensureCursorVisible();
  418. }
  419. //-----------------------------------------------------------------------------
  420. void ctkConsoleWidget::clear()
  421. {
  422. this->Implementation->clear();
  423. // For some reason the QCompleter tries to set the focus policy to
  424. // NoFocus, set let's make sure we set it back to the default WheelFocus.
  425. this->Implementation->setFocusPolicy(Qt::WheelFocus);
  426. }
  427. //-----------------------------------------------------------------------------
  428. void ctkConsoleWidget::internalExecuteCommand(const QString& Command)
  429. {
  430. emit this->executeCommand(Command);
  431. }