Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwidgettextcontrol.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7
8#ifndef QT_NO_TEXTCONTROL
9
10#include <qfont.h>
11#include <qpainter.h>
12#include <qevent.h>
13#include <qdebug.h>
14#if QT_CONFIG(draganddrop)
15#include <qdrag.h>
16#endif
17#include <qclipboard.h>
18#include <qstyle.h>
19#include "private/qapplication_p.h"
20#include "private/qtextdocumentlayout_p.h"
21#include "private/qabstracttextdocumentlayout_p.h"
22#if QT_CONFIG(menu)
23#include "private/qmenu_p.h"
24#endif
25#include "qtextdocument.h"
26#include "private/qtextdocument_p.h"
27#include "private/qtextdocumentfragment_p.h"
28#include "qtextlist.h"
29#include "private/qwidgettextcontrol_p.h"
30#if QT_CONFIG(style_stylesheet)
31# include "private/qstylesheetstyle_p.h"
32#endif
33#if QT_CONFIG(graphicsview)
34#include "qgraphicssceneevent.h"
35#endif
37#include "private/qpagedpaintdevice_p.h"
39#include "qstylehints.h"
40#include "private/qtextcursor_p.h"
41
42#include <qtextformat.h>
43#include <qdatetime.h>
44#include <qbuffer.h>
45#include <qapplication.h>
46#include <limits.h>
47#include <qtexttable.h>
48#include <qvariant.h>
49#include <qurl.h>
50#include <qdesktopservices.h>
51#include <qinputmethod.h>
52#if QT_CONFIG(tooltip)
53#include <qtooltip.h>
54#endif
55#include <qstyleoption.h>
56#if QT_CONFIG(lineedit)
57#include <QtWidgets/qlineedit.h>
58#endif
59#include <QtGui/qaccessible.h>
60#include <QtCore/qmetaobject.h>
61#ifdef Q_OS_WASM
62#include <QtCore/private/qstdweb_p.h>
63#endif
64
65#include <private/qoffsetstringarray_p.h>
66
67#if QT_CONFIG(shortcut)
68#include "private/qapplication_p.h"
69#include "private/qshortcutmap_p.h"
70#include <qkeysequence.h>
71#define ACCEL_KEY(k) (!QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)
72 && !QGuiApplicationPrivate::instance()->shortcutMap.hasShortcutForKeySequence(k) ?
73 u'\t' + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
74
75#else
76#define ACCEL_KEY(k) QString()
77#endif
78
79#include <algorithm>
80
81QT_BEGIN_NAMESPACE
82
83using namespace Qt::StringLiterals;
84
85// could go into QTextCursor...
86static QTextLine currentTextLine(const QTextCursor &cursor)
87{
88 const QTextBlock block = cursor.block();
89 if (!block.isValid())
90 return QTextLine();
91
92 const QTextLayout *layout = block.layout();
93 if (!layout)
94 return QTextLine();
95
96 const int relativePos = cursor.position() - block.position();
97 return layout->lineForTextPosition(relativePos);
98}
99
100QWidgetTextControlPrivate::QWidgetTextControlPrivate()
101 : doc(nullptr), cursorOn(false), cursorVisible(false), cursorIsFocusIndicator(false),
102#ifndef Q_OS_ANDROID
103 interactionFlags(Qt::TextEditorInteraction),
104#else
105 interactionFlags(Qt::TextEditable | Qt::TextSelectableByKeyboard),
106#endif
107 dragEnabled(true),
108#if QT_CONFIG(draganddrop)
109 mousePressed(false), mightStartDrag(false),
110#endif
113 overwriteMode(false),
114 acceptRichText(true),
115 preeditCursor(0), hideCursor(false),
116 hasFocus(false),
117#ifdef QT_KEYPAD_NAVIGATION
118 hasEditFocus(false),
119#endif
120 isEnabled(true),
123 openExternalLinks(false),
125{}
126
127bool QWidgetTextControlPrivate::cursorMoveKeyEvent(QKeyEvent *e)
128{
129#ifdef QT_NO_SHORTCUT
130 Q_UNUSED(e);
131#endif
132
133 Q_Q(QWidgetTextControl);
134 if (cursor.isNull())
135 return false;
136
137 const QTextCursor oldSelection = cursor;
138 const int oldCursorPos = cursor.position();
139
140 QTextCursor::MoveMode mode = QTextCursor::MoveAnchor;
141 QTextCursor::MoveOperation op = QTextCursor::NoMove;
142
143 if (false) {
144 }
145#ifndef QT_NO_SHORTCUT
146 if (e == QKeySequence::MoveToNextChar) {
147 op = QTextCursor::Right;
148 }
149 else if (e == QKeySequence::MoveToPreviousChar) {
150 op = QTextCursor::Left;
151 }
152 else if (e == QKeySequence::SelectNextChar) {
153 op = QTextCursor::Right;
154 mode = QTextCursor::KeepAnchor;
155 }
156 else if (e == QKeySequence::SelectPreviousChar) {
157 op = QTextCursor::Left;
158 mode = QTextCursor::KeepAnchor;
159 }
160 else if (e == QKeySequence::SelectNextWord) {
161 op = QTextCursor::WordRight;
162 mode = QTextCursor::KeepAnchor;
163 }
164 else if (e == QKeySequence::SelectPreviousWord) {
165 op = QTextCursor::WordLeft;
166 mode = QTextCursor::KeepAnchor;
167 }
168 else if (e == QKeySequence::SelectStartOfLine) {
169 op = QTextCursor::StartOfLine;
170 mode = QTextCursor::KeepAnchor;
171 }
172 else if (e == QKeySequence::SelectEndOfLine) {
173 op = QTextCursor::EndOfLine;
174 mode = QTextCursor::KeepAnchor;
175 }
176 else if (e == QKeySequence::SelectStartOfBlock) {
177 op = QTextCursor::StartOfBlock;
178 mode = QTextCursor::KeepAnchor;
179 }
180 else if (e == QKeySequence::SelectEndOfBlock) {
181 op = QTextCursor::EndOfBlock;
182 mode = QTextCursor::KeepAnchor;
183 }
184 else if (e == QKeySequence::SelectStartOfDocument) {
185 op = QTextCursor::Start;
186 mode = QTextCursor::KeepAnchor;
187 }
188 else if (e == QKeySequence::SelectEndOfDocument) {
189 op = QTextCursor::End;
190 mode = QTextCursor::KeepAnchor;
191 }
192 else if (e == QKeySequence::SelectPreviousLine) {
193 op = QTextCursor::Up;
194 mode = QTextCursor::KeepAnchor;
195 {
196 QTextBlock block = cursor.block();
197 QTextLine line = currentTextLine(cursor);
198 if (!block.previous().isValid()
199 && line.isValid()
200 && line.lineNumber() == 0)
201 op = QTextCursor::Start;
202 }
203 }
204 else if (e == QKeySequence::SelectNextLine) {
205 op = QTextCursor::Down;
206 mode = QTextCursor::KeepAnchor;
207 {
208 QTextBlock block = cursor.block();
209 QTextLine line = currentTextLine(cursor);
210 if (!block.next().isValid()
211 && line.isValid()
212 && line.lineNumber() == block.layout()->lineCount() - 1)
213 op = QTextCursor::End;
214 }
215 }
216 else if (e == QKeySequence::MoveToNextWord) {
217 op = QTextCursor::WordRight;
218 }
219 else if (e == QKeySequence::MoveToPreviousWord) {
220 op = QTextCursor::WordLeft;
221 }
222 else if (e == QKeySequence::MoveToEndOfBlock) {
223 op = QTextCursor::EndOfBlock;
224 }
225 else if (e == QKeySequence::MoveToStartOfBlock) {
226 op = QTextCursor::StartOfBlock;
227 }
228 else if (e == QKeySequence::MoveToNextLine) {
229 op = QTextCursor::Down;
230 }
231 else if (e == QKeySequence::MoveToPreviousLine) {
232 op = QTextCursor::Up;
233 }
234 else if (e == QKeySequence::MoveToStartOfLine) {
235 op = QTextCursor::StartOfLine;
236 }
237 else if (e == QKeySequence::MoveToEndOfLine) {
238 op = QTextCursor::EndOfLine;
239 }
240 else if (e == QKeySequence::MoveToStartOfDocument) {
241 op = QTextCursor::Start;
242 }
243 else if (e == QKeySequence::MoveToEndOfDocument) {
244 op = QTextCursor::End;
245 }
246#endif // QT_NO_SHORTCUT
247 else {
248 return false;
249 }
250
251// Except for pageup and pagedown, OS X has very different behavior, we don't do it all, but
252// here's the breakdown:
253// Shift still works as an anchor, but only one of the other keys can be down Ctrl (Command),
254// Alt (Option), or Meta (Control).
255// Command/Control + Left/Right -- Move to left or right of the line
256// + Up/Down -- Move to top bottom of the file. (Control doesn't move the cursor)
257// Option + Left/Right -- Move one word Left/right.
258// + Up/Down -- Begin/End of Paragraph.
259// Home/End Top/Bottom of file. (usually don't move the cursor, but will select)
260
261 bool visualNavigation = cursor.visualNavigation();
262 cursor.setVisualNavigation(true);
263 const bool moved = cursor.movePosition(op, mode);
264 cursor.setVisualNavigation(visualNavigation);
265 q->ensureCursorVisible();
266
267 bool ignoreNavigationEvents = ignoreUnusedNavigationEvents;
268 bool isNavigationEvent = e->key() == Qt::Key_Up || e->key() == Qt::Key_Down;
269
270#ifdef QT_KEYPAD_NAVIGATION
271 ignoreNavigationEvents = ignoreNavigationEvents || QApplicationPrivate::keypadNavigationEnabled();
272 isNavigationEvent = isNavigationEvent ||
273 (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
274 && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right));
275#else
276 isNavigationEvent = isNavigationEvent || e->key() == Qt::Key_Left || e->key() == Qt::Key_Right;
277#endif
278
279 if (moved) {
280 if (cursor.position() != oldCursorPos)
281 emit q->cursorPositionChanged();
282 emit q->microFocusChanged();
283 } else if (ignoreNavigationEvents && isNavigationEvent && oldSelection.anchor() == cursor.anchor()) {
284 return false;
285 }
286
287 selectionChanged(/*forceEmitSelectionChanged =*/(mode == QTextCursor::KeepAnchor));
288
289 repaintOldAndNewSelection(oldSelection);
290
291 return true;
292}
293
295{
296 Q_Q(QWidgetTextControl);
297
298 QTextCharFormat fmt = cursor.charFormat();
299 if (fmt == lastCharFormat)
300 return;
301 lastCharFormat = fmt;
302
303 emit q->currentCharFormatChanged(fmt);
304 emit q->microFocusChanged();
305}
306
308{
309 QTextBlockFormat blockFmt = cursor.blockFormat();
310
311 QTextList *list = cursor.currentList();
312 if (!list) {
313 QTextBlockFormat modifier;
314 modifier.setIndent(blockFmt.indent() + 1);
315 cursor.mergeBlockFormat(modifier);
316 } else {
317 QTextListFormat format = list->format();
318 format.setIndent(format.indent() + 1);
319
320 if (list->itemNumber(cursor.block()) == 1)
321 list->setFormat(format);
322 else
323 cursor.createList(format);
324 }
325}
326
328{
329 QTextBlockFormat blockFmt = cursor.blockFormat();
330
331 QTextList *list = cursor.currentList();
332
333 if (!list) {
334 QTextBlockFormat modifier;
335 modifier.setIndent(blockFmt.indent() - 1);
336 cursor.mergeBlockFormat(modifier);
337 } else {
338 QTextListFormat listFmt = list->format();
339 listFmt.setIndent(listFmt.indent() - 1);
340 list->setFormat(listFmt);
341 }
342}
343
345{
346 QTextTable *table = cursor.currentTable();
347 QTextTableCell cell = table->cellAt(cursor);
348
349 int newColumn = cell.column() + cell.columnSpan();
350 int newRow = cell.row();
351
352 if (newColumn >= table->columns()) {
353 newColumn = 0;
354 ++newRow;
355 if (newRow >= table->rows())
356 table->insertRows(table->rows(), 1);
357 }
358
359 cell = table->cellAt(newRow, newColumn);
360 cursor = cell.firstCursorPosition();
361}
362
364{
365 QTextTable *table = cursor.currentTable();
366 QTextTableCell cell = table->cellAt(cursor);
367
368 int newColumn = cell.column() - 1;
369 int newRow = cell.row();
370
371 if (newColumn < 0) {
372 newColumn = table->columns() - 1;
373 --newRow;
374 if (newRow < 0)
375 return;
376 }
377
378 cell = table->cellAt(newRow, newColumn);
379 cursor = cell.firstCursorPosition();
380}
381
383{
384 cursor.beginEditBlock();
385
386 QTextBlockFormat blockFmt = cursor.blockFormat();
387
388 QTextListFormat listFmt;
389 listFmt.setStyle(QTextListFormat::ListDisc);
390 listFmt.setIndent(blockFmt.indent() + 1);
391
392 blockFmt.setIndent(0);
393 cursor.setBlockFormat(blockFmt);
394
395 cursor.createList(listFmt);
396
397 cursor.endEditBlock();
398}
399
400void QWidgetTextControlPrivate::init(Qt::TextFormat format, const QString &text, QTextDocument *document)
401{
402 Q_Q(QWidgetTextControl);
403 setContent(format, text, document);
404
405 doc->setUndoRedoEnabled(interactionFlags & Qt::TextEditable);
406 q->setCursorWidth(-1);
407}
408
409void QWidgetTextControlPrivate::setContent(Qt::TextFormat format, const QString &text, QTextDocument *document)
410{
411 Q_Q(QWidgetTextControl);
412
413 // for use when called from setPlainText. we may want to re-use the currently
414 // set char format then.
415 const QTextCharFormat charFormatForInsertion = cursor.charFormat();
416
417 bool clearDocument = true;
418 if (!doc) {
419 if (document) {
420 doc = document;
421 } else {
422 palette = QApplication::palette("QWidgetTextControl");
423 doc = new QTextDocument(q);
424 }
425 clearDocument = false;
427 cursor = QTextCursor(doc);
428
429// #### doc->documentLayout()->setPaintDevice(viewport);
430
431 QObjectPrivate::connect(doc, &QTextDocument::contentsChanged, this,
432 &QWidgetTextControlPrivate::_q_updateCurrentCharFormatAndSelection);
433 QObjectPrivate::connect(doc, &QTextDocument::cursorPositionChanged, this,
434 &QWidgetTextControlPrivate::_q_emitCursorPosChanged);
435 QObjectPrivate::connect(doc, &QTextDocument::documentLayoutChanged, this,
436 &QWidgetTextControlPrivate::_q_documentLayoutChanged);
437
438 // convenience signal forwards
439 QObject::connect(doc, &QTextDocument::undoAvailable, q, &QWidgetTextControl::undoAvailable);
440 QObject::connect(doc, &QTextDocument::redoAvailable, q, &QWidgetTextControl::redoAvailable);
441 QObject::connect(doc, &QTextDocument::modificationChanged, q,
442 &QWidgetTextControl::modificationChanged);
443 QObject::connect(doc, &QTextDocument::blockCountChanged, q,
444 &QWidgetTextControl::blockCountChanged);
445 }
446
447 bool previousUndoRedoState = doc->isUndoRedoEnabled();
448 if (!document)
449 doc->setUndoRedoEnabled(false);
450
451 //Saving the index save some time.
452 static int contentsChangedIndex = QMetaMethod::fromSignal(&QTextDocument::contentsChanged).methodIndex();
453 static int textChangedIndex = QMetaMethod::fromSignal(&QWidgetTextControl::textChanged).methodIndex();
454 // avoid multiple textChanged() signals being emitted
455 QMetaObject::disconnect(doc, contentsChangedIndex, q, textChangedIndex);
456
457 if (!text.isEmpty()) {
458 // clear 'our' cursor for insertion to prevent
459 // the emission of the cursorPositionChanged() signal.
460 // instead we emit it only once at the end instead of
461 // at the end of the document after loading and when
462 // positioning the cursor again to the start of the
463 // document.
464 cursor = QTextCursor();
465 if (format == Qt::PlainText) {
466 QTextCursor formatCursor(doc);
467 // put the setPlainText and the setCharFormat into one edit block,
468 // so that the syntax highlight triggers only /once/ for the entire
469 // document, not twice.
470 formatCursor.beginEditBlock();
471 doc->setPlainText(text);
472 doc->setUndoRedoEnabled(false);
473 formatCursor.select(QTextCursor::Document);
474 formatCursor.setCharFormat(charFormatForInsertion);
475 formatCursor.endEditBlock();
476#if QT_CONFIG(textmarkdownreader)
477 } else if (format == Qt::MarkdownText) {
478 doc->setMarkdown(text);
479 doc->setUndoRedoEnabled(false);
480#endif
481 } else {
482#ifndef QT_NO_TEXTHTMLPARSER
483 doc->setHtml(text);
484#else
485 doc->setPlainText(text);
486#endif
487 doc->setUndoRedoEnabled(false);
488 }
489 cursor = QTextCursor(doc);
490 } else if (clearDocument) {
491 doc->clear();
492 }
493 cursor.setCharFormat(charFormatForInsertion);
494
495 QMetaObject::connect(doc, contentsChangedIndex, q, textChangedIndex);
496 emit q->textChanged();
497 if (!document)
498 doc->setUndoRedoEnabled(previousUndoRedoState);
500 if (!document)
501 doc->setModified(false);
502
503 q->ensureCursorVisible();
504 emit q->cursorPositionChanged();
505
506 QObjectPrivate::connect(doc, &QTextDocument::contentsChange, this,
507 &QWidgetTextControlPrivate::_q_contentsChanged, Qt::UniqueConnection);
508}
509
511{
512
513#ifdef Q_OS_WASM
514 // QDrag::exec() will crash without asyncify; disable drag instead.
515 if (!qstdweb::haveAsyncify())
516 return;
517#endif
518
519#if QT_CONFIG(draganddrop)
520 Q_Q(QWidgetTextControl);
521 mousePressed = false;
522 if (!contextWidget)
523 return;
524 QMimeData *data = q->createMimeDataFromSelection();
525
526 QDrag *drag = new QDrag(contextWidget);
527 drag->setMimeData(data);
528
529 Qt::DropActions actions = Qt::CopyAction;
530 Qt::DropAction action;
531 if (interactionFlags & Qt::TextEditable) {
532 actions |= Qt::MoveAction;
533 action = drag->exec(actions, Qt::MoveAction);
534 } else {
535 action = drag->exec(actions, Qt::CopyAction);
536 }
537
538 if (action == Qt::MoveAction && drag->target() != contextWidget)
539 cursor.removeSelectedText();
540#endif
541}
542
543void QWidgetTextControlPrivate::setCursorPosition(const QPointF &pos)
544{
545 Q_Q(QWidgetTextControl);
546 const int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
547 if (cursorPos == -1)
548 return;
549 cursor.setPosition(cursorPos);
550}
551
552void QWidgetTextControlPrivate::setCursorPosition(int pos, QTextCursor::MoveMode mode)
553{
554 cursor.setPosition(pos, mode);
555
556 if (mode != QTextCursor::KeepAnchor) {
557 selectedWordOnDoubleClick = QTextCursor();
558 selectedBlockOnTrippleClick = QTextCursor();
559 }
560}
561
563{
564 Q_Q(QWidgetTextControl);
565 emit q->updateRequest(cursorRectPlusUnicodeDirectionMarkers(cursor));
566}
567
568void QWidgetTextControlPrivate::repaintOldAndNewSelection(const QTextCursor &oldSelection)
569{
570 Q_Q(QWidgetTextControl);
571 if (cursor.hasSelection()
572 && oldSelection.hasSelection()
573 && cursor.currentFrame() == oldSelection.currentFrame()
574 && !cursor.hasComplexSelection()
575 && !oldSelection.hasComplexSelection()
576 && cursor.anchor() == oldSelection.anchor()
577 ) {
578 QTextCursor differenceSelection(doc);
579 differenceSelection.setPosition(oldSelection.position());
580 differenceSelection.setPosition(cursor.position(), QTextCursor::KeepAnchor);
581 emit q->updateRequest(q->selectionRect(differenceSelection));
582 } else {
583 if (!oldSelection.isNull())
584 emit q->updateRequest(q->selectionRect(oldSelection) | cursorRectPlusUnicodeDirectionMarkers(oldSelection));
585 emit q->updateRequest(q->selectionRect() | cursorRectPlusUnicodeDirectionMarkers(cursor));
586 }
587}
588
589void QWidgetTextControlPrivate::selectionChanged(bool forceEmitSelectionChanged /*=false*/)
590{
591 Q_Q(QWidgetTextControl);
592 if (forceEmitSelectionChanged) {
593 emit q->selectionChanged();
594#if QT_CONFIG(accessibility)
595 if (q->parent() && q->parent()->isWidgetType()) {
596 QAccessibleTextSelectionEvent ev(q->parent(), cursor.anchor(), cursor.position());
597 QAccessible::updateAccessibility(&ev);
598 }
599#endif
600 }
601
602 if (cursor.position() == lastSelectionPosition
603 && cursor.anchor() == lastSelectionAnchor)
604 return;
605
606 bool selectionStateChange = (cursor.hasSelection()
607 != (lastSelectionPosition != lastSelectionAnchor));
608 if (selectionStateChange)
609 emit q->copyAvailable(cursor.hasSelection());
610
611 if (!forceEmitSelectionChanged
612 && (selectionStateChange
613 || (cursor.hasSelection()
614 && (cursor.position() != lastSelectionPosition
615 || cursor.anchor() != lastSelectionAnchor)))) {
616 emit q->selectionChanged();
617#if QT_CONFIG(accessibility)
618 if (q->parent() && q->parent()->isWidgetType()) {
619 QAccessibleTextSelectionEvent ev(q->parent(), cursor.anchor(), cursor.position());
620 QAccessible::updateAccessibility(&ev);
621 }
622#endif
623 }
624 emit q->microFocusChanged();
625 lastSelectionPosition = cursor.position();
626 lastSelectionAnchor = cursor.anchor();
627}
628
634
635#ifndef QT_NO_CLIPBOARD
637{
638 QClipboard *clipboard = QGuiApplication::clipboard();
639 if (!cursor.hasSelection() || !clipboard->supportsSelection())
640 return;
641 Q_Q(QWidgetTextControl);
642 QMimeData *data = q->createMimeDataFromSelection();
643 clipboard->setMimeData(data, QClipboard::Selection);
644}
645#endif
646
647void QWidgetTextControlPrivate::_q_emitCursorPosChanged(const QTextCursor &someCursor)
648{
649 Q_Q(QWidgetTextControl);
650 if (someCursor.isCopyOf(cursor)) {
651 emit q->cursorPositionChanged();
652 emit q->microFocusChanged();
653 }
654}
655
656void QWidgetTextControlPrivate::_q_contentsChanged(int from, int charsRemoved, int charsAdded)
657{
658#if QT_CONFIG(accessibility)
659 Q_Q(QWidgetTextControl);
660
661 if (QAccessible::isActive() && q->parent() && q->parent()->isWidgetType()) {
662 QTextCursor tmp(doc);
663 tmp.setPosition(from);
664 // when setting a new text document the length is off
665 // QTBUG-32583 - characterCount is off by 1 requires the -1
666 tmp.setPosition(qMin(doc->characterCount() - 1, from + charsAdded), QTextCursor::KeepAnchor);
667 QString newText = tmp.selectedText();
668
669 // always report the right number of removed chars, but in lack of the real string use spaces
670 QString oldText = QString(charsRemoved, u' ');
671
672 QAccessibleEvent *ev = nullptr;
673 if (charsRemoved == 0) {
674 ev = new QAccessibleTextInsertEvent(q->parent(), from, newText);
675 } else if (charsAdded == 0) {
676 ev = new QAccessibleTextRemoveEvent(q->parent(), from, oldText);
677 } else {
678 ev = new QAccessibleTextUpdateEvent(q->parent(), from, oldText, newText);
679 }
680 QAccessible::updateAccessibility(ev);
681 delete ev;
682 }
683#else
684 Q_UNUSED(from);
685 Q_UNUSED(charsRemoved);
686 Q_UNUSED(charsAdded);
687#endif
688}
689
691{
692 Q_Q(QWidgetTextControl);
693 QAbstractTextDocumentLayout *layout = doc->documentLayout();
694 QObject::connect(layout, &QAbstractTextDocumentLayout::update, q,
695 &QWidgetTextControl::updateRequest);
696 QObjectPrivate::connect(layout, &QAbstractTextDocumentLayout::updateBlock, this,
697 &QWidgetTextControlPrivate::_q_updateBlock);
698 QObject::connect(layout, &QAbstractTextDocumentLayout::documentSizeChanged, q,
699 &QWidgetTextControl::documentSizeChanged);
700}
701
703{
704 if (cursorVisible == visible)
705 return;
706
707 cursorVisible = visible;
709
710 if (cursorVisible)
711 connect(QGuiApplication::styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetTextControlPrivate::updateCursorBlinking);
712 else
713 disconnect(QGuiApplication::styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetTextControlPrivate::updateCursorBlinking);
714}
715
717{
718 cursorBlinkTimer.stop();
719 if (cursorVisible) {
720 int flashTime = QGuiApplication::styleHints()->cursorFlashTime();
721 if (flashTime >= 2)
722 cursorBlinkTimer.start(flashTime / 2, q_func());
723 }
724
727}
728
729void QWidgetTextControlPrivate::extendWordwiseSelection(int suggestedNewPosition, qreal mouseXPosition)
730{
731 Q_Q(QWidgetTextControl);
732
733 // if inside the initial selected word keep that
734 if (suggestedNewPosition >= selectedWordOnDoubleClick.selectionStart()
735 && suggestedNewPosition <= selectedWordOnDoubleClick.selectionEnd()) {
736 q->setTextCursor(selectedWordOnDoubleClick);
737 return;
738 }
739
740 QTextCursor curs = selectedWordOnDoubleClick;
741 curs.setPosition(suggestedNewPosition, QTextCursor::KeepAnchor);
742
743 if (!curs.movePosition(QTextCursor::StartOfWord))
744 return;
745 const int wordStartPos = curs.position();
746
747 const int blockPos = curs.block().position();
748 const QPointF blockCoordinates = q->blockBoundingRect(curs.block()).topLeft();
749
750 QTextLine line = currentTextLine(curs);
751 if (!line.isValid())
752 return;
753
754 const qreal wordStartX = line.cursorToX(curs.position() - blockPos) + blockCoordinates.x();
755
756 if (!curs.movePosition(QTextCursor::EndOfWord))
757 return;
758 const int wordEndPos = curs.position();
759
760 const QTextLine otherLine = currentTextLine(curs);
761 if (otherLine.textStart() != line.textStart()
762 || wordEndPos == wordStartPos)
763 return;
764
765 const qreal wordEndX = line.cursorToX(curs.position() - blockPos) + blockCoordinates.x();
766
767 if (!wordSelectionEnabled && (mouseXPosition < wordStartX || mouseXPosition > wordEndX))
768 return;
769
771 if (suggestedNewPosition < selectedWordOnDoubleClick.position()) {
772 cursor.setPosition(selectedWordOnDoubleClick.selectionEnd());
773 setCursorPosition(wordStartPos, QTextCursor::KeepAnchor);
774 } else {
775 cursor.setPosition(selectedWordOnDoubleClick.selectionStart());
776 setCursorPosition(wordEndPos, QTextCursor::KeepAnchor);
777 }
778 } else {
779 // keep the already selected word even when moving to the left
780 // (#39164)
781 if (suggestedNewPosition < selectedWordOnDoubleClick.position())
782 cursor.setPosition(selectedWordOnDoubleClick.selectionEnd());
783 else
784 cursor.setPosition(selectedWordOnDoubleClick.selectionStart());
785
786 const qreal differenceToStart = mouseXPosition - wordStartX;
787 const qreal differenceToEnd = wordEndX - mouseXPosition;
788
789 if (differenceToStart < differenceToEnd)
790 setCursorPosition(wordStartPos, QTextCursor::KeepAnchor);
791 else
792 setCursorPosition(wordEndPos, QTextCursor::KeepAnchor);
793 }
794
795 if (interactionFlags & Qt::TextSelectableByMouse) {
796#ifndef QT_NO_CLIPBOARD
798#endif
800 }
801}
802
804{
805 Q_Q(QWidgetTextControl);
806
807 // if inside the initial selected line keep that
808 if (suggestedNewPosition >= selectedBlockOnTrippleClick.selectionStart()
809 && suggestedNewPosition <= selectedBlockOnTrippleClick.selectionEnd()) {
810 q->setTextCursor(selectedBlockOnTrippleClick);
811 return;
812 }
813
814 if (suggestedNewPosition < selectedBlockOnTrippleClick.position()) {
815 cursor.setPosition(selectedBlockOnTrippleClick.selectionEnd());
816 cursor.setPosition(suggestedNewPosition, QTextCursor::KeepAnchor);
817 cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
818 } else {
819 cursor.setPosition(selectedBlockOnTrippleClick.selectionStart());
820 cursor.setPosition(suggestedNewPosition, QTextCursor::KeepAnchor);
821 cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
822 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
823 }
824
825 if (interactionFlags & Qt::TextSelectableByMouse) {
826#ifndef QT_NO_CLIPBOARD
828#endif
830 }
831}
832
834{
835 if (!(interactionFlags & Qt::TextEditable) || !cursor.hasSelection())
836 return;
837 cursor.removeSelectedText();
838}
839
840void QWidgetTextControl::undo()
841{
842 Q_D(QWidgetTextControl);
843 d->repaintSelection();
844 const int oldCursorPos = d->cursor.position();
845 d->doc->undo(&d->cursor);
846 if (d->cursor.position() != oldCursorPos)
847 emit cursorPositionChanged();
848 emit microFocusChanged();
849 ensureCursorVisible();
850}
851
852void QWidgetTextControl::redo()
853{
854 Q_D(QWidgetTextControl);
855 d->repaintSelection();
856 const int oldCursorPos = d->cursor.position();
857 d->doc->redo(&d->cursor);
858 if (d->cursor.position() != oldCursorPos)
859 emit cursorPositionChanged();
860 emit microFocusChanged();
861 ensureCursorVisible();
862}
863
864QWidgetTextControl::QWidgetTextControl(QObject *parent)
865 : QInputControl(QInputControl::TextEdit, *new QWidgetTextControlPrivate, parent)
866{
867 Q_D(QWidgetTextControl);
868 d->init();
869}
870
871QWidgetTextControl::QWidgetTextControl(const QString &text, QObject *parent)
872 : QInputControl(QInputControl::TextEdit, *new QWidgetTextControlPrivate, parent)
873{
874 Q_D(QWidgetTextControl);
875 d->init(Qt::RichText, text);
876}
877
878QWidgetTextControl::QWidgetTextControl(QTextDocument *doc, QObject *parent)
879 : QInputControl(QInputControl::TextEdit, *new QWidgetTextControlPrivate, parent)
880{
881 Q_D(QWidgetTextControl);
882 d->init(Qt::RichText, QString(), doc);
883}
884
885QWidgetTextControl::~QWidgetTextControl()
886{
887}
888
889void QWidgetTextControl::setDocument(QTextDocument *document)
890{
891 Q_D(QWidgetTextControl);
892 if (d->doc == document)
893 return;
894
895 d->doc->disconnect(this);
896 d->doc->documentLayout()->disconnect(this);
897 d->doc->documentLayout()->setPaintDevice(nullptr);
898
899 if (d->doc->parent() == this)
900 delete d->doc;
901
902 d->doc = nullptr;
903 d->setContent(Qt::RichText, QString(), document);
904}
905
906QTextDocument *QWidgetTextControl::document() const
907{
908 Q_D(const QWidgetTextControl);
909 return d->doc;
910}
911
912void QWidgetTextControl::setTextCursor(const QTextCursor &cursor, bool selectionClipboard)
913{
914 Q_D(QWidgetTextControl);
915 d->cursorIsFocusIndicator = false;
916 const bool posChanged = cursor.position() != d->cursor.position();
917 const QTextCursor oldSelection = d->cursor;
918 d->cursor = cursor;
919 d->cursorOn = d->hasFocus
920 && (d->interactionFlags & (Qt::TextSelectableByKeyboard | Qt::TextEditable));
921 d->_q_updateCurrentCharFormatAndSelection();
922 ensureCursorVisible();
923 d->repaintOldAndNewSelection(oldSelection);
924 if (posChanged)
925 emit cursorPositionChanged();
926
927#ifndef QT_NO_CLIPBOARD
928 if (selectionClipboard)
929 d->setClipboardSelection();
930#else
931 Q_UNUSED(selectionClipboard);
932#endif
933}
934
935QTextCursor QWidgetTextControl::textCursor() const
936{
937 Q_D(const QWidgetTextControl);
938 return d->cursor;
939}
940
941#ifndef QT_NO_CLIPBOARD
942
943void QWidgetTextControl::cut()
944{
945 Q_D(QWidgetTextControl);
946 if (!(d->interactionFlags & Qt::TextEditable) || !d->cursor.hasSelection())
947 return;
948 copy();
949 d->cursor.removeSelectedText();
950}
951
952void QWidgetTextControl::copy()
953{
954 Q_D(QWidgetTextControl);
955 if (!d->cursor.hasSelection())
956 return;
957 QMimeData *data = createMimeDataFromSelection();
958 QGuiApplication::clipboard()->setMimeData(data);
959}
960
961void QWidgetTextControl::paste(QClipboard::Mode mode)
962{
963 const QMimeData *md = QGuiApplication::clipboard()->mimeData(mode);
964 if (md)
965 insertFromMimeData(md);
966}
967#endif
968
969void QWidgetTextControl::clear()
970{
971 Q_D(QWidgetTextControl);
972 // clears and sets empty content
973 d->extraSelections.clear();
974 d->setContent();
975}
976
977
978void QWidgetTextControl::selectAll()
979{
980 Q_D(QWidgetTextControl);
981 const int selectionLength = qAbs(d->cursor.position() - d->cursor.anchor());
982 const int oldCursorPos = d->cursor.position();
983 d->cursor.select(QTextCursor::Document);
984 d->selectionChanged(selectionLength != qAbs(d->cursor.position() - d->cursor.anchor()));
985 d->cursorIsFocusIndicator = false;
986 if (d->cursor.position() != oldCursorPos)
987 emit cursorPositionChanged();
988 emit updateRequest();
989}
990
991void QWidgetTextControl::processEvent(QEvent *e, const QPointF &coordinateOffset, QWidget *contextWidget)
992{
993 QTransform t;
994 t.translate(coordinateOffset.x(), coordinateOffset.y());
995 processEvent(e, t, contextWidget);
996}
997
998void QWidgetTextControl::processEvent(QEvent *e, const QTransform &transform, QWidget *contextWidget)
999{
1000 Q_D(QWidgetTextControl);
1001 if (d->interactionFlags == Qt::NoTextInteraction) {
1002 e->ignore();
1003 return;
1004 }
1005
1006 d->contextWidget = contextWidget;
1007
1008 if (!d->contextWidget) {
1009 switch (e->type()) {
1010#if QT_CONFIG(graphicsview)
1011 case QEvent::GraphicsSceneMouseMove:
1012 case QEvent::GraphicsSceneMousePress:
1013 case QEvent::GraphicsSceneMouseRelease:
1014 case QEvent::GraphicsSceneMouseDoubleClick:
1015 case QEvent::GraphicsSceneContextMenu:
1016 case QEvent::GraphicsSceneHoverEnter:
1017 case QEvent::GraphicsSceneHoverMove:
1018 case QEvent::GraphicsSceneHoverLeave:
1019 case QEvent::GraphicsSceneHelp:
1020 case QEvent::GraphicsSceneDragEnter:
1021 case QEvent::GraphicsSceneDragMove:
1022 case QEvent::GraphicsSceneDragLeave:
1023 case QEvent::GraphicsSceneDrop: {
1024 QGraphicsSceneEvent *ev = static_cast<QGraphicsSceneEvent *>(e);
1025 d->contextWidget = ev->widget();
1026 break;
1027 }
1028#endif // QT_CONFIG(graphicsview)
1029 default: break;
1030 };
1031 }
1032
1033 switch (e->type()) {
1034 case QEvent::KeyPress:
1035 d->keyPressEvent(static_cast<QKeyEvent *>(e));
1036 break;
1037 case QEvent::MouseButtonPress: {
1038 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1039 d->mousePressEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1040 ev->buttons(), ev->globalPosition());
1041 break; }
1042 case QEvent::MouseMove: {
1043 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1044 d->mouseMoveEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1045 ev->buttons(), ev->globalPosition());
1046 break; }
1047 case QEvent::MouseButtonRelease: {
1048 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1049 d->mouseReleaseEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1050 ev->buttons(), ev->globalPosition());
1051 break; }
1052 case QEvent::MouseButtonDblClick: {
1053 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1054 d->mouseDoubleClickEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1055 ev->buttons(), ev->globalPosition());
1056 break; }
1057 case QEvent::InputMethod:
1058 d->inputMethodEvent(static_cast<QInputMethodEvent *>(e));
1059 break;
1060#ifndef QT_NO_CONTEXTMENU
1061 case QEvent::ContextMenu: {
1062 QContextMenuEvent *ev = static_cast<QContextMenuEvent *>(e);
1063 d->contextMenuEvent(ev->globalPos(), transform.map(ev->pos()), contextWidget);
1064 break; }
1065#endif // QT_NO_CONTEXTMENU
1066 case QEvent::FocusIn:
1067 case QEvent::FocusOut:
1068 d->focusEvent(static_cast<QFocusEvent *>(e));
1069 break;
1070
1071 case QEvent::EnabledChange:
1072 d->isEnabled = e->isAccepted();
1073 break;
1074
1075#if QT_CONFIG(tooltip)
1076 case QEvent::ToolTip: {
1077 QHelpEvent *ev = static_cast<QHelpEvent *>(e);
1078 d->showToolTip(ev->globalPos(), transform.map(ev->pos()), contextWidget);
1079 break;
1080 }
1081#endif // QT_CONFIG(tooltip)
1082
1083#if QT_CONFIG(draganddrop)
1084 case QEvent::DragEnter: {
1085 QDragEnterEvent *ev = static_cast<QDragEnterEvent *>(e);
1086 if (d->dragEnterEvent(e, ev->mimeData()))
1087 ev->acceptProposedAction();
1088 break;
1089 }
1090 case QEvent::DragLeave:
1091 d->dragLeaveEvent();
1092 break;
1093 case QEvent::DragMove: {
1094 QDragMoveEvent *ev = static_cast<QDragMoveEvent *>(e);
1095 if (d->dragMoveEvent(e, ev->mimeData(), transform.map(ev->position())))
1096 ev->acceptProposedAction();
1097 break;
1098 }
1099 case QEvent::Drop: {
1100 QDropEvent *ev = static_cast<QDropEvent *>(e);
1101 if (d->dropEvent(ev->mimeData(), transform.map(ev->position()), ev->dropAction(), ev->source()))
1102 ev->acceptProposedAction();
1103 break;
1104 }
1105#endif
1106
1107#if QT_CONFIG(graphicsview)
1108 case QEvent::GraphicsSceneMousePress: {
1109 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1110 d->mousePressEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1111 ev->screenPos());
1112 break; }
1113 case QEvent::GraphicsSceneMouseMove: {
1114 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1115 d->mouseMoveEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1116 ev->screenPos());
1117 break; }
1118 case QEvent::GraphicsSceneMouseRelease: {
1119 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1120 d->mouseReleaseEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1121 ev->screenPos());
1122 break; }
1123 case QEvent::GraphicsSceneMouseDoubleClick: {
1124 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1125 d->mouseDoubleClickEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1126 ev->screenPos());
1127 break; }
1128 case QEvent::GraphicsSceneContextMenu: {
1129 QGraphicsSceneContextMenuEvent *ev = static_cast<QGraphicsSceneContextMenuEvent *>(e);
1130 d->contextMenuEvent(ev->screenPos(), transform.map(ev->pos()), contextWidget);
1131 break; }
1132
1133 case QEvent::GraphicsSceneHoverMove: {
1134 QGraphicsSceneHoverEvent *ev = static_cast<QGraphicsSceneHoverEvent *>(e);
1135 d->mouseMoveEvent(ev, Qt::NoButton, transform.map(ev->pos()), ev->modifiers(),Qt::NoButton,
1136 ev->screenPos());
1137 break; }
1138
1139 case QEvent::GraphicsSceneDragEnter: {
1140 QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
1141 if (d->dragEnterEvent(e, ev->mimeData()))
1142 ev->acceptProposedAction();
1143 break; }
1144 case QEvent::GraphicsSceneDragLeave:
1145 d->dragLeaveEvent();
1146 break;
1147 case QEvent::GraphicsSceneDragMove: {
1148 QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
1149 if (d->dragMoveEvent(e, ev->mimeData(), transform.map(ev->pos())))
1150 ev->acceptProposedAction();
1151 break; }
1152 case QEvent::GraphicsSceneDrop: {
1153 QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
1154 if (d->dropEvent(ev->mimeData(), transform.map(ev->pos()), ev->dropAction(), ev->source()))
1155 ev->accept();
1156 break; }
1157#endif // QT_CONFIG(graphicsview)
1158#ifdef QT_KEYPAD_NAVIGATION
1159 case QEvent::EnterEditFocus:
1160 case QEvent::LeaveEditFocus:
1161 if (QApplicationPrivate::keypadNavigationEnabled())
1162 d->editFocusEvent(e);
1163 break;
1164#endif
1165 case QEvent::ShortcutOverride:
1166 if (d->interactionFlags & Qt::TextEditable) {
1167 QKeyEvent* ke = static_cast<QKeyEvent *>(e);
1168 if (isCommonTextEditShortcut(ke))
1169 ke->accept();
1170 }
1171 break;
1172 default:
1173 break;
1174 }
1175}
1176
1177bool QWidgetTextControl::event(QEvent *e)
1178{
1179 return QObject::event(e);
1180}
1181
1182void QWidgetTextControl::timerEvent(QTimerEvent *e)
1183{
1184 Q_D(QWidgetTextControl);
1185 if (e->timerId() == d->cursorBlinkTimer.timerId()) {
1186 d->cursorOn = !d->cursorOn;
1187
1188 if (d->cursor.hasSelection())
1189 d->cursorOn &= (QApplication::style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected)
1190 != 0);
1191
1192 d->repaintCursor();
1193 } else if (e->timerId() == d->trippleClickTimer.timerId()) {
1194 d->trippleClickTimer.stop();
1195 }
1196}
1197
1198void QWidgetTextControl::setPlainText(const QString &text)
1199{
1200 Q_D(QWidgetTextControl);
1201 d->setContent(Qt::PlainText, text);
1202}
1203
1204#if QT_CONFIG(textmarkdownreader)
1205void QWidgetTextControl::setMarkdown(const QString &text)
1206{
1207 Q_D(QWidgetTextControl);
1208 d->setContent(Qt::MarkdownText, text);
1209}
1210#endif
1211
1212void QWidgetTextControl::setHtml(const QString &text)
1213{
1214 Q_D(QWidgetTextControl);
1215 d->setContent(Qt::RichText, text);
1216}
1217
1218void QWidgetTextControlPrivate::keyPressEvent(QKeyEvent *e)
1219{
1220 Q_Q(QWidgetTextControl);
1221#ifndef QT_NO_SHORTCUT
1222 if (e == QKeySequence::SelectAll) {
1223 e->accept();
1224 q->selectAll();
1225#ifndef QT_NO_CLIPBOARD
1226 setClipboardSelection();
1227#endif
1228 return;
1229 }
1230#ifndef QT_NO_CLIPBOARD
1231 else if (e == QKeySequence::Copy) {
1232 e->accept();
1233 q->copy();
1234 return;
1235 }
1236#endif
1237#endif // QT_NO_SHORTCUT
1238
1239 if (interactionFlags & Qt::TextSelectableByKeyboard
1240 && cursorMoveKeyEvent(e))
1241 goto accept;
1242
1243 if (interactionFlags & Qt::LinksAccessibleByKeyboard) {
1244 if ((e->key() == Qt::Key_Return
1245 || e->key() == Qt::Key_Enter
1246#ifdef QT_KEYPAD_NAVIGATION
1247 || e->key() == Qt::Key_Select
1248#endif
1249 )
1250 && cursor.hasSelection()) {
1251
1252 e->accept();
1253 activateLinkUnderCursor();
1254 return;
1255 }
1256 }
1257
1258 if (!(interactionFlags & Qt::TextEditable)) {
1259 e->ignore();
1260 return;
1261 }
1262
1263 if (e->key() == Qt::Key_Direction_L || e->key() == Qt::Key_Direction_R) {
1264 QTextBlockFormat fmt;
1265 fmt.setLayoutDirection((e->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft);
1266 cursor.mergeBlockFormat(fmt);
1267 goto accept;
1268 }
1269
1270 // schedule a repaint of the region of the cursor, as when we move it we
1271 // want to make sure the old cursor disappears (not noticeable when moving
1272 // only a few pixels but noticeable when jumping between cells in tables for
1273 // example)
1274 repaintSelection();
1275
1276 if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~(Qt::ShiftModifier | Qt::GroupSwitchModifier))) {
1277 QTextBlockFormat blockFmt = cursor.blockFormat();
1278 QTextList *list = cursor.currentList();
1279 if (list && cursor.atBlockStart() && !cursor.hasSelection()) {
1280 list->remove(cursor.block());
1281 } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
1282 blockFmt.setIndent(blockFmt.indent() - 1);
1283 cursor.setBlockFormat(blockFmt);
1284 } else {
1285 QTextCursor localCursor = cursor;
1286 localCursor.deletePreviousChar();
1287 if (cursor.d)
1288 cursor.d->setX();
1289 }
1290 goto accept;
1291 }
1292#ifndef QT_NO_SHORTCUT
1293 else if (e == QKeySequence::InsertParagraphSeparator) {
1294 insertParagraphSeparator();
1295 e->accept();
1296 goto accept;
1297 } else if (e == QKeySequence::InsertLineSeparator) {
1298 cursor.insertText(QString(QChar::LineSeparator));
1299 e->accept();
1300 goto accept;
1301 }
1302#endif
1303 if (false) {
1304 }
1305#ifndef QT_NO_SHORTCUT
1306 else if (e == QKeySequence::Undo) {
1307 q->undo();
1308 }
1309 else if (e == QKeySequence::Redo) {
1310 q->redo();
1311 }
1312#ifndef QT_NO_CLIPBOARD
1313 else if (e == QKeySequence::Cut) {
1314 q->cut();
1315 }
1316 else if (e == QKeySequence::Paste) {
1317 QClipboard::Mode mode = QClipboard::Clipboard;
1318 if (QGuiApplication::clipboard()->supportsSelection()) {
1319 if (e->modifiers() == (Qt::CTRL | Qt::SHIFT) && e->key() == Qt::Key_Insert)
1320 mode = QClipboard::Selection;
1321 }
1322 q->paste(mode);
1323 }
1324#endif
1325 else if (e == QKeySequence::Delete) {
1326 QTextCursor localCursor = cursor;
1327 localCursor.deleteChar();
1328 if (cursor.d)
1329 cursor.d->setX();
1330 } else if (e == QKeySequence::Backspace) {
1331 QTextCursor localCursor = cursor;
1332 localCursor.deletePreviousChar();
1333 if (cursor.d)
1334 cursor.d->setX();
1335 }else if (e == QKeySequence::DeleteEndOfWord) {
1336 if (!cursor.hasSelection())
1337 cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor);
1338 cursor.removeSelectedText();
1339 }
1340 else if (e == QKeySequence::DeleteStartOfWord) {
1341 if (!cursor.hasSelection())
1342 cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
1343 cursor.removeSelectedText();
1344 }
1345 else if (e == QKeySequence::DeleteEndOfLine) {
1346 QTextBlock block = cursor.block();
1347 if (cursor.position() == block.position() + block.length() - 2)
1348 cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
1349 else
1350 cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
1351 cursor.removeSelectedText();
1352 }
1353#endif // QT_NO_SHORTCUT
1354 else {
1355 goto process;
1356 }
1357 goto accept;
1358
1359process:
1360 {
1361 if (q->isAcceptableInput(e)) {
1362 if (overwriteMode
1363 // no need to call deleteChar() if we have a selection, insertText
1364 // does it already
1365 && !cursor.hasSelection()
1366 && !cursor.atBlockEnd())
1367 cursor.deleteChar();
1368
1369 cursor.insertText(e->text());
1370 selectionChanged();
1371 } else {
1372 e->ignore();
1373 return;
1374 }
1375 }
1376
1377 accept:
1378
1379#ifndef QT_NO_CLIPBOARD
1380 setClipboardSelection();
1381#endif
1382
1383 e->accept();
1384 cursorOn = true;
1385
1386 q->ensureCursorVisible();
1387
1388 updateCurrentCharFormat();
1389}
1390
1391QVariant QWidgetTextControl::loadResource(int type, const QUrl &name)
1392{
1393 Q_UNUSED(type);
1394 Q_UNUSED(name);
1395 return QVariant();
1396}
1397
1398void QWidgetTextControlPrivate::_q_updateBlock(const QTextBlock &block)
1399{
1400 Q_Q(QWidgetTextControl);
1401 QRectF br = q->blockBoundingRect(block);
1402 br.setRight(qreal(INT_MAX)); // the block might have shrunk
1403 emit q->updateRequest(br);
1404}
1405
1407{
1408 Q_Q(const QWidgetTextControl);
1409 const QTextBlock block = doc->findBlock(position);
1410 if (!block.isValid())
1411 return QRectF();
1412 const QAbstractTextDocumentLayout *docLayout = doc->documentLayout();
1413 const QTextLayout *layout = block.layout();
1414 const QPointF layoutPos = q->blockBoundingRect(block).topLeft();
1415 int relativePos = position - block.position();
1416 if (preeditCursor != 0) {
1417 int preeditPos = layout->preeditAreaPosition();
1418 if (relativePos == preeditPos)
1419 relativePos += preeditCursor;
1420 else if (relativePos > preeditPos)
1421 relativePos += layout->preeditAreaText().size();
1422 }
1423 QTextLine line = layout->lineForTextPosition(relativePos);
1424
1425 int cursorWidth;
1426 {
1427 bool ok = false;
1428 cursorWidth = docLayout->property("cursorWidth").toInt(&ok);
1429 if (!ok)
1430 cursorWidth = 1;
1431 }
1432
1433 QRectF r;
1434
1435 if (line.isValid()) {
1436 qreal x = line.cursorToX(relativePos);
1437 qreal w = 0;
1438 if (overwriteMode) {
1439 if (relativePos < line.textLength() - line.textStart())
1440 w = line.cursorToX(relativePos + 1) - x;
1441 else
1442 w = QFontMetrics(block.layout()->font()).horizontalAdvance(u' '); // in sync with QTextLine::draw()
1443 }
1444 r = QRectF(layoutPos.x() + x, layoutPos.y() + line.y(),
1445 cursorWidth + w, line.height());
1446 } else {
1447 r = QRectF(layoutPos.x(), layoutPos.y(), cursorWidth, 10); // #### correct height
1448 }
1449
1450 return r;
1451}
1452
1453namespace {
1454struct QTextFrameComparator {
1455 bool operator()(QTextFrame *frame, int position) { return frame->firstPosition() < position; }
1456 bool operator()(int position, QTextFrame *frame) { return position < frame->firstPosition(); }
1457};
1458}
1459
1460static QRectF boundingRectOfFloatsInSelection(const QTextCursor &cursor)
1461{
1462 QRectF r;
1463 QTextFrame *frame = cursor.currentFrame();
1464 const QList<QTextFrame *> children = frame->childFrames();
1465
1466 const QList<QTextFrame *>::ConstIterator firstFrame = std::lower_bound(children.constBegin(), children.constEnd(),
1467 cursor.selectionStart(), QTextFrameComparator());
1468 const QList<QTextFrame *>::ConstIterator lastFrame = std::upper_bound(children.constBegin(), children.constEnd(),
1469 cursor.selectionEnd(), QTextFrameComparator());
1470 for (QList<QTextFrame *>::ConstIterator it = firstFrame; it != lastFrame; ++it) {
1471 if ((*it)->frameFormat().position() != QTextFrameFormat::InFlow)
1472 r |= frame->document()->documentLayout()->frameBoundingRect(*it);
1473 }
1474 return r;
1475}
1476
1477QRectF QWidgetTextControl::selectionRect(const QTextCursor &cursor) const
1478{
1479 Q_D(const QWidgetTextControl);
1480
1481 QRectF r = d->rectForPosition(cursor.selectionStart());
1482
1483 if (cursor.hasComplexSelection() && cursor.currentTable()) {
1484 QTextTable *table = cursor.currentTable();
1485
1486 r = d->doc->documentLayout()->frameBoundingRect(table);
1487 /*
1488 int firstRow, numRows, firstColumn, numColumns;
1489 cursor.selectedTableCells(&firstRow, &numRows, &firstColumn, &numColumns);
1490
1491 const QTextTableCell firstCell = table->cellAt(firstRow, firstColumn);
1492 const QTextTableCell lastCell = table->cellAt(firstRow + numRows - 1, firstColumn + numColumns - 1);
1493
1494 const QAbstractTextDocumentLayout * const layout = doc->documentLayout();
1495
1496 QRectF tableSelRect = layout->blockBoundingRect(firstCell.firstCursorPosition().block());
1497
1498 for (int col = firstColumn; col < firstColumn + numColumns; ++col) {
1499 const QTextTableCell cell = table->cellAt(firstRow, col);
1500 const qreal y = layout->blockBoundingRect(cell.firstCursorPosition().block()).top();
1501
1502 tableSelRect.setTop(qMin(tableSelRect.top(), y));
1503 }
1504
1505 for (int row = firstRow; row < firstRow + numRows; ++row) {
1506 const QTextTableCell cell = table->cellAt(row, firstColumn);
1507 const qreal x = layout->blockBoundingRect(cell.firstCursorPosition().block()).left();
1508
1509 tableSelRect.setLeft(qMin(tableSelRect.left(), x));
1510 }
1511
1512 for (int col = firstColumn; col < firstColumn + numColumns; ++col) {
1513 const QTextTableCell cell = table->cellAt(firstRow + numRows - 1, col);
1514 const qreal y = layout->blockBoundingRect(cell.lastCursorPosition().block()).bottom();
1515
1516 tableSelRect.setBottom(qMax(tableSelRect.bottom(), y));
1517 }
1518
1519 for (int row = firstRow; row < firstRow + numRows; ++row) {
1520 const QTextTableCell cell = table->cellAt(row, firstColumn + numColumns - 1);
1521 const qreal x = layout->blockBoundingRect(cell.lastCursorPosition().block()).right();
1522
1523 tableSelRect.setRight(qMax(tableSelRect.right(), x));
1524 }
1525
1526 r = tableSelRect.toRect();
1527 */
1528 } else if (cursor.hasSelection()) {
1529 const int position = cursor.selectionStart();
1530 const int anchor = cursor.selectionEnd();
1531 const QTextBlock posBlock = d->doc->findBlock(position);
1532 const QTextBlock anchorBlock = d->doc->findBlock(anchor);
1533 if (posBlock == anchorBlock && posBlock.isValid() && posBlock.layout()->lineCount()) {
1534 const QTextLine posLine = posBlock.layout()->lineForTextPosition(position - posBlock.position());
1535 const QTextLine anchorLine = anchorBlock.layout()->lineForTextPosition(anchor - anchorBlock.position());
1536
1537 const int firstLine = qMin(posLine.lineNumber(), anchorLine.lineNumber());
1538 const int lastLine = qMax(posLine.lineNumber(), anchorLine.lineNumber());
1539 const QTextLayout *layout = posBlock.layout();
1540 r = QRectF();
1541 for (int i = firstLine; i <= lastLine; ++i) {
1542 r |= layout->lineAt(i).rect();
1543 r |= layout->lineAt(i).naturalTextRect(); // might be bigger in the case of wrap not enabled
1544 }
1545 r.translate(blockBoundingRect(posBlock).topLeft());
1546 } else {
1547 QRectF anchorRect = d->rectForPosition(cursor.selectionEnd());
1548 r |= anchorRect;
1549 r |= boundingRectOfFloatsInSelection(cursor);
1550 QRectF frameRect(d->doc->documentLayout()->frameBoundingRect(cursor.currentFrame()));
1551 r.setLeft(frameRect.left());
1552 r.setRight(frameRect.right());
1553 }
1554 if (r.isValid())
1555 r.adjust(-1, -1, 1, 1);
1556 }
1557
1558 return r;
1559}
1560
1561QRectF QWidgetTextControl::selectionRect() const
1562{
1563 Q_D(const QWidgetTextControl);
1564 return selectionRect(d->cursor);
1565}
1566
1567void QWidgetTextControlPrivate::mousePressEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
1568 Qt::MouseButtons buttons, const QPointF &globalPos)
1569{
1570 Q_Q(QWidgetTextControl);
1571
1572 mousePressPos = pos;
1573
1574#if QT_CONFIG(draganddrop)
1575 mightStartDrag = false;
1576#endif
1577
1578 if (sendMouseEventToInputContext(
1579 e, QEvent::MouseButtonPress, button, pos, modifiers, buttons, globalPos)) {
1580 return;
1581 }
1582
1583 if (interactionFlags & Qt::LinksAccessibleByMouse) {
1584 anchorOnMousePress = q->anchorAt(pos);
1585
1587 cursorIsFocusIndicator = false;
1589 cursor.clearSelection();
1590 }
1591 }
1592 if (!(button & Qt::LeftButton) ||
1593 !((interactionFlags & Qt::TextSelectableByMouse) || (interactionFlags & Qt::TextEditable))) {
1594 e->ignore();
1595 return;
1596 }
1597 bool wasValid = blockWithMarkerUnderMouse.isValid();
1598 blockWithMarkerUnderMouse = q->blockWithMarkerAt(pos);
1599 if (wasValid != blockWithMarkerUnderMouse.isValid())
1600 emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
1601
1602
1603 cursorIsFocusIndicator = false;
1604 const QTextCursor oldSelection = cursor;
1605 const int oldCursorPos = cursor.position();
1606
1607 mousePressed = (interactionFlags & Qt::TextSelectableByMouse);
1608
1610
1611 if (trippleClickTimer.isActive()
1612 && ((pos - trippleClickPoint).manhattanLength() < QApplication::startDragDistance())) {
1613
1614 cursor.movePosition(QTextCursor::StartOfBlock);
1615 cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
1616 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
1617 selectedBlockOnTrippleClick = cursor;
1618
1619 anchorOnMousePress = QString();
1620 blockWithMarkerUnderMouse = QTextBlock();
1621 emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
1622
1623 trippleClickTimer.stop();
1624 } else {
1625 int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
1626 if (cursorPos == -1) {
1627 e->ignore();
1628 return;
1629 }
1630
1631 if (modifiers == Qt::ShiftModifier && (interactionFlags & Qt::TextSelectableByMouse)) {
1632 if (wordSelectionEnabled && !selectedWordOnDoubleClick.hasSelection()) {
1633 selectedWordOnDoubleClick = cursor;
1634 selectedWordOnDoubleClick.select(QTextCursor::WordUnderCursor);
1635 }
1636
1637 if (selectedBlockOnTrippleClick.hasSelection())
1639 else if (selectedWordOnDoubleClick.hasSelection())
1640 extendWordwiseSelection(cursorPos, pos.x());
1641 else if (!wordSelectionEnabled)
1642 setCursorPosition(cursorPos, QTextCursor::KeepAnchor);
1643 } else {
1644
1645 if (dragEnabled
1646 && cursor.hasSelection()
1647 && !cursorIsFocusIndicator
1648 && cursorPos >= cursor.selectionStart()
1649 && cursorPos <= cursor.selectionEnd()
1650 && q->hitTest(pos, Qt::ExactHit) != -1) {
1651#if QT_CONFIG(draganddrop)
1652 mightStartDrag = true;
1653#endif
1654 return;
1655 }
1656
1657 setCursorPosition(cursorPos);
1658 }
1659 }
1660
1661 if (interactionFlags & Qt::TextEditable) {
1662 q->ensureCursorVisible();
1663 if (cursor.position() != oldCursorPos)
1664 emit q->cursorPositionChanged();
1666 } else {
1667 if (cursor.position() != oldCursorPos) {
1668 emit q->cursorPositionChanged();
1669 emit q->microFocusChanged();
1670 }
1672 }
1673 repaintOldAndNewSelection(oldSelection);
1674 hadSelectionOnMousePress = cursor.hasSelection();
1675}
1676
1677void QWidgetTextControlPrivate::mouseMoveEvent(QEvent *e, Qt::MouseButton button, const QPointF &mousePos, Qt::KeyboardModifiers modifiers,
1678 Qt::MouseButtons buttons, const QPointF &globalPos)
1679{
1680 Q_Q(QWidgetTextControl);
1681
1682 if (interactionFlags & Qt::LinksAccessibleByMouse) {
1683 QString anchor = q->anchorAt(mousePos);
1684 if (anchor != highlightedAnchor) {
1685 highlightedAnchor = anchor;
1686 emit q->linkHovered(anchor);
1687 }
1688 }
1689
1690 if (buttons & Qt::LeftButton) {
1691 const bool editable = interactionFlags & Qt::TextEditable;
1692
1693 if (!(mousePressed
1694 || editable
1695 || mightStartDrag
1696 || selectedWordOnDoubleClick.hasSelection()
1697 || selectedBlockOnTrippleClick.hasSelection()))
1698 return;
1699
1700 const QTextCursor oldSelection = cursor;
1701 const int oldCursorPos = cursor.position();
1702
1703 if (mightStartDrag) {
1704 if ((mousePos - mousePressPos).manhattanLength() > QApplication::startDragDistance())
1706 return;
1707 }
1708
1709 const qreal mouseX = qreal(mousePos.x());
1710
1711 int newCursorPos = q->hitTest(mousePos, Qt::FuzzyHit);
1712
1713 if (isPreediting()) {
1714 // note: oldCursorPos not including preedit
1715 int selectionStartPos = q->hitTest(mousePressPos, Qt::FuzzyHit);
1716
1717 if (newCursorPos != selectionStartPos) {
1719 // commit invalidates positions
1720 newCursorPos = q->hitTest(mousePos, Qt::FuzzyHit);
1721 selectionStartPos = q->hitTest(mousePressPos, Qt::FuzzyHit);
1722 setCursorPosition(selectionStartPos);
1723 }
1724 }
1725
1726 if (newCursorPos == -1)
1727 return;
1728
1729 if (mousePressed && wordSelectionEnabled && !selectedWordOnDoubleClick.hasSelection()) {
1730 selectedWordOnDoubleClick = cursor;
1731 selectedWordOnDoubleClick.select(QTextCursor::WordUnderCursor);
1732 }
1733
1734 if (selectedBlockOnTrippleClick.hasSelection())
1735 extendBlockwiseSelection(newCursorPos);
1736 else if (selectedWordOnDoubleClick.hasSelection())
1737 extendWordwiseSelection(newCursorPos, mouseX);
1738 else if (mousePressed && !isPreediting())
1739 setCursorPosition(newCursorPos, QTextCursor::KeepAnchor);
1740
1741 if (interactionFlags & Qt::TextEditable) {
1742 // don't call ensureVisible for the visible cursor to avoid jumping
1743 // scrollbars. the autoscrolling ensures smooth scrolling if necessary.
1744 //q->ensureCursorVisible();
1745 if (cursor.position() != oldCursorPos)
1746 emit q->cursorPositionChanged();
1748#ifndef QT_NO_IM
1749 if (contextWidget)
1750 QGuiApplication::inputMethod()->update(Qt::ImQueryInput);
1751#endif //QT_NO_IM
1752 } else {
1753 //emit q->visibilityRequest(QRectF(mousePos, QSizeF(1, 1)));
1754 if (cursor.position() != oldCursorPos) {
1755 emit q->cursorPositionChanged();
1756 emit q->microFocusChanged();
1757 }
1758 }
1760 repaintOldAndNewSelection(oldSelection);
1761 } else {
1762 bool wasValid = blockWithMarkerUnderMouse.isValid();
1763 blockWithMarkerUnderMouse = q->blockWithMarkerAt(mousePos);
1764 if (wasValid != blockWithMarkerUnderMouse.isValid())
1765 emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
1766 }
1767
1768 sendMouseEventToInputContext(e, QEvent::MouseMove, button, mousePos, modifiers, buttons, globalPos);
1769}
1770
1771void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
1772 Qt::MouseButtons buttons, const QPointF &globalPos)
1773{
1774 Q_Q(QWidgetTextControl);
1775
1776 const QTextCursor oldSelection = cursor;
1777 if (sendMouseEventToInputContext(
1778 e, QEvent::MouseButtonRelease, button, pos, modifiers, buttons, globalPos)) {
1779 repaintOldAndNewSelection(oldSelection);
1780 return;
1781 }
1782
1783 const int oldCursorPos = cursor.position();
1784
1785#if QT_CONFIG(draganddrop)
1786 if (mightStartDrag && (button & Qt::LeftButton)) {
1787 mousePressed = false;
1788 setCursorPosition(pos);
1789 cursor.clearSelection();
1790 selectionChanged();
1791 }
1792#endif
1793 if (mousePressed) {
1794 mousePressed = false;
1795#ifndef QT_NO_CLIPBOARD
1798 } else if (button == Qt::MiddleButton
1799 && (interactionFlags & Qt::TextEditable)
1800 && QGuiApplication::clipboard()->supportsSelection()) {
1801 setCursorPosition(pos);
1802 const QMimeData *md = QGuiApplication::clipboard()->mimeData(QClipboard::Selection);
1803 if (md)
1804 q->insertFromMimeData(md);
1805#endif
1806 }
1807
1808 repaintOldAndNewSelection(oldSelection);
1809
1810 if (cursor.position() != oldCursorPos) {
1811 emit q->cursorPositionChanged();
1812 emit q->microFocusChanged();
1813 }
1814
1815 // toggle any checkbox that the user clicks
1816 if ((interactionFlags & Qt::TextEditable) && (button & Qt::LeftButton) &&
1817 (blockWithMarkerUnderMouse.isValid()) && !cursor.hasSelection()) {
1818 QTextBlock markerBlock = q->blockWithMarkerAt(pos);
1819 if (markerBlock == blockWithMarkerUnderMouse) {
1820 auto fmt = blockWithMarkerUnderMouse.blockFormat();
1821 switch (fmt.marker()) {
1822 case QTextBlockFormat::MarkerType::Unchecked :
1823 fmt.setMarker(QTextBlockFormat::MarkerType::Checked);
1824 break;
1825 case QTextBlockFormat::MarkerType::Checked:
1826 fmt.setMarker(QTextBlockFormat::MarkerType::Unchecked);
1827 break;
1828 default:
1829 break;
1830 }
1831 cursor.setBlockFormat(fmt);
1832 }
1833 }
1834
1835 if (interactionFlags & Qt::LinksAccessibleByMouse) {
1836
1837 // Ignore event unless left button has been pressed
1838 if (!(button & Qt::LeftButton)) {
1839 e->ignore();
1840 return;
1841 }
1842
1843 const QString anchor = q->anchorAt(pos);
1844
1845 // Ignore event without selection anchor
1846 if (anchor.isEmpty()) {
1847 e->ignore();
1848 return;
1849 }
1850
1851 if (!cursor.hasSelection()
1852 || (anchor == anchorOnMousePress && hadSelectionOnMousePress)) {
1853
1854 const int anchorPos = q->hitTest(pos, Qt::ExactHit);
1855
1856 // Ignore event without valid anchor position
1857 if (anchorPos < 0) {
1858 e->ignore();
1859 return;
1860 }
1861
1862 cursor.setPosition(anchorPos);
1863 activateLinkUnderCursor(std::exchange(anchorOnMousePress, QString()));
1864 }
1865 }
1866}
1867
1868void QWidgetTextControlPrivate::mouseDoubleClickEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos,
1869 Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons,
1870 const QPointF &globalPos)
1871{
1872 Q_Q(QWidgetTextControl);
1873
1874 if (button == Qt::LeftButton
1875 && (interactionFlags & Qt::TextSelectableByMouse)) {
1876
1877#if QT_CONFIG(draganddrop)
1878 mightStartDrag = false;
1879#endif
1881
1882 const QTextCursor oldSelection = cursor;
1883 setCursorPosition(pos);
1884 QTextLine line = currentTextLine(cursor);
1885 bool doEmit = false;
1886 if (line.isValid() && line.textLength()) {
1887 cursor.select(QTextCursor::WordUnderCursor);
1888 doEmit = true;
1889 }
1890 repaintOldAndNewSelection(oldSelection);
1891
1892 cursorIsFocusIndicator = false;
1893 selectedWordOnDoubleClick = cursor;
1894
1895 trippleClickPoint = pos;
1896 trippleClickTimer.start(QApplication::doubleClickInterval(), q);
1897 if (doEmit) {
1899#ifndef QT_NO_CLIPBOARD
1901#endif
1902 emit q->cursorPositionChanged();
1903 }
1904 } else if (!sendMouseEventToInputContext(e, QEvent::MouseButtonDblClick, button, pos,
1905 modifiers, buttons, globalPos)) {
1906 e->ignore();
1907 }
1908}
1909
1910bool QWidgetTextControlPrivate::sendMouseEventToInputContext(
1911 QEvent *e, QEvent::Type eventType, Qt::MouseButton button, const QPointF &pos,
1912 Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPointF &globalPos)
1913{
1914 Q_UNUSED(eventType);
1915 Q_UNUSED(button);
1916 Q_UNUSED(pos);
1917 Q_UNUSED(modifiers);
1918 Q_UNUSED(buttons);
1919 Q_UNUSED(globalPos);
1920#if !defined(QT_NO_IM)
1921 Q_Q(QWidgetTextControl);
1922
1923 if (isPreediting()) {
1924 QTextLayout *layout = cursor.block().layout();
1925 int cursorPos = q->hitTest(pos, Qt::FuzzyHit) - cursor.position();
1926
1927 if (cursorPos < 0 || cursorPos > layout->preeditAreaText().size())
1928 cursorPos = -1;
1929
1930 if (cursorPos >= 0) {
1931 if (eventType == QEvent::MouseButtonRelease)
1932 QGuiApplication::inputMethod()->invokeAction(QInputMethod::Click, cursorPos);
1933
1934 e->setAccepted(true);
1935 return true;
1936 }
1937 }
1938#else
1939 Q_UNUSED(e);
1940#endif
1941 return false;
1942}
1943
1944void QWidgetTextControlPrivate::contextMenuEvent(const QPointF &screenPos, const QPointF &docPos, QWidget *contextWidget)
1945{
1946#ifdef QT_NO_CONTEXTMENU
1947 Q_UNUSED(screenPos);
1948 Q_UNUSED(docPos);
1949 Q_UNUSED(contextWidget);
1950#else
1951 Q_Q(QWidgetTextControl);
1952 QMenu *menu = q->createStandardContextMenu(docPos, contextWidget);
1953 if (!menu)
1954 return;
1955 menu->setAttribute(Qt::WA_DeleteOnClose);
1956
1957 if (auto *widget = qobject_cast<QWidget *>(parent)) {
1958 if (auto *window = widget->window()->windowHandle())
1959 QMenuPrivate::get(menu)->topData()->initialScreen = window->screen();
1960 }
1961
1962 menu->popup(screenPos.toPoint());
1963#endif
1964}
1965
1966bool QWidgetTextControlPrivate::dragEnterEvent(QEvent *e, const QMimeData *mimeData)
1967{
1968 Q_Q(QWidgetTextControl);
1969 if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData)) {
1970 e->ignore();
1971 return false;
1972 }
1973
1974 dndFeedbackCursor = QTextCursor();
1975
1976 return true; // accept proposed action
1977}
1978
1980{
1981 Q_Q(QWidgetTextControl);
1982
1983 const QRectF crect = q->cursorRect(dndFeedbackCursor);
1984 dndFeedbackCursor = QTextCursor();
1985
1986 if (crect.isValid())
1987 emit q->updateRequest(crect);
1988}
1989
1990bool QWidgetTextControlPrivate::dragMoveEvent(QEvent *e, const QMimeData *mimeData, const QPointF &pos)
1991{
1992 Q_Q(QWidgetTextControl);
1993 if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData)) {
1994 e->ignore();
1995 return false;
1996 }
1997
1998 const int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
1999 if (cursorPos != -1) {
2000 QRectF crect = q->cursorRect(dndFeedbackCursor);
2001 if (crect.isValid())
2002 emit q->updateRequest(crect);
2003
2004 dndFeedbackCursor = cursor;
2005 dndFeedbackCursor.setPosition(cursorPos);
2006
2007 crect = q->cursorRect(dndFeedbackCursor);
2008 emit q->updateRequest(crect);
2009 }
2010
2011 return true; // accept proposed action
2012}
2013
2014bool QWidgetTextControlPrivate::dropEvent(const QMimeData *mimeData, const QPointF &pos, Qt::DropAction dropAction, QObject *source)
2015{
2016 Q_Q(QWidgetTextControl);
2017 dndFeedbackCursor = QTextCursor();
2018
2019 if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData))
2020 return false;
2021
2023
2024 QTextCursor insertionCursor = q->cursorForPosition(pos);
2025 insertionCursor.beginEditBlock();
2026
2027 if (dropAction == Qt::MoveAction && source == contextWidget)
2028 cursor.removeSelectedText();
2029
2030 cursor = insertionCursor;
2031 q->insertFromMimeData(mimeData);
2032 insertionCursor.endEditBlock();
2033 q->ensureCursorVisible();
2034 return true; // accept proposed action
2035}
2036
2037void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
2038{
2039 Q_Q(QWidgetTextControl);
2040 if (!(interactionFlags & (Qt::TextEditable | Qt::TextSelectableByMouse)) || cursor.isNull()) {
2041 e->ignore();
2042 return;
2043 }
2044 bool isGettingInput = !e->commitString().isEmpty()
2045 || e->preeditString() != cursor.block().layout()->preeditAreaText()
2046 || e->replacementLength() > 0;
2047
2048 if (!isGettingInput && e->attributes().isEmpty()) {
2049 e->ignore();
2050 return;
2051 }
2052
2053 int oldCursorPos = cursor.position();
2054
2055 cursor.beginEditBlock();
2056 if (isGettingInput) {
2057 cursor.removeSelectedText();
2058 }
2059
2060 QTextBlock block;
2061
2062 // insert commit string
2063 if (!e->commitString().isEmpty() || e->replacementLength()) {
2064 auto *mimeData = QInputControl::mimeDataForInputEvent(e);
2065 if (mimeData && q->canInsertFromMimeData(mimeData)) {
2066 q->insertFromMimeData(mimeData);
2067 } else {
2068 if (e->commitString().endsWith(QChar::LineFeed))
2069 block = cursor.block(); // Remember the block where the preedit text is
2070 QTextCursor c = cursor;
2071 c.setPosition(c.position() + e->replacementStart());
2072 c.setPosition(c.position() + e->replacementLength(), QTextCursor::KeepAnchor);
2073 c.insertText(e->commitString());
2074 }
2075 }
2076
2077 for (int i = 0; i < e->attributes().size(); ++i) {
2078 const QInputMethodEvent::Attribute &a = e->attributes().at(i);
2079 if (a.type == QInputMethodEvent::Selection) {
2080 QTextCursor oldCursor = cursor;
2081 int blockStart = a.start + cursor.block().position();
2082 cursor.setPosition(blockStart, QTextCursor::MoveAnchor);
2083 cursor.setPosition(blockStart + a.length, QTextCursor::KeepAnchor);
2084 q->ensureCursorVisible();
2085 repaintOldAndNewSelection(oldCursor);
2086 }
2087 }
2088
2089 if (!block.isValid())
2090 block = cursor.block();
2091 QTextLayout *layout = block.layout();
2092 if (isGettingInput)
2093 layout->setPreeditArea(cursor.position() - block.position(), e->preeditString());
2094 QList<QTextLayout::FormatRange> overrides;
2095 overrides.reserve(e->attributes().size());
2096 const int oldPreeditCursor = preeditCursor;
2097 preeditCursor = e->preeditString().size();
2098 hideCursor = false;
2099 for (int i = 0; i < e->attributes().size(); ++i) {
2100 const QInputMethodEvent::Attribute &a = e->attributes().at(i);
2101 if (a.type == QInputMethodEvent::Cursor) {
2102 preeditCursor = a.start;
2103 hideCursor = !a.length;
2104 } else if (a.type == QInputMethodEvent::TextFormat) {
2105 QTextCharFormat f = cursor.charFormat();
2106 f.merge(qvariant_cast<QTextFormat>(a.value).toCharFormat());
2107 if (f.isValid()) {
2108 QTextLayout::FormatRange o;
2109 o.start = a.start + cursor.position() - block.position();
2110 o.length = a.length;
2111 o.format = f;
2112
2113 // Make sure list is sorted by start index
2114 QList<QTextLayout::FormatRange>::iterator it = overrides.end();
2115 while (it != overrides.begin()) {
2116 QList<QTextLayout::FormatRange>::iterator previous = it - 1;
2117 if (o.start >= previous->start) {
2118 overrides.insert(it, o);
2119 break;
2120 }
2121 it = previous;
2122 }
2123
2124 if (it == overrides.begin())
2125 overrides.prepend(o);
2126 }
2127 }
2128 }
2129
2130 if (cursor.charFormat().isValid()) {
2131 int start = cursor.position() - block.position();
2132 int end = start + e->preeditString().size();
2133
2134 QList<QTextLayout::FormatRange>::iterator it = overrides.begin();
2135 while (it != overrides.end()) {
2136 QTextLayout::FormatRange range = *it;
2137 int rangeStart = range.start;
2138 if (rangeStart > start) {
2139 QTextLayout::FormatRange o;
2140 o.start = start;
2141 o.length = rangeStart - start;
2142 o.format = cursor.charFormat();
2143 it = overrides.insert(it, o) + 1;
2144 }
2145
2146 ++it;
2147 start = range.start + range.length;
2148 }
2149
2150 if (start < end) {
2151 QTextLayout::FormatRange o;
2152 o.start = start;
2153 o.length = end - start;
2154 o.format = cursor.charFormat();
2155 overrides.append(o);
2156 }
2157 }
2158 layout->setFormats(overrides);
2159
2160 cursor.endEditBlock();
2161
2162 if (cursor.d)
2163 cursor.d->setX();
2164 if (oldCursorPos != cursor.position())
2165 emit q->cursorPositionChanged();
2166 if (oldPreeditCursor != preeditCursor)
2167 emit q->microFocusChanged();
2168}
2169
2170QVariant QWidgetTextControl::inputMethodQuery(Qt::InputMethodQuery property, QVariant argument) const
2171{
2172 Q_D(const QWidgetTextControl);
2173 QTextBlock block = d->cursor.block();
2174 switch(property) {
2175 case Qt::ImCursorRectangle:
2176 return cursorRect();
2177 case Qt::ImAnchorRectangle:
2178 return d->rectForPosition(d->cursor.anchor());
2179 case Qt::ImFont:
2180 return QVariant(d->cursor.charFormat().font());
2181 case Qt::ImCursorPosition: {
2182 const QPointF pt = argument.toPointF();
2183 if (!pt.isNull())
2184 return QVariant(cursorForPosition(pt).position() - block.position());
2185 return QVariant(d->cursor.position() - block.position()); }
2186 case Qt::ImSurroundingText:
2187 return QVariant(block.text());
2188 case Qt::ImCurrentSelection: {
2189 QMimeData *mimeData = createMimeDataFromSelection();
2190 mimeData->deleteLater();
2191 return QInputControl::selectionWrapper(mimeData);
2192 }
2193 case Qt::ImMaximumTextLength:
2194 return QVariant(); // No limit.
2195 case Qt::ImAnchorPosition:
2196 return QVariant(d->cursor.anchor() - block.position());
2197 case Qt::ImAbsolutePosition: {
2198 const QPointF pt = argument.toPointF();
2199 if (!pt.isNull())
2200 return QVariant(cursorForPosition(pt).position());
2201 return QVariant(d->cursor.position()); }
2202 case Qt::ImTextAfterCursor:
2203 {
2204 int maxLength = argument.isValid() ? argument.toInt() : 1024;
2205 QTextCursor tmpCursor = d->cursor;
2206 int localPos = d->cursor.position() - block.position();
2207 QString result = block.text().mid(localPos);
2208 while (result.size() < maxLength) {
2209 int currentBlock = tmpCursor.blockNumber();
2210 tmpCursor.movePosition(QTextCursor::NextBlock);
2211 if (tmpCursor.blockNumber() == currentBlock)
2212 break;
2213 result += u'\n' + tmpCursor.block().text();
2214 }
2215 return QVariant(result);
2216 }
2217 case Qt::ImTextBeforeCursor:
2218 {
2219 int maxLength = argument.isValid() ? argument.toInt() : 1024;
2220 QTextCursor tmpCursor = d->cursor;
2221 int localPos = d->cursor.position() - block.position();
2222 int numBlocks = 0;
2223 int resultLen = localPos;
2224 while (resultLen < maxLength) {
2225 int currentBlock = tmpCursor.blockNumber();
2226 tmpCursor.movePosition(QTextCursor::PreviousBlock);
2227 if (tmpCursor.blockNumber() == currentBlock)
2228 break;
2229 numBlocks++;
2230 resultLen += tmpCursor.block().length();
2231 }
2232 QString result;
2233 while (numBlocks) {
2234 result += tmpCursor.block().text() + u'\n';
2235 tmpCursor.movePosition(QTextCursor::NextBlock);
2236 --numBlocks;
2237 }
2238 result += QStringView{block.text()}.mid(0, localPos);
2239 return QVariant(result);
2240 }
2241 default:
2242 return QVariant();
2243 }
2244}
2245
2246void QWidgetTextControl::setFocus(bool focus, Qt::FocusReason reason)
2247{
2248 QFocusEvent ev(focus ? QEvent::FocusIn : QEvent::FocusOut,
2249 reason);
2250 processEvent(&ev);
2251}
2252
2253void QWidgetTextControlPrivate::focusEvent(QFocusEvent *e)
2254{
2255 Q_Q(QWidgetTextControl);
2256 emit q->updateRequest(q->selectionRect());
2257 if (e->gotFocus()) {
2258#ifdef QT_KEYPAD_NAVIGATION
2259 if (!QApplicationPrivate::keypadNavigationEnabled() || (hasEditFocus && (e->reason() == Qt::PopupFocusReason))) {
2260#endif
2261 cursorOn = (interactionFlags & (Qt::TextSelectableByKeyboard | Qt::TextEditable));
2262 if (interactionFlags & Qt::TextEditable) {
2263 setCursorVisible(true);
2264 }
2265#ifdef QT_KEYPAD_NAVIGATION
2266 }
2267#endif
2268 } else {
2269 setCursorVisible(false);
2270 cursorOn = false;
2271
2272 if (cursorIsFocusIndicator
2273 && e->reason() != Qt::ActiveWindowFocusReason
2274 && e->reason() != Qt::PopupFocusReason
2275 && cursor.hasSelection()) {
2276 cursor.clearSelection();
2277 }
2278 }
2279 hasFocus = e->gotFocus();
2280}
2281
2282QString QWidgetTextControlPrivate::anchorForCursor(const QTextCursor &anchorCursor) const
2283{
2284 if (anchorCursor.hasSelection()) {
2285 QTextCursor cursor = anchorCursor;
2286 if (cursor.selectionStart() != cursor.position())
2287 cursor.setPosition(cursor.selectionStart());
2288 cursor.movePosition(QTextCursor::NextCharacter);
2289 QTextCharFormat fmt = cursor.charFormat();
2290 if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref))
2291 return fmt.stringProperty(QTextFormat::AnchorHref);
2292 }
2293 return QString();
2294}
2295
2296#ifdef QT_KEYPAD_NAVIGATION
2297void QWidgetTextControlPrivate::editFocusEvent(QEvent *e)
2298{
2299 Q_Q(QWidgetTextControl);
2300
2301 if (QApplicationPrivate::keypadNavigationEnabled()) {
2302 if (e->type() == QEvent::EnterEditFocus && interactionFlags & Qt::TextEditable) {
2303 const QTextCursor oldSelection = cursor;
2304 const int oldCursorPos = cursor.position();
2305 const bool moved = cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
2306 q->ensureCursorVisible();
2307 if (moved) {
2308 if (cursor.position() != oldCursorPos)
2309 emit q->cursorPositionChanged();
2310 emit q->microFocusChanged();
2311 }
2312 selectionChanged();
2313 repaintOldAndNewSelection(oldSelection);
2314
2315 setBlinkingCursorEnabled(true);
2316 } else
2317 setBlinkingCursorEnabled(false);
2318 }
2319
2320 hasEditFocus = e->type() == QEvent::EnterEditFocus;
2321}
2322#endif
2323
2324#ifndef QT_NO_CONTEXTMENU
2325void setActionIcon(QAction *action, const QString &name)
2326{
2327 const QIcon icon = QIcon::fromTheme(name);
2328 if (!icon.isNull())
2329 action->setIcon(icon);
2330}
2331
2332QMenu *QWidgetTextControl::createStandardContextMenu(const QPointF &pos, QWidget *parent)
2333{
2334 Q_D(QWidgetTextControl);
2335
2336 const bool showTextSelectionActions = d->interactionFlags & (Qt::TextEditable | Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
2337
2338 d->linkToCopy = QString();
2339 if (!pos.isNull())
2340 d->linkToCopy = anchorAt(pos);
2341
2342 if (d->linkToCopy.isEmpty() && !showTextSelectionActions)
2343 return nullptr;
2344
2345 QMenu *menu = new QMenu(parent);
2346 QAction *a;
2347
2348 if (d->interactionFlags & Qt::TextEditable) {
2349 a = menu->addAction(tr("&Undo") + ACCEL_KEY(QKeySequence::Undo), this, SLOT(undo()));
2350 a->setEnabled(d->doc->isUndoAvailable());
2351 a->setObjectName(QStringLiteral("edit-undo"));
2352 setActionIcon(a, QStringLiteral("edit-undo"));
2353 a = menu->addAction(tr("&Redo") + ACCEL_KEY(QKeySequence::Redo), this, SLOT(redo()));
2354 a->setEnabled(d->doc->isRedoAvailable());
2355 a->setObjectName(QStringLiteral("edit-redo"));
2356 setActionIcon(a, QStringLiteral("edit-redo"));
2357 menu->addSeparator();
2358
2359#ifndef QT_NO_CLIPBOARD
2360 a = menu->addAction(tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut), this, SLOT(cut()));
2361 a->setEnabled(d->cursor.hasSelection());
2362 a->setObjectName(QStringLiteral("edit-cut"));
2363 setActionIcon(a, QStringLiteral("edit-cut"));
2364#endif
2365 }
2366
2367#ifndef QT_NO_CLIPBOARD
2368 if (showTextSelectionActions) {
2369 a = menu->addAction(tr("&Copy") + ACCEL_KEY(QKeySequence::Copy), this, SLOT(copy()));
2370 a->setEnabled(d->cursor.hasSelection());
2371 a->setObjectName(QStringLiteral("edit-copy"));
2372 setActionIcon(a, QStringLiteral("edit-copy"));
2373 }
2374
2375 if ((d->interactionFlags & Qt::LinksAccessibleByKeyboard)
2376 || (d->interactionFlags & Qt::LinksAccessibleByMouse)) {
2377
2378 a = menu->addAction(tr("Copy &Link Location"), this, SLOT(_q_copyLink()));
2379 a->setEnabled(!d->linkToCopy.isEmpty());
2380 a->setObjectName(QStringLiteral("link-copy"));
2381 }
2382#endif // QT_NO_CLIPBOARD
2383
2384 if (d->interactionFlags & Qt::TextEditable) {
2385#ifndef QT_NO_CLIPBOARD
2386 a = menu->addAction(tr("&Paste") + ACCEL_KEY(QKeySequence::Paste), this, SLOT(paste()));
2387 a->setEnabled(canPaste());
2388 a->setObjectName(QStringLiteral("edit-paste"));
2389 setActionIcon(a, QStringLiteral("edit-paste"));
2390#endif
2391 a = menu->addAction(tr("Delete"), this, SLOT(_q_deleteSelected()));
2392 a->setEnabled(d->cursor.hasSelection());
2393 a->setObjectName(QStringLiteral("edit-delete"));
2394 setActionIcon(a, QStringLiteral("edit-delete"));
2395 }
2396
2397
2398 if (showTextSelectionActions) {
2399 menu->addSeparator();
2400 a = menu->addAction(tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll), this, SLOT(selectAll()));
2401 a->setEnabled(!d->doc->isEmpty());
2402 a->setObjectName(QStringLiteral("select-all"));
2403 setActionIcon(a, QStringLiteral("edit-select-all"));
2404 }
2405
2406 if ((d->interactionFlags & Qt::TextEditable) && QGuiApplication::styleHints()->useRtlExtensions()) {
2407 menu->addSeparator();
2408 QUnicodeControlCharacterMenu *ctrlCharacterMenu = new QUnicodeControlCharacterMenu(this, menu);
2409 menu->addMenu(ctrlCharacterMenu);
2410 }
2411
2412 return menu;
2413}
2414#endif // QT_NO_CONTEXTMENU
2415
2416QTextCursor QWidgetTextControl::cursorForPosition(const QPointF &pos) const
2417{
2418 Q_D(const QWidgetTextControl);
2419 int cursorPos = hitTest(pos, Qt::FuzzyHit);
2420 if (cursorPos == -1)
2421 cursorPos = 0;
2422 QTextCursor c(d->doc);
2423 c.setPosition(cursorPos);
2424 return c;
2425}
2426
2427QRectF QWidgetTextControl::cursorRect(const QTextCursor &cursor) const
2428{
2429 Q_D(const QWidgetTextControl);
2430 if (cursor.isNull())
2431 return QRectF();
2432
2433 return d->rectForPosition(cursor.position());
2434}
2435
2436QRectF QWidgetTextControl::cursorRect() const
2437{
2438 Q_D(const QWidgetTextControl);
2439 return cursorRect(d->cursor);
2440}
2441
2442QRectF QWidgetTextControlPrivate::cursorRectPlusUnicodeDirectionMarkers(const QTextCursor &cursor) const
2443{
2444 if (cursor.isNull())
2445 return QRectF();
2446
2447 return rectForPosition(cursor.position()).adjusted(-4, 0, 4, 0);
2448}
2449
2450QString QWidgetTextControl::anchorAt(const QPointF &pos) const
2451{
2452 Q_D(const QWidgetTextControl);
2453 return d->doc->documentLayout()->anchorAt(pos);
2454}
2455
2456QString QWidgetTextControl::anchorAtCursor() const
2457{
2458 Q_D(const QWidgetTextControl);
2459
2460 return d->anchorForCursor(d->cursor);
2461}
2462
2463QTextBlock QWidgetTextControl::blockWithMarkerAt(const QPointF &pos) const
2464{
2465 Q_D(const QWidgetTextControl);
2466 return d->doc->documentLayout()->blockWithMarkerAt(pos);
2467}
2468
2469bool QWidgetTextControl::overwriteMode() const
2470{
2471 Q_D(const QWidgetTextControl);
2472 return d->overwriteMode;
2473}
2474
2475void QWidgetTextControl::setOverwriteMode(bool overwrite)
2476{
2477 Q_D(QWidgetTextControl);
2478 d->overwriteMode = overwrite;
2479}
2480
2481int QWidgetTextControl::cursorWidth() const
2482{
2483 Q_D(const QWidgetTextControl);
2484 return d->doc->documentLayout()->property("cursorWidth").toInt();
2485}
2486
2487void QWidgetTextControl::setCursorWidth(int width)
2488{
2489 Q_D(QWidgetTextControl);
2490 if (width == -1)
2491 width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth, nullptr, qobject_cast<QWidget *>(parent()));
2492 d->doc->documentLayout()->setProperty("cursorWidth", width);
2493 d->repaintCursor();
2494}
2495
2496bool QWidgetTextControl::acceptRichText() const
2497{
2498 Q_D(const QWidgetTextControl);
2499 return d->acceptRichText;
2500}
2501
2502void QWidgetTextControl::setAcceptRichText(bool accept)
2503{
2504 Q_D(QWidgetTextControl);
2505 d->acceptRichText = accept;
2506}
2507
2508#if QT_CONFIG(textedit)
2509
2510void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections)
2511{
2512 Q_D(QWidgetTextControl);
2513
2514 QMultiHash<int, int> hash;
2515 for (int i = 0; i < d->extraSelections.size(); ++i) {
2516 const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(i);
2517 hash.insert(esel.cursor.anchor(), i);
2518 }
2519
2520 for (int i = 0; i < selections.size(); ++i) {
2521 const QTextEdit::ExtraSelection &sel = selections.at(i);
2522 const auto it = hash.constFind(sel.cursor.anchor());
2523 if (it != hash.cend()) {
2524 const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
2525 if (esel.cursor.position() == sel.cursor.position()
2526 && esel.format == sel.format) {
2527 hash.erase(it);
2528 continue;
2529 }
2530 }
2531 QRectF r = selectionRect(sel.cursor);
2532 if (sel.format.boolProperty(QTextFormat::FullWidthSelection)) {
2533 r.setLeft(0);
2534 r.setWidth(qreal(INT_MAX));
2535 }
2536 emit updateRequest(r);
2537 }
2538
2539 for (auto it = hash.cbegin(); it != hash.cend(); ++it) {
2540 const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
2541 QRectF r = selectionRect(esel.cursor);
2542 if (esel.format.boolProperty(QTextFormat::FullWidthSelection)) {
2543 r.setLeft(0);
2544 r.setWidth(qreal(INT_MAX));
2545 }
2546 emit updateRequest(r);
2547 }
2548
2549 d->extraSelections.resize(selections.size());
2550 for (int i = 0; i < selections.size(); ++i) {
2551 d->extraSelections[i].cursor = selections.at(i).cursor;
2552 d->extraSelections[i].format = selections.at(i).format;
2553 }
2554}
2555
2556QList<QTextEdit::ExtraSelection> QWidgetTextControl::extraSelections() const
2557{
2558 Q_D(const QWidgetTextControl);
2559 QList<QTextEdit::ExtraSelection> selections;
2560 const int numExtraSelections = d->extraSelections.size();
2561 selections.reserve(numExtraSelections);
2562 for (int i = 0; i < numExtraSelections; ++i) {
2563 QTextEdit::ExtraSelection sel;
2564 const QAbstractTextDocumentLayout::Selection &sel2 = d->extraSelections.at(i);
2565 sel.cursor = sel2.cursor;
2566 sel.format = sel2.format;
2567 selections.append(sel);
2568 }
2569 return selections;
2570}
2571
2572#endif // QT_CONFIG(textedit)
2573
2574void QWidgetTextControl::setTextWidth(qreal width)
2575{
2576 Q_D(QWidgetTextControl);
2577 d->doc->setTextWidth(width);
2578}
2579
2580qreal QWidgetTextControl::textWidth() const
2581{
2582 Q_D(const QWidgetTextControl);
2583 return d->doc->textWidth();
2584}
2585
2586QSizeF QWidgetTextControl::size() const
2587{
2588 Q_D(const QWidgetTextControl);
2589 return d->doc->size();
2590}
2591
2592void QWidgetTextControl::setOpenExternalLinks(bool open)
2593{
2594 Q_D(QWidgetTextControl);
2595 d->openExternalLinks = open;
2596}
2597
2598bool QWidgetTextControl::openExternalLinks() const
2599{
2600 Q_D(const QWidgetTextControl);
2601 return d->openExternalLinks;
2602}
2603
2604bool QWidgetTextControl::ignoreUnusedNavigationEvents() const
2605{
2606 Q_D(const QWidgetTextControl);
2607 return d->ignoreUnusedNavigationEvents;
2608}
2609
2610void QWidgetTextControl::setIgnoreUnusedNavigationEvents(bool ignore)
2611{
2612 Q_D(QWidgetTextControl);
2613 d->ignoreUnusedNavigationEvents = ignore;
2614}
2615
2616void QWidgetTextControl::moveCursor(QTextCursor::MoveOperation op, QTextCursor::MoveMode mode)
2617{
2618 Q_D(QWidgetTextControl);
2619 const QTextCursor oldSelection = d->cursor;
2620 const bool moved = d->cursor.movePosition(op, mode);
2621 d->_q_updateCurrentCharFormatAndSelection();
2622 ensureCursorVisible();
2623 d->repaintOldAndNewSelection(oldSelection);
2624 if (moved)
2625 emit cursorPositionChanged();
2626}
2627
2628bool QWidgetTextControl::canPaste() const
2629{
2630#ifndef QT_NO_CLIPBOARD
2631 Q_D(const QWidgetTextControl);
2632 if (d->interactionFlags & Qt::TextEditable) {
2633 const QMimeData *md = QGuiApplication::clipboard()->mimeData();
2634 return md && canInsertFromMimeData(md);
2635 }
2636#endif
2637 return false;
2638}
2639
2640void QWidgetTextControl::setCursorIsFocusIndicator(bool b)
2641{
2642 Q_D(QWidgetTextControl);
2643 d->cursorIsFocusIndicator = b;
2644 d->repaintCursor();
2645}
2646
2647bool QWidgetTextControl::cursorIsFocusIndicator() const
2648{
2649 Q_D(const QWidgetTextControl);
2650 return d->cursorIsFocusIndicator;
2651}
2652
2653
2654void QWidgetTextControl::setDragEnabled(bool enabled)
2655{
2656 Q_D(QWidgetTextControl);
2657 d->dragEnabled = enabled;
2658}
2659
2660bool QWidgetTextControl::isDragEnabled() const
2661{
2662 Q_D(const QWidgetTextControl);
2663 return d->dragEnabled;
2664}
2665
2666void QWidgetTextControl::setWordSelectionEnabled(bool enabled)
2667{
2668 Q_D(QWidgetTextControl);
2669 d->wordSelectionEnabled = enabled;
2670}
2671
2672bool QWidgetTextControl::isWordSelectionEnabled() const
2673{
2674 Q_D(const QWidgetTextControl);
2675 return d->wordSelectionEnabled;
2676}
2677
2678bool QWidgetTextControl::isPreediting()
2679{
2680 return d_func()->isPreediting();
2681}
2682
2683#ifndef QT_NO_PRINTER
2684void QWidgetTextControl::print(QPagedPaintDevice *printer) const
2685{
2686 Q_D(const QWidgetTextControl);
2687 if (!printer)
2688 return;
2689 QTextDocument *tempDoc = nullptr;
2690 const QTextDocument *doc = d->doc;
2691 if (QPagedPaintDevicePrivate::get(printer)->printSelectionOnly) {
2692 if (!d->cursor.hasSelection())
2693 return;
2694 tempDoc = new QTextDocument(const_cast<QTextDocument *>(doc));
2695 tempDoc->setResourceProvider(doc->resourceProvider());
2696 tempDoc->setMetaInformation(QTextDocument::DocumentTitle, doc->metaInformation(QTextDocument::DocumentTitle));
2697 tempDoc->setPageSize(doc->pageSize());
2698 tempDoc->setDefaultFont(doc->defaultFont());
2699 tempDoc->setUseDesignMetrics(doc->useDesignMetrics());
2700 QTextCursor(tempDoc).insertFragment(d->cursor.selection());
2701 doc = tempDoc;
2702
2703 // copy the custom object handlers
2704 doc->documentLayout()->d_func()->handlers = d->doc->documentLayout()->d_func()->handlers;
2705 }
2706 doc->print(printer);
2707 delete tempDoc;
2708}
2709#endif
2710
2711QMimeData *QWidgetTextControl::createMimeDataFromSelection() const
2712{
2713 Q_D(const QWidgetTextControl);
2714 const QTextDocumentFragment fragment(d->cursor);
2715 return new QTextEditMimeData(fragment);
2716}
2717
2718bool QWidgetTextControl::canInsertFromMimeData(const QMimeData *source) const
2719{
2720 Q_D(const QWidgetTextControl);
2721 if (d->acceptRichText)
2722 return (source->hasText() && !source->text().isEmpty())
2723 || source->hasHtml()
2724 || source->hasFormat("application/x-qrichtext"_L1)
2725 || source->hasFormat("application/x-qt-richtext"_L1);
2726 else
2727 return source->hasText() && !source->text().isEmpty();
2728}
2729
2730void QWidgetTextControl::insertFromMimeData(const QMimeData *source)
2731{
2732 Q_D(QWidgetTextControl);
2733 if (!(d->interactionFlags & Qt::TextEditable) || !source)
2734 return;
2735
2736 bool hasData = false;
2737 QTextDocumentFragment fragment;
2738#if QT_CONFIG(textmarkdownreader)
2739 const auto formats = source->formats();
2740 if (formats.size() && formats.first() == "text/markdown"_L1) {
2741 auto s = QString::fromUtf8(source->data("text/markdown"_L1));
2742 fragment = QTextDocumentFragment::fromMarkdown(s);
2743 hasData = true;
2744 } else
2745#endif
2746#ifndef QT_NO_TEXTHTMLPARSER
2747 if (source->hasFormat("application/x-qrichtext"_L1) && d->acceptRichText) {
2748 // x-qrichtext is always UTF-8 (taken from Qt3 since we don't use it anymore).
2749 const QString richtext = "<meta name=\"qrichtext\" content=\"1\" />"_L1
2750 + QString::fromUtf8(source->data("application/x-qrichtext"_L1));
2751 fragment = QTextDocumentFragment::fromHtml(richtext, d->doc);
2752 hasData = true;
2753 } else if (source->hasHtml() && d->acceptRichText) {
2754 fragment = QTextDocumentFragment::fromHtml(source->html(), d->doc);
2755 hasData = true;
2756 }
2757#endif // QT_NO_TEXTHTMLPARSER
2758 if (!hasData) {
2759 const QString text = source->text();
2760 if (!text.isNull()) {
2761 fragment = QTextDocumentFragment::fromPlainText(text);
2762 hasData = true;
2763 }
2764 }
2765
2766 if (hasData)
2767 d->cursor.insertFragment(fragment);
2768 ensureCursorVisible();
2769}
2770
2771bool QWidgetTextControl::findNextPrevAnchor(const QTextCursor &startCursor, bool next, QTextCursor &newAnchor)
2772{
2773 Q_D(QWidgetTextControl);
2774
2775 int anchorStart = -1;
2776 QString anchorHref;
2777 int anchorEnd = -1;
2778
2779 if (next) {
2780 const int startPos = startCursor.selectionEnd();
2781
2782 QTextBlock block = d->doc->findBlock(startPos);
2783 QTextBlock::Iterator it = block.begin();
2784
2785 while (!it.atEnd() && it.fragment().position() < startPos)
2786 ++it;
2787
2788 while (block.isValid()) {
2789 anchorStart = -1;
2790
2791 // find next anchor
2792 for (; !it.atEnd(); ++it) {
2793 const QTextFragment fragment = it.fragment();
2794 const QTextCharFormat fmt = fragment.charFormat();
2795
2796 if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref)) {
2797 anchorStart = fragment.position();
2798 anchorHref = fmt.anchorHref();
2799 break;
2800 }
2801 }
2802
2803 if (anchorStart != -1) {
2804 anchorEnd = -1;
2805
2806 // find next non-anchor fragment
2807 for (; !it.atEnd(); ++it) {
2808 const QTextFragment fragment = it.fragment();
2809 const QTextCharFormat fmt = fragment.charFormat();
2810
2811 if (!fmt.isAnchor() || fmt.anchorHref() != anchorHref) {
2812 anchorEnd = fragment.position();
2813 break;
2814 }
2815 }
2816
2817 if (anchorEnd == -1)
2818 anchorEnd = block.position() + block.length() - 1;
2819
2820 // make found selection
2821 break;
2822 }
2823
2824 block = block.next();
2825 it = block.begin();
2826 }
2827 } else {
2828 int startPos = startCursor.selectionStart();
2829 if (startPos > 0)
2830 --startPos;
2831
2832 QTextBlock block = d->doc->findBlock(startPos);
2833 QTextBlock::Iterator blockStart = block.begin();
2834 QTextBlock::Iterator it = block.end();
2835
2836 if (startPos == block.position()) {
2837 it = block.begin();
2838 } else {
2839 do {
2840 if (it == blockStart) {
2841 it = QTextBlock::Iterator();
2842 block = QTextBlock();
2843 } else {
2844 --it;
2845 }
2846 } while (!it.atEnd() && it.fragment().position() + it.fragment().length() - 1 > startPos);
2847 }
2848
2849 while (block.isValid()) {
2850 anchorStart = -1;
2851
2852 if (!it.atEnd()) {
2853 do {
2854 const QTextFragment fragment = it.fragment();
2855 const QTextCharFormat fmt = fragment.charFormat();
2856
2857 if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref)) {
2858 anchorStart = fragment.position() + fragment.length();
2859 anchorHref = fmt.anchorHref();
2860 break;
2861 }
2862
2863 if (it == blockStart)
2864 it = QTextBlock::Iterator();
2865 else
2866 --it;
2867 } while (!it.atEnd());
2868 }
2869
2870 if (anchorStart != -1 && !it.atEnd()) {
2871 anchorEnd = -1;
2872
2873 do {
2874 const QTextFragment fragment = it.fragment();
2875 const QTextCharFormat fmt = fragment.charFormat();
2876
2877 if (!fmt.isAnchor() || fmt.anchorHref() != anchorHref) {
2878 anchorEnd = fragment.position() + fragment.length();
2879 break;
2880 }
2881
2882 if (it == blockStart)
2883 it = QTextBlock::Iterator();
2884 else
2885 --it;
2886 } while (!it.atEnd());
2887
2888 if (anchorEnd == -1)
2889 anchorEnd = qMax(0, block.position());
2890
2891 break;
2892 }
2893
2894 block = block.previous();
2895 it = block.end();
2896 if (it != block.begin())
2897 --it;
2898 blockStart = block.begin();
2899 }
2900
2901 }
2902
2903 if (anchorStart != -1 && anchorEnd != -1) {
2904 newAnchor = d->cursor;
2905 newAnchor.setPosition(anchorStart);
2906 newAnchor.setPosition(anchorEnd, QTextCursor::KeepAnchor);
2907 return true;
2908 }
2909
2910 return false;
2911}
2912
2913void QWidgetTextControlPrivate::activateLinkUnderCursor(QString href)
2914{
2915 QTextCursor oldCursor = cursor;
2916
2917 if (href.isEmpty()) {
2918 QTextCursor tmp = cursor;
2919 if (tmp.selectionStart() != tmp.position())
2920 tmp.setPosition(tmp.selectionStart());
2921 tmp.movePosition(QTextCursor::NextCharacter);
2922 href = tmp.charFormat().anchorHref();
2923 }
2924 if (href.isEmpty())
2925 return;
2926
2927 if (!cursor.hasSelection()) {
2928 QTextBlock block = cursor.block();
2929 const int cursorPos = cursor.position();
2930
2931 QTextBlock::Iterator it = block.begin();
2932 QTextBlock::Iterator linkFragment;
2933
2934 for (; !it.atEnd(); ++it) {
2935 QTextFragment fragment = it.fragment();
2936 const int fragmentPos = fragment.position();
2937 if (fragmentPos <= cursorPos &&
2938 fragmentPos + fragment.length() > cursorPos) {
2939 linkFragment = it;
2940 break;
2941 }
2942 }
2943
2944 if (!linkFragment.atEnd()) {
2945 it = linkFragment;
2946 cursor.setPosition(it.fragment().position());
2947 if (it != block.begin()) {
2948 do {
2949 --it;
2950 QTextFragment fragment = it.fragment();
2951 if (fragment.charFormat().anchorHref() != href)
2952 break;
2953 cursor.setPosition(fragment.position());
2954 } while (it != block.begin());
2955 }
2956
2957 for (it = linkFragment; !it.atEnd(); ++it) {
2958 QTextFragment fragment = it.fragment();
2959 if (fragment.charFormat().anchorHref() != href)
2960 break;
2961 cursor.setPosition(fragment.position() + fragment.length(), QTextCursor::KeepAnchor);
2962 }
2963 }
2964 }
2965
2966 if (hasFocus) {
2968 } else {
2969 cursorIsFocusIndicator = false;
2970 cursor.clearSelection();
2971 }
2972 repaintOldAndNewSelection(oldCursor);
2973
2974#ifndef QT_NO_DESKTOPSERVICES
2976 QDesktopServices::openUrl(QUrl{href});
2977 else
2978#endif
2979 emit q_func()->linkActivated(href);
2980}
2981
2982#if QT_CONFIG(tooltip)
2983void QWidgetTextControlPrivate::showToolTip(const QPoint &globalPos, const QPointF &pos, QWidget *contextWidget)
2984{
2985 const QString toolTip = q_func()->cursorForPosition(pos).charFormat().toolTip();
2986 if (toolTip.isEmpty())
2987 return;
2988 QToolTip::showText(globalPos, toolTip, contextWidget);
2989}
2990#endif // QT_CONFIG(tooltip)
2991
2993{
2994 QTextLayout *layout = cursor.block().layout();
2995 if (layout && !layout->preeditAreaText().isEmpty())
2996 return true;
2997
2998 return false;
2999}
3000
3002{
3003 if (!isPreediting())
3004 return;
3005
3006 QGuiApplication::inputMethod()->commit();
3007
3008 if (!isPreediting())
3009 return;
3010
3011 cursor.beginEditBlock();
3012 preeditCursor = 0;
3013 QTextBlock block = cursor.block();
3014 QTextLayout *layout = block.layout();
3015 layout->setPreeditArea(-1, QString());
3016 layout->clearFormats();
3017 cursor.endEditBlock();
3018}
3019
3020bool QWidgetTextControl::setFocusToNextOrPreviousAnchor(bool next)
3021{
3022 Q_D(QWidgetTextControl);
3023
3024 if (!(d->interactionFlags & Qt::LinksAccessibleByKeyboard))
3025 return false;
3026
3027 QRectF crect = selectionRect();
3028 emit updateRequest(crect);
3029
3030 // If we don't have a current anchor, we start from the start/end
3031 if (!d->cursor.hasSelection()) {
3032 d->cursor = QTextCursor(d->doc);
3033 if (next)
3034 d->cursor.movePosition(QTextCursor::Start);
3035 else
3036 d->cursor.movePosition(QTextCursor::End);
3037 }
3038
3039 QTextCursor newAnchor;
3040 if (findNextPrevAnchor(d->cursor, next, newAnchor)) {
3041 d->cursor = newAnchor;
3042 d->cursorIsFocusIndicator = true;
3043 } else {
3044 d->cursor.clearSelection();
3045 }
3046
3047 if (d->cursor.hasSelection()) {
3048 crect = selectionRect();
3049 emit updateRequest(crect);
3050 emit visibilityRequest(crect);
3051 return true;
3052 } else {
3053 return false;
3054 }
3055}
3056
3057bool QWidgetTextControl::setFocusToAnchor(const QTextCursor &newCursor)
3058{
3059 Q_D(QWidgetTextControl);
3060
3061 if (!(d->interactionFlags & Qt::LinksAccessibleByKeyboard))
3062 return false;
3063
3064 // Verify that this is an anchor.
3065 const QString anchorHref = d->anchorForCursor(newCursor);
3066 if (anchorHref.isEmpty())
3067 return false;
3068
3069 // and process it
3070 QRectF crect = selectionRect();
3071 emit updateRequest(crect);
3072
3073 d->cursor.setPosition(newCursor.selectionStart());
3074 d->cursor.setPosition(newCursor.selectionEnd(), QTextCursor::KeepAnchor);
3075 d->cursorIsFocusIndicator = true;
3076
3077 crect = selectionRect();
3078 emit updateRequest(crect);
3079 emit visibilityRequest(crect);
3080 return true;
3081}
3082
3083void QWidgetTextControl::setTextInteractionFlags(Qt::TextInteractionFlags flags)
3084{
3085 Q_D(QWidgetTextControl);
3086 if (flags == d->interactionFlags)
3087 return;
3088 d->interactionFlags = flags;
3089
3090 if (d->hasFocus)
3091 d->setCursorVisible(flags & Qt::TextEditable);
3092}
3093
3094Qt::TextInteractionFlags QWidgetTextControl::textInteractionFlags() const
3095{
3096 Q_D(const QWidgetTextControl);
3097 return d->interactionFlags;
3098}
3099
3100void QWidgetTextControl::mergeCurrentCharFormat(const QTextCharFormat &modifier)
3101{
3102 Q_D(QWidgetTextControl);
3103 d->cursor.mergeCharFormat(modifier);
3104 d->updateCurrentCharFormat();
3105}
3106
3107void QWidgetTextControl::setCurrentCharFormat(const QTextCharFormat &format)
3108{
3109 Q_D(QWidgetTextControl);
3110 d->cursor.setCharFormat(format);
3111 d->updateCurrentCharFormat();
3112}
3113
3114QTextCharFormat QWidgetTextControl::currentCharFormat() const
3115{
3116 Q_D(const QWidgetTextControl);
3117 return d->cursor.charFormat();
3118}
3119
3120void QWidgetTextControl::insertPlainText(const QString &text)
3121{
3122 Q_D(QWidgetTextControl);
3123 d->cursor.insertText(text);
3124}
3125
3126#ifndef QT_NO_TEXTHTMLPARSER
3127void QWidgetTextControl::insertHtml(const QString &text)
3128{
3129 Q_D(QWidgetTextControl);
3130 d->cursor.insertHtml(text);
3131}
3132#endif // QT_NO_TEXTHTMLPARSER
3133
3134QPointF QWidgetTextControl::anchorPosition(const QString &name) const
3135{
3136 Q_D(const QWidgetTextControl);
3137 if (name.isEmpty())
3138 return QPointF();
3139
3140 QRectF r;
3141 for (QTextBlock block = d->doc->begin(); block.isValid(); block = block.next()) {
3142 QTextCharFormat format = block.charFormat();
3143 if (format.isAnchor() && format.anchorNames().contains(name)) {
3144 r = d->rectForPosition(block.position());
3145 break;
3146 }
3147
3148 for (QTextBlock::Iterator it = block.begin(); !it.atEnd(); ++it) {
3149 QTextFragment fragment = it.fragment();
3150 format = fragment.charFormat();
3151 if (format.isAnchor() && format.anchorNames().contains(name)) {
3152 r = d->rectForPosition(fragment.position());
3153 block = QTextBlock();
3154 break;
3155 }
3156 }
3157 }
3158 if (!r.isValid())
3159 return QPointF();
3160 return QPointF(0, r.top());
3161}
3162
3163void QWidgetTextControl::adjustSize()
3164{
3165 Q_D(QWidgetTextControl);
3166 d->doc->adjustSize();
3167}
3168
3169bool QWidgetTextControl::find(const QString &exp, QTextDocument::FindFlags options)
3170{
3171 Q_D(QWidgetTextControl);
3172 QTextCursor search = d->doc->find(exp, d->cursor, options);
3173 if (search.isNull())
3174 return false;
3175
3176 setTextCursor(search);
3177 return true;
3178}
3179
3180#if QT_CONFIG(regularexpression)
3181bool QWidgetTextControl::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
3182{
3183 Q_D(QWidgetTextControl);
3184 QTextCursor search = d->doc->find(exp, d->cursor, options);
3185 if (search.isNull())
3186 return false;
3187
3188 setTextCursor(search);
3189 return true;
3190}
3191#endif
3192
3193QString QWidgetTextControl::toPlainText() const
3194{
3195 return document()->toPlainText();
3196}
3197
3198#ifndef QT_NO_TEXTHTMLPARSER
3199QString QWidgetTextControl::toHtml() const
3200{
3201 return document()->toHtml();
3202}
3203#endif
3204
3205#if QT_CONFIG(textmarkdownwriter)
3206QString QWidgetTextControl::toMarkdown(QTextDocument::MarkdownFeatures features) const
3207{
3208 return document()->toMarkdown(features);
3209}
3210#endif
3211
3213{
3214 // clear blockFormat properties that the user is unlikely to want duplicated:
3215 // - don't insert <hr/> automatically
3216 // - the next paragraph after a heading should be a normal paragraph
3217 // - remove the bottom margin from the last list item before appending
3218 // - the next checklist item after a checked item should be unchecked
3219 auto blockFmt = cursor.blockFormat();
3220 auto charFmt = cursor.charFormat();
3221 blockFmt.clearProperty(QTextFormat::BlockTrailingHorizontalRulerWidth);
3222 if (blockFmt.hasProperty(QTextFormat::HeadingLevel)) {
3223 blockFmt.clearProperty(QTextFormat::HeadingLevel);
3224 charFmt = QTextCharFormat();
3225 }
3226 if (cursor.currentList()) {
3227 auto existingFmt = cursor.blockFormat();
3228 existingFmt.clearProperty(QTextBlockFormat::BlockBottomMargin);
3229 cursor.setBlockFormat(existingFmt);
3230 if (blockFmt.marker() == QTextBlockFormat::MarkerType::Checked)
3231 blockFmt.setMarker(QTextBlockFormat::MarkerType::Unchecked);
3232 }
3233
3234 // After a blank line, reset block and char formats. I.e. you can end a list,
3235 // block quote, etc. by hitting enter twice, and get back to normal paragraph style.
3236 if (cursor.block().text().isEmpty() &&
3237 !cursor.blockFormat().hasProperty(QTextFormat::BlockTrailingHorizontalRulerWidth) &&
3238 !cursor.blockFormat().hasProperty(QTextFormat::BlockCodeLanguage)) {
3239 blockFmt = QTextBlockFormat();
3240 const bool blockFmtChanged = (cursor.blockFormat() != blockFmt);
3241 charFmt = QTextCharFormat();
3242 cursor.setBlockFormat(blockFmt);
3243 cursor.setCharFormat(charFmt);
3244 // If the user hit enter twice just to get back to default format,
3245 // don't actually insert a new block. But if the user then hits enter
3246 // yet again, the block format will not change, so we will insert a block.
3247 // This is what many word processors do.
3248 if (blockFmtChanged)
3249 return;
3250 }
3251
3252 cursor.insertBlock(blockFmt, charFmt);
3253}
3254
3255void QWidgetTextControlPrivate::append(const QString &text, Qt::TextFormat format)
3256{
3257 QTextCursor tmp(doc);
3258 tmp.beginEditBlock();
3259 tmp.movePosition(QTextCursor::End);
3260
3261 if (!doc->isEmpty())
3262 tmp.insertBlock(cursor.blockFormat(), cursor.charFormat());
3263 else
3264 tmp.setCharFormat(cursor.charFormat());
3265
3266 // preserve the char format
3267 QTextCharFormat oldCharFormat = cursor.charFormat();
3268
3269#ifndef QT_NO_TEXTHTMLPARSER
3270 if (format == Qt::RichText || (format == Qt::AutoText && Qt::mightBeRichText(text))) {
3271 tmp.insertHtml(text);
3272 } else {
3273 tmp.insertText(text);
3274 }
3275#else
3276 Q_UNUSED(format);
3277 tmp.insertText(text);
3278#endif // QT_NO_TEXTHTMLPARSER
3279 if (!cursor.hasSelection())
3280 cursor.setCharFormat(oldCharFormat);
3281
3282 tmp.endEditBlock();
3283}
3284
3285void QWidgetTextControl::append(const QString &text)
3286{
3287 Q_D(QWidgetTextControl);
3288 d->append(text, Qt::AutoText);
3289}
3290
3291void QWidgetTextControl::appendHtml(const QString &html)
3292{
3293 Q_D(QWidgetTextControl);
3294 d->append(html, Qt::RichText);
3295}
3296
3297void QWidgetTextControl::appendPlainText(const QString &text)
3298{
3299 Q_D(QWidgetTextControl);
3300 d->append(text, Qt::PlainText);
3301}
3302
3303
3304void QWidgetTextControl::ensureCursorVisible()
3305{
3306 Q_D(QWidgetTextControl);
3307 QRectF crect = d->rectForPosition(d->cursor.position()).adjusted(-5, 0, 5, 0);
3308 emit visibilityRequest(crect);
3309 emit microFocusChanged();
3310}
3311
3312QPalette QWidgetTextControl::palette() const
3313{
3314 Q_D(const QWidgetTextControl);
3315 return d->palette;
3316}
3317
3318void QWidgetTextControl::setPalette(const QPalette &pal)
3319{
3320 Q_D(QWidgetTextControl);
3321 d->palette = pal;
3322}
3323
3324QAbstractTextDocumentLayout::PaintContext QWidgetTextControl::getPaintContext(QWidget *widget) const
3325{
3326 Q_D(const QWidgetTextControl);
3327
3328 QAbstractTextDocumentLayout::PaintContext ctx;
3329
3330 ctx.selections = d->extraSelections;
3331 ctx.palette = d->palette;
3332#if QT_CONFIG(style_stylesheet)
3333 if (widget) {
3334 if (auto cssStyle = qt_styleSheet(widget->style())) {
3335 QStyleOption option;
3336 option.initFrom(widget);
3337 cssStyle->styleSheetPalette(widget, &option, &ctx.palette);
3338 }
3339 }
3340#endif // style_stylesheet
3341 if (d->cursorOn && d->isEnabled) {
3342 if (d->hideCursor)
3343 ctx.cursorPosition = -1;
3344 else if (d->preeditCursor != 0)
3345 ctx.cursorPosition = - (d->preeditCursor + 2);
3346 else
3347 ctx.cursorPosition = d->cursor.position();
3348 }
3349
3350 if (!d->dndFeedbackCursor.isNull())
3351 ctx.cursorPosition = d->dndFeedbackCursor.position();
3352#ifdef QT_KEYPAD_NAVIGATION
3353 if (!QApplicationPrivate::keypadNavigationEnabled() || d->hasEditFocus)
3354#endif
3355 if (d->cursor.hasSelection()) {
3356 QAbstractTextDocumentLayout::Selection selection;
3357 selection.cursor = d->cursor;
3358 if (d->cursorIsFocusIndicator) {
3359 QStyleOption opt;
3360 opt.palette = ctx.palette;
3361 QStyleHintReturnVariant ret;
3362 QStyle *style = QApplication::style();
3363 if (widget)
3364 style = widget->style();
3365 style->styleHint(QStyle::SH_TextControl_FocusIndicatorTextCharFormat, &opt, widget, &ret);
3366 selection.format = qvariant_cast<QTextFormat>(ret.variant).toCharFormat();
3367 } else {
3368 QPalette::ColorGroup cg = d->hasFocus ? QPalette::Active : QPalette::Inactive;
3369 selection.format.setBackground(ctx.palette.brush(cg, QPalette::Highlight));
3370 selection.format.setForeground(ctx.palette.brush(cg, QPalette::HighlightedText));
3371 QStyleOption opt;
3372 QStyle *style = QApplication::style();
3373 if (widget) {
3374 opt.initFrom(widget);
3375 style = widget->style();
3376 }
3377 if (style->styleHint(QStyle::SH_RichText_FullWidthSelection, &opt, widget))
3378 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
3379 }
3380 ctx.selections.append(selection);
3381 }
3382
3383 return ctx;
3384}
3385
3386void QWidgetTextControl::drawContents(QPainter *p, const QRectF &rect, QWidget *widget)
3387{
3388 Q_D(QWidgetTextControl);
3389 p->save();
3390 QAbstractTextDocumentLayout::PaintContext ctx = getPaintContext(widget);
3391 if (rect.isValid())
3392 p->setClipRect(rect, Qt::IntersectClip);
3393 ctx.clip = rect;
3394
3395 d->doc->documentLayout()->draw(p, ctx);
3396 p->restore();
3397}
3398
3400{
3401#ifndef QT_NO_CLIPBOARD
3402 QMimeData *md = new QMimeData;
3403 md->setText(linkToCopy);
3404 QGuiApplication::clipboard()->setMimeData(md);
3405#endif
3406}
3407
3408int QWidgetTextControl::hitTest(const QPointF &point, Qt::HitTestAccuracy accuracy) const
3409{
3410 Q_D(const QWidgetTextControl);
3411 return d->doc->documentLayout()->hitTest(point, accuracy);
3412}
3413
3414QRectF QWidgetTextControl::blockBoundingRect(const QTextBlock &block) const
3415{
3416 Q_D(const QWidgetTextControl);
3417 return d->doc->documentLayout()->blockBoundingRect(block);
3418}
3419
3420#ifndef QT_NO_CONTEXTMENU
3421#define NUM_CONTROL_CHARACTERS 14
3423 const char *text;
3425} qt_controlCharacters[NUM_CONTROL_CHARACTERS] = {
3426 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRM Left-to-right mark"), 0x200e },
3427 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLM Right-to-left mark"), 0x200f },
3428 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWJ Zero width joiner"), 0x200d },
3429 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWNJ Zero width non-joiner"), 0x200c },
3430 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWSP Zero width space"), 0x200b },
3431 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRE Start of left-to-right embedding"), 0x202a },
3432 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLE Start of right-to-left embedding"), 0x202b },
3433 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRO Start of left-to-right override"), 0x202d },
3434 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLO Start of right-to-left override"), 0x202e },
3435 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "PDF Pop directional formatting"), 0x202c },
3436 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRI Left-to-right isolate"), 0x2066 },
3437 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLI Right-to-left isolate"), 0x2067 },
3438 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "FSI First strong isolate"), 0x2068 },
3439 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "PDI Pop directional isolate"), 0x2069 }
3441
3442QUnicodeControlCharacterMenu::QUnicodeControlCharacterMenu(QObject *_editWidget, QWidget *parent)
3443 : QMenu(parent), editWidget(_editWidget)
3444{
3445 setTitle(tr("Insert Unicode control character"));
3446 for (int i = 0; i < NUM_CONTROL_CHARACTERS; ++i) {
3447 addAction(tr(qt_controlCharacters[i].text), this, SLOT(menuActionTriggered()));
3448 }
3449}
3450
3451void QUnicodeControlCharacterMenu::menuActionTriggered()
3452{
3453 QAction *a = qobject_cast<QAction *>(sender());
3454 int idx = actions().indexOf(a);
3455 if (idx < 0 || idx >= NUM_CONTROL_CHARACTERS)
3456 return;
3457 QChar c(qt_controlCharacters[idx].character);
3458 QString str(c);
3459
3460#if QT_CONFIG(textedit)
3461 if (QTextEdit *edit = qobject_cast<QTextEdit *>(editWidget)) {
3462 edit->insertPlainText(str);
3463 return;
3464 }
3465#endif
3466 if (QWidgetTextControl *control = qobject_cast<QWidgetTextControl *>(editWidget)) {
3467 control->insertPlainText(str);
3468 }
3469#if QT_CONFIG(lineedit)
3470 if (QLineEdit *edit = qobject_cast<QLineEdit *>(editWidget)) {
3471 edit->insert(str);
3472 return;
3473 }
3474#endif
3475}
3476#endif // QT_NO_CONTEXTMENU
3477
3478static constexpr auto supportedMimeTypes = qOffsetStringArray(
3479 "text/plain",
3480 "text/html"
3481#if QT_CONFIG(textmarkdownwriter)
3482 , "text/markdown"
3483#endif
3484#if QT_CONFIG(textodfwriter)
3485 , "application/vnd.oasis.opendocument.text"
3486#endif
3487);
3488
3489/*! \internal
3490 \reimp
3491*/
3493{
3494 if (!fragment.isEmpty()) {
3495 constexpr auto size = supportedMimeTypes.count();
3496 QStringList ret;
3497 ret.reserve(size);
3498 for (int i = 0; i < size; ++i)
3499 ret.emplace_back(QLatin1StringView(supportedMimeTypes.at(i)));
3500
3501 return ret;
3502 }
3503
3504 return QMimeData::formats();
3505}
3506
3507/*! \internal
3508 \reimp
3509*/
3510bool QTextEditMimeData::hasFormat(const QString &format) const
3511{
3512 if (!fragment.isEmpty()) {
3513 constexpr auto size = supportedMimeTypes.count();
3514 for (int i = 0; i < size; ++i) {
3515 if (format == QLatin1StringView(supportedMimeTypes.at(i)))
3516 return true;
3517 }
3518 return false;
3519 }
3520
3521 return QMimeData::hasFormat(format);
3522}
3523
3524QVariant QTextEditMimeData::retrieveData(const QString &mimeType, QMetaType type) const
3525{
3526 if (!fragment.isEmpty())
3527 setup();
3528 return QMimeData::retrieveData(mimeType, type);
3529}
3530
3531void QTextEditMimeData::setup() const
3532{
3533 QTextEditMimeData *that = const_cast<QTextEditMimeData *>(this);
3534#ifndef QT_NO_TEXTHTMLPARSER
3535 that->setData("text/html"_L1, fragment.toHtml().toUtf8());
3536#endif
3537#if QT_CONFIG(textmarkdownwriter)
3538 that->setData("text/markdown"_L1, fragment.toMarkdown().toUtf8());
3539#endif
3540#ifndef QT_NO_TEXTODFWRITER
3541 {
3542 QBuffer buffer;
3543 QTextDocumentWriter writer(&buffer, "ODF");
3544 writer.write(fragment);
3545 buffer.close();
3546 that->setData("application/vnd.oasis.opendocument.text"_L1, buffer.data());
3547 }
3548#endif
3549 that->setText(fragment.toPlainText());
3550 fragment = QTextDocumentFragment();
3551}
3552
3553QT_END_NAMESPACE
3554
3555#include "moc_qwidgettextcontrol_p.cpp"
3556
3557#endif // QT_NO_TEXTCONTROL
\inmodule QtCore \reentrant
Definition qbuffer.h:17
friend class QWidget
Definition qpainter.h:432
\inmodule QtCore\reentrant
Definition qpoint.h:232
The QTextDocumentWriter class provides a format-independent interface for writing a QTextDocument to ...
virtual QStringList formats() const override
\reentrant
Definition qtexttable.h:19
void setCursorVisible(bool visible)
void _q_contentsChanged(int from, int charsRemoved, int charsAdded)
void selectionChanged(bool forceEmitSelectionChanged=false)
void extendWordwiseSelection(int suggestedNewPosition, qreal mouseXPosition)
void setCursorPosition(int pos, QTextCursor::MoveMode mode=QTextCursor::MoveAnchor)
bool dragEnterEvent(QEvent *e, const QMimeData *mimeData)
QRectF rectForPosition(int position) const
void extendBlockwiseSelection(int suggestedNewPosition)
#define ACCEL_KEY(k)
Definition qlineedit.cpp:56
static QRectF boundingRectOfFloatsInSelection(const QTextCursor &cursor)
static constexpr auto supportedMimeTypes
#define NUM_CONTROL_CHARACTERS
static QTextLine currentTextLine(const QTextCursor &cursor)
void setActionIcon(QAction *action, const QString &name)