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::Enter:
1043 d->updateHighlightedAnchor(transform.map(static_cast<QEnterEvent *>(e)->position()));
1044 break;
1045 case QEvent::Leave:
1046 d->resetHighlightedAnchor();
1047 break;
1048 case QEvent::MouseMove: {
1049 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1050 d->mouseMoveEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1051 ev->buttons(), ev->globalPosition());
1052 break; }
1053 case QEvent::MouseButtonRelease: {
1054 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1055 d->mouseReleaseEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1056 ev->buttons(), ev->globalPosition());
1057 break; }
1058 case QEvent::MouseButtonDblClick: {
1059 QMouseEvent *ev = static_cast<QMouseEvent *>(e);
1060 d->mouseDoubleClickEvent(ev, ev->button(), transform.map(ev->position()), ev->modifiers(),
1061 ev->buttons(), ev->globalPosition());
1062 break; }
1063 case QEvent::InputMethod:
1064 d->inputMethodEvent(static_cast<QInputMethodEvent *>(e));
1065 break;
1066#ifndef QT_NO_CONTEXTMENU
1067 case QEvent::ContextMenu: {
1068 QContextMenuEvent *ev = static_cast<QContextMenuEvent *>(e);
1069 d->contextMenuEvent(ev->globalPos(), transform.map(ev->pos()), contextWidget);
1070 break; }
1071#endif // QT_NO_CONTEXTMENU
1072 case QEvent::FocusIn:
1073 case QEvent::FocusOut:
1074 d->focusEvent(static_cast<QFocusEvent *>(e));
1075 break;
1076
1077 case QEvent::EnabledChange:
1078 d->isEnabled = e->isAccepted();
1079 break;
1080
1081#if QT_CONFIG(tooltip)
1082 case QEvent::ToolTip: {
1083 QHelpEvent *ev = static_cast<QHelpEvent *>(e);
1084 d->showToolTip(ev->globalPos(), transform.map(ev->pos()), contextWidget);
1085 break;
1086 }
1087#endif // QT_CONFIG(tooltip)
1088
1089#if QT_CONFIG(draganddrop)
1090 case QEvent::DragEnter: {
1091 QDragEnterEvent *ev = static_cast<QDragEnterEvent *>(e);
1092 if (d->dragEnterEvent(e, ev->mimeData()))
1093 ev->acceptProposedAction();
1094 break;
1095 }
1096 case QEvent::DragLeave:
1097 d->dragLeaveEvent();
1098 break;
1099 case QEvent::DragMove: {
1100 QDragMoveEvent *ev = static_cast<QDragMoveEvent *>(e);
1101 if (d->dragMoveEvent(e, ev->mimeData(), transform.map(ev->position())))
1102 ev->acceptProposedAction();
1103 break;
1104 }
1105 case QEvent::Drop: {
1106 QDropEvent *ev = static_cast<QDropEvent *>(e);
1107 if (d->dropEvent(ev->mimeData(), transform.map(ev->position()), ev->dropAction(), ev->source()))
1108 ev->acceptProposedAction();
1109 break;
1110 }
1111#endif
1112
1113#if QT_CONFIG(graphicsview)
1114 case QEvent::GraphicsSceneMousePress: {
1115 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1116 d->mousePressEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1117 ev->screenPos());
1118 break; }
1119 case QEvent::GraphicsSceneMouseMove: {
1120 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1121 d->mouseMoveEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1122 ev->screenPos());
1123 break; }
1124 case QEvent::GraphicsSceneMouseRelease: {
1125 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1126 d->mouseReleaseEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1127 ev->screenPos());
1128 break; }
1129 case QEvent::GraphicsSceneMouseDoubleClick: {
1130 QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
1131 d->mouseDoubleClickEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
1132 ev->screenPos());
1133 break; }
1134 case QEvent::GraphicsSceneContextMenu: {
1135 QGraphicsSceneContextMenuEvent *ev = static_cast<QGraphicsSceneContextMenuEvent *>(e);
1136 d->contextMenuEvent(ev->screenPos(), transform.map(ev->pos()), contextWidget);
1137 break; }
1138
1139 case QEvent::GraphicsSceneHoverMove: {
1140 QGraphicsSceneHoverEvent *ev = static_cast<QGraphicsSceneHoverEvent *>(e);
1141 d->mouseMoveEvent(ev, Qt::NoButton, transform.map(ev->pos()), ev->modifiers(),Qt::NoButton,
1142 ev->screenPos());
1143 break; }
1144
1145 case QEvent::GraphicsSceneDragEnter: {
1146 QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
1147 if (d->dragEnterEvent(e, ev->mimeData()))
1148 ev->acceptProposedAction();
1149 break; }
1150 case QEvent::GraphicsSceneDragLeave:
1151 d->dragLeaveEvent();
1152 break;
1153 case QEvent::GraphicsSceneDragMove: {
1154 QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
1155 if (d->dragMoveEvent(e, ev->mimeData(), transform.map(ev->pos())))
1156 ev->acceptProposedAction();
1157 break; }
1158 case QEvent::GraphicsSceneDrop: {
1159 QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
1160 if (d->dropEvent(ev->mimeData(), transform.map(ev->pos()), ev->dropAction(), ev->source()))
1161 ev->accept();
1162 break; }
1163#endif // QT_CONFIG(graphicsview)
1164#ifdef QT_KEYPAD_NAVIGATION
1165 case QEvent::EnterEditFocus:
1166 case QEvent::LeaveEditFocus:
1167 if (QApplicationPrivate::keypadNavigationEnabled())
1168 d->editFocusEvent(e);
1169 break;
1170#endif
1171 case QEvent::ShortcutOverride:
1172 if (d->interactionFlags & Qt::TextEditable) {
1173 QKeyEvent* ke = static_cast<QKeyEvent *>(e);
1174 if (isCommonTextEditShortcut(ke))
1175 ke->accept();
1176 }
1177 break;
1178 default:
1179 break;
1180 }
1181}
1182
1183bool QWidgetTextControl::event(QEvent *e)
1184{
1185 return QObject::event(e);
1186}
1187
1188void QWidgetTextControl::timerEvent(QTimerEvent *e)
1189{
1190 Q_D(QWidgetTextControl);
1191 if (e->timerId() == d->cursorBlinkTimer.timerId()) {
1192 d->cursorOn = !d->cursorOn;
1193
1194 if (d->cursor.hasSelection())
1195 d->cursorOn &= (QApplication::style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected)
1196 != 0);
1197
1198 d->repaintCursor();
1199 } else if (e->timerId() == d->trippleClickTimer.timerId()) {
1200 d->trippleClickTimer.stop();
1201 }
1202}
1203
1204void QWidgetTextControl::setPlainText(const QString &text)
1205{
1206 Q_D(QWidgetTextControl);
1207 d->setContent(Qt::PlainText, text);
1208}
1209
1210#if QT_CONFIG(textmarkdownreader)
1211void QWidgetTextControl::setMarkdown(const QString &text)
1212{
1213 Q_D(QWidgetTextControl);
1214 d->setContent(Qt::MarkdownText, text);
1215}
1216#endif
1217
1218void QWidgetTextControl::setHtml(const QString &text)
1219{
1220 Q_D(QWidgetTextControl);
1221 d->setContent(Qt::RichText, text);
1222}
1223
1224void QWidgetTextControlPrivate::keyPressEvent(QKeyEvent *e)
1225{
1226 Q_Q(QWidgetTextControl);
1227#ifndef QT_NO_SHORTCUT
1228 if (e == QKeySequence::SelectAll) {
1229 e->accept();
1230 q->selectAll();
1231#ifndef QT_NO_CLIPBOARD
1232 setClipboardSelection();
1233#endif
1234 return;
1235 }
1236#ifndef QT_NO_CLIPBOARD
1237 else if (e == QKeySequence::Copy) {
1238 e->accept();
1239 q->copy();
1240 return;
1241 }
1242#endif
1243#endif // QT_NO_SHORTCUT
1244
1245 if (interactionFlags & Qt::TextSelectableByKeyboard
1246 && cursorMoveKeyEvent(e))
1247 goto accept;
1248
1249 if (interactionFlags & Qt::LinksAccessibleByKeyboard) {
1250 if ((e->key() == Qt::Key_Return
1251 || e->key() == Qt::Key_Enter
1252#ifdef QT_KEYPAD_NAVIGATION
1253 || e->key() == Qt::Key_Select
1254#endif
1255 )
1256 && cursor.hasSelection()) {
1257
1258 e->accept();
1259 activateLinkUnderCursor();
1260 return;
1261 }
1262 }
1263
1264 if (!(interactionFlags & Qt::TextEditable)) {
1265 e->ignore();
1266 return;
1267 }
1268
1269 if (e->key() == Qt::Key_Direction_L || e->key() == Qt::Key_Direction_R) {
1270 QTextBlockFormat fmt;
1271 fmt.setLayoutDirection((e->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft);
1272 cursor.mergeBlockFormat(fmt);
1273 goto accept;
1274 }
1275
1276 // schedule a repaint of the region of the cursor, as when we move it we
1277 // want to make sure the old cursor disappears (not noticeable when moving
1278 // only a few pixels but noticeable when jumping between cells in tables for
1279 // example)
1280 repaintSelection();
1281
1282 if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~(Qt::ShiftModifier | Qt::GroupSwitchModifier))) {
1283 QTextBlockFormat blockFmt = cursor.blockFormat();
1284 QTextList *list = cursor.currentList();
1285 if (list && cursor.atBlockStart() && !cursor.hasSelection()) {
1286 list->remove(cursor.block());
1287 } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
1288 blockFmt.setIndent(blockFmt.indent() - 1);
1289 cursor.setBlockFormat(blockFmt);
1290 } else {
1291 QTextCursor localCursor = cursor;
1292 localCursor.deletePreviousChar();
1293 if (cursor.d)
1294 cursor.d->setX();
1295 }
1296 goto accept;
1297 }
1298#ifndef QT_NO_SHORTCUT
1299 else if (e == QKeySequence::InsertParagraphSeparator) {
1300 insertParagraphSeparator();
1301 e->accept();
1302 goto accept;
1303 } else if (e == QKeySequence::InsertLineSeparator) {
1304 cursor.insertText(QString(QChar::LineSeparator));
1305 e->accept();
1306 goto accept;
1307 }
1308#endif
1309 if (false) {
1310 }
1311#ifndef QT_NO_SHORTCUT
1312 else if (e == QKeySequence::Undo) {
1313 q->undo();
1314 }
1315 else if (e == QKeySequence::Redo) {
1316 q->redo();
1317 }
1318#ifndef QT_NO_CLIPBOARD
1319 else if (e == QKeySequence::Cut) {
1320 q->cut();
1321 }
1322 else if (e == QKeySequence::Paste) {
1323 QClipboard::Mode mode = QClipboard::Clipboard;
1324 if (QGuiApplication::clipboard()->supportsSelection()) {
1325 if (e->modifiers() == (Qt::CTRL | Qt::SHIFT) && e->key() == Qt::Key_Insert)
1326 mode = QClipboard::Selection;
1327 }
1328 q->paste(mode);
1329 }
1330#endif
1331 else if (e == QKeySequence::Delete) {
1332 QTextCursor localCursor = cursor;
1333 localCursor.deleteChar();
1334 if (cursor.d)
1335 cursor.d->setX();
1336 } else if (e == QKeySequence::Backspace) {
1337 QTextCursor localCursor = cursor;
1338 localCursor.deletePreviousChar();
1339 if (cursor.d)
1340 cursor.d->setX();
1341 }else if (e == QKeySequence::DeleteEndOfWord) {
1342 if (!cursor.hasSelection())
1343 cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor);
1344 cursor.removeSelectedText();
1345 }
1346 else if (e == QKeySequence::DeleteStartOfWord) {
1347 if (!cursor.hasSelection())
1348 cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
1349 cursor.removeSelectedText();
1350 }
1351 else if (e == QKeySequence::DeleteEndOfLine) {
1352 QTextBlock block = cursor.block();
1353 if (cursor.position() == block.position() + block.length() - 2)
1354 cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
1355 else
1356 cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
1357 cursor.removeSelectedText();
1358 }
1359#endif // QT_NO_SHORTCUT
1360 else {
1361 goto process;
1362 }
1363 goto accept;
1364
1365process:
1366 {
1367 if (q->isAcceptableInput(e)) {
1368 if (overwriteMode
1369 // no need to call deleteChar() if we have a selection, insertText
1370 // does it already
1371 && !cursor.hasSelection()
1372 && !cursor.atBlockEnd())
1373 cursor.deleteChar();
1374
1375 cursor.insertText(e->text());
1376 selectionChanged();
1377 } else {
1378 e->ignore();
1379 return;
1380 }
1381 }
1382
1383 accept:
1384
1385#ifndef QT_NO_CLIPBOARD
1386 setClipboardSelection();
1387#endif
1388
1389 e->accept();
1390 cursorOn = true;
1391
1392 q->ensureCursorVisible();
1393
1394 updateCurrentCharFormat();
1395}
1396
1397QVariant QWidgetTextControl::loadResource(int type, const QUrl &name)
1398{
1399 Q_UNUSED(type);
1400 Q_UNUSED(name);
1401 return QVariant();
1402}
1403
1404void QWidgetTextControlPrivate::_q_updateBlock(const QTextBlock &block)
1405{
1406 Q_Q(QWidgetTextControl);
1407 QRectF br = q->blockBoundingRect(block);
1408 br.setRight(qreal(INT_MAX)); // the block might have shrunk
1409 emit q->updateRequest(br);
1410}
1411
1413{
1414 Q_Q(const QWidgetTextControl);
1415 const QTextBlock block = doc->findBlock(position);
1416 if (!block.isValid())
1417 return QRectF();
1418 const QAbstractTextDocumentLayout *docLayout = doc->documentLayout();
1419 const QTextLayout *layout = block.layout();
1420 const QPointF layoutPos = q->blockBoundingRect(block).topLeft();
1421 int relativePos = position - block.position();
1422 if (preeditCursor != 0) {
1423 int preeditPos = layout->preeditAreaPosition();
1424 if (relativePos == preeditPos)
1425 relativePos += preeditCursor;
1426 else if (relativePos > preeditPos)
1427 relativePos += layout->preeditAreaText().size();
1428 }
1429 QTextLine line = layout->lineForTextPosition(relativePos);
1430
1431 int cursorWidth;
1432 {
1433 bool ok = false;
1434 cursorWidth = docLayout->property("cursorWidth").toInt(&ok);
1435 if (!ok)
1436 cursorWidth = 1;
1437 }
1438
1439 QRectF r;
1440
1441 if (line.isValid()) {
1442 qreal x = line.cursorToX(relativePos);
1443 qreal w = 0;
1444 if (overwriteMode) {
1445 if (relativePos < line.textLength() - line.textStart())
1446 w = line.cursorToX(relativePos + 1) - x;
1447 else
1448 w = QFontMetrics(block.layout()->font()).horizontalAdvance(u' '); // in sync with QTextLine::draw()
1449 }
1450 r = QRectF(layoutPos.x() + x, layoutPos.y() + line.y(),
1451 cursorWidth + w, line.height());
1452 } else {
1453 r = QRectF(layoutPos.x(), layoutPos.y(), cursorWidth, 10); // #### correct height
1454 }
1455
1456 return r;
1457}
1458
1459namespace {
1460struct QTextFrameComparator {
1461 bool operator()(QTextFrame *frame, int position) { return frame->firstPosition() < position; }
1462 bool operator()(int position, QTextFrame *frame) { return position < frame->firstPosition(); }
1463};
1464}
1465
1466static QRectF boundingRectOfFloatsInSelection(const QTextCursor &cursor)
1467{
1468 QRectF r;
1469 QTextFrame *frame = cursor.currentFrame();
1470 const QList<QTextFrame *> children = frame->childFrames();
1471
1472 const QList<QTextFrame *>::ConstIterator firstFrame = std::lower_bound(children.constBegin(), children.constEnd(),
1473 cursor.selectionStart(), QTextFrameComparator());
1474 const QList<QTextFrame *>::ConstIterator lastFrame = std::upper_bound(children.constBegin(), children.constEnd(),
1475 cursor.selectionEnd(), QTextFrameComparator());
1476 for (QList<QTextFrame *>::ConstIterator it = firstFrame; it != lastFrame; ++it) {
1477 if ((*it)->frameFormat().position() != QTextFrameFormat::InFlow)
1478 r |= frame->document()->documentLayout()->frameBoundingRect(*it);
1479 }
1480 return r;
1481}
1482
1483QRectF QWidgetTextControl::selectionRect(const QTextCursor &cursor) const
1484{
1485 Q_D(const QWidgetTextControl);
1486
1487 QRectF r = d->rectForPosition(cursor.selectionStart());
1488
1489 if (cursor.hasComplexSelection() && cursor.currentTable()) {
1490 QTextTable *table = cursor.currentTable();
1491
1492 r = d->doc->documentLayout()->frameBoundingRect(table);
1493 /*
1494 int firstRow, numRows, firstColumn, numColumns;
1495 cursor.selectedTableCells(&firstRow, &numRows, &firstColumn, &numColumns);
1496
1497 const QTextTableCell firstCell = table->cellAt(firstRow, firstColumn);
1498 const QTextTableCell lastCell = table->cellAt(firstRow + numRows - 1, firstColumn + numColumns - 1);
1499
1500 const QAbstractTextDocumentLayout * const layout = doc->documentLayout();
1501
1502 QRectF tableSelRect = layout->blockBoundingRect(firstCell.firstCursorPosition().block());
1503
1504 for (int col = firstColumn; col < firstColumn + numColumns; ++col) {
1505 const QTextTableCell cell = table->cellAt(firstRow, col);
1506 const qreal y = layout->blockBoundingRect(cell.firstCursorPosition().block()).top();
1507
1508 tableSelRect.setTop(qMin(tableSelRect.top(), y));
1509 }
1510
1511 for (int row = firstRow; row < firstRow + numRows; ++row) {
1512 const QTextTableCell cell = table->cellAt(row, firstColumn);
1513 const qreal x = layout->blockBoundingRect(cell.firstCursorPosition().block()).left();
1514
1515 tableSelRect.setLeft(qMin(tableSelRect.left(), x));
1516 }
1517
1518 for (int col = firstColumn; col < firstColumn + numColumns; ++col) {
1519 const QTextTableCell cell = table->cellAt(firstRow + numRows - 1, col);
1520 const qreal y = layout->blockBoundingRect(cell.lastCursorPosition().block()).bottom();
1521
1522 tableSelRect.setBottom(qMax(tableSelRect.bottom(), y));
1523 }
1524
1525 for (int row = firstRow; row < firstRow + numRows; ++row) {
1526 const QTextTableCell cell = table->cellAt(row, firstColumn + numColumns - 1);
1527 const qreal x = layout->blockBoundingRect(cell.lastCursorPosition().block()).right();
1528
1529 tableSelRect.setRight(qMax(tableSelRect.right(), x));
1530 }
1531
1532 r = tableSelRect.toRect();
1533 */
1534 } else if (cursor.hasSelection()) {
1535 const int position = cursor.selectionStart();
1536 const int anchor = cursor.selectionEnd();
1537 const QTextBlock posBlock = d->doc->findBlock(position);
1538 const QTextBlock anchorBlock = d->doc->findBlock(anchor);
1539 if (posBlock == anchorBlock && posBlock.isValid() && posBlock.layout()->lineCount()) {
1540 const QTextLine posLine = posBlock.layout()->lineForTextPosition(position - posBlock.position());
1541 const QTextLine anchorLine = anchorBlock.layout()->lineForTextPosition(anchor - anchorBlock.position());
1542
1543 const int firstLine = qMin(posLine.lineNumber(), anchorLine.lineNumber());
1544 const int lastLine = qMax(posLine.lineNumber(), anchorLine.lineNumber());
1545 const QTextLayout *layout = posBlock.layout();
1546 r = QRectF();
1547 for (int i = firstLine; i <= lastLine; ++i) {
1548 r |= layout->lineAt(i).rect();
1549 r |= layout->lineAt(i).naturalTextRect(); // might be bigger in the case of wrap not enabled
1550 }
1551 r.translate(blockBoundingRect(posBlock).topLeft());
1552 } else {
1553 QRectF anchorRect = d->rectForPosition(cursor.selectionEnd());
1554 r |= anchorRect;
1555 r |= boundingRectOfFloatsInSelection(cursor);
1556 QRectF frameRect(d->doc->documentLayout()->frameBoundingRect(cursor.currentFrame()));
1557 r.setLeft(frameRect.left());
1558 r.setRight(frameRect.right());
1559 }
1560 if (r.isValid())
1561 r.adjust(-1, -1, 1, 1);
1562 }
1563
1564 return r;
1565}
1566
1567QRectF QWidgetTextControl::selectionRect() const
1568{
1569 Q_D(const QWidgetTextControl);
1570 return selectionRect(d->cursor);
1571}
1572
1573void QWidgetTextControlPrivate::mousePressEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
1574 Qt::MouseButtons buttons, const QPointF &globalPos)
1575{
1576 Q_Q(QWidgetTextControl);
1577
1578 mousePressPos = pos;
1579
1580#if QT_CONFIG(draganddrop)
1581 mightStartDrag = false;
1582#endif
1583
1584 if (sendMouseEventToInputContext(
1585 e, QEvent::MouseButtonPress, button, pos, modifiers, buttons, globalPos)) {
1586 return;
1587 }
1588
1589 if (interactionFlags & Qt::LinksAccessibleByMouse) {
1590 anchorOnMousePress = q->anchorAt(pos);
1591
1593 cursorIsFocusIndicator = false;
1595 cursor.clearSelection();
1596 }
1597 }
1598 if (!(button & Qt::LeftButton) ||
1599 !((interactionFlags & Qt::TextSelectableByMouse) || (interactionFlags & Qt::TextEditable))) {
1600 e->ignore();
1601 return;
1602 }
1603 bool wasValid = blockWithMarkerUnderMouse.isValid();
1604 blockWithMarkerUnderMouse = q->blockWithMarkerAt(pos);
1605 if (wasValid != blockWithMarkerUnderMouse.isValid())
1606 emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
1607
1608
1609 cursorIsFocusIndicator = false;
1610 const QTextCursor oldSelection = cursor;
1611 const int oldCursorPos = cursor.position();
1612
1613 mousePressed = (interactionFlags & Qt::TextSelectableByMouse);
1614
1616
1617 if (trippleClickTimer.isActive()
1618 && ((pos - trippleClickPoint).manhattanLength() < QApplication::startDragDistance())) {
1619
1620 cursor.movePosition(QTextCursor::StartOfBlock);
1621 cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
1622 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
1623 selectedBlockOnTrippleClick = cursor;
1624
1625 anchorOnMousePress = QString();
1626 blockWithMarkerUnderMouse = QTextBlock();
1627 emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
1628
1629 trippleClickTimer.stop();
1630 } else {
1631 int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
1632 if (cursorPos == -1) {
1633 e->ignore();
1634 return;
1635 }
1636
1637 if (modifiers == Qt::ShiftModifier && (interactionFlags & Qt::TextSelectableByMouse)) {
1638 if (wordSelectionEnabled && !selectedWordOnDoubleClick.hasSelection()) {
1639 selectedWordOnDoubleClick = cursor;
1640 selectedWordOnDoubleClick.select(QTextCursor::WordUnderCursor);
1641 }
1642
1643 if (selectedBlockOnTrippleClick.hasSelection())
1645 else if (selectedWordOnDoubleClick.hasSelection())
1646 extendWordwiseSelection(cursorPos, pos.x());
1647 else if (!wordSelectionEnabled)
1648 setCursorPosition(cursorPos, QTextCursor::KeepAnchor);
1649 } else {
1650
1651 if (dragEnabled
1652 && cursor.hasSelection()
1653 && !cursorIsFocusIndicator
1654 && cursorPos >= cursor.selectionStart()
1655 && cursorPos <= cursor.selectionEnd()
1656 && q->hitTest(pos, Qt::ExactHit) != -1) {
1657#if QT_CONFIG(draganddrop)
1658 mightStartDrag = true;
1659#endif
1660 return;
1661 }
1662
1663 setCursorPosition(cursorPos);
1664 }
1665 }
1666
1667 if (interactionFlags & Qt::TextEditable) {
1668 q->ensureCursorVisible();
1669 if (cursor.position() != oldCursorPos)
1670 emit q->cursorPositionChanged();
1672 } else {
1673 if (cursor.position() != oldCursorPos) {
1674 emit q->cursorPositionChanged();
1675 emit q->microFocusChanged();
1676 }
1678 }
1679 repaintOldAndNewSelection(oldSelection);
1680 hadSelectionOnMousePress = cursor.hasSelection();
1681}
1682
1683void QWidgetTextControlPrivate::mouseMoveEvent(QEvent *e, Qt::MouseButton button, const QPointF &mousePos, Qt::KeyboardModifiers modifiers,
1684 Qt::MouseButtons buttons, const QPointF &globalPos)
1685{
1686 Q_Q(QWidgetTextControl);
1687
1688 if (interactionFlags & Qt::LinksAccessibleByMouse)
1689 updateHighlightedAnchor(mousePos);
1690
1691 if (buttons & Qt::LeftButton) {
1692 const bool editable = interactionFlags & Qt::TextEditable;
1693
1694 if (!(mousePressed
1695 || editable
1696 || mightStartDrag
1697 || selectedWordOnDoubleClick.hasSelection()
1698 || selectedBlockOnTrippleClick.hasSelection()))
1699 return;
1700
1701 const QTextCursor oldSelection = cursor;
1702 const int oldCursorPos = cursor.position();
1703
1704 if (mightStartDrag) {
1705 if ((mousePos - mousePressPos).manhattanLength() > QApplication::startDragDistance())
1707 return;
1708 }
1709
1710 const qreal mouseX = qreal(mousePos.x());
1711
1712 int newCursorPos = q->hitTest(mousePos, Qt::FuzzyHit);
1713
1714 if (isPreediting()) {
1715 // note: oldCursorPos not including preedit
1716 int selectionStartPos = q->hitTest(mousePressPos, Qt::FuzzyHit);
1717
1718 if (newCursorPos != selectionStartPos) {
1720 // commit invalidates positions
1721 newCursorPos = q->hitTest(mousePos, Qt::FuzzyHit);
1722 selectionStartPos = q->hitTest(mousePressPos, Qt::FuzzyHit);
1723 setCursorPosition(selectionStartPos);
1724 }
1725 }
1726
1727 if (newCursorPos == -1)
1728 return;
1729
1730 if (mousePressed && wordSelectionEnabled && !selectedWordOnDoubleClick.hasSelection()) {
1731 selectedWordOnDoubleClick = cursor;
1732 selectedWordOnDoubleClick.select(QTextCursor::WordUnderCursor);
1733 }
1734
1735 if (selectedBlockOnTrippleClick.hasSelection())
1736 extendBlockwiseSelection(newCursorPos);
1737 else if (selectedWordOnDoubleClick.hasSelection())
1738 extendWordwiseSelection(newCursorPos, mouseX);
1739 else if (mousePressed && !isPreediting())
1740 setCursorPosition(newCursorPos, QTextCursor::KeepAnchor);
1741
1742 if (interactionFlags & Qt::TextEditable) {
1743 // don't call ensureVisible for the visible cursor to avoid jumping
1744 // scrollbars. the autoscrolling ensures smooth scrolling if necessary.
1745 //q->ensureCursorVisible();
1746 if (cursor.position() != oldCursorPos)
1747 emit q->cursorPositionChanged();
1749#ifndef QT_NO_IM
1750 if (contextWidget)
1751 QGuiApplication::inputMethod()->update(Qt::ImQueryInput);
1752#endif //QT_NO_IM
1753 } else {
1754 //emit q->visibilityRequest(QRectF(mousePos, QSizeF(1, 1)));
1755 if (cursor.position() != oldCursorPos) {
1756 emit q->cursorPositionChanged();
1757 emit q->microFocusChanged();
1758 }
1759 }
1761 repaintOldAndNewSelection(oldSelection);
1762 } else {
1763 bool wasValid = blockWithMarkerUnderMouse.isValid();
1764 blockWithMarkerUnderMouse = q->blockWithMarkerAt(mousePos);
1765 if (wasValid != blockWithMarkerUnderMouse.isValid())
1766 emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
1767 }
1768
1769 sendMouseEventToInputContext(e, QEvent::MouseMove, button, mousePos, modifiers, buttons, globalPos);
1770}
1771
1772void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
1773 Qt::MouseButtons buttons, const QPointF &globalPos)
1774{
1775 Q_Q(QWidgetTextControl);
1776
1777 const QTextCursor oldSelection = cursor;
1778 if (sendMouseEventToInputContext(
1779 e, QEvent::MouseButtonRelease, button, pos, modifiers, buttons, globalPos)) {
1780 repaintOldAndNewSelection(oldSelection);
1781 return;
1782 }
1783
1784 const int oldCursorPos = cursor.position();
1785
1786#if QT_CONFIG(draganddrop)
1787 if (mightStartDrag && (button & Qt::LeftButton)) {
1788 mousePressed = false;
1789 setCursorPosition(pos);
1790 cursor.clearSelection();
1791 selectionChanged();
1792 }
1793#endif
1794 if (mousePressed) {
1795 mousePressed = false;
1796#ifndef QT_NO_CLIPBOARD
1799 } else if (button == Qt::MiddleButton
1800 && (interactionFlags & Qt::TextEditable)
1801 && QGuiApplication::clipboard()->supportsSelection()) {
1802 setCursorPosition(pos);
1803 const QMimeData *md = QGuiApplication::clipboard()->mimeData(QClipboard::Selection);
1804 if (md)
1805 q->insertFromMimeData(md);
1806#endif
1807 }
1808
1809 repaintOldAndNewSelection(oldSelection);
1810
1811 if (cursor.position() != oldCursorPos) {
1812 emit q->cursorPositionChanged();
1813 emit q->microFocusChanged();
1814 }
1815
1816 // toggle any checkbox that the user clicks
1817 if ((interactionFlags & Qt::TextEditable) && (button & Qt::LeftButton) &&
1818 (blockWithMarkerUnderMouse.isValid()) && !cursor.hasSelection()) {
1819 QTextBlock markerBlock = q->blockWithMarkerAt(pos);
1820 if (markerBlock == blockWithMarkerUnderMouse) {
1821 auto fmt = blockWithMarkerUnderMouse.blockFormat();
1822 switch (fmt.marker()) {
1823 case QTextBlockFormat::MarkerType::Unchecked :
1824 fmt.setMarker(QTextBlockFormat::MarkerType::Checked);
1825 break;
1826 case QTextBlockFormat::MarkerType::Checked:
1827 fmt.setMarker(QTextBlockFormat::MarkerType::Unchecked);
1828 break;
1829 default:
1830 break;
1831 }
1832 cursor.setBlockFormat(fmt);
1833 }
1834 }
1835
1836 if (interactionFlags & Qt::LinksAccessibleByMouse) {
1837
1838 // Ignore event unless left button has been pressed
1839 if (!(button & Qt::LeftButton)) {
1840 e->ignore();
1841 return;
1842 }
1843
1844 const QString anchor = q->anchorAt(pos);
1845
1846 // Ignore event without selection anchor
1847 if (anchor.isEmpty()) {
1848 e->ignore();
1849 return;
1850 }
1851
1852 if (!cursor.hasSelection()
1853 || (anchor == anchorOnMousePress && hadSelectionOnMousePress)) {
1854
1855 const int anchorPos = q->hitTest(pos, Qt::ExactHit);
1856
1857 // Ignore event without valid anchor position
1858 if (anchorPos < 0) {
1859 e->ignore();
1860 return;
1861 }
1862
1863 cursor.setPosition(anchorPos);
1864 activateLinkUnderCursor(std::exchange(anchorOnMousePress, QString()));
1865 }
1866 }
1867}
1868
1869void QWidgetTextControlPrivate::mouseDoubleClickEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos,
1870 Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons,
1871 const QPointF &globalPos)
1872{
1873 Q_Q(QWidgetTextControl);
1874
1875 if (button == Qt::LeftButton
1876 && (interactionFlags & Qt::TextSelectableByMouse)) {
1877
1878#if QT_CONFIG(draganddrop)
1879 mightStartDrag = false;
1880#endif
1882
1883 const QTextCursor oldSelection = cursor;
1884 setCursorPosition(pos);
1885 QTextLine line = currentTextLine(cursor);
1886 bool doEmit = false;
1887 if (line.isValid() && line.textLength()) {
1888 cursor.select(QTextCursor::WordUnderCursor);
1889 doEmit = true;
1890 }
1891 repaintOldAndNewSelection(oldSelection);
1892
1893 cursorIsFocusIndicator = false;
1894 selectedWordOnDoubleClick = cursor;
1895
1896 trippleClickPoint = pos;
1897 trippleClickTimer.start(QApplication::doubleClickInterval(), q);
1898 if (doEmit) {
1900#ifndef QT_NO_CLIPBOARD
1902#endif
1903 emit q->cursorPositionChanged();
1904 }
1905 } else if (!sendMouseEventToInputContext(e, QEvent::MouseButtonDblClick, button, pos,
1906 modifiers, buttons, globalPos)) {
1907 e->ignore();
1908 }
1909}
1910
1911bool QWidgetTextControlPrivate::sendMouseEventToInputContext(
1912 QEvent *e, QEvent::Type eventType, Qt::MouseButton button, const QPointF &pos,
1913 Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPointF &globalPos)
1914{
1915 Q_UNUSED(eventType);
1916 Q_UNUSED(button);
1917 Q_UNUSED(pos);
1918 Q_UNUSED(modifiers);
1919 Q_UNUSED(buttons);
1920 Q_UNUSED(globalPos);
1921#if !defined(QT_NO_IM)
1922 Q_Q(QWidgetTextControl);
1923
1924 if (isPreediting()) {
1925 QTextLayout *layout = cursor.block().layout();
1926 int cursorPos = q->hitTest(pos, Qt::FuzzyHit) - cursor.position();
1927
1928 if (cursorPos < 0 || cursorPos > layout->preeditAreaText().size())
1929 cursorPos = -1;
1930
1931 if (cursorPos >= 0) {
1932 if (eventType == QEvent::MouseButtonRelease)
1933 QGuiApplication::inputMethod()->invokeAction(QInputMethod::Click, cursorPos);
1934
1935 e->setAccepted(true);
1936 return true;
1937 }
1938 }
1939#else
1940 Q_UNUSED(e);
1941#endif
1942 return false;
1943}
1944
1945void QWidgetTextControlPrivate::contextMenuEvent(const QPointF &screenPos, const QPointF &docPos, QWidget *contextWidget)
1946{
1947#ifdef QT_NO_CONTEXTMENU
1948 Q_UNUSED(screenPos);
1949 Q_UNUSED(docPos);
1950 Q_UNUSED(contextWidget);
1951#else
1952 Q_Q(QWidgetTextControl);
1953 QMenu *menu = q->createStandardContextMenu(docPos, contextWidget);
1954 if (!menu)
1955 return;
1956 menu->setAttribute(Qt::WA_DeleteOnClose);
1957
1958 if (auto *widget = qobject_cast<QWidget *>(parent)) {
1959 if (auto *window = widget->window()->windowHandle())
1960 QMenuPrivate::get(menu)->topData()->initialScreen = window->screen();
1961 }
1962
1963 menu->popup(screenPos.toPoint());
1964#endif
1965}
1966
1967bool QWidgetTextControlPrivate::dragEnterEvent(QEvent *e, const QMimeData *mimeData)
1968{
1969 Q_Q(QWidgetTextControl);
1970 if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData)) {
1971 e->ignore();
1972 return false;
1973 }
1974
1975 dndFeedbackCursor = QTextCursor();
1976
1977 return true; // accept proposed action
1978}
1979
1981{
1982 Q_Q(QWidgetTextControl);
1983
1984 const QRectF crect = q->cursorRect(dndFeedbackCursor);
1985 dndFeedbackCursor = QTextCursor();
1986
1987 if (crect.isValid())
1988 emit q->updateRequest(crect);
1989}
1990
1991bool QWidgetTextControlPrivate::dragMoveEvent(QEvent *e, const QMimeData *mimeData, const QPointF &pos)
1992{
1993 Q_Q(QWidgetTextControl);
1994 if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData)) {
1995 e->ignore();
1996 return false;
1997 }
1998
1999 const int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
2000 if (cursorPos != -1) {
2001 QRectF crect = q->cursorRect(dndFeedbackCursor);
2002 if (crect.isValid())
2003 emit q->updateRequest(crect);
2004
2005 dndFeedbackCursor = cursor;
2006 dndFeedbackCursor.setPosition(cursorPos);
2007
2008 crect = q->cursorRect(dndFeedbackCursor);
2009 emit q->updateRequest(crect);
2010 }
2011
2012 return true; // accept proposed action
2013}
2014
2015bool QWidgetTextControlPrivate::dropEvent(const QMimeData *mimeData, const QPointF &pos, Qt::DropAction dropAction, QObject *source)
2016{
2017 Q_Q(QWidgetTextControl);
2018 dndFeedbackCursor = QTextCursor();
2019
2020 if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData))
2021 return false;
2022
2024
2025 QTextCursor insertionCursor = q->cursorForPosition(pos);
2026 insertionCursor.beginEditBlock();
2027
2028 if (dropAction == Qt::MoveAction && source == contextWidget)
2029 cursor.removeSelectedText();
2030
2031 cursor = insertionCursor;
2032 q->insertFromMimeData(mimeData);
2033 insertionCursor.endEditBlock();
2034 q->ensureCursorVisible();
2035 return true; // accept proposed action
2036}
2037
2038void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
2039{
2040 Q_Q(QWidgetTextControl);
2041 if (!(interactionFlags & (Qt::TextEditable | Qt::TextSelectableByMouse)) || cursor.isNull()) {
2042 e->ignore();
2043 return;
2044 }
2045 bool isGettingInput = !e->commitString().isEmpty()
2046 || e->preeditString() != cursor.block().layout()->preeditAreaText()
2047 || e->replacementLength() > 0;
2048
2049 if (!isGettingInput && e->attributes().isEmpty()) {
2050 e->ignore();
2051 return;
2052 }
2053
2054 int oldCursorPos = cursor.position();
2055
2056 cursor.beginEditBlock();
2057 if (isGettingInput) {
2058 cursor.removeSelectedText();
2059 }
2060
2061 QTextBlock block;
2062
2063 // insert commit string
2064 if (!e->commitString().isEmpty() || e->replacementLength()) {
2065 auto *mimeData = QInputControl::mimeDataForInputEvent(e);
2066 if (mimeData && q->canInsertFromMimeData(mimeData)) {
2067 q->insertFromMimeData(mimeData);
2068 } else {
2069 if (e->commitString().endsWith(QChar::LineFeed))
2070 block = cursor.block(); // Remember the block where the preedit text is
2071 QTextCursor c = cursor;
2072 c.setPosition(c.position() + e->replacementStart());
2073 c.setPosition(c.position() + e->replacementLength(), QTextCursor::KeepAnchor);
2074 c.insertText(e->commitString());
2075 }
2076 }
2077
2078 for (int i = 0; i < e->attributes().size(); ++i) {
2079 const QInputMethodEvent::Attribute &a = e->attributes().at(i);
2080 if (a.type == QInputMethodEvent::Selection) {
2081 QTextCursor oldCursor = cursor;
2082 int blockStart = a.start + cursor.block().position();
2083 cursor.setPosition(blockStart, QTextCursor::MoveAnchor);
2084 cursor.setPosition(blockStart + a.length, QTextCursor::KeepAnchor);
2085 q->ensureCursorVisible();
2086 repaintOldAndNewSelection(oldCursor);
2087 }
2088 }
2089
2090 if (!block.isValid())
2091 block = cursor.block();
2092 QTextLayout *layout = block.layout();
2093 if (isGettingInput)
2094 layout->setPreeditArea(cursor.position() - block.position(), e->preeditString());
2095 QList<QTextLayout::FormatRange> overrides;
2096 overrides.reserve(e->attributes().size());
2097 const int oldPreeditCursor = preeditCursor;
2098 preeditCursor = e->preeditString().size();
2099 hideCursor = false;
2100 for (int i = 0; i < e->attributes().size(); ++i) {
2101 const QInputMethodEvent::Attribute &a = e->attributes().at(i);
2102 if (a.type == QInputMethodEvent::Cursor) {
2103 preeditCursor = a.start;
2104 hideCursor = !a.length;
2105 } else if (a.type == QInputMethodEvent::TextFormat) {
2106 QTextCharFormat f = cursor.charFormat();
2107 f.merge(qvariant_cast<QTextFormat>(a.value).toCharFormat());
2108 if (f.isValid()) {
2109 QTextLayout::FormatRange o;
2110 o.start = a.start + cursor.position() - block.position();
2111 o.length = a.length;
2112 o.format = f;
2113
2114 // Make sure list is sorted by start index
2115 QList<QTextLayout::FormatRange>::iterator it = overrides.end();
2116 while (it != overrides.begin()) {
2117 QList<QTextLayout::FormatRange>::iterator previous = it - 1;
2118 if (o.start >= previous->start) {
2119 overrides.insert(it, o);
2120 break;
2121 }
2122 it = previous;
2123 }
2124
2125 if (it == overrides.begin())
2126 overrides.prepend(o);
2127 }
2128 }
2129 }
2130
2131 if (cursor.charFormat().isValid()) {
2132 int start = cursor.position() - block.position();
2133 int end = start + e->preeditString().size();
2134
2135 QList<QTextLayout::FormatRange>::iterator it = overrides.begin();
2136 while (it != overrides.end()) {
2137 QTextLayout::FormatRange range = *it;
2138 int rangeStart = range.start;
2139 if (rangeStart > start) {
2140 QTextLayout::FormatRange o;
2141 o.start = start;
2142 o.length = rangeStart - start;
2143 o.format = cursor.charFormat();
2144 it = overrides.insert(it, o) + 1;
2145 }
2146
2147 ++it;
2148 start = range.start + range.length;
2149 }
2150
2151 if (start < end) {
2152 QTextLayout::FormatRange o;
2153 o.start = start;
2154 o.length = end - start;
2155 o.format = cursor.charFormat();
2156 overrides.append(o);
2157 }
2158 }
2159 layout->setFormats(overrides);
2160
2161 cursor.endEditBlock();
2162
2163 if (cursor.d)
2164 cursor.d->setX();
2165 if (oldCursorPos != cursor.position())
2166 emit q->cursorPositionChanged();
2167 if (oldPreeditCursor != preeditCursor)
2168 emit q->microFocusChanged();
2169}
2170
2171QVariant QWidgetTextControl::inputMethodQuery(Qt::InputMethodQuery property, QVariant argument) const
2172{
2173 Q_D(const QWidgetTextControl);
2174 QTextBlock block = d->cursor.block();
2175 switch(property) {
2176 case Qt::ImCursorRectangle:
2177 return cursorRect();
2178 case Qt::ImAnchorRectangle:
2179 return d->rectForPosition(d->cursor.anchor());
2180 case Qt::ImFont:
2181 return QVariant(d->cursor.charFormat().font());
2182 case Qt::ImCursorPosition: {
2183 const QPointF pt = argument.toPointF();
2184 if (!pt.isNull())
2185 return QVariant(cursorForPosition(pt).position() - block.position());
2186 return QVariant(d->cursor.position() - block.position()); }
2187 case Qt::ImSurroundingText:
2188 return QVariant(block.text());
2189 case Qt::ImCurrentSelection: {
2190 QMimeData *mimeData = createMimeDataFromSelection();
2191 mimeData->deleteLater();
2192 return QInputControl::selectionWrapper(mimeData);
2193 }
2194 case Qt::ImMaximumTextLength:
2195 return QVariant(); // No limit.
2196 case Qt::ImAnchorPosition:
2197 return QVariant(d->cursor.anchor() - block.position());
2198 case Qt::ImAbsolutePosition: {
2199 const QPointF pt = argument.toPointF();
2200 if (!pt.isNull())
2201 return QVariant(cursorForPosition(pt).position());
2202 return QVariant(d->cursor.position()); }
2203 case Qt::ImTextAfterCursor:
2204 {
2205 int maxLength = argument.isValid() ? argument.toInt() : 1024;
2206 QTextCursor tmpCursor = d->cursor;
2207 int localPos = d->cursor.position() - block.position();
2208 QString result = block.text().mid(localPos);
2209 while (result.size() < maxLength) {
2210 int currentBlock = tmpCursor.blockNumber();
2211 tmpCursor.movePosition(QTextCursor::NextBlock);
2212 if (tmpCursor.blockNumber() == currentBlock)
2213 break;
2214 result += u'\n' + tmpCursor.block().text();
2215 }
2216 return QVariant(result);
2217 }
2218 case Qt::ImTextBeforeCursor:
2219 {
2220 int maxLength = argument.isValid() ? argument.toInt() : 1024;
2221 QTextCursor tmpCursor = d->cursor;
2222 int localPos = d->cursor.position() - block.position();
2223 int numBlocks = 0;
2224 int resultLen = localPos;
2225 while (resultLen < maxLength) {
2226 int currentBlock = tmpCursor.blockNumber();
2227 tmpCursor.movePosition(QTextCursor::PreviousBlock);
2228 if (tmpCursor.blockNumber() == currentBlock)
2229 break;
2230 numBlocks++;
2231 resultLen += tmpCursor.block().length();
2232 }
2233 QString result;
2234 while (numBlocks) {
2235 result += tmpCursor.block().text() + u'\n';
2236 tmpCursor.movePosition(QTextCursor::NextBlock);
2237 --numBlocks;
2238 }
2239 result += QStringView{block.text()}.mid(0, localPos);
2240 return QVariant(result);
2241 }
2242 default:
2243 return QVariant();
2244 }
2245}
2246
2247void QWidgetTextControl::setFocus(bool focus, Qt::FocusReason reason)
2248{
2249 QFocusEvent ev(focus ? QEvent::FocusIn : QEvent::FocusOut,
2250 reason);
2251 processEvent(&ev);
2252}
2253
2254void QWidgetTextControlPrivate::focusEvent(QFocusEvent *e)
2255{
2256 Q_Q(QWidgetTextControl);
2257 emit q->updateRequest(q->selectionRect());
2258 if (e->gotFocus()) {
2259#ifdef QT_KEYPAD_NAVIGATION
2260 if (!QApplicationPrivate::keypadNavigationEnabled() || (hasEditFocus && (e->reason() == Qt::PopupFocusReason))) {
2261#endif
2262 cursorOn = (interactionFlags & (Qt::TextSelectableByKeyboard | Qt::TextEditable));
2263 if (interactionFlags & Qt::TextEditable) {
2264 setCursorVisible(true);
2265 }
2266#ifdef QT_KEYPAD_NAVIGATION
2267 }
2268#endif
2269 } else {
2270 setCursorVisible(false);
2271 cursorOn = false;
2272
2273 if (cursorIsFocusIndicator
2274 && e->reason() != Qt::ActiveWindowFocusReason
2275 && e->reason() != Qt::PopupFocusReason
2276 && cursor.hasSelection()) {
2277 cursor.clearSelection();
2278 }
2279 }
2280 hasFocus = e->gotFocus();
2281}
2282
2283QString QWidgetTextControlPrivate::anchorForCursor(const QTextCursor &anchorCursor) const
2284{
2285 if (anchorCursor.hasSelection()) {
2286 QTextCursor cursor = anchorCursor;
2287 if (cursor.selectionStart() != cursor.position())
2288 cursor.setPosition(cursor.selectionStart());
2289 cursor.movePosition(QTextCursor::NextCharacter);
2290 QTextCharFormat fmt = cursor.charFormat();
2291 if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref))
2292 return fmt.stringProperty(QTextFormat::AnchorHref);
2293 }
2294 return QString();
2295}
2296
2297#ifdef QT_KEYPAD_NAVIGATION
2298void QWidgetTextControlPrivate::editFocusEvent(QEvent *e)
2299{
2300 Q_Q(QWidgetTextControl);
2301
2302 if (QApplicationPrivate::keypadNavigationEnabled()) {
2303 if (e->type() == QEvent::EnterEditFocus && interactionFlags & Qt::TextEditable) {
2304 const QTextCursor oldSelection = cursor;
2305 const int oldCursorPos = cursor.position();
2306 const bool moved = cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
2307 q->ensureCursorVisible();
2308 if (moved) {
2309 if (cursor.position() != oldCursorPos)
2310 emit q->cursorPositionChanged();
2311 emit q->microFocusChanged();
2312 }
2313 selectionChanged();
2314 repaintOldAndNewSelection(oldSelection);
2315
2316 setBlinkingCursorEnabled(true);
2317 } else
2318 setBlinkingCursorEnabled(false);
2319 }
2320
2321 hasEditFocus = e->type() == QEvent::EnterEditFocus;
2322}
2323#endif
2324
2325#ifndef QT_NO_CONTEXTMENU
2326void setActionIcon(QAction *action, const QString &name)
2327{
2328 const QIcon icon = QIcon::fromTheme(name);
2329 if (!icon.isNull())
2330 action->setIcon(icon);
2331}
2332
2333QMenu *QWidgetTextControl::createStandardContextMenu(const QPointF &pos, QWidget *parent)
2334{
2335 Q_D(QWidgetTextControl);
2336
2337 const bool showTextSelectionActions = d->interactionFlags & (Qt::TextEditable | Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
2338
2339 d->linkToCopy = QString();
2340 if (!pos.isNull())
2341 d->linkToCopy = anchorAt(pos);
2342
2343 if (d->linkToCopy.isEmpty() && !showTextSelectionActions)
2344 return nullptr;
2345
2346 QMenu *menu = new QMenu(parent);
2347 QAction *a;
2348
2349 if (d->interactionFlags & Qt::TextEditable) {
2350 a = menu->addAction(tr("&Undo") + ACCEL_KEY(QKeySequence::Undo), this, SLOT(undo()));
2351 a->setEnabled(d->doc->isUndoAvailable());
2352 a->setObjectName(QStringLiteral("edit-undo"));
2353 setActionIcon(a, QStringLiteral("edit-undo"));
2354 a = menu->addAction(tr("&Redo") + ACCEL_KEY(QKeySequence::Redo), this, SLOT(redo()));
2355 a->setEnabled(d->doc->isRedoAvailable());
2356 a->setObjectName(QStringLiteral("edit-redo"));
2357 setActionIcon(a, QStringLiteral("edit-redo"));
2358 menu->addSeparator();
2359
2360#ifndef QT_NO_CLIPBOARD
2361 a = menu->addAction(tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut), this, SLOT(cut()));
2362 a->setEnabled(d->cursor.hasSelection());
2363 a->setObjectName(QStringLiteral("edit-cut"));
2364 setActionIcon(a, QStringLiteral("edit-cut"));
2365#endif
2366 }
2367
2368#ifndef QT_NO_CLIPBOARD
2369 if (showTextSelectionActions) {
2370 a = menu->addAction(tr("&Copy") + ACCEL_KEY(QKeySequence::Copy), this, SLOT(copy()));
2371 a->setEnabled(d->cursor.hasSelection());
2372 a->setObjectName(QStringLiteral("edit-copy"));
2373 setActionIcon(a, QStringLiteral("edit-copy"));
2374 }
2375
2376 if ((d->interactionFlags & Qt::LinksAccessibleByKeyboard)
2377 || (d->interactionFlags & Qt::LinksAccessibleByMouse)) {
2378
2379 a = menu->addAction(tr("Copy &Link Location"), this, SLOT(_q_copyLink()));
2380 a->setEnabled(!d->linkToCopy.isEmpty());
2381 a->setObjectName(QStringLiteral("link-copy"));
2382 }
2383#endif // QT_NO_CLIPBOARD
2384
2385 if (d->interactionFlags & Qt::TextEditable) {
2386#ifndef QT_NO_CLIPBOARD
2387 a = menu->addAction(tr("&Paste") + ACCEL_KEY(QKeySequence::Paste), this, SLOT(paste()));
2388 a->setEnabled(canPaste());
2389 a->setObjectName(QStringLiteral("edit-paste"));
2390 setActionIcon(a, QStringLiteral("edit-paste"));
2391#endif
2392 a = menu->addAction(tr("Delete"), this, SLOT(_q_deleteSelected()));
2393 a->setEnabled(d->cursor.hasSelection());
2394 a->setObjectName(QStringLiteral("edit-delete"));
2395 setActionIcon(a, QStringLiteral("edit-delete"));
2396 }
2397
2398
2399 if (showTextSelectionActions) {
2400 menu->addSeparator();
2401 a = menu->addAction(tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll), this, SLOT(selectAll()));
2402 a->setEnabled(!d->doc->isEmpty());
2403 a->setObjectName(QStringLiteral("select-all"));
2404 setActionIcon(a, QStringLiteral("edit-select-all"));
2405 }
2406
2407 if ((d->interactionFlags & Qt::TextEditable) && QGuiApplication::styleHints()->useRtlExtensions()) {
2408 menu->addSeparator();
2409 QUnicodeControlCharacterMenu *ctrlCharacterMenu = new QUnicodeControlCharacterMenu(this, menu);
2410 menu->addMenu(ctrlCharacterMenu);
2411 }
2412
2413 return menu;
2414}
2415#endif // QT_NO_CONTEXTMENU
2416
2417QTextCursor QWidgetTextControl::cursorForPosition(const QPointF &pos) const
2418{
2419 Q_D(const QWidgetTextControl);
2420 int cursorPos = hitTest(pos, Qt::FuzzyHit);
2421 if (cursorPos == -1)
2422 cursorPos = 0;
2423 QTextCursor c(d->doc);
2424 c.setPosition(cursorPos);
2425 return c;
2426}
2427
2428QRectF QWidgetTextControl::cursorRect(const QTextCursor &cursor) const
2429{
2430 Q_D(const QWidgetTextControl);
2431 if (cursor.isNull())
2432 return QRectF();
2433
2434 return d->rectForPosition(cursor.position());
2435}
2436
2437QRectF QWidgetTextControl::cursorRect() const
2438{
2439 Q_D(const QWidgetTextControl);
2440 return cursorRect(d->cursor);
2441}
2442
2443QRectF QWidgetTextControlPrivate::cursorRectPlusUnicodeDirectionMarkers(const QTextCursor &cursor) const
2444{
2445 if (cursor.isNull())
2446 return QRectF();
2447
2448 return rectForPosition(cursor.position()).adjusted(-4, 0, 4, 0);
2449}
2450
2451QString QWidgetTextControl::anchorAt(const QPointF &pos) const
2452{
2453 Q_D(const QWidgetTextControl);
2454 return d->doc->documentLayout()->anchorAt(pos);
2455}
2456
2457QString QWidgetTextControl::anchorAtCursor() const
2458{
2459 Q_D(const QWidgetTextControl);
2460
2461 return d->anchorForCursor(d->cursor);
2462}
2463
2464QTextBlock QWidgetTextControl::blockWithMarkerAt(const QPointF &pos) const
2465{
2466 Q_D(const QWidgetTextControl);
2467 return d->doc->documentLayout()->blockWithMarkerAt(pos);
2468}
2469
2470bool QWidgetTextControl::overwriteMode() const
2471{
2472 Q_D(const QWidgetTextControl);
2473 return d->overwriteMode;
2474}
2475
2476void QWidgetTextControl::setOverwriteMode(bool overwrite)
2477{
2478 Q_D(QWidgetTextControl);
2479 d->overwriteMode = overwrite;
2480}
2481
2482int QWidgetTextControl::cursorWidth() const
2483{
2484 Q_D(const QWidgetTextControl);
2485 return d->doc->documentLayout()->property("cursorWidth").toInt();
2486}
2487
2488void QWidgetTextControl::setCursorWidth(int width)
2489{
2490 Q_D(QWidgetTextControl);
2491 if (width == -1)
2492 width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth, nullptr, qobject_cast<QWidget *>(parent()));
2493 d->doc->documentLayout()->setProperty("cursorWidth", width);
2494 d->repaintCursor();
2495}
2496
2497bool QWidgetTextControl::acceptRichText() const
2498{
2499 Q_D(const QWidgetTextControl);
2500 return d->acceptRichText;
2501}
2502
2503void QWidgetTextControl::setAcceptRichText(bool accept)
2504{
2505 Q_D(QWidgetTextControl);
2506 d->acceptRichText = accept;
2507}
2508
2509#if QT_CONFIG(textedit)
2510
2511void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections)
2512{
2513 Q_D(QWidgetTextControl);
2514
2515 QMultiHash<int, int> hash;
2516 for (int i = 0; i < d->extraSelections.size(); ++i) {
2517 const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(i);
2518 hash.insert(esel.cursor.anchor(), i);
2519 }
2520
2521 for (int i = 0; i < selections.size(); ++i) {
2522 const QTextEdit::ExtraSelection &sel = selections.at(i);
2523 const auto it = hash.constFind(sel.cursor.anchor());
2524 if (it != hash.cend()) {
2525 const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
2526 if (esel.cursor.position() == sel.cursor.position()
2527 && esel.format == sel.format) {
2528 hash.erase(it);
2529 continue;
2530 }
2531 }
2532 QRectF r = selectionRect(sel.cursor);
2533 if (sel.format.boolProperty(QTextFormat::FullWidthSelection)) {
2534 r.setLeft(0);
2535 r.setWidth(qreal(INT_MAX));
2536 }
2537 emit updateRequest(r);
2538 }
2539
2540 for (auto it = hash.cbegin(); it != hash.cend(); ++it) {
2541 const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
2542 QRectF r = selectionRect(esel.cursor);
2543 if (esel.format.boolProperty(QTextFormat::FullWidthSelection)) {
2544 r.setLeft(0);
2545 r.setWidth(qreal(INT_MAX));
2546 }
2547 emit updateRequest(r);
2548 }
2549
2550 d->extraSelections.resize(selections.size());
2551 for (int i = 0; i < selections.size(); ++i) {
2552 d->extraSelections[i].cursor = selections.at(i).cursor;
2553 d->extraSelections[i].format = selections.at(i).format;
2554 }
2555}
2556
2557QList<QTextEdit::ExtraSelection> QWidgetTextControl::extraSelections() const
2558{
2559 Q_D(const QWidgetTextControl);
2560 QList<QTextEdit::ExtraSelection> selections;
2561 const int numExtraSelections = d->extraSelections.size();
2562 selections.reserve(numExtraSelections);
2563 for (int i = 0; i < numExtraSelections; ++i) {
2564 QTextEdit::ExtraSelection sel;
2565 const QAbstractTextDocumentLayout::Selection &sel2 = d->extraSelections.at(i);
2566 sel.cursor = sel2.cursor;
2567 sel.format = sel2.format;
2568 selections.append(sel);
2569 }
2570 return selections;
2571}
2572
2573#endif // QT_CONFIG(textedit)
2574
2575void QWidgetTextControl::setTextWidth(qreal width)
2576{
2577 Q_D(QWidgetTextControl);
2578 d->doc->setTextWidth(width);
2579}
2580
2581qreal QWidgetTextControl::textWidth() const
2582{
2583 Q_D(const QWidgetTextControl);
2584 return d->doc->textWidth();
2585}
2586
2587QSizeF QWidgetTextControl::size() const
2588{
2589 Q_D(const QWidgetTextControl);
2590 return d->doc->size();
2591}
2592
2593void QWidgetTextControl::setOpenExternalLinks(bool open)
2594{
2595 Q_D(QWidgetTextControl);
2596 d->openExternalLinks = open;
2597}
2598
2599bool QWidgetTextControl::openExternalLinks() const
2600{
2601 Q_D(const QWidgetTextControl);
2602 return d->openExternalLinks;
2603}
2604
2605bool QWidgetTextControl::ignoreUnusedNavigationEvents() const
2606{
2607 Q_D(const QWidgetTextControl);
2608 return d->ignoreUnusedNavigationEvents;
2609}
2610
2611void QWidgetTextControl::setIgnoreUnusedNavigationEvents(bool ignore)
2612{
2613 Q_D(QWidgetTextControl);
2614 d->ignoreUnusedNavigationEvents = ignore;
2615}
2616
2617void QWidgetTextControl::moveCursor(QTextCursor::MoveOperation op, QTextCursor::MoveMode mode)
2618{
2619 Q_D(QWidgetTextControl);
2620 const QTextCursor oldSelection = d->cursor;
2621 const bool moved = d->cursor.movePosition(op, mode);
2622 d->_q_updateCurrentCharFormatAndSelection();
2623 ensureCursorVisible();
2624 d->repaintOldAndNewSelection(oldSelection);
2625 if (moved)
2626 emit cursorPositionChanged();
2627}
2628
2629bool QWidgetTextControl::canPaste() const
2630{
2631#ifndef QT_NO_CLIPBOARD
2632 Q_D(const QWidgetTextControl);
2633 if (d->interactionFlags & Qt::TextEditable) {
2634 const QMimeData *md = QGuiApplication::clipboard()->mimeData();
2635 return md && canInsertFromMimeData(md);
2636 }
2637#endif
2638 return false;
2639}
2640
2641void QWidgetTextControl::setCursorIsFocusIndicator(bool b)
2642{
2643 Q_D(QWidgetTextControl);
2644 d->cursorIsFocusIndicator = b;
2645 d->repaintCursor();
2646}
2647
2648bool QWidgetTextControl::cursorIsFocusIndicator() const
2649{
2650 Q_D(const QWidgetTextControl);
2651 return d->cursorIsFocusIndicator;
2652}
2653
2654
2655void QWidgetTextControl::setDragEnabled(bool enabled)
2656{
2657 Q_D(QWidgetTextControl);
2658 d->dragEnabled = enabled;
2659}
2660
2661bool QWidgetTextControl::isDragEnabled() const
2662{
2663 Q_D(const QWidgetTextControl);
2664 return d->dragEnabled;
2665}
2666
2667void QWidgetTextControl::setWordSelectionEnabled(bool enabled)
2668{
2669 Q_D(QWidgetTextControl);
2670 d->wordSelectionEnabled = enabled;
2671}
2672
2673bool QWidgetTextControl::isWordSelectionEnabled() const
2674{
2675 Q_D(const QWidgetTextControl);
2676 return d->wordSelectionEnabled;
2677}
2678
2679bool QWidgetTextControl::isPreediting()
2680{
2681 return d_func()->isPreediting();
2682}
2683
2684#ifndef QT_NO_PRINTER
2685void QWidgetTextControl::print(QPagedPaintDevice *printer) const
2686{
2687 Q_D(const QWidgetTextControl);
2688 if (!printer)
2689 return;
2690 QTextDocument *tempDoc = nullptr;
2691 const QTextDocument *doc = d->doc;
2692 if (QPagedPaintDevicePrivate::get(printer)->printSelectionOnly) {
2693 if (!d->cursor.hasSelection())
2694 return;
2695 tempDoc = new QTextDocument(const_cast<QTextDocument *>(doc));
2696 tempDoc->setResourceProvider(doc->resourceProvider());
2697 tempDoc->setMetaInformation(QTextDocument::DocumentTitle, doc->metaInformation(QTextDocument::DocumentTitle));
2698 tempDoc->setPageSize(doc->pageSize());
2699 tempDoc->setDefaultFont(doc->defaultFont());
2700 tempDoc->setUseDesignMetrics(doc->useDesignMetrics());
2701 QTextCursor(tempDoc).insertFragment(d->cursor.selection());
2702 doc = tempDoc;
2703
2704 // copy the custom object handlers
2705 doc->documentLayout()->d_func()->handlers = d->doc->documentLayout()->d_func()->handlers;
2706 }
2707 doc->print(printer);
2708 delete tempDoc;
2709}
2710#endif
2711
2712QMimeData *QWidgetTextControl::createMimeDataFromSelection() const
2713{
2714 Q_D(const QWidgetTextControl);
2715 const QTextDocumentFragment fragment(d->cursor);
2716 return new QTextEditMimeData(fragment);
2717}
2718
2719bool QWidgetTextControl::canInsertFromMimeData(const QMimeData *source) const
2720{
2721 Q_D(const QWidgetTextControl);
2722 if (d->acceptRichText)
2723 return (source->hasText() && !source->text().isEmpty())
2724 || source->hasHtml()
2725 || source->hasFormat("application/x-qrichtext"_L1)
2726 || source->hasFormat("application/x-qt-richtext"_L1);
2727 else
2728 return source->hasText() && !source->text().isEmpty();
2729}
2730
2731void QWidgetTextControl::insertFromMimeData(const QMimeData *source)
2732{
2733 Q_D(QWidgetTextControl);
2734 if (!(d->interactionFlags & Qt::TextEditable) || !source)
2735 return;
2736
2737 bool hasData = false;
2738 QTextDocumentFragment fragment;
2739#if QT_CONFIG(textmarkdownreader)
2740 const auto formats = source->formats();
2741 if (formats.size() && formats.first() == "text/markdown"_L1) {
2742 auto s = QString::fromUtf8(source->data("text/markdown"_L1));
2743 fragment = QTextDocumentFragment::fromMarkdown(s);
2744 hasData = true;
2745 } else
2746#endif
2747#ifndef QT_NO_TEXTHTMLPARSER
2748 if (source->hasFormat("application/x-qrichtext"_L1) && d->acceptRichText) {
2749 // x-qrichtext is always UTF-8 (taken from Qt3 since we don't use it anymore).
2750 const QString richtext = "<meta name=\"qrichtext\" content=\"1\" />"_L1
2751 + QString::fromUtf8(source->data("application/x-qrichtext"_L1));
2752 fragment = QTextDocumentFragment::fromHtml(richtext, d->doc);
2753 hasData = true;
2754 } else if (source->hasHtml() && d->acceptRichText) {
2755 fragment = QTextDocumentFragment::fromHtml(source->html(), d->doc);
2756 hasData = true;
2757 }
2758#endif // QT_NO_TEXTHTMLPARSER
2759 if (!hasData) {
2760 const QString text = source->text();
2761 if (!text.isNull()) {
2762 fragment = QTextDocumentFragment::fromPlainText(text);
2763 hasData = true;
2764 }
2765 }
2766
2767 if (hasData)
2768 d->cursor.insertFragment(fragment);
2769 ensureCursorVisible();
2770}
2771
2772bool QWidgetTextControl::findNextPrevAnchor(const QTextCursor &startCursor, bool next, QTextCursor &newAnchor)
2773{
2774 Q_D(QWidgetTextControl);
2775
2776 int anchorStart = -1;
2777 QString anchorHref;
2778 int anchorEnd = -1;
2779
2780 if (next) {
2781 const int startPos = startCursor.selectionEnd();
2782
2783 QTextBlock block = d->doc->findBlock(startPos);
2784 QTextBlock::Iterator it = block.begin();
2785
2786 while (!it.atEnd() && it.fragment().position() < startPos)
2787 ++it;
2788
2789 while (block.isValid()) {
2790 anchorStart = -1;
2791
2792 // find next anchor
2793 for (; !it.atEnd(); ++it) {
2794 const QTextFragment fragment = it.fragment();
2795 const QTextCharFormat fmt = fragment.charFormat();
2796
2797 if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref)) {
2798 anchorStart = fragment.position();
2799 anchorHref = fmt.anchorHref();
2800 break;
2801 }
2802 }
2803
2804 if (anchorStart != -1) {
2805 anchorEnd = -1;
2806
2807 // find next non-anchor fragment
2808 for (; !it.atEnd(); ++it) {
2809 const QTextFragment fragment = it.fragment();
2810 const QTextCharFormat fmt = fragment.charFormat();
2811
2812 if (!fmt.isAnchor() || fmt.anchorHref() != anchorHref) {
2813 anchorEnd = fragment.position();
2814 break;
2815 }
2816 }
2817
2818 if (anchorEnd == -1)
2819 anchorEnd = block.position() + block.length() - 1;
2820
2821 // make found selection
2822 break;
2823 }
2824
2825 block = block.next();
2826 it = block.begin();
2827 }
2828 } else {
2829 int startPos = startCursor.selectionStart();
2830 if (startPos > 0)
2831 --startPos;
2832
2833 QTextBlock block = d->doc->findBlock(startPos);
2834 QTextBlock::Iterator blockStart = block.begin();
2835 QTextBlock::Iterator it = block.end();
2836
2837 if (startPos == block.position()) {
2838 it = block.begin();
2839 } else {
2840 do {
2841 if (it == blockStart) {
2842 it = QTextBlock::Iterator();
2843 block = QTextBlock();
2844 } else {
2845 --it;
2846 }
2847 } while (!it.atEnd() && it.fragment().position() + it.fragment().length() - 1 > startPos);
2848 }
2849
2850 while (block.isValid()) {
2851 anchorStart = -1;
2852
2853 if (!it.atEnd()) {
2854 do {
2855 const QTextFragment fragment = it.fragment();
2856 const QTextCharFormat fmt = fragment.charFormat();
2857
2858 if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref)) {
2859 anchorStart = fragment.position() + fragment.length();
2860 anchorHref = fmt.anchorHref();
2861 break;
2862 }
2863
2864 if (it == blockStart)
2865 it = QTextBlock::Iterator();
2866 else
2867 --it;
2868 } while (!it.atEnd());
2869 }
2870
2871 if (anchorStart != -1 && !it.atEnd()) {
2872 anchorEnd = -1;
2873
2874 do {
2875 const QTextFragment fragment = it.fragment();
2876 const QTextCharFormat fmt = fragment.charFormat();
2877
2878 if (!fmt.isAnchor() || fmt.anchorHref() != anchorHref) {
2879 anchorEnd = fragment.position() + fragment.length();
2880 break;
2881 }
2882
2883 if (it == blockStart)
2884 it = QTextBlock::Iterator();
2885 else
2886 --it;
2887 } while (!it.atEnd());
2888
2889 if (anchorEnd == -1)
2890 anchorEnd = qMax(0, block.position());
2891
2892 break;
2893 }
2894
2895 block = block.previous();
2896 it = block.end();
2897 if (it != block.begin())
2898 --it;
2899 blockStart = block.begin();
2900 }
2901
2902 }
2903
2904 if (anchorStart != -1 && anchorEnd != -1) {
2905 newAnchor = d->cursor;
2906 newAnchor.setPosition(anchorStart);
2907 newAnchor.setPosition(anchorEnd, QTextCursor::KeepAnchor);
2908 return true;
2909 }
2910
2911 return false;
2912}
2913
2914void QWidgetTextControlPrivate::activateLinkUnderCursor(QString href)
2915{
2916 QTextCursor oldCursor = cursor;
2917
2918 if (href.isEmpty()) {
2919 QTextCursor tmp = cursor;
2920 if (tmp.selectionStart() != tmp.position())
2921 tmp.setPosition(tmp.selectionStart());
2922 tmp.movePosition(QTextCursor::NextCharacter);
2923 href = tmp.charFormat().anchorHref();
2924 }
2925 if (href.isEmpty())
2926 return;
2927
2928 if (!cursor.hasSelection()) {
2929 QTextBlock block = cursor.block();
2930 const int cursorPos = cursor.position();
2931
2932 QTextBlock::Iterator it = block.begin();
2933 QTextBlock::Iterator linkFragment;
2934
2935 for (; !it.atEnd(); ++it) {
2936 QTextFragment fragment = it.fragment();
2937 const int fragmentPos = fragment.position();
2938 if (fragmentPos <= cursorPos &&
2939 fragmentPos + fragment.length() > cursorPos) {
2940 linkFragment = it;
2941 break;
2942 }
2943 }
2944
2945 if (!linkFragment.atEnd()) {
2946 it = linkFragment;
2947 cursor.setPosition(it.fragment().position());
2948 if (it != block.begin()) {
2949 do {
2950 --it;
2951 QTextFragment fragment = it.fragment();
2952 if (fragment.charFormat().anchorHref() != href)
2953 break;
2954 cursor.setPosition(fragment.position());
2955 } while (it != block.begin());
2956 }
2957
2958 for (it = linkFragment; !it.atEnd(); ++it) {
2959 QTextFragment fragment = it.fragment();
2960 if (fragment.charFormat().anchorHref() != href)
2961 break;
2962 cursor.setPosition(fragment.position() + fragment.length(), QTextCursor::KeepAnchor);
2963 }
2964 }
2965 }
2966
2967 if (hasFocus) {
2969 } else {
2970 cursorIsFocusIndicator = false;
2971 cursor.clearSelection();
2972 }
2973 repaintOldAndNewSelection(oldCursor);
2974
2975#ifndef QT_NO_DESKTOPSERVICES
2977 QDesktopServices::openUrl(QUrl{href});
2978 else
2979#endif
2980 emit q_func()->linkActivated(href);
2981}
2982
2983void QWidgetTextControlPrivate::updateHighlightedAnchor(QPointF mousePos)
2984{
2985 Q_Q(QWidgetTextControl);
2986 const QString anchor = q->anchorAt(mousePos);
2987 if (anchor != highlightedAnchor) {
2988 highlightedAnchor = anchor;
2989 emit q->linkHovered(anchor);
2990 }
2991}
2992
2994{
2995 Q_Q(QWidgetTextControl);
2996 if (!highlightedAnchor.isEmpty()) {
2997 highlightedAnchor.clear();
2998 emit q->linkHovered(QString());
2999 }
3000}
3001
3002#if QT_CONFIG(tooltip)
3003void QWidgetTextControlPrivate::showToolTip(const QPoint &globalPos, const QPointF &pos, QWidget *contextWidget)
3004{
3005 const QString toolTip = q_func()->cursorForPosition(pos).charFormat().toolTip();
3006 if (toolTip.isEmpty())
3007 return;
3008 QToolTip::showText(globalPos, toolTip, contextWidget);
3009}
3010#endif // QT_CONFIG(tooltip)
3011
3013{
3014 QTextLayout *layout = cursor.block().layout();
3015 if (layout && !layout->preeditAreaText().isEmpty())
3016 return true;
3017
3018 return false;
3019}
3020
3022{
3023 if (!isPreediting())
3024 return;
3025
3026 QGuiApplication::inputMethod()->commit();
3027
3028 if (!isPreediting())
3029 return;
3030
3031 cursor.beginEditBlock();
3032 preeditCursor = 0;
3033 QTextBlock block = cursor.block();
3034 QTextLayout *layout = block.layout();
3035 layout->setPreeditArea(-1, QString());
3036 layout->clearFormats();
3037 cursor.endEditBlock();
3038}
3039
3040bool QWidgetTextControl::setFocusToNextOrPreviousAnchor(bool next)
3041{
3042 Q_D(QWidgetTextControl);
3043
3044 if (!(d->interactionFlags & Qt::LinksAccessibleByKeyboard))
3045 return false;
3046
3047 QRectF crect = selectionRect();
3048 emit updateRequest(crect);
3049
3050 // If we don't have a current anchor, we start from the start/end
3051 if (!d->cursor.hasSelection()) {
3052 d->cursor = QTextCursor(d->doc);
3053 if (next)
3054 d->cursor.movePosition(QTextCursor::Start);
3055 else
3056 d->cursor.movePosition(QTextCursor::End);
3057 }
3058
3059 QTextCursor newAnchor;
3060 if (findNextPrevAnchor(d->cursor, next, newAnchor)) {
3061 d->cursor = newAnchor;
3062 d->cursorIsFocusIndicator = true;
3063 } else {
3064 d->cursor.clearSelection();
3065 }
3066
3067 if (d->cursor.hasSelection()) {
3068 crect = selectionRect();
3069 emit updateRequest(crect);
3070 emit visibilityRequest(crect);
3071 return true;
3072 } else {
3073 return false;
3074 }
3075}
3076
3077bool QWidgetTextControl::setFocusToAnchor(const QTextCursor &newCursor)
3078{
3079 Q_D(QWidgetTextControl);
3080
3081 if (!(d->interactionFlags & Qt::LinksAccessibleByKeyboard))
3082 return false;
3083
3084 // Verify that this is an anchor.
3085 const QString anchorHref = d->anchorForCursor(newCursor);
3086 if (anchorHref.isEmpty())
3087 return false;
3088
3089 // and process it
3090 QRectF crect = selectionRect();
3091 emit updateRequest(crect);
3092
3093 d->cursor.setPosition(newCursor.selectionStart());
3094 d->cursor.setPosition(newCursor.selectionEnd(), QTextCursor::KeepAnchor);
3095 d->cursorIsFocusIndicator = true;
3096
3097 crect = selectionRect();
3098 emit updateRequest(crect);
3099 emit visibilityRequest(crect);
3100 return true;
3101}
3102
3103void QWidgetTextControl::setTextInteractionFlags(Qt::TextInteractionFlags flags)
3104{
3105 Q_D(QWidgetTextControl);
3106 if (flags == d->interactionFlags)
3107 return;
3108 d->interactionFlags = flags;
3109
3110 if (d->hasFocus)
3111 d->setCursorVisible(flags & Qt::TextEditable);
3112}
3113
3114Qt::TextInteractionFlags QWidgetTextControl::textInteractionFlags() const
3115{
3116 Q_D(const QWidgetTextControl);
3117 return d->interactionFlags;
3118}
3119
3120void QWidgetTextControl::mergeCurrentCharFormat(const QTextCharFormat &modifier)
3121{
3122 Q_D(QWidgetTextControl);
3123 d->cursor.mergeCharFormat(modifier);
3124 d->updateCurrentCharFormat();
3125}
3126
3127void QWidgetTextControl::setCurrentCharFormat(const QTextCharFormat &format)
3128{
3129 Q_D(QWidgetTextControl);
3130 d->cursor.setCharFormat(format);
3131 d->updateCurrentCharFormat();
3132}
3133
3134QTextCharFormat QWidgetTextControl::currentCharFormat() const
3135{
3136 Q_D(const QWidgetTextControl);
3137 return d->cursor.charFormat();
3138}
3139
3140void QWidgetTextControl::insertPlainText(const QString &text)
3141{
3142 Q_D(QWidgetTextControl);
3143 d->cursor.insertText(text);
3144}
3145
3146#ifndef QT_NO_TEXTHTMLPARSER
3147void QWidgetTextControl::insertHtml(const QString &text)
3148{
3149 Q_D(QWidgetTextControl);
3150 d->cursor.insertHtml(text);
3151}
3152#endif // QT_NO_TEXTHTMLPARSER
3153
3154QPointF QWidgetTextControl::anchorPosition(const QString &name) const
3155{
3156 Q_D(const QWidgetTextControl);
3157 if (name.isEmpty())
3158 return QPointF();
3159
3160 QRectF r;
3161 for (QTextBlock block = d->doc->begin(); block.isValid(); block = block.next()) {
3162 QTextCharFormat format = block.charFormat();
3163 if (format.isAnchor() && format.anchorNames().contains(name)) {
3164 r = d->rectForPosition(block.position());
3165 break;
3166 }
3167
3168 for (QTextBlock::Iterator it = block.begin(); !it.atEnd(); ++it) {
3169 QTextFragment fragment = it.fragment();
3170 format = fragment.charFormat();
3171 if (format.isAnchor() && format.anchorNames().contains(name)) {
3172 r = d->rectForPosition(fragment.position());
3173 block = QTextBlock();
3174 break;
3175 }
3176 }
3177 }
3178 if (!r.isValid())
3179 return QPointF();
3180 return QPointF(0, r.top());
3181}
3182
3183void QWidgetTextControl::adjustSize()
3184{
3185 Q_D(QWidgetTextControl);
3186 d->doc->adjustSize();
3187}
3188
3189bool QWidgetTextControl::find(const QString &exp, QTextDocument::FindFlags options)
3190{
3191 Q_D(QWidgetTextControl);
3192 QTextCursor search = d->doc->find(exp, d->cursor, options);
3193 if (search.isNull())
3194 return false;
3195
3196 setTextCursor(search);
3197 return true;
3198}
3199
3200#if QT_CONFIG(regularexpression)
3201bool QWidgetTextControl::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
3202{
3203 Q_D(QWidgetTextControl);
3204 QTextCursor search = d->doc->find(exp, d->cursor, options);
3205 if (search.isNull())
3206 return false;
3207
3208 setTextCursor(search);
3209 return true;
3210}
3211#endif
3212
3213QString QWidgetTextControl::toPlainText() const
3214{
3215 return document()->toPlainText();
3216}
3217
3218#ifndef QT_NO_TEXTHTMLPARSER
3219QString QWidgetTextControl::toHtml() const
3220{
3221 return document()->toHtml();
3222}
3223#endif
3224
3225#if QT_CONFIG(textmarkdownwriter)
3226QString QWidgetTextControl::toMarkdown(QTextDocument::MarkdownFeatures features) const
3227{
3228 return document()->toMarkdown(features);
3229}
3230#endif
3231
3233{
3234 // clear blockFormat properties that the user is unlikely to want duplicated:
3235 // - don't insert <hr/> automatically
3236 // - the next paragraph after a heading should be a normal paragraph
3237 // - remove the bottom margin from the last list item before appending
3238 // - the next checklist item after a checked item should be unchecked
3239 auto blockFmt = cursor.blockFormat();
3240 auto charFmt = cursor.charFormat();
3241 blockFmt.clearProperty(QTextFormat::BlockTrailingHorizontalRulerWidth);
3242 if (blockFmt.hasProperty(QTextFormat::HeadingLevel)) {
3243 blockFmt.clearProperty(QTextFormat::HeadingLevel);
3244 charFmt = QTextCharFormat();
3245 }
3246 if (cursor.currentList()) {
3247 auto existingFmt = cursor.blockFormat();
3248 existingFmt.clearProperty(QTextBlockFormat::BlockBottomMargin);
3249 cursor.setBlockFormat(existingFmt);
3250 if (blockFmt.marker() == QTextBlockFormat::MarkerType::Checked)
3251 blockFmt.setMarker(QTextBlockFormat::MarkerType::Unchecked);
3252 }
3253
3254 // After a blank line, reset block and char formats. I.e. you can end a list,
3255 // block quote, etc. by hitting enter twice, and get back to normal paragraph style.
3256 if (cursor.block().text().isEmpty() &&
3257 !cursor.blockFormat().hasProperty(QTextFormat::BlockTrailingHorizontalRulerWidth) &&
3258 !cursor.blockFormat().hasProperty(QTextFormat::BlockCodeLanguage)) {
3259 blockFmt = QTextBlockFormat();
3260 const bool blockFmtChanged = (cursor.blockFormat() != blockFmt);
3261 charFmt = QTextCharFormat();
3262 cursor.setBlockFormat(blockFmt);
3263 cursor.setCharFormat(charFmt);
3264 // If the user hit enter twice just to get back to default format,
3265 // don't actually insert a new block. But if the user then hits enter
3266 // yet again, the block format will not change, so we will insert a block.
3267 // This is what many word processors do.
3268 if (blockFmtChanged)
3269 return;
3270 }
3271
3272 cursor.insertBlock(blockFmt, charFmt);
3273}
3274
3275void QWidgetTextControlPrivate::append(const QString &text, Qt::TextFormat format)
3276{
3277 QTextCursor tmp(doc);
3278 tmp.beginEditBlock();
3279 tmp.movePosition(QTextCursor::End);
3280
3281 if (!doc->isEmpty())
3282 tmp.insertBlock(cursor.blockFormat(), cursor.charFormat());
3283 else
3284 tmp.setCharFormat(cursor.charFormat());
3285
3286 // preserve the char format
3287 QTextCharFormat oldCharFormat = cursor.charFormat();
3288
3289#ifndef QT_NO_TEXTHTMLPARSER
3290 if (format == Qt::RichText || (format == Qt::AutoText && Qt::mightBeRichText(text))) {
3291 tmp.insertHtml(text);
3292 } else {
3293 tmp.insertText(text);
3294 }
3295#else
3296 Q_UNUSED(format);
3297 tmp.insertText(text);
3298#endif // QT_NO_TEXTHTMLPARSER
3299 if (!cursor.hasSelection())
3300 cursor.setCharFormat(oldCharFormat);
3301
3302 tmp.endEditBlock();
3303}
3304
3305void QWidgetTextControl::append(const QString &text)
3306{
3307 Q_D(QWidgetTextControl);
3308 d->append(text, Qt::AutoText);
3309}
3310
3311void QWidgetTextControl::appendHtml(const QString &html)
3312{
3313 Q_D(QWidgetTextControl);
3314 d->append(html, Qt::RichText);
3315}
3316
3317void QWidgetTextControl::appendPlainText(const QString &text)
3318{
3319 Q_D(QWidgetTextControl);
3320 d->append(text, Qt::PlainText);
3321}
3322
3323
3324void QWidgetTextControl::ensureCursorVisible()
3325{
3326 Q_D(QWidgetTextControl);
3327 QRectF crect = d->rectForPosition(d->cursor.position()).adjusted(-5, 0, 5, 0);
3328 emit visibilityRequest(crect);
3329 emit microFocusChanged();
3330}
3331
3332QPalette QWidgetTextControl::palette() const
3333{
3334 Q_D(const QWidgetTextControl);
3335 return d->palette;
3336}
3337
3338void QWidgetTextControl::setPalette(const QPalette &pal)
3339{
3340 Q_D(QWidgetTextControl);
3341 d->palette = pal;
3342}
3343
3344QAbstractTextDocumentLayout::PaintContext QWidgetTextControl::getPaintContext(QWidget *widget) const
3345{
3346 Q_D(const QWidgetTextControl);
3347
3348 QAbstractTextDocumentLayout::PaintContext ctx;
3349
3350 ctx.selections = d->extraSelections;
3351 ctx.palette = d->palette;
3352#if QT_CONFIG(style_stylesheet)
3353 if (widget) {
3354 if (auto cssStyle = qt_styleSheet(widget->style())) {
3355 QStyleOption option;
3356 option.initFrom(widget);
3357 cssStyle->styleSheetPalette(widget, &option, &ctx.palette);
3358 }
3359 }
3360#endif // style_stylesheet
3361 if (d->cursorOn && d->isEnabled) {
3362 if (d->hideCursor)
3363 ctx.cursorPosition = -1;
3364 else if (d->preeditCursor != 0)
3365 ctx.cursorPosition = - (d->preeditCursor + 2);
3366 else
3367 ctx.cursorPosition = d->cursor.position();
3368 }
3369
3370 if (!d->dndFeedbackCursor.isNull())
3371 ctx.cursorPosition = d->dndFeedbackCursor.position();
3372#ifdef QT_KEYPAD_NAVIGATION
3373 if (!QApplicationPrivate::keypadNavigationEnabled() || d->hasEditFocus)
3374#endif
3375 if (d->cursor.hasSelection()) {
3376 QAbstractTextDocumentLayout::Selection selection;
3377 selection.cursor = d->cursor;
3378 if (d->cursorIsFocusIndicator) {
3379 QStyleOption opt;
3380 opt.palette = ctx.palette;
3381 QStyleHintReturnVariant ret;
3382 QStyle *style = QApplication::style();
3383 if (widget)
3384 style = widget->style();
3385 style->styleHint(QStyle::SH_TextControl_FocusIndicatorTextCharFormat, &opt, widget, &ret);
3386 selection.format = qvariant_cast<QTextFormat>(ret.variant).toCharFormat();
3387 } else {
3388 QPalette::ColorGroup cg = d->hasFocus ? QPalette::Active : QPalette::Inactive;
3389 selection.format.setBackground(ctx.palette.brush(cg, QPalette::Highlight));
3390 selection.format.setForeground(ctx.palette.brush(cg, QPalette::HighlightedText));
3391 QStyleOption opt;
3392 QStyle *style = QApplication::style();
3393 if (widget) {
3394 opt.initFrom(widget);
3395 style = widget->style();
3396 }
3397 if (style->styleHint(QStyle::SH_RichText_FullWidthSelection, &opt, widget))
3398 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
3399 }
3400 ctx.selections.append(selection);
3401 }
3402
3403 return ctx;
3404}
3405
3406void QWidgetTextControl::drawContents(QPainter *p, const QRectF &rect, QWidget *widget)
3407{
3408 Q_D(QWidgetTextControl);
3409 p->save();
3410 QAbstractTextDocumentLayout::PaintContext ctx = getPaintContext(widget);
3411 if (rect.isValid())
3412 p->setClipRect(rect, Qt::IntersectClip);
3413 ctx.clip = rect;
3414
3415 d->doc->documentLayout()->draw(p, ctx);
3416 p->restore();
3417}
3418
3420{
3421#ifndef QT_NO_CLIPBOARD
3422 QMimeData *md = new QMimeData;
3423 md->setText(linkToCopy);
3424 QGuiApplication::clipboard()->setMimeData(md);
3425#endif
3426}
3427
3428int QWidgetTextControl::hitTest(const QPointF &point, Qt::HitTestAccuracy accuracy) const
3429{
3430 Q_D(const QWidgetTextControl);
3431 return d->doc->documentLayout()->hitTest(point, accuracy);
3432}
3433
3434QRectF QWidgetTextControl::blockBoundingRect(const QTextBlock &block) const
3435{
3436 Q_D(const QWidgetTextControl);
3437 return d->doc->documentLayout()->blockBoundingRect(block);
3438}
3439
3440#ifndef QT_NO_CONTEXTMENU
3441#define NUM_CONTROL_CHARACTERS 14
3443 const char *text;
3445} qt_controlCharacters[NUM_CONTROL_CHARACTERS] = {
3446 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRM Left-to-right mark"), 0x200e },
3447 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLM Right-to-left mark"), 0x200f },
3448 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWJ Zero width joiner"), 0x200d },
3449 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWNJ Zero width non-joiner"), 0x200c },
3450 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWSP Zero width space"), 0x200b },
3451 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRE Start of left-to-right embedding"), 0x202a },
3452 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLE Start of right-to-left embedding"), 0x202b },
3453 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRO Start of left-to-right override"), 0x202d },
3454 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLO Start of right-to-left override"), 0x202e },
3455 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "PDF Pop directional formatting"), 0x202c },
3456 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRI Left-to-right isolate"), 0x2066 },
3457 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLI Right-to-left isolate"), 0x2067 },
3458 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "FSI First strong isolate"), 0x2068 },
3459 { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "PDI Pop directional isolate"), 0x2069 }
3461
3462QUnicodeControlCharacterMenu::QUnicodeControlCharacterMenu(QObject *_editWidget, QWidget *parent)
3463 : QMenu(parent), editWidget(_editWidget)
3464{
3465 setTitle(tr("Insert Unicode control character"));
3466 for (int i = 0; i < NUM_CONTROL_CHARACTERS; ++i) {
3467 addAction(tr(qt_controlCharacters[i].text), this, SLOT(menuActionTriggered()));
3468 }
3469}
3470
3471void QUnicodeControlCharacterMenu::menuActionTriggered()
3472{
3473 QAction *a = qobject_cast<QAction *>(sender());
3474 int idx = actions().indexOf(a);
3475 if (idx < 0 || idx >= NUM_CONTROL_CHARACTERS)
3476 return;
3477 QChar c(qt_controlCharacters[idx].character);
3478 QString str(c);
3479
3480#if QT_CONFIG(textedit)
3481 if (QTextEdit *edit = qobject_cast<QTextEdit *>(editWidget)) {
3482 edit->insertPlainText(str);
3483 return;
3484 }
3485#endif
3486 if (QWidgetTextControl *control = qobject_cast<QWidgetTextControl *>(editWidget)) {
3487 control->insertPlainText(str);
3488 }
3489#if QT_CONFIG(lineedit)
3490 if (QLineEdit *edit = qobject_cast<QLineEdit *>(editWidget)) {
3491 edit->insert(str);
3492 return;
3493 }
3494#endif
3495}
3496#endif // QT_NO_CONTEXTMENU
3497
3498static constexpr auto supportedMimeTypes = qOffsetStringArray(
3499 "text/plain",
3500 "text/html"
3501#if QT_CONFIG(textmarkdownwriter)
3502 , "text/markdown"
3503#endif
3504#if QT_CONFIG(textodfwriter)
3505 , "application/vnd.oasis.opendocument.text"
3506#endif
3507);
3508
3509/*! \internal
3510 \reimp
3511*/
3513{
3514 if (!fragment.isEmpty()) {
3515 constexpr auto size = supportedMimeTypes.count();
3516 QStringList ret;
3517 ret.reserve(size);
3518 for (int i = 0; i < size; ++i)
3519 ret.emplace_back(QLatin1StringView(supportedMimeTypes.at(i)));
3520
3521 return ret;
3522 }
3523
3524 return QMimeData::formats();
3525}
3526
3527/*! \internal
3528 \reimp
3529*/
3530bool QTextEditMimeData::hasFormat(const QString &format) const
3531{
3532 if (!fragment.isEmpty()) {
3533 constexpr auto size = supportedMimeTypes.count();
3534 for (int i = 0; i < size; ++i) {
3535 if (format == QLatin1StringView(supportedMimeTypes.at(i)))
3536 return true;
3537 }
3538 return false;
3539 }
3540
3541 return QMimeData::hasFormat(format);
3542}
3543
3544QVariant QTextEditMimeData::retrieveData(const QString &mimeType, QMetaType type) const
3545{
3546 if (!fragment.isEmpty())
3547 setup();
3548 return QMimeData::retrieveData(mimeType, type);
3549}
3550
3551void QTextEditMimeData::setup() const
3552{
3553 QTextEditMimeData *that = const_cast<QTextEditMimeData *>(this);
3554#ifndef QT_NO_TEXTHTMLPARSER
3555 that->setData("text/html"_L1, fragment.toHtml().toUtf8());
3556#endif
3557#if QT_CONFIG(textmarkdownwriter)
3558 that->setData("text/markdown"_L1, fragment.toMarkdown().toUtf8());
3559#endif
3560#ifndef QT_NO_TEXTODFWRITER
3561 {
3562 QBuffer buffer;
3563 QTextDocumentWriter writer(&buffer, "ODF");
3564 writer.write(fragment);
3565 buffer.close();
3566 that->setData("application/vnd.oasis.opendocument.text"_L1, buffer.data());
3567 }
3568#endif
3569 that->setText(fragment.toPlainText());
3570 fragment = QTextDocumentFragment();
3571}
3572
3573QT_END_NAMESPACE
3574
3575#include "moc_qwidgettextcontrol_p.cpp"
3576
3577#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)