ctkConsoleWidget.cpp 15 KB

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