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