Debian Codegraph @

src/Gui/TextEdit.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QApplication>
25 #include <QKeyEvent>
26 #include <QPainter>
27 #include <QRegularExpression>
28 #include <QRegularExpressionMatch>
29 #include <QShortcut>
30 #include <QTextCursor>
31
32 #include <FCConfig.h>
33
34 #include "CallTips.h"
35 #include "TextEdit.h"
36 #include "SyntaxHighlighter.h"
37 #include "Tools.h"
38 #include <Base/Color.h>
39
40
41 using namespace Gui;
42
43 /**
44 * Constructs a TextEdit which is a child of 'parent'.
45 */
46 TextEdit::TextEdit(QWidget* parent)
47 : QPlainTextEdit(parent)
48 , cursorPosition(0)
49 , listBox(nullptr)
50 {
51 // create the window for call tips
52 callTipsList = new CallTipsList(this);
53 callTipsList->setFrameStyle(QFrame::Box);
54 callTipsList->setFrameShadow(QFrame::Raised);
55 callTipsList->setLineWidth(2);
56 installEventFilter(callTipsList);
57 viewport()->installEventFilter(callTipsList);
58 callTipsList->setSelectionMode(QAbstractItemView::SingleSelection);
59 callTipsList->hide();
60
61 // Note: Set the correct context to this shortcut as we may use several instances of this
62 // class at a time
63 auto shortcut = new QShortcut(this);
64 shortcut->setKey(QKeySequence(QStringLiteral("CTRL+Space")));
65 shortcut->setContext(Qt::WidgetShortcut);
66 connect(shortcut, &QShortcut::activated, this, &TextEdit::complete);
67
68 auto shortcutFind = new QShortcut(this);
69 shortcutFind->setKey(QKeySequence::Find);
70 shortcutFind->setContext(Qt::WidgetShortcut);
71 connect(shortcutFind, &QShortcut::activated, this, &TextEdit::showSearchBar);
72
73 auto shortcutNext = new QShortcut(this);
74 shortcutNext->setKey(QKeySequence::FindNext);
75 shortcutNext->setContext(Qt::WidgetShortcut);
76 connect(shortcutNext, &QShortcut::activated, this, &TextEdit::findNext);
77
78 auto shortcutPrev = new QShortcut(this);
79 shortcutPrev->setKey(QKeySequence::FindPrevious);
80 shortcutPrev->setContext(Qt::WidgetShortcut);
81 connect(shortcutPrev, &QShortcut::activated, this, &TextEdit::findPrevious);
82 }
83
84 /** Destroys the object and frees any allocated resources */
85 TextEdit::~TextEdit() = default;
86
87 /**
88 * Set the approproriate item of the completion box or hide it, if needed.
89 */
90 void TextEdit::keyPressEvent(QKeyEvent* e)
91 {
92 // We want input to be appended to document before doing calltips
93 QPlainTextEdit::keyPressEvent(e);
94
95 // This can't be done in CompletionList::eventFilter() because we must first perform
96 // the event and afterwards update the list widget
97 if (listBox && listBox->isVisible()) {
98 // Get the word under the cursor
99 QTextCursor cursor = textCursor();
100 cursor.movePosition(QTextCursor::StartOfWord);
101 // the cursor has moved to outside the word prefix
102 if (cursor.position() < cursorPosition - wordPrefix.length()
103 || cursor.position() > cursorPosition) {
104 listBox->hide();
105 return;
106 }
107 cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
108 listBox->keyboardSearch(cursor.selectedText());
109 cursor.clearSelection();
110 }
111
112
113 if (e->key() == Qt::Key_Period) {
114 // QTextCursor cursor = this->textCursor();
115 // In Qt 4.8 there is a strange behaviour because when pressing ":"
116 // then key is also set to 'Period' instead of 'Colon'. So we have
117 // to make sure we only handle the period.
118 if (e->text() == QLatin1String(".")) {
119 // analyse context and show available call tips
120 // TODO: idk why we need to remove the . from the input string (- 1). This shouldn't be
121 // needed
122 QString textToBeCompleted = getInputString().left(getInputStringPosition() - 1);
123 callTipsList->showTips(textToBeCompleted);
124 }
125 }
126
127 // This can't be done in CallTipsList::eventFilter() because we must first perform
128 // the event and afterwards update the list widget
129 if (callTipsList->isVisible()) {
130 callTipsList->validateCursor();
131 }
132 }
133
134 int TextEdit::getInputStringPosition()
135 {
136 return textCursor().positionInBlock();
137 }
138
139 QString TextEdit::getInputString()
140 {
141 return textCursor().block().text();
142 }
143
144 void TextEdit::wheelEvent(QWheelEvent* e)
145 {
146 // Reimplement from QPlainText::wheelEvent as zoom is only allowed natively if !isReadOnly
147 if (e->modifiers() & Qt::ControlModifier) {
148 float delta = e->angleDelta().y() / 120.f;
149 zoomInF(delta);
150 return;
151 }
152 QPlainTextEdit::wheelEvent(e);
153 }
154
155 /**
156 * Completes the word.
157 */
158 void TextEdit::complete()
159 {
160 QTextBlock block = textCursor().block();
161 if (!block.isValid()) {
162 return;
163 }
164 int cursorPos = textCursor().position() - block.position();
165 QString para = block.text();
166 int wordStart = cursorPos;
167 while (wordStart > 0 && para[wordStart - 1].isLetterOrNumber()) {
168 --wordStart;
169 }
170 wordPrefix = para.mid(wordStart, cursorPos - wordStart);
171 if (wordPrefix.isEmpty()) {
172 return;
173 }
174
175 QStringList list = toPlainText().split(QRegularExpression(QLatin1String("\\W+")));
176 QMap<QString, QString> map;
177 QStringList::Iterator it = list.begin();
178 while (it != list.end()) {
179 if ((*it).startsWith(wordPrefix) && (*it).length() > wordPrefix.length()) {
180 map[(*it).toLower()] = *it;
181 }
182 ++it;
183 }
184
185 if (map.count() == 1) {
186 insertPlainText((*map.begin()).mid(wordPrefix.length()));
187 }
188 else if (map.count() > 1) {
189 if (!listBox) {
190 createListBox();
191 }
192 listBox->clear();
193 listBox->addItems(map.values());
194 listBox->setFont(QFont(font().family(), 8));
195
196 this->cursorPosition = textCursor().position();
197
198 // get the minimum width and height of the box
199 int h = 0;
200 int w = 0;
201 for (int i = 0; i < listBox->count(); ++i) {
202 QRect r = listBox->visualItemRect(listBox->item(i));
203 w = qMax(w, r.width());
204 h += r.height();
205 }
206
207 // Add an offset
208 w += 2 * listBox->frameWidth();
209 h += 2 * listBox->frameWidth();
210
211 // get the start position of the word prefix
212 QTextCursor cursor = textCursor();
213 cursor.movePosition(QTextCursor::StartOfWord);
214 QRect rect = cursorRect(cursor);
215 int posX = rect.x();
216 int posY = rect.y();
217 int boxH = h;
218
219 // Decide whether to show downstairs or upstairs
220 if (posY > viewport()->height() / 2) {
221 h = qMin(qMin(h, posY), 250);
222 if (h < boxH) {
223 w += style()->pixelMetric(QStyle::PM_ScrollBarExtent);
224 }
225 listBox->setGeometry(posX, posY - h, w, h);
226 }
227 else {
228 h = qMin(qMin(h, viewport()->height() - fontMetrics().height() - posY), 250);
229 if (h < boxH) {
230 w += style()->pixelMetric(QStyle::PM_ScrollBarExtent);
231 }
232 listBox->setGeometry(posX, posY + fontMetrics().height(), w, h);
233 }
234
235 listBox->setCurrentRow(0);
236 listBox->show();
237 }
238 }
239
240 /**
241 * Creates the listbox containing all possibilities for the completion.
242 * The listbox is closed when ESC is pressed, the text edit field loses focus or a
243 * mouse button was pressed.
244 */
245 void TextEdit::createListBox()
246 {
247 listBox = new CompletionList(this);
248 listBox->setFrameStyle(QFrame::Box);
249 listBox->setFrameShadow(QFrame::Raised);
250 listBox->setLineWidth(2);
251 installEventFilter(listBox);
252 viewport()->installEventFilter(listBox);
253 listBox->setSelectionMode(QAbstractItemView::SingleSelection);
254 listBox->hide();
255 }
256
257 // ------------------------------------------------------------------------------
258
259 namespace Gui
260 {
261 struct TextEditorP
262 {
263 bool highlightLine = true;
264 bool visibleMarker = true;
265 QMap<QString, QColor> colormap; // Color map
266 TextEditorP()
267 {
268 colormap[QLatin1String("Text")] = qApp->palette().windowText().color();
269 colormap[QLatin1String("Bookmark")] = Qt::cyan;
270 colormap[QLatin1String("Breakpoint")] = Qt::red;
271 colormap[QLatin1String("Keyword")] = Qt::blue;
272 colormap[QLatin1String("Comment")] = QColor(0, 170, 0);
273 colormap[QLatin1String("Block comment")] = QColor(160, 160, 164);
274 colormap[QLatin1String("Number")] = Qt::blue;
275 colormap[QLatin1String("String")] = Qt::red;
276 colormap[QLatin1String("Character")] = Qt::red;
277 colormap[QLatin1String("Class name")] = QColor(255, 170, 0);
278 colormap[QLatin1String("Define name")] = QColor(255, 170, 0);
279 colormap[QLatin1String("Operator")] = QColor(160, 160, 164);
280 colormap[QLatin1String("Python output")] = QColor(170, 170, 127);
281 colormap[QLatin1String("Python error")] = Qt::red;
282 colormap[QLatin1String("Current line highlight")] = QColor(224, 224, 224);
283 }
284 };
285 } // namespace Gui
286
287 /**
288 * Constructs a TextEditor which is a child of 'parent' and does the
289 * syntax highlighting for the Python language.
290 */
291 TextEditor::TextEditor(QWidget* parent)
292 : TextEdit(parent)
293 , WindowParameter("Editor")
294 , highlighter(nullptr)
295 {
296 d = new TextEditorP();
297 lineNumberArea = new LineMarker(this);
298
299 QFont serifFont = QFontDatabase::systemFont(QFontDatabase::FixedFont);
300 serifFont.setPointSize(10);
301 setFont(serifFont);
302
303 ParameterGrp::handle hPrefGrp = getWindowParameter();
304 hPrefGrp->Attach(this);
305
306 // set colors and font
307 hPrefGrp->NotifyAll();
308
309 connect(this, &QPlainTextEdit::cursorPositionChanged, this, &TextEditor::highlightCurrentLine);
310 connect(this, &QPlainTextEdit::blockCountChanged, this, &TextEditor::updateLineNumberAreaWidth);
311 connect(this, &QPlainTextEdit::updateRequest, this, &TextEditor::updateLineNumberArea);
312
313 updateLineNumberAreaWidth(0);
314 highlightCurrentLine();
315 }
316
317 /** Destroys the object and frees any allocated resources */
318 TextEditor::~TextEditor()
319 {
320 getWindowParameter()->Detach(this);
321 delete highlighter;
322 delete d;
323 }
324
325 void TextEditor::setVisibleLineNumbers(bool value)
326 {
327 lineNumberArea->setVisible(value);
328 d->visibleMarker = value;
329 }
330
331 bool TextEditor::isVisibleLineNumbers() const
332 {
333 return d->visibleMarker;
334 }
335
336 void TextEditor::setEnabledHighlightCurrentLine(bool value)
337 {
338 d->highlightLine = value;
339 }
340
341 bool TextEditor::isEnabledHighlightCurrentLine() const
342 {
343 return d->highlightLine;
344 }
345
346 int TextEditor::lineNumberAreaWidth()
347 {
348 return QtTools::horizontalAdvance(fontMetrics(), QLatin1String("0000")) + 10;
349 }
350
351 void TextEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
352 {
353 int left = isVisibleLineNumbers() ? lineNumberAreaWidth() : 0;
354 setViewportMargins(left, 0, 0, 0);
355 }
356
357 void TextEditor::updateLineNumberArea(const QRect& rect, int dy)
358 {
359 if (isVisibleLineNumbers()) {
360 if (dy) {
361 lineNumberArea->scroll(0, dy);
362 }
363 else {
364 lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
365 }
366
367 if (rect.contains(viewport()->rect())) {
368 updateLineNumberAreaWidth(0);
369 }
370 }
371 }
372
373 void TextEditor::resizeEvent(QResizeEvent* e)
374 {
375 QPlainTextEdit::resizeEvent(e);
376
377 if (isVisibleLineNumbers()) {
378 QRect cr = contentsRect();
379 int width = lineNumberAreaWidth();
380 lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), width, cr.height()));
381 }
382 }
383
384 void TextEditor::highlightCurrentLine()
385 {
386 QList<QTextEdit::ExtraSelection> extraSelections;
387
388 if (!isReadOnly() && isEnabledHighlightCurrentLine()) {
389 QTextEdit::ExtraSelection selection;
390 QColor lineColor = d->colormap[QLatin1String("Current line highlight")];
391 unsigned int col = Base::Color::asPackedRGB<QColor>(lineColor);
392 ParameterGrp::handle hPrefGrp = getWindowParameter();
393 auto value = static_cast<unsigned long>(col);
394 value = hPrefGrp->GetUnsigned("Current line highlight", value);
395 col = static_cast<unsigned int>(value);
396 lineColor.setRgb((col >> 24) & 0xff, (col >> 16) & 0xff, (col >> 8) & 0xff);
397 selection.format.setBackground(lineColor);
398 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
399 selection.cursor = textCursor();
400 selection.cursor.clearSelection();
401 extraSelections.append(selection);
402 }
403
404 setExtraSelections(extraSelections);
405 }
406
407 void TextEditor::drawMarker(int line, int x, int y, QPainter* p)
408 {
409 Q_UNUSED(line);
410 Q_UNUSED(x);
411 Q_UNUSED(y);
412 Q_UNUSED(p);
413 }
414
415 void TextEditor::lineNumberAreaPaintEvent(QPaintEvent* event)
416 {
417 if (!isVisibleLineNumbers()) {
418 return;
419 }
420 QPainter painter(lineNumberArea);
421 // painter.fillRect(event->rect(), Qt::lightGray);
422
423 QTextBlock block = firstVisibleBlock();
424 int blockNumber = block.blockNumber();
425 int top = (int)blockBoundingGeometry(block).translated(contentOffset()).top();
426 int bottom = top + (int)blockBoundingRect(block).height();
427
428 while (block.isValid() && top <= event->rect().bottom()) {
429 if (block.isVisible() && bottom >= event->rect().top()) {
430 QString number = QString::number(blockNumber + 1);
431 QPalette pal = palette();
432 QColor color = pal.windowText().color();
433 painter.setPen(color);
434 painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number);
435 drawMarker(blockNumber + 1, 1, top, &painter);
436 }
437
438 block = block.next();
439 top = bottom;
440 bottom = top + (int)blockBoundingRect(block).height();
441 ++blockNumber;
442 }
443 }
444
445 void TextEditor::setSyntaxHighlighter(SyntaxHighlighter* sh)
446 {
447 sh->setDocument(this->document());
448 this->highlighter = sh;
449 }
450
451 /** Sets the font, font size and tab size of the editor. */
452 void TextEditor::OnChange(Base::Subject<const char*>& rCaller, const char* sReason)
453 {
454 Q_UNUSED(rCaller);
455 ParameterGrp::handle hPrefGrp = getWindowParameter();
456 if (strcmp(sReason, "FontSize") == 0 || strcmp(sReason, "Font") == 0) {
457 #ifdef FC_OS_LINUX
458 int fontSize = hPrefGrp->GetInt("FontSize", 15);
459 #else
460 int fontSize = hPrefGrp->GetInt("FontSize", 10);
461 #endif
462 QFont font;
463 auto fontName = hPrefGrp->GetASCII("Font");
464 if (fontName.empty()) {
465 font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
466 font.setPointSize(fontSize);
467 }
468 else {
469 font = QFont(QString::fromStdString(fontName), fontSize);
470 }
471 setFont(font);
472 lineNumberArea->setFont(font);
473 }
474 else {
475 QMap<QString, QColor>::Iterator it = d->colormap.find(QString::fromLatin1(sReason));
476 if (it != d->colormap.end()) {
477 QColor color = it.value();
478 unsigned int col = Base::Color::asPackedRGB<QColor>(color);
479 auto value = static_cast<unsigned long>(col);
480 value = hPrefGrp->GetUnsigned(sReason, value);
481 col = static_cast<unsigned int>(value);
482 color.setRgb((col >> 24) & 0xff, (col >> 16) & 0xff, (col >> 8) & 0xff);
483 if (this->highlighter) {
484 this->highlighter->setColor(QLatin1String(sReason), color);
485 }
486 }
487 }
488
489 if (strcmp(sReason, "TabSize") == 0 || strcmp(sReason, "FontSize") == 0) {
490 int tabWidth = hPrefGrp->GetInt("TabSize", 4);
491 QFontMetrics metric(font());
492 int fontSize = QtTools::horizontalAdvance(metric, QLatin1Char('0'));
493 setTabStopDistance(tabWidth * fontSize);
494 }
495
496 // Enables/Disables Line number in the Macro Editor from Edit->Preferences->Editor menu.
497 if (strcmp(sReason, "EnableLineNumber") == 0) {
498 int width = 0;
499 QRect cr = contentsRect();
500 if (hPrefGrp->GetBool("EnableLineNumber", true)) {
501 width = lineNumberAreaWidth();
502 }
503 lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), width, cr.height()));
504 }
505 }
506
507 // ------------------------------------------------------------------------------
508
509 PythonTextEditor::PythonTextEditor(QWidget* parent)
510 : TextEditor(parent)
511 {}
512
513 PythonTextEditor::~PythonTextEditor() = default;
514
515 void PythonTextEditor::prepend(const QString& str)
516 {
517 QTextCursor cursor = textCursor();
518 // for each selected block insert a tab or spaces
519 int selStart = cursor.selectionStart();
520 int selEnd = cursor.selectionEnd();
521 QTextBlock block;
522 cursor.beginEditBlock();
523 for (block = document()->begin(); block.isValid(); block = block.next()) {
524 int pos = block.position();
525 int off = block.length() - 1;
526 // at least one char of the block is part of the selection
527 if (pos >= selStart || pos + off >= selStart) {
528 if (pos + 1 > selEnd) {
529 break; // end of selection reached
530 }
531 cursor.setPosition(block.position());
532 cursor.insertText(str);
533 selEnd += str.length();
534 }
535 }
536
537 cursor.endEditBlock();
538 }
539
540 void PythonTextEditor::remove(const QString& str)
541 {
542 QTextCursor cursor = textCursor();
543 int selStart = cursor.selectionStart();
544 int selEnd = cursor.selectionEnd();
545 QTextBlock block;
546 cursor.beginEditBlock();
547 for (block = document()->begin(); block.isValid(); block = block.next()) {
548 int pos = block.position();
549 int off = block.length() - 1;
550 // at least one char of the block is part of the selection
551 if (pos >= selStart || pos + off >= selStart) {
552 if (pos + 1 > selEnd) {
553 break; // end of selection reached
554 }
555 QString text = block.text();
556 if (text.startsWith(str)) {
557 cursor.setPosition(block.position());
558 for (int i = 0; i < str.length(); i++) {
559 cursor.deleteChar();
560 selEnd--;
561 }
562 }
563 }
564 }
565
566 cursor.endEditBlock();
567 }
568
569 void PythonTextEditor::keyPressEvent(QKeyEvent* e)
570 {
571 if (e->key() == Qt::Key_Tab) {
572 ParameterGrp::handle hPrefGrp = getWindowParameter();
573 bool space = hPrefGrp->GetBool("Spaces", true);
574 int indent = hPrefGrp->GetInt("IndentSize", 4);
575 QString ch = space ? QString(indent, QLatin1Char(' ')) : QStringLiteral("\t");
576
577 QTextCursor cursor = textCursor();
578 if (!cursor.hasSelection()) {
579 // insert a single tab or several spaces
580 cursor.beginEditBlock();
581 cursor.insertText(ch);
582 cursor.endEditBlock();
583 }
584 else {
585 prepend(ch);
586 }
587
588 return;
589 }
590 else if (e->key() == Qt::Key_Backtab) {
591 QTextCursor cursor = textCursor();
592 if (!cursor.hasSelection()) {
593 return; // Shift+Tab should not do anything
594 }
595 // If some text is selected we remove a leading tab or
596 // spaces from each selected block
597 ParameterGrp::handle hPrefGrp = getWindowParameter();
598 bool space = hPrefGrp->GetBool("Spaces", true);
599 int indent = hPrefGrp->GetInt("IndentSize", 4);
600 QString ch = space ? QString(indent, QLatin1Char(' ')) : QStringLiteral("\t");
601
602 // if possible remove one tab or several spaces
603 remove(ch);
604 return;
605 }
606
607 TextEditor::keyPressEvent(e);
608 }
609
610
611 LineMarker::LineMarker(TextEditor* editor)
612 : QWidget(editor)
613 , textEditor(editor)
614 {}
615
616 LineMarker::~LineMarker() = default;
617
618 QSize LineMarker::sizeHint() const
619 {
620 return {textEditor->lineNumberAreaWidth(), 0};
621 }
622
623 void LineMarker::paintEvent(QPaintEvent* e)
624 {
625 textEditor->lineNumberAreaPaintEvent(e);
626 }
627
628 // ------------------------------------------------------------------------------
629
630 CompletionList::CompletionList(QPlainTextEdit* parent)
631 : QListWidget(parent)
632 , textEdit(parent)
633 {
634 // make the user assume that the widget is active
635 QPalette pal = parent->palette();
636 pal.setColor(
637 QPalette::Inactive,
638 QPalette::Highlight,
639 pal.color(QPalette::Active, QPalette::Highlight)
640 );
641 pal.setColor(
642 QPalette::Inactive,
643 QPalette::HighlightedText,
644 pal.color(QPalette::Active, QPalette::HighlightedText)
645 );
646 parent->setPalette(pal);
647
648 connect(this, &CompletionList::itemActivated, this, &CompletionList::completionItem);
649 }
650
651 CompletionList::~CompletionList() = default;
652
653 void CompletionList::findCurrentWord(const QString& wordPrefix)
654 {
655 for (int i = 0; i < count(); ++i) {
656 QString text = item(i)->text();
657 if (text.startsWith(wordPrefix)) {
658 setCurrentRow(i);
659 return;
660 }
661 }
662
663 if (currentItem()) {
664 currentItem()->setSelected(false);
665 }
666 }
667
668 /**
669 * Get all incoming events of the text edit and redirect some of them, like key up and
670 * down, mouse press events, ... to the widget itself.
671 */
672 bool CompletionList::eventFilter(QObject* watched, QEvent* event)
673 {
674 if (isVisible() && watched == textEdit->viewport()) {
675 if (event->type() == QEvent::MouseButtonPress) {
676 hide();
677 }
678 }
679 else if (isVisible() && watched == textEdit) {
680 if (event->type() == QEvent::KeyPress) {
681 auto ke = static_cast<QKeyEvent*>(event);
682 if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) {
683 keyPressEvent(ke);
684 return true;
685 }
686 else if (ke->key() == Qt::Key_PageUp || ke->key() == Qt::Key_PageDown) {
687 keyPressEvent(ke);
688 return true;
689 }
690 else if (ke->key() == Qt::Key_Escape) {
691 hide();
692 return true;
693 }
694 else if (ke->key() == Qt::Key_Space) {
695 hide();
696 return false;
697 }
698 else if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) {
699 Q_EMIT itemActivated(currentItem());
700 return true;
701 }
702 }
703 else if (event->type() == QEvent::FocusOut) {
704 if (!hasFocus()) {
705 hide();
706 }
707 }
708 }
709
710 return QListWidget::eventFilter(watched, event);
711 }
712
713 /**
714 * If an item was chosen (either by clicking or pressing enter) the rest of the word is completed.
715 * The listbox is closed without destroying it.
716 */
717 void CompletionList::completionItem(QListWidgetItem* item)
718 {
719 hide();
720 QString text = item->text();
721 QTextCursor cursor = textEdit->textCursor();
722 cursor.movePosition(QTextCursor::StartOfWord);
723 cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
724 cursor.insertText(text);
725 textEdit->ensureCursorVisible();
726 }
727
728 #include "moc_TextEdit.cpp"