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
qquicktextinput.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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#include "qquickwindow.h"
8
9#include <private/qqmlglobal_p.h>
10#include <private/qv4scopedvalue_p.h>
11
12#include <QtCore/qcoreapplication.h>
13#include <QtCore/qmimedata.h>
14#include <QtQml/qqmlinfo.h>
15#include <QtGui/qevent.h>
16#include <QTextBoundaryFinder>
18#include <QtQuick/qsgsimplerectnode.h>
19
20#include <QtGui/qstylehints.h>
21#include <QtGui/qinputmethod.h>
22#include <QtCore/qmath.h>
23
24#if QT_CONFIG(accessibility)
25#include "qaccessible.h"
26#include "qquickaccessibleattached_p.h"
27#endif
28
29#include <QtGui/private/qtextengine_p.h>
30#include <QtGui/private/qinputcontrol_p.h>
31
33
34DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)
35Q_STATIC_LOGGING_CATEGORY(lcQuickTextInput, "qt.quick.textInput")
36
37/*!
38 \qmltype TextInput
39 \nativetype QQuickTextInput
40 \inqmlmodule QtQuick
41 \ingroup qtquick-visual
42 \ingroup qtquick-input
43 \inherits Item
44 \brief Displays an editable line of text.
45
46 The TextInput type displays a single line of editable plain text.
47
48 TextInput is used to accept a line of text input. Input constraints
49 can be placed on a TextInput item (for example, through a \l validator or \l inputMask),
50 and setting \l echoMode to an appropriate value enables TextInput to be used for
51 a password input field.
52
53 To react to the user accepting text via the Return or Enter keys, handle
54 the \l accepted() signal. When Return or Enter are pressed and the text
55 input loses focus, \l editingFinished() will be emitted. When the text is
56 edited in any way by the user, \l textEdited() is emitted. These signals
57 \l {Property change signals}{should be preferred} over \c textChanged()
58 in most cases.
59
60 On \macos, the Up/Down key bindings for Home/End are explicitly disabled.
61 If you want such bindings (on any platform), you will need to construct them in QML.
62
63 \sa TextEdit, Text
64*/
65QQuickTextInput::QQuickTextInput(QQuickItem* parent)
66: QQuickImplicitSizeItem(*(new QQuickTextInputPrivate), parent)
67{
68 Q_D(QQuickTextInput);
69 d->init();
70}
71
72QQuickTextInput::QQuickTextInput(QQuickTextInputPrivate &dd, QQuickItem *parent)
73: QQuickImplicitSizeItem(dd, parent)
74{
75 Q_D(QQuickTextInput);
76 d->init();
77}
78
79QQuickTextInput::~QQuickTextInput()
80{
81}
82
83void QQuickTextInput::componentComplete()
84{
85 Q_D(QQuickTextInput);
86
87 QQuickImplicitSizeItem::componentComplete();
88
89 d->checkIsValid();
90 d->updateLayout();
91 updateCursorRectangle();
92 if (d->cursorComponent && isCursorVisible())
93 QQuickTextUtil::createCursor(d);
94#if QT_CONFIG(accessibility)
95 if (QAccessible::isActive())
96 d->accessibilityActiveChanged(true);
97#endif
98}
99
100/*!
101 \qmlproperty string QtQuick::TextInput::text
102
103 The text in the TextInput.
104
105 Note that some keyboards use a predictive function. In this case,
106 the text being composed by the input method is not part of this property.
107 The part of the text related to the predictions is underlined and stored in
108 the \l preeditText property. To get whole text displayed in the TextInput
109 use \l displayText property.
110
111 \sa clear(), displayText, preeditText, accepted(), editingFinished(),
112 textEdited()
113*/
114QString QQuickTextInput::text() const
115{
116 Q_D(const QQuickTextInput);
117
118 QString content = d->m_text;
119 QString res = d->m_maskData ? d->stripString(content) : content;
120 return (res.isNull() ? QString::fromLatin1("") : res);
121}
122
123void QQuickTextInput::invalidate()
124{
125 Q_D(QQuickTextInput);
126 d->updateLayout();
127 invalidateFontCaches();
128}
129
130void QQuickTextInput::setText(const QString &s)
131{
132 Q_D(QQuickTextInput);
133 if (s == text())
134 return;
135
136#if QT_CONFIG(im)
137 d->cancelPreedit();
138#endif
139 d->internalSetText(s, -1, false);
140}
141
142
143/*!
144 \qmlproperty enumeration QtQuick::TextInput::renderType
145
146 Override the default rendering type for this component.
147
148 Supported render types are:
149
150 \value TextInput.QtRendering Text is rendered using a scalable distance field for each glyph.
151 \value TextInput.NativeRendering Text is rendered using a platform-specific technique.
152 \value TextInput.CurveRendering Text is rendered using a curve rasterizer running directly on
153 the graphics hardware. (Introduced in Qt 6.7.0.)
154
155 Select \c TextInput.NativeRendering if you prefer text to look native on the target platform and do
156 not require advanced features such as transformation of the text. Using such features in
157 combination with the NativeRendering render type will lend poor and sometimes pixelated
158 results.
159
160 Both \c TextInput.QtRendering and \c TextInput.CurveRendering are hardware-accelerated techniques.
161 \c QtRendering is the faster of the two, but uses more memory and will exhibit rendering
162 artifacts at large sizes. \c CurveRendering should be considered as an alternative in cases
163 where \c QtRendering does not give good visual results or where reducing graphics memory
164 consumption is a priority.
165
166 The default rendering type is determined by \l QQuickWindow::textRenderType().
167*/
168QQuickTextInput::RenderType QQuickTextInput::renderType() const
169{
170 Q_D(const QQuickTextInput);
171 return d->renderType;
172}
173
174void QQuickTextInput::setRenderType(QQuickTextInput::RenderType renderType)
175{
176 Q_D(QQuickTextInput);
177 if (d->renderType == renderType)
178 return;
179
180 d->renderType = renderType;
181 emit renderTypeChanged();
182
183 if (isComponentComplete())
184 d->updateLayout();
185}
186
187/*!
188 \qmlproperty int QtQuick::TextInput::length
189
190 Returns the total number of characters in the TextInput item.
191
192 If the TextInput has an inputMask the length will include mask characters and may differ
193 from the length of the string returned by the \l text property.
194
195 This property can be faster than querying the length the \l text property as it doesn't
196 require any copying or conversion of the TextInput's internal string data.
197*/
198
199int QQuickTextInput::length() const
200{
201 Q_D(const QQuickTextInput);
202 return d->m_text.size();
203}
204
205/*!
206 \qmlmethod string QtQuick::TextInput::getText(int start, int end)
207
208 Returns the section of text that is between the \a start and \a end positions.
209
210 If the TextInput has an inputMask the length will include mask characters.
211*/
212
213QString QQuickTextInput::getText(int start, int end) const
214{
215 Q_D(const QQuickTextInput);
216
217 if (start > end)
218 qSwap(start, end);
219
220 return d->m_text.mid(start, end - start);
221}
222
223QString QQuickTextInputPrivate::realText() const
224{
225 QString res = m_maskData ? stripString(m_text) : m_text;
226 return (res.isNull() ? QString::fromLatin1("") : res);
227}
228
229/*!
230 \qmlproperty string QtQuick::TextInput::font.family
231
232 Sets the family name of the font.
233
234 \include qmltypereference.qdoc qml-font-family
235*/
236
237/*!
238 \qmlproperty string QtQuick::TextInput::font.styleName
239 \since 5.6
240
241 Sets the style name of the font.
242
243 The style name is case insensitive. If set, the font will be matched against style name instead
244 of the font properties \l font.weight, \l font.bold and \l font.italic.
245*/
246
247/*!
248 \qmlproperty bool QtQuick::TextInput::font.bold
249
250 Sets whether the font weight is bold.
251*/
252
253/*!
254 \qmlproperty int QtQuick::TextInput::font.weight
255
256 \include qmltypereference.qdoc qml-font-weight
257*/
258
259/*!
260 \qmlproperty bool QtQuick::TextInput::font.italic
261
262 Sets whether the font has an italic style.
263*/
264
265/*!
266 \qmlproperty bool QtQuick::TextInput::font.underline
267
268 Sets whether the text is underlined.
269*/
270
271/*!
272 \qmlproperty bool QtQuick::TextInput::font.strikeout
273
274 Sets whether the font has a strikeout style.
275*/
276
277/*!
278 \qmlproperty real QtQuick::TextInput::font.pointSize
279
280 Sets the font size in points. The point size must be greater than zero.
281*/
282
283/*!
284 \qmlproperty int QtQuick::TextInput::font.pixelSize
285
286 Sets the font size in pixels.
287
288 Using this function makes the font device dependent.
289 Use \c pointSize to set the size of the font in a device independent manner.
290*/
291
292/*!
293 \qmlproperty real QtQuick::TextInput::font.letterSpacing
294
295 Sets the letter spacing for the font.
296
297 \include qmltypereference.qdoc qml-font-letter-spacing
298*/
299
300/*!
301 \qmlproperty real QtQuick::TextInput::font.wordSpacing
302
303 Sets the word spacing for the font.
304
305 \include qmltypereference.qdoc qml-font-word-spacing
306*/
307
308/*!
309 \qmlproperty enumeration QtQuick::TextInput::font.capitalization
310
311 Sets the capitalization for the text.
312
313 \include qmltypereference.qdoc qml-font-capitalization
314*/
315
316/*!
317 \qmlproperty enumeration QtQuick::TextInput::font.hintingPreference
318 \since 5.8
319
320 Sets the preferred hinting on the text.
321
322 \include qmltypereference.qdoc qml-font-hinting-preference
323*/
324
325/*!
326 \qmlproperty bool QtQuick::TextInput::font.kerning
327 \since 5.10
328
329 \include qmltypereference.qdoc qml-font-kerning
330*/
331
332/*!
333 \qmlproperty bool QtQuick::TextInput::font.preferShaping
334 \since 5.10
335
336 \include qmltypereference.qdoc qml-font-prefer-shaping
337*/
338
339/*!
340 \qmlproperty object QtQuick::TextInput::font.variableAxes
341 \since 6.7
342
343 \include qmltypereference.qdoc qml-font-variable-axes
344*/
345
346/*!
347 \qmlproperty object QtQuick::TextInput::font.features
348 \since 6.6
349
350 \include qmltypereference.qdoc qml-font-features
351*/
352
353/*!
354 \qmlproperty bool QtQuick::TextInput::font.contextFontMerging
355 \since 6.8
356
357 \include qmltypereference.qdoc qml-font-context-font-merging
358*/
359
360/*!
361 \qmlproperty bool QtQuick::TextInput::font.preferTypoLineMetrics
362 \since 6.8
363
364 \include qmltypereference.qdoc qml-font-prefer-typo-line-metrics
365*/
366QFont QQuickTextInput::font() const
367{
368 Q_D(const QQuickTextInput);
369 return d->sourceFont;
370}
371
372void QQuickTextInput::setFont(const QFont &font)
373{
374 Q_D(QQuickTextInput);
375 if (d->sourceFont == font)
376 return;
377
378 d->sourceFont = font;
379 QFont oldFont = d->font;
380 d->font = font;
381 if (d->font.pointSizeF() != -1) {
382 // 0.5pt resolution
383 qreal size = qRound(d->font.pointSizeF()*2.0);
384 d->font.setPointSizeF(size/2.0);
385 }
386 if (oldFont != d->font) {
387 d->updateLayout();
388 updateCursorRectangle();
389#if QT_CONFIG(im)
390 updateInputMethod(Qt::ImCursorRectangle | Qt::ImFont | Qt::ImAnchorRectangle);
391#endif
392 }
393 emit fontChanged(d->sourceFont);
394}
395
396/*!
397 \qmlproperty color QtQuick::TextInput::color
398
399 The text color.
400*/
401QColor QQuickTextInput::color() const
402{
403 Q_D(const QQuickTextInput);
404 return d->color;
405}
406
407void QQuickTextInput::setColor(const QColor &c)
408{
409 Q_D(QQuickTextInput);
410 if (c != d->color) {
411 d->color = c;
412 d->textLayoutDirty = true;
413 d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
414 polish();
415 update();
416 emit colorChanged();
417 }
418}
419
420
421/*!
422 \qmlproperty color QtQuick::TextInput::selectionColor
423
424 The text highlight color, used behind selections.
425*/
426QColor QQuickTextInput::selectionColor() const
427{
428 Q_D(const QQuickTextInput);
429 return d->selectionColor;
430}
431
432void QQuickTextInput::setSelectionColor(const QColor &color)
433{
434 Q_D(QQuickTextInput);
435 if (d->selectionColor == color)
436 return;
437
438 d->selectionColor = color;
439 if (d->hasSelectedText()) {
440 d->textLayoutDirty = true;
441 d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
442 polish();
443 update();
444 }
445 emit selectionColorChanged();
446}
447/*!
448 \qmlproperty color QtQuick::TextInput::selectedTextColor
449
450 The highlighted text color, used in selections.
451*/
452QColor QQuickTextInput::selectedTextColor() const
453{
454 Q_D(const QQuickTextInput);
455 return d->selectedTextColor;
456}
457
458void QQuickTextInput::setSelectedTextColor(const QColor &color)
459{
460 Q_D(QQuickTextInput);
461 if (d->selectedTextColor == color)
462 return;
463
464 d->selectedTextColor = color;
465 if (d->hasSelectedText()) {
466 d->textLayoutDirty = true;
467 d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
468 polish();
469 update();
470 }
471 emit selectedTextColorChanged();
472}
473
474/*!
475 \qmlproperty enumeration QtQuick::TextInput::effectiveHorizontalAlignment
476 \readonly
477
478 When using the attached property LayoutMirroring::enabled to mirror application
479 layouts, the horizontal alignment of text will also be mirrored. However, the property
480 \l horizontalAlignment will remain unchanged. To query the effective horizontal alignment
481 of TextInput, use the read-only property \c effectiveHorizontalAlignment.
482*/
483/*!
484 \qmlproperty enumeration QtQuick::TextInput::horizontalAlignment
485 \qmlproperty enumeration QtQuick::TextInput::verticalAlignment
486
487 Sets the horizontal alignment of the text within the TextInput item's
488 width and height. By default, the text alignment follows the natural alignment
489 of the text, for example text that is read from left to right will be aligned to
490 the left.
491
492 TextInput does not have vertical alignment, as the natural height is
493 exactly the height of the single line of text. If you set the height
494 manually to something larger, TextInput will always be top aligned
495 vertically. You can use anchors to align it however you want within
496 another item.
497
498 The valid values for \c horizontalAlignment are \c TextInput.AlignLeft, \c TextInput.AlignRight and
499 \c TextInput.AlignHCenter.
500
501 Valid values for \c verticalAlignment are \c TextInput.AlignTop (default),
502 \c TextInput.AlignBottom \c TextInput.AlignVCenter.
503
504 When using the attached property LayoutMirroring::enabled to mirror application
505 layouts, the horizontal alignment of text will also be mirrored. However, the property
506 \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment
507 of TextInput, use the read-only property \l effectiveHorizontalAlignment.
508*/
509QQuickTextInput::HAlignment QQuickTextInput::hAlign() const
510{
511 Q_D(const QQuickTextInput);
512 return d->hAlign;
513}
514
515void QQuickTextInput::setHAlign(HAlignment align)
516{
517 Q_D(QQuickTextInput);
518
519 if (d->setHAlign(align, true) && isComponentComplete()) {
520 d->updateLayout();
521 updateCursorRectangle();
522 }
523}
524
525void QQuickTextInput::resetHAlign()
526{
527 Q_D(QQuickTextInput);
528 d->hAlignImplicit = true;
529 if (d->determineHorizontalAlignment() && isComponentComplete()) {
530 d->updateLayout();
531 updateCursorRectangle();
532 }
533}
534
535QQuickTextInput::HAlignment QQuickTextInput::effectiveHAlign() const
536{
537 Q_D(const QQuickTextInput);
538 QQuickTextInput::HAlignment effectiveAlignment = d->hAlign;
539 if (!d->hAlignImplicit && d->effectiveLayoutMirror) {
540 switch (d->hAlign) {
541 case QQuickTextInput::AlignLeft:
542 effectiveAlignment = QQuickTextInput::AlignRight;
543 break;
544 case QQuickTextInput::AlignRight:
545 effectiveAlignment = QQuickTextInput::AlignLeft;
546 break;
547 default:
548 break;
549 }
550 }
551 return effectiveAlignment;
552}
553
554bool QQuickTextInputPrivate::setHAlign(QQuickTextInput::HAlignment align, bool forceAlign)
555{
556 Q_Q(QQuickTextInput);
557 if (align > QQuickTextInput::AlignHCenter)
558 return false; // justify is not supported
559
560 if (hAlign == align && !forceAlign)
561 return false;
562
563 const bool wasImplicit = hAlignImplicit;
564 const auto oldEffectiveHAlign = q->effectiveHAlign();
565
566 hAlignImplicit = !forceAlign;
567 if (hAlign != align) {
568 hAlign = align;
569 emit q->horizontalAlignmentChanged(align);
570 }
571
572 if (q->effectiveHAlign() != oldEffectiveHAlign) {
573 emit q->effectiveHorizontalAlignmentChanged();
574 return true;
575 }
576
577 if (forceAlign && wasImplicit) {
578 // QTBUG-120052 - when horizontal text alignment is set explicitly,
579 // we need notify any other controls that may depend on it, like QQuickPlaceholderText
580 emit q->effectiveHorizontalAlignmentChanged();
581 }
582 return false;
583}
584
585Qt::LayoutDirection QQuickTextInputPrivate::textDirection() const
586{
587 QString text = m_text;
588#if QT_CONFIG(im)
589 if (text.isEmpty())
590 text = m_textLayout.preeditAreaText();
591#endif
592
593 const QChar *character = text.constData();
594 while (!character->isNull()) {
595 switch (character->direction()) {
596 case QChar::DirL:
597 return Qt::LeftToRight;
598 case QChar::DirR:
599 case QChar::DirAL:
600 case QChar::DirAN:
601 return Qt::RightToLeft;
602 default:
603 break;
604 }
605 character++;
606 }
607 return Qt::LayoutDirectionAuto;
608}
609
610Qt::LayoutDirection QQuickTextInputPrivate::layoutDirection() const
611{
612 Qt::LayoutDirection direction = m_layoutDirection;
613 if (direction == Qt::LayoutDirectionAuto) {
614 direction = textDirection();
615#if QT_CONFIG(im)
616 if (direction == Qt::LayoutDirectionAuto)
617 direction = QGuiApplication::inputMethod()->inputDirection();
618#endif
619 }
620 return (direction == Qt::LayoutDirectionAuto) ? Qt::LeftToRight : direction;
621}
622
623bool QQuickTextInputPrivate::determineHorizontalAlignment()
624{
625 if (!hAlignImplicit)
626 return false;
627
628 // if no explicit alignment has been set, follow the natural layout direction of the text
629 Qt::LayoutDirection direction = textDirection();
630#if QT_CONFIG(im)
631 if (direction == Qt::LayoutDirectionAuto)
632 direction = QGuiApplication::inputMethod()->inputDirection();
633#endif
634
635 const auto implicitHAlign = direction == Qt::RightToLeft ?
636 QQuickTextInput::AlignRight : QQuickTextInput::AlignLeft;
637 return setHAlign(implicitHAlign);
638}
639
640QQuickTextInput::VAlignment QQuickTextInput::vAlign() const
641{
642 Q_D(const QQuickTextInput);
643 return d->vAlign;
644}
645
646void QQuickTextInput::setVAlign(QQuickTextInput::VAlignment alignment)
647{
648 Q_D(QQuickTextInput);
649 if (alignment == d->vAlign)
650 return;
651 d->vAlign = alignment;
652 emit verticalAlignmentChanged(d->vAlign);
653 if (isComponentComplete()) {
654 updateCursorRectangle();
655 d->updateBaselineOffset();
656 }
657}
658
659/*!
660 \qmlproperty enumeration QtQuick::TextInput::wrapMode
661
662 Set this property to wrap the text to the TextInput item's width.
663 The text will only wrap if an explicit width has been set.
664
665 \value TextInput.NoWrap
666 (default) no wrapping will be performed. If the text contains
667 insufficient newlines, then \l contentWidth will exceed a set width.
668 \value TextInput.WordWrap
669 wrapping is done on word boundaries only. If a word is too long,
670 \l contentWidth will exceed a set width.
671 \value TextInput.WrapAnywhere
672 wrapping is done at any point on a line, even if it occurs in the middle of a word.
673 \value TextInput.Wrap
674 if possible, wrapping occurs at a word boundary; otherwise it will occur
675 at the appropriate point on the line, even in the middle of a word.
676
677 The default is TextInput.NoWrap. If you set a width, consider using TextInput.Wrap.
678*/
679QQuickTextInput::WrapMode QQuickTextInput::wrapMode() const
680{
681 Q_D(const QQuickTextInput);
682 return d->wrapMode;
683}
684
685void QQuickTextInput::setWrapMode(WrapMode mode)
686{
687 Q_D(QQuickTextInput);
688 if (mode == d->wrapMode)
689 return;
690 d->wrapMode = mode;
691 d->updateLayout();
692 updateCursorRectangle();
693 emit wrapModeChanged();
694}
695
696void QQuickTextInputPrivate::mirrorChange()
697{
698 Q_Q(QQuickTextInput);
699 if (q->isComponentComplete()) {
700 if (!hAlignImplicit && (hAlign == QQuickTextInput::AlignRight || hAlign == QQuickTextInput::AlignLeft)) {
701 q->updateCursorRectangle();
702 emit q->effectiveHorizontalAlignmentChanged();
703 }
704 }
705}
706
707/*!
708 \qmlproperty bool QtQuick::TextInput::readOnly
709
710 Sets whether user input can modify the contents of the TextInput.
711
712 If readOnly is set to true, then user input will not affect the text
713 property. Any bindings or attempts to set the text property will still
714 work.
715*/
716bool QQuickTextInput::isReadOnly() const
717{
718 Q_D(const QQuickTextInput);
719 return d->m_readOnly;
720}
721
722void QQuickTextInput::setReadOnly(bool ro)
723{
724 Q_D(QQuickTextInput);
725 if (d->m_readOnly == ro)
726 return;
727
728#if QT_CONFIG(im)
729 setFlag(QQuickItem::ItemAcceptsInputMethod, !ro);
730#endif
731 d->m_readOnly = ro;
732 d->setCursorPosition(d->end());
733#if QT_CONFIG(im)
734 updateInputMethod(Qt::ImEnabled);
735#endif
736 q_canPasteChanged();
737 d->emitUndoRedoChanged();
738 emit readOnlyChanged(ro);
739 if (ro) {
740 setCursorVisible(false);
741 } else if (hasActiveFocus()) {
742 setCursorVisible(true);
743 }
744 update();
745}
746
747/*!
748 \qmlproperty int QtQuick::TextInput::maximumLength
749 The maximum permitted length of the text in the TextInput.
750
751 If the text is too long, it is truncated at the limit.
752
753 By default, this property contains a value of 32767.
754*/
755int QQuickTextInput::maxLength() const
756{
757 Q_D(const QQuickTextInput);
758 return d->m_maxLength;
759}
760
761void QQuickTextInput::setMaxLength(int ml)
762{
763 Q_D(QQuickTextInput);
764 if (d->m_maxLength == ml || d->m_maskData)
765 return;
766
767 d->m_maxLength = ml;
768 d->internalSetText(d->m_text, -1, false);
769
770 emit maximumLengthChanged(ml);
771}
772
773/*!
774 \qmlproperty bool QtQuick::TextInput::cursorVisible
775 Set to true when the TextInput shows a cursor.
776
777 This property is set and unset when the TextInput gets active focus, so that other
778 properties can be bound to whether the cursor is currently showing. As it
779 gets set and unset automatically, when you set the value yourself you must
780 keep in mind that your value may be overwritten.
781
782 It can be set directly in script, for example if a KeyProxy might
783 forward keys to it and you desire it to look active when this happens
784 (but without actually giving it active focus).
785
786 It should not be set directly on the item, like in the below QML,
787 as the specified value will be overridden and lost on focus changes.
788
789 \code
790 TextInput {
791 text: "Text"
792 cursorVisible: false
793 }
794 \endcode
795
796 In the above snippet the cursor will still become visible when the
797 TextInput gains active focus.
798*/
799bool QQuickTextInput::isCursorVisible() const
800{
801 Q_D(const QQuickTextInput);
802 return d->cursorVisible;
803}
804
805void QQuickTextInput::setCursorVisible(bool on)
806{
807 Q_D(QQuickTextInput);
808 if (d->cursorVisible == on)
809 return;
810 d->cursorVisible = on;
811 if (on && isComponentComplete())
812 QQuickTextUtil::createCursor(d);
813 if (!d->cursorItem)
814 d->updateCursorBlinking();
815 emit cursorVisibleChanged(d->cursorVisible);
816}
817
818/*!
819 \qmlproperty int QtQuick::TextInput::cursorPosition
820 The position of the cursor in the TextInput. The cursor is positioned between
821 characters.
822
823 \note The \e characters in this case refer to the string of \l QChar objects,
824 therefore 16-bit Unicode characters, and the position is considered an index
825 into this string. This does not necessarily correspond to individual graphemes
826 in the writing system, as a single grapheme may be represented by multiple
827 Unicode characters, such as in the case of surrogate pairs, linguistic
828 ligatures or diacritics.
829
830 \l displayText is different if echoMode is set to \c {TextInput.Password}:
831 then each passwordCharacter is a "narrow" character (the cursorPosition always
832 moves by 1), even if the text in the TextInput is not.
833*/
834int QQuickTextInput::cursorPosition() const
835{
836 Q_D(const QQuickTextInput);
837 return d->m_cursor;
838}
839
840void QQuickTextInput::setCursorPosition(int cp)
841{
842 Q_D(QQuickTextInput);
843 if (cp < 0 || cp > text().size())
844 return;
845 d->moveCursor(cp);
846}
847
848/*!
849 \qmlproperty rectangle QtQuick::TextInput::cursorRectangle
850 \readonly
851
852 The rectangle where the standard text cursor is rendered within the text input. Read only.
853
854 The position and height of a custom cursorDelegate are updated to follow the cursorRectangle
855 automatically when it changes. The width of the delegate is unaffected by changes in the
856 cursor rectangle.
857*/
858
859QRectF QQuickTextInput::cursorRectangle() const
860{
861 Q_D(const QQuickTextInput);
862
863 int c = d->m_cursor;
864#if QT_CONFIG(im)
865 c += d->m_preeditCursor;
866#endif
867 if (d->m_echoMode == NoEcho)
868 c = 0;
869 QTextLine l = d->m_textLayout.lineForTextPosition(c);
870 if (!l.isValid())
871 return QRectF();
872 qreal x = l.cursorToX(c) - d->hscroll + leftPadding();
873 qreal y = l.y() - d->vscroll + topPadding();
874 qreal w = 1;
875 if (d->overwriteMode) {
876 if (c < text().size())
877 w = l.cursorToX(c + 1) - x;
878 else
879 w = QFontMetrics(font()).horizontalAdvance(QLatin1Char(' ')); // in sync with QTextLine::draw()
880 }
881 return QRectF(x, y, w, l.height());
882}
883
884/*!
885 \qmlproperty int QtQuick::TextInput::selectionStart
886
887 The cursor position before the first character in the current selection.
888
889 This property is read-only. To change the selection, use select(start,end),
890 selectAll(), or selectWord().
891
892 \readonly
893 \sa selectionEnd, cursorPosition, selectedText
894*/
895int QQuickTextInput::selectionStart() const
896{
897 Q_D(const QQuickTextInput);
898 return d->lastSelectionStart;
899}
900/*!
901 \qmlproperty int QtQuick::TextInput::selectionEnd
902
903 The cursor position after the last character in the current selection.
904
905 This property is read-only. To change the selection, use select(start,end),
906 selectAll(), or selectWord().
907
908 \readonly
909 \sa selectionStart, cursorPosition, selectedText
910*/
911int QQuickTextInput::selectionEnd() const
912{
913 Q_D(const QQuickTextInput);
914 return d->lastSelectionEnd;
915}
916/*!
917 \qmlmethod void QtQuick::TextInput::select(int start, int end)
918
919 Causes the text from \a start to \a end to be selected.
920
921 If either start or end is out of range, the selection is not changed.
922
923 After calling this, selectionStart will become the lesser
924 and selectionEnd will become the greater (regardless of the order passed
925 to this method).
926
927 \sa selectionStart, selectionEnd
928*/
929void QQuickTextInput::select(int start, int end)
930{
931 Q_D(QQuickTextInput);
932 if (start < 0 || end < 0 || start > d->m_text.size() || end > d->m_text.size())
933 return;
934 d->setSelection(start, end-start);
935}
936
937/*!
938 \qmlproperty string QtQuick::TextInput::selectedText
939 \readonly
940
941 This read-only property provides the text currently selected in the
942 text input.
943
944 It is equivalent to the following snippet, but is faster and easier
945 to use.
946
947 \qml
948 myTextInput.text.toString().substring(myTextInput.selectionStart,
949 myTextInput.selectionEnd);
950 \endqml
951*/
952QString QQuickTextInput::selectedText() const
953{
954 Q_D(const QQuickTextInput);
955 return d->selectedText();
956}
957
958/*!
959 \qmlproperty bool QtQuick::TextInput::activeFocusOnPress
960
961 Whether the TextInput should gain active focus on a mouse press. By default this is
962 set to true.
963*/
964bool QQuickTextInput::focusOnPress() const
965{
966 Q_D(const QQuickTextInput);
967 return d->focusOnPress;
968}
969
970void QQuickTextInput::setFocusOnPress(bool b)
971{
972 Q_D(QQuickTextInput);
973 if (d->focusOnPress == b)
974 return;
975
976 d->focusOnPress = b;
977
978 emit activeFocusOnPressChanged(d->focusOnPress);
979}
980/*!
981 \qmlproperty bool QtQuick::TextInput::autoScroll
982
983 Whether the TextInput should scroll when the text is longer than the width. By default this is
984 set to true.
985
986 \sa ensureVisible()
987*/
988bool QQuickTextInput::autoScroll() const
989{
990 Q_D(const QQuickTextInput);
991 return d->autoScroll;
992}
993
994void QQuickTextInput::setAutoScroll(bool b)
995{
996 Q_D(QQuickTextInput);
997 if (d->autoScroll == b)
998 return;
999
1000 d->autoScroll = b;
1001 //We need to repaint so that the scrolling is taking into account.
1002 updateCursorRectangle();
1003 emit autoScrollChanged(d->autoScroll);
1004}
1005
1006#if QT_CONFIG(validator)
1007/*!
1008 \qmlproperty Validator QtQuick::TextInput::validator
1009
1010 Allows you to set a validator on the TextInput. When a validator is set
1011 the TextInput will only accept input which leaves the text property in
1012 an acceptable or intermediate state. The accepted signal will only be sent
1013 if the text is in an acceptable state when enter is pressed.
1014
1015 Currently supported validators are IntValidator, DoubleValidator
1016 and RegularExpressionValidator. An example of using validators is shown
1017 below, which allows input of integers between 11 and 31 into the
1018 text input:
1019
1020 \code
1021 import QtQuick 2.0
1022 TextInput{
1023 validator: IntValidator{bottom: 11; top: 31;}
1024 focus: true
1025 }
1026 \endcode
1027
1028 \sa acceptableInput, inputMask
1029*/
1030
1031QValidator* QQuickTextInput::validator() const
1032{
1033 Q_D(const QQuickTextInput);
1034 return d->m_validator;
1035}
1036
1037void QQuickTextInput::setValidator(QValidator* v)
1038{
1039 Q_D(QQuickTextInput);
1040 if (d->m_validator == v)
1041 return;
1042
1043 if (d->m_validator) {
1044 qmlobject_disconnect(
1045 d->m_validator, QValidator, SIGNAL(changed()),
1046 this, QQuickTextInput, SLOT(q_validatorChanged()));
1047 }
1048
1049 d->m_validator = v;
1050
1051 if (d->m_validator) {
1052 qmlobject_connect(
1053 d->m_validator, QValidator, SIGNAL(changed()),
1054 this, QQuickTextInput, SLOT(q_validatorChanged()));
1055 }
1056
1057 if (isComponentComplete())
1058 d->checkIsValid();
1059
1060 emit validatorChanged();
1061}
1062
1063void QQuickTextInput::q_validatorChanged()
1064{
1065 Q_D(QQuickTextInput);
1066 d->checkIsValid();
1067}
1068#endif // validator
1069
1070QRectF QQuickTextInputPrivate::anchorRectangle() const
1071{
1072 Q_Q(const QQuickTextInput);
1073 QRectF rect;
1074 int a;
1075 // Unfortunately we cannot use selectionStart() and selectionEnd()
1076 // since they always assume that the selectionStart is logically before selectionEnd.
1077 // To rely on that would cause havoc if the user was interactively moving the end selection
1078 // handle to become before the start selection
1079 if (m_selstart == m_selend)
1080 // This is to handle the case when there is "no selection" while moving the handle onto the
1081 // same position as the other handle (in which case it would hide the selection handles)
1082 a = m_cursor;
1083 else
1084 a = m_selstart == m_cursor ? m_selend : m_selstart;
1085 if (a >= 0) {
1086#if QT_CONFIG(im)
1087 a += m_preeditCursor;
1088#endif
1089 if (m_echoMode == QQuickTextInput::NoEcho)
1090 a = 0;
1091 QTextLine l = m_textLayout.lineForTextPosition(a);
1092 if (l.isValid()) {
1093 qreal x = l.cursorToX(a) - hscroll + q->leftPadding();
1094 qreal y = l.y() - vscroll + q->topPadding();
1095 rect.setRect(x, y, 1, l.height());
1096 }
1097 }
1098 return rect;
1099}
1100
1101void QQuickTextInputPrivate::checkIsValid()
1102{
1103 Q_Q(QQuickTextInput);
1104
1105 ValidatorState state = hasAcceptableInput(m_text);
1106 if (!m_maskData)
1107 m_validInput = state != InvalidInput;
1108 if (state != AcceptableInput) {
1109 if (m_acceptableInput) {
1110 m_acceptableInput = false;
1111 emit q->acceptableInputChanged();
1112 }
1113 } else if (!m_acceptableInput) {
1114 m_acceptableInput = true;
1115 emit q->acceptableInputChanged();
1116 }
1117}
1118
1119/*!
1120 \qmlproperty string QtQuick::TextInput::inputMask
1121
1122 Allows you to set an input mask on the TextInput, restricting the allowable
1123 text inputs. See QLineEdit::inputMask for further details, as the exact
1124 same mask strings are used by TextInput.
1125
1126 \sa acceptableInput, validator
1127*/
1128QString QQuickTextInput::inputMask() const
1129{
1130 Q_D(const QQuickTextInput);
1131 return d->inputMask();
1132}
1133
1134void QQuickTextInput::setInputMask(const QString &im)
1135{
1136 Q_D(QQuickTextInput);
1137 QString canonicalInputMask = im;
1138 if (im.lastIndexOf(QLatin1Char(';')) == -1)
1139 canonicalInputMask.append(QLatin1String("; "));
1140 if (d->inputMask() == canonicalInputMask)
1141 return;
1142
1143 d->setInputMask(im);
1144 emit inputMaskChanged(d->inputMask());
1145}
1146
1147/*!
1148 \qmlproperty bool QtQuick::TextInput::acceptableInput
1149 \readonly
1150
1151 This property is always true unless a validator or input mask has been set.
1152 If a validator or input mask has been set, this property will only be true
1153 if the current text is acceptable to the validator or input mask as a final
1154 string (not as an intermediate string).
1155*/
1156bool QQuickTextInput::hasAcceptableInput() const
1157{
1158 Q_D(const QQuickTextInput);
1159 return d->m_acceptableInput;
1160}
1161
1162/*!
1163 \qmlsignal QtQuick::TextInput::accepted()
1164
1165 This signal is emitted when the Return or Enter key is pressed.
1166 Note that if there is a \l validator or \l inputMask set on the text
1167 input, the signal will only be emitted if the input is in an acceptable
1168 state.
1169
1170 \sa editingFinished(), textEdited()
1171*/
1172
1173/*!
1174 \qmlsignal QtQuick::TextInput::editingFinished()
1175 \since 5.2
1176
1177 This signal is emitted when the Return or Enter key is pressed or
1178 the text input loses focus. Note that if there is a validator or
1179 inputMask set on the text input and enter/return is pressed, this
1180 signal will only be emitted if the input follows
1181 the inputMask and the validator returns an acceptable state.
1182
1183 \sa accepted(), textEdited()
1184*/
1185
1186/*!
1187 \qmlsignal QtQuick::TextInput::textEdited()
1188 \since 5.9
1189
1190 This signal is emitted whenever the text is edited. Unlike \c textChanged(),
1191 this signal is not emitted when the text is changed programmatically, for example,
1192 by changing the value of the \c text property or by calling \c clear().
1193
1194 \sa accepted(), editingFinished()
1195*/
1196
1197#if QT_CONFIG(im)
1198Qt::InputMethodHints QQuickTextInputPrivate::effectiveInputMethodHints() const
1199{
1200 Qt::InputMethodHints hints = inputMethodHints;
1201 if (m_echoMode == QQuickTextInput::NoEcho)
1202 hints |= Qt::ImhHiddenText;
1203 else if (m_echoMode == QQuickTextInput::Password || m_echoMode == QQuickTextInput::PasswordEchoOnEdit)
1204 hints &= ~Qt::ImhHiddenText;
1205 if (m_echoMode != QQuickTextInput::Normal)
1206 hints |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText | Qt::ImhSensitiveData);
1207 return hints;
1208}
1209#endif
1210
1211/*!
1212 \qmlproperty enumeration QtQuick::TextInput::echoMode
1213
1214 Specifies how the text should be displayed in the TextInput.
1215
1216 \value TextInput.Normal Displays the text as it is. (Default)
1217 \value TextInput.Password Displays the \l passwordCharacter instead of the actual characters.
1218 While editing, newly entered characters are displayed in clear text
1219 for a short period specified by the \l passwordMaskDelay property.
1220 \value TextInput.NoEcho Displays nothing.
1221 \value TextInput.PasswordEchoOnEdit Content is masked as with \c TextInput.Password. During
1222 editing, newly entered characters are displayed in clear text as
1223 long as the TextInput has active focus.
1224*/
1225QQuickTextInput::EchoMode QQuickTextInput::echoMode() const
1226{
1227 Q_D(const QQuickTextInput);
1228 return QQuickTextInput::EchoMode(d->m_echoMode);
1229}
1230
1231void QQuickTextInput::setEchoMode(QQuickTextInput::EchoMode echo)
1232{
1233 Q_D(QQuickTextInput);
1234 if (echoMode() == echo)
1235 return;
1236 d->cancelPasswordEchoTimer();
1237 d->m_echoMode = echo;
1238 d->m_passwordEchoEditing = false;
1239#if QT_CONFIG(im)
1240 updateInputMethod(Qt::ImHints);
1241#endif
1242 d->updateDisplayText();
1243 updateCursorRectangle();
1244
1245 // If this control is used for password input, we want to minimize
1246 // the possibility of string reallocation not to leak (parts of)
1247 // the password.
1248 if (d->m_echoMode != QQuickTextInput::Normal)
1249 d->m_text.reserve(30);
1250
1251 emit echoModeChanged(echoMode());
1252}
1253
1254/*!
1255 \qmlproperty enumeration QtQuick::TextInput::inputMethodHints
1256
1257 Provides hints to the input method about the expected content of the text input and how it
1258 should operate.
1259
1260 The value is a bit-wise combination of flags, or Qt.ImhNone if no hints are set.
1261
1262 Flags that alter behaviour are:
1263
1264 \value Qt.ImhHiddenText Characters should be hidden, as is typically used when entering passwords.
1265
1266 Note that Android IMEs deliberately only
1267 allow Latin/ASCII character input for password fields.
1268 \value Qt.ImhSensitiveData Typed text should not be stored by the active input method
1269 in any persistent storage like predictive user dictionary.
1270
1271 Note that the Qt Framework treats this as a visible password
1272 and in this case Android IMEs deliberately only
1273 allow Latin/ASCII character input.
1274 \value Qt.ImhNoAutoUppercase The input method should not try to automatically switch to
1275 upper case when a sentence ends.
1276 \value Qt.ImhPreferNumbers Numbers are preferred (but not required).
1277 \value Qt.ImhPreferUppercase Upper case letters are preferred (but not required).
1278 \value Qt.ImhPreferLowercase Lower case letters are preferred (but not required).
1279 \value Qt.ImhNoPredictiveText Do not use predictive text (i.e. dictionary lookup) while typing.
1280 \value Qt.ImhDate The text editor functions as a date field.
1281 \value Qt.ImhTime The text editor functions as a time field.
1282
1283 Flags that restrict input (exclusive flags) are:
1284
1285 \value Qt.ImhDigitsOnly Only digits are allowed.
1286 \value Qt.ImhFormattedNumbersOnly Only number input is allowed. This includes decimal point and minus sign.
1287 \value Qt.ImhUppercaseOnly Only upper case letter input is allowed.
1288 \value Qt.ImhLowercaseOnly Only lower case letter input is allowed.
1289 \value Qt.ImhDialableCharactersOnly Only characters suitable for phone dialing are allowed.
1290 \value Qt.ImhEmailCharactersOnly Only characters suitable for email addresses are allowed.
1291 \value Qt.ImhUrlCharactersOnly Only characters suitable for URLs are allowed.
1292
1293 Masks:
1294
1295 \value Qt.ImhExclusiveInputMask This mask yields nonzero if any of the exclusive flags are used.
1296*/
1297
1298Qt::InputMethodHints QQuickTextInput::inputMethodHints() const
1299{
1300#if !QT_CONFIG(im)
1301 return Qt::ImhNone;
1302#else
1303 Q_D(const QQuickTextInput);
1304 return d->inputMethodHints;
1305#endif // im
1306}
1307
1308void QQuickTextInput::setInputMethodHints(Qt::InputMethodHints hints)
1309{
1310#if !QT_CONFIG(im)
1311 Q_UNUSED(hints);
1312#else
1313 Q_D(QQuickTextInput);
1314
1315 if (hints == d->inputMethodHints)
1316 return;
1317
1318 d->inputMethodHints = hints;
1319 updateInputMethod(Qt::ImHints);
1320 emit inputMethodHintsChanged();
1321#endif // im
1322}
1323
1324/*!
1325 \qmlproperty Component QtQuick::TextInput::cursorDelegate
1326 The delegate for the cursor in the TextInput.
1327
1328 If you set a cursorDelegate for a TextInput, this delegate will be used for
1329 drawing the cursor instead of the standard cursor. An instance of the
1330 delegate will be created and managed by the TextInput when a cursor is
1331 needed, and the x property of the delegate instance will be set so as
1332 to be one pixel before the top left of the current character.
1333
1334 Note that the root item of the delegate component must be a QQuickItem or
1335 QQuickItem derived item.
1336*/
1337QQmlComponent* QQuickTextInput::cursorDelegate() const
1338{
1339 Q_D(const QQuickTextInput);
1340 return d->cursorComponent;
1341}
1342
1343void QQuickTextInput::setCursorDelegate(QQmlComponent* c)
1344{
1345 Q_D(QQuickTextInput);
1346 QQuickTextUtil::setCursorDelegate(d, c);
1347}
1348
1349void QQuickTextInput::createCursor()
1350{
1351 Q_D(QQuickTextInput);
1352 d->cursorPending = true;
1353 QQuickTextUtil::createCursor(d);
1354}
1355
1356/*!
1357 \qmlmethod rect QtQuick::TextInput::positionToRectangle(int pos)
1358
1359 This function takes a character position \a pos and returns the rectangle
1360 that the cursor would occupy, if it was placed at that character position.
1361
1362 This is similar to setting the cursorPosition, and then querying the cursor
1363 rectangle, but the cursorPosition is not changed.
1364*/
1365QRectF QQuickTextInput::positionToRectangle(int pos) const
1366{
1367 Q_D(const QQuickTextInput);
1368 if (d->m_echoMode == NoEcho)
1369 pos = 0;
1370#if QT_CONFIG(im)
1371 else if (pos > d->m_cursor)
1372 pos += d->preeditAreaText().size();
1373#endif
1374 QTextLine l = d->m_textLayout.lineForTextPosition(pos);
1375 if (!l.isValid())
1376 return QRectF();
1377 qreal x = l.cursorToX(pos) - d->hscroll;
1378 qreal y = l.y() - d->vscroll;
1379 qreal w = 1;
1380 if (d->overwriteMode) {
1381 if (pos < text().size())
1382 w = l.cursorToX(pos + 1) - x;
1383 else
1384 w = QFontMetrics(font()).horizontalAdvance(QLatin1Char(' ')); // in sync with QTextLine::draw()
1385 }
1386 return QRectF(x, y, w, l.height());
1387}
1388
1389/*!
1390 \qmlmethod int QtQuick::TextInput::positionAt(real x, real y, CursorPosition position)
1391
1392 This function returns the character position at
1393 \a x and \a y pixels from the top left of the textInput. Position 0 is before the
1394 first character, position 1 is after the first character but before the second,
1395 and so on until position text.length, which is after all characters.
1396
1397 This means that for all x values before the first character this function returns 0,
1398 and for all x values after the last character this function returns text.length. If
1399 the y value is above the text the position will be that of the nearest character on
1400 the first line and if it is below the text the position of the nearest character
1401 on the last line will be returned.
1402
1403 The cursor \a position parameter specifies how the cursor position should be resolved:
1404
1405 \value TextInput.CursorBetweenCharacters
1406 Returns the position between characters that is nearest x.
1407 This is the default value.
1408 \value TextInput.CursorOnCharacter
1409 Returns the position before the character that is nearest x.
1410*/
1411
1412int QQuickTextInput::positionAt(qreal x, qreal y, QQuickTextInput::CursorPosition positionQuick) const
1413{
1414 Q_D(const QQuickTextInput);
1415
1416 QTextLine::CursorPosition position = QTextLine::CursorPosition(positionQuick);
1417
1418 int pos = d->positionAt(x, y, position);
1419 const int cursor = d->m_cursor;
1420 if (pos > cursor) {
1421#if QT_CONFIG(im)
1422 const int preeditLength = d->preeditAreaText().size();
1423 pos = pos > cursor + preeditLength
1424 ? pos - preeditLength
1425 : cursor;
1426#else
1427 pos = cursor;
1428#endif
1429 }
1430 return pos;
1431}
1432
1433int QQuickTextInputPrivate::positionAt(qreal x, qreal y, QTextLine::CursorPosition position) const
1434{
1435 Q_Q(const QQuickTextInput);
1436 x += hscroll - q->leftPadding();
1437 y += vscroll - q->topPadding();
1438 QTextLine line = m_textLayout.lineAt(0);
1439 for (int i = 1; i < m_textLayout.lineCount(); ++i) {
1440 QTextLine nextLine = m_textLayout.lineAt(i);
1441
1442 if (y < (line.rect().bottom() + nextLine.y()) / 2)
1443 break;
1444 line = nextLine;
1445 }
1446 return line.isValid() ? line.xToCursor(x, position) : 0;
1447}
1448
1449/*!
1450 \qmlproperty bool QtQuick::TextInput::overwriteMode
1451 \since 5.8
1452
1453 Whether text entered by the user will overwrite existing text.
1454
1455 As with many text editors, the text editor widget can be configured
1456 to insert or overwrite existing text with new text entered by the user.
1457
1458 If this property is \c true, existing text is overwritten, character-for-character
1459 by new text; otherwise, text is inserted at the cursor position, displacing
1460 existing text.
1461
1462 By default, this property is \c false (new text does not overwrite existing text).
1463*/
1464bool QQuickTextInput::overwriteMode() const
1465{
1466 Q_D(const QQuickTextInput);
1467 return d->overwriteMode;
1468}
1469
1470void QQuickTextInput::setOverwriteMode(bool overwrite)
1471{
1472 Q_D(QQuickTextInput);
1473 if (d->overwriteMode == overwrite)
1474 return;
1475 d->overwriteMode = overwrite;
1476 emit overwriteModeChanged(overwrite);
1477}
1478
1479void QQuickTextInput::keyPressEvent(QKeyEvent* ev)
1480{
1481 Q_D(QQuickTextInput);
1482 // Don't allow MacOSX up/down support, and we don't allow a completer.
1483 bool ignore = (ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) && ev->modifiers() == Qt::NoModifier;
1484 if (!ignore && (d->lastSelectionStart == d->lastSelectionEnd) && (ev->key() == Qt::Key_Right || ev->key() == Qt::Key_Left)) {
1485 // Ignore when moving off the end unless there is a selection,
1486 // because then moving will do something (deselect).
1487 int cursorPosition = d->m_cursor;
1488 if (cursorPosition == 0)
1489 ignore = ev->key() == (d->layoutDirection() == Qt::LeftToRight ? Qt::Key_Left : Qt::Key_Right);
1490 if (!ignore && cursorPosition == d->m_text.size())
1491 ignore = ev->key() == (d->layoutDirection() == Qt::LeftToRight ? Qt::Key_Right : Qt::Key_Left);
1492 }
1493 if (ignore) {
1494 ev->ignore();
1495 } else {
1496 d->processKeyEvent(ev);
1497 }
1498 if (!ev->isAccepted())
1499 QQuickImplicitSizeItem::keyPressEvent(ev);
1500}
1501
1502#if QT_CONFIG(im)
1503void QQuickTextInput::inputMethodEvent(QInputMethodEvent *ev)
1504{
1505 Q_D(QQuickTextInput);
1506 const bool wasComposing = d->hasImState;
1507 d->processInputMethodEvent(ev);
1508 if (!ev->isAccepted())
1509 QQuickImplicitSizeItem::inputMethodEvent(ev);
1510
1511 if (wasComposing != d->hasImState)
1512 emit inputMethodComposingChanged();
1513}
1514#endif
1515
1516void QQuickTextInput::mouseDoubleClickEvent(QMouseEvent *event)
1517{
1518 Q_D(QQuickTextInput);
1519
1520 if (d->selectByMouse && event->button() == Qt::LeftButton &&
1521 QQuickDeliveryAgentPrivate::isEventFromMouseOrTouchpad(event)) {
1522#if QT_CONFIG(im)
1523 d->commitPreedit();
1524#endif
1525 int cursor = d->positionAt(event->position());
1526 d->selectWordAtPos(cursor);
1527 event->setAccepted(true);
1528 if (!d->hasPendingTripleClick()) {
1529 d->tripleClickStartPoint = event->position();
1530 d->tripleClickTimer.start();
1531 }
1532 } else {
1533 if (d->sendMouseEventToInputContext(event))
1534 return;
1535 QQuickImplicitSizeItem::mouseDoubleClickEvent(event);
1536 }
1537}
1538
1539void QQuickTextInput::mousePressEvent(QMouseEvent *event)
1540{
1541 Q_D(QQuickTextInput);
1542
1543 d->pressPos = event->position();
1544
1545 if (d->sendMouseEventToInputContext(event))
1546 return;
1547
1548 d->hadSelectionOnMousePress = d->hasSelectedText();
1549
1550 const bool isMouse = QQuickDeliveryAgentPrivate::isEventFromMouseOrTouchpad(event);
1551 if (d->selectByMouse &&
1552 (isMouse
1553#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
1554 || d->selectByTouchDrag
1555#endif
1556 )) {
1557 setKeepMouseGrab(false);
1558 d->selectPressed = true;
1559 QPointF distanceVector = d->pressPos - d->tripleClickStartPoint;
1560 if (d->hasPendingTripleClick()
1561 && distanceVector.manhattanLength() < QGuiApplication::styleHints()->startDragDistance()) {
1562 event->setAccepted(true);
1563 selectAll();
1564 return;
1565 }
1566 }
1567
1568 if (isMouse
1569#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
1570 || d->selectByTouchDrag
1571#endif
1572 ) {
1573 bool mark = (event->modifiers() & Qt::ShiftModifier) && d->selectByMouse;
1574 int cursor = d->positionAt(event->position());
1575 d->moveCursor(cursor, mark);
1576 }
1577
1578 if (d->focusOnPress && !qGuiApp->styleHints()->setFocusOnTouchRelease())
1579 ensureActiveFocus(Qt::MouseFocusReason);
1580
1581 event->setAccepted(true);
1582}
1583
1584void QQuickTextInput::mouseMoveEvent(QMouseEvent *event)
1585{
1586 Q_D(QQuickTextInput);
1587 if (!QQuickDeliveryAgentPrivate::isEventFromMouseOrTouchpad(event)
1588#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
1589 && ! d->selectByTouchDrag
1590#endif
1591 )
1592 return;
1593
1594 if (d->selectPressed) {
1595 if (qAbs(int(event->position().x() - d->pressPos.x())) > QGuiApplication::styleHints()->startDragDistance())
1596 setKeepMouseGrab(true);
1597
1598#if QT_CONFIG(im)
1599 if (d->composeMode()) {
1600 // start selection
1601 int startPos = d->positionAt(d->pressPos);
1602 int currentPos = d->positionAt(event->position());
1603 if (startPos != currentPos)
1604 d->setSelection(startPos, currentPos - startPos);
1605 } else
1606#endif
1607 {
1608 moveCursorSelection(d->positionAt(event->position()), d->mouseSelectionMode);
1609 }
1610 event->setAccepted(true);
1611 } else {
1612 QQuickImplicitSizeItem::mouseMoveEvent(event);
1613 }
1614}
1615
1616void QQuickTextInput::mouseReleaseEvent(QMouseEvent *event)
1617{
1618 Q_D(QQuickTextInput);
1619 if (d->sendMouseEventToInputContext(event))
1620 return;
1621 if (d->selectPressed) {
1622 d->selectPressed = false;
1623 setKeepMouseGrab(false);
1624 }
1625 const bool isMouse = QQuickDeliveryAgentPrivate::isEventFromMouseOrTouchpad(event)
1626#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
1627 || d->selectByTouchDrag
1628#endif
1629 ;
1630
1631#if QT_CONFIG(clipboard)
1632 if (isMouse && QGuiApplication::clipboard()->supportsSelection()) {
1633 if (event->button() == Qt::LeftButton) {
1634 d->copy(QClipboard::Selection);
1635 } else if (!d->m_readOnly && event->button() == Qt::MiddleButton) {
1636 d->deselect();
1637 d->insert(QGuiApplication::clipboard()->text(QClipboard::Selection));
1638 }
1639 }
1640#endif
1641
1642 // On a touchscreen or with a stylus, set cursor position and focus on release, not on press;
1643 // if Flickable steals the grab in the meantime, the cursor won't move.
1644 // Check d->hasSelectedText() to keep touch-and-hold word selection working.
1645 // But if text was selected already on press, deselect it on release.
1646 if (!isMouse && (!d->hasSelectedText() || d->hadSelectionOnMousePress))
1647 d->moveCursor(d->positionAt(event->position()), false);
1648 // On Android, after doing a long-press to start selection, we see a release event,
1649 // even though there was no press event. So reset hadSelectionOnMousePress to avoid
1650 // it getting stuck in true state.
1651 d->hadSelectionOnMousePress = false;
1652
1653 if (d->focusOnPress && qGuiApp->styleHints()->setFocusOnTouchRelease())
1654 ensureActiveFocus(Qt::MouseFocusReason);
1655
1656 if (!event->isAccepted())
1657 QQuickImplicitSizeItem::mouseReleaseEvent(event);
1658}
1659
1660#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
1661bool QQuickTextInputPrivate::handleContextMenuEvent(QContextMenuEvent *event)
1662#else
1663bool QQuickTextInput::contextMenuEvent(QContextMenuEvent *event)
1664#endif
1665{
1666 Q_Q(QQuickTextInput);
1667 const QPoint pos = event->reason() == QContextMenuEvent::Keyboard
1668 ? q->cursorRectangle().center().toPoint() : event->pos();
1669 QContextMenuEvent mapped(event->reason(), pos, event->globalPos(),
1670 event->modifiers());
1671 const bool eventProcessed = QQuickItemPrivate::handleContextMenuEvent(&mapped);
1672 event->setAccepted(mapped.isAccepted());
1673 return eventProcessed;
1674}
1675
1676bool QQuickTextInputPrivate::sendMouseEventToInputContext(QMouseEvent *event)
1677{
1678#if QT_CONFIG(im)
1679 if (composeMode()) {
1680 int tmp_cursor = positionAt(event->position());
1681 int mousePos = tmp_cursor - m_cursor;
1682 if (mousePos >= 0 && mousePos <= m_textLayout.preeditAreaText().size()) {
1683 if (event->type() == QEvent::MouseButtonRelease) {
1684 QGuiApplication::inputMethod()->invokeAction(QInputMethod::Click, mousePos);
1685 }
1686 return true;
1687 }
1688 }
1689#else
1690 Q_UNUSED(event);
1691#endif
1692
1693 return false;
1694}
1695
1696void QQuickTextInput::mouseUngrabEvent()
1697{
1698 Q_D(QQuickTextInput);
1699 d->selectPressed = false;
1700 setKeepMouseGrab(false);
1701}
1702
1703bool QQuickTextInput::event(QEvent* ev)
1704{
1705#if QT_CONFIG(shortcut)
1706 Q_D(QQuickTextInput);
1707 if (ev->type() == QEvent::ShortcutOverride) {
1708 if (d->m_readOnly) {
1709 ev->ignore();
1710 return false;
1711 }
1712 QKeyEvent* ke = static_cast<QKeyEvent*>(ev);
1713 if (ke == QKeySequence::Copy
1714 || ke == QKeySequence::Paste
1715 || ke == QKeySequence::Cut
1716 || ke == QKeySequence::Redo
1717 || ke == QKeySequence::Undo
1718 || ke == QKeySequence::MoveToNextWord
1719 || ke == QKeySequence::MoveToPreviousWord
1720 || ke == QKeySequence::MoveToStartOfDocument
1721 || ke == QKeySequence::MoveToEndOfDocument
1722 || ke == QKeySequence::SelectNextWord
1723 || ke == QKeySequence::SelectPreviousWord
1724 || ke == QKeySequence::SelectStartOfLine
1725 || ke == QKeySequence::SelectEndOfLine
1726 || ke == QKeySequence::SelectStartOfBlock
1727 || ke == QKeySequence::SelectEndOfBlock
1728 || ke == QKeySequence::SelectStartOfDocument
1729 || ke == QKeySequence::SelectAll
1730 || ke == QKeySequence::SelectEndOfDocument
1731 || ke == QKeySequence::DeleteCompleteLine) {
1732 ke->accept();
1733 return true;
1734 } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier
1735 || ke->modifiers() == Qt::KeypadModifier) {
1736 if (ke->key() < Qt::Key_Escape) {
1737 ke->accept();
1738 return true;
1739 } else {
1740 switch (ke->key()) {
1741 case Qt::Key_Delete:
1742 case Qt::Key_Home:
1743 case Qt::Key_End:
1744 case Qt::Key_Backspace:
1745 case Qt::Key_Left:
1746 case Qt::Key_Right:
1747 ke->accept();
1748 return true;
1749 default:
1750 break;
1751 }
1752 }
1753 }
1754 ev->ignore();
1755 }
1756#endif
1757
1758 return QQuickImplicitSizeItem::event(ev);
1759}
1760
1761void QQuickTextInput::geometryChange(const QRectF &newGeometry,
1762 const QRectF &oldGeometry)
1763{
1764 Q_D(QQuickTextInput);
1765 if (!d->inLayout) {
1766 if (newGeometry.width() != oldGeometry.width())
1767 d->updateLayout();
1768 else if (newGeometry.height() != oldGeometry.height() && d->vAlign != QQuickTextInput::AlignTop)
1769 d->updateBaselineOffset();
1770 updateCursorRectangle();
1771 }
1772 QQuickImplicitSizeItem::geometryChange(newGeometry, oldGeometry);
1773}
1774
1775void QQuickTextInput::itemChange(ItemChange change, const ItemChangeData &value)
1776{
1777 Q_D(QQuickTextInput);
1778 Q_UNUSED(value);
1779 switch (change) {
1780 case ItemDevicePixelRatioHasChanged:
1781 if (d->containsUnscalableGlyphs) {
1782 // Native rendering optimizes for a given pixel grid, so its results must not be scaled.
1783 // Text layout code respects the current device pixel ratio automatically, we only need
1784 // to rerun layout after the ratio changed.
1785 d->updateLayout();
1786 }
1787 break;
1788
1789 default:
1790 break;
1791 }
1792 QQuickImplicitSizeItem::itemChange(change, value);
1793}
1794
1795void QQuickTextInputPrivate::ensureVisible(int position, int preeditCursor, int preeditLength)
1796{
1797 Q_Q(QQuickTextInput);
1798 QTextLine textLine = m_textLayout.lineForTextPosition(position + preeditCursor);
1799 const qreal width = qMax<qreal>(0, q->width() - q->leftPadding() - q->rightPadding());
1800 qreal cix = 0;
1801 qreal widthUsed = 0;
1802 if (textLine.isValid()) {
1803 cix = textLine.cursorToX(position + preeditLength);
1804 const qreal cursorWidth = cix >= 0 ? cix : width - cix;
1805 widthUsed = qMax(textLine.naturalTextWidth(), cursorWidth);
1806 }
1807 int previousScroll = hscroll;
1808
1809 if (widthUsed <= width) {
1810 hscroll = 0;
1811 } else {
1812 Q_ASSERT(textLine.isValid());
1813 if (cix - hscroll >= width) {
1814 // text doesn't fit, cursor is to the right of br (scroll right)
1815 hscroll = cix - width;
1816 } else if (cix - hscroll < 0 && hscroll < widthUsed) {
1817 // text doesn't fit, cursor is to the left of br (scroll left)
1818 hscroll = cix;
1819 } else if (widthUsed - hscroll < width) {
1820 // text doesn't fit, text document is to the left of br; align
1821 // right
1822 hscroll = widthUsed - width;
1823 } else if (width - hscroll > widthUsed) {
1824 // text doesn't fit, text document is to the right of br; align
1825 // left
1826 hscroll = width - widthUsed;
1827 }
1828#if QT_CONFIG(im)
1829 if (preeditLength > 0) {
1830 // check to ensure long pre-edit text doesn't push the cursor
1831 // off to the left
1832 cix = textLine.cursorToX(position + qMax(0, preeditCursor - 1));
1833 if (cix < hscroll)
1834 hscroll = cix;
1835 }
1836#endif
1837 }
1838 if (previousScroll != hscroll)
1839 textLayoutDirty = true;
1840}
1841
1842void QQuickTextInputPrivate::updateHorizontalScroll()
1843{
1844 if (autoScroll && m_echoMode != QQuickTextInput::NoEcho) {
1845#if QT_CONFIG(im)
1846 const int preeditLength = m_textLayout.preeditAreaText().size();
1847 ensureVisible(m_cursor, m_preeditCursor, preeditLength);
1848#else
1849 ensureVisible(m_cursor);
1850#endif
1851 } else {
1852 hscroll = 0;
1853 }
1854}
1855
1856void QQuickTextInputPrivate::updateVerticalScroll()
1857{
1858 Q_Q(QQuickTextInput);
1859#if QT_CONFIG(im)
1860 const int preeditLength = m_textLayout.preeditAreaText().size();
1861#endif
1862 const qreal height = qMax<qreal>(0, q->height() - q->topPadding() - q->bottomPadding());
1863 qreal heightUsed = contentSize.height();
1864 qreal previousScroll = vscroll;
1865
1866 if (!autoScroll || heightUsed <= height) {
1867 // text fits in br; use vscroll for alignment
1868 vscroll = -QQuickTextUtil::alignedY(
1869 heightUsed, height, vAlign & ~(Qt::AlignAbsolute|Qt::AlignHorizontal_Mask));
1870 } else {
1871#if QT_CONFIG(im)
1872 QTextLine currentLine = m_textLayout.lineForTextPosition(m_cursor + preeditLength);
1873#else
1874 QTextLine currentLine = m_textLayout.lineForTextPosition(m_cursor);
1875#endif
1876 QRectF r = currentLine.isValid() ? currentLine.rect() : QRectF();
1877 qreal top = r.top();
1878 int bottom = r.bottom();
1879
1880 if (bottom - vscroll >= height) {
1881 // text doesn't fit, cursor is to the below the br (scroll down)
1882 vscroll = bottom - height;
1883 } else if (top - vscroll < 0 && vscroll < heightUsed) {
1884 // text doesn't fit, cursor is above br (scroll up)
1885 vscroll = top;
1886 } else if (heightUsed - vscroll < height) {
1887 // text doesn't fit, text document is to the left of br; align
1888 // right
1889 vscroll = heightUsed - height;
1890 }
1891#if QT_CONFIG(im)
1892 if (preeditLength > 0) {
1893 // check to ensure long pre-edit text doesn't push the cursor
1894 // off the top
1895 currentLine = m_textLayout.lineForTextPosition(m_cursor + qMax(0, m_preeditCursor - 1));
1896 top = currentLine.isValid() ? currentLine.rect().top() : 0;
1897 if (top < vscroll)
1898 vscroll = top;
1899 }
1900#endif
1901 }
1902 if (previousScroll != vscroll)
1903 textLayoutDirty = true;
1904}
1905
1906void QQuickTextInput::triggerPreprocess()
1907{
1908 Q_D(QQuickTextInput);
1909 if (d->updateType == QQuickTextInputPrivate::UpdateNone)
1910 d->updateType = QQuickTextInputPrivate::UpdateOnlyPreprocess;
1911 polish();
1912 update();
1913}
1914
1915void QQuickTextInput::updatePolish()
1916{
1917 invalidateFontCaches();
1918}
1919
1920void QQuickTextInput::invalidateFontCaches()
1921{
1922 Q_D(QQuickTextInput);
1923
1924 if (d->m_textLayout.engine() != nullptr)
1925 d->m_textLayout.engine()->resetFontEngineCache();
1926}
1927
1928void QQuickTextInput::ensureActiveFocus(Qt::FocusReason reason)
1929{
1930 bool hadActiveFocus = hasActiveFocus();
1931 forceActiveFocus(reason);
1932#if QT_CONFIG(im)
1933 Q_D(QQuickTextInput);
1934 // re-open input panel on press if already focused
1935 if (hasActiveFocus() && hadActiveFocus && !d->m_readOnly)
1936 qGuiApp->inputMethod()->show();
1937#else
1938 Q_UNUSED(hadActiveFocus);
1939#endif
1940}
1941
1942QSGNode *QQuickTextInput::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
1943{
1944 Q_UNUSED(data);
1945 Q_D(QQuickTextInput);
1946
1947 if (d->updateType != QQuickTextInputPrivate::UpdatePaintNode && oldNode != nullptr) {
1948 // Update done in preprocess() in the nodes
1949 d->updateType = QQuickTextInputPrivate::UpdateNone;
1950 return oldNode;
1951 }
1952
1953 d->updateType = QQuickTextInputPrivate::UpdateNone;
1954
1955 QSGInternalTextNode *node = static_cast<QSGInternalTextNode *>(oldNode);
1956 if (node == nullptr)
1957 node = d->sceneGraphContext()->createInternalTextNode(d->sceneGraphRenderContext());
1958 d->textNode = node;
1959
1960 const bool showCursor = !isReadOnly() && d->cursorItem == nullptr && d->cursorVisible && d->m_blinkStatus;
1961
1962 if (!d->textLayoutDirty && oldNode != nullptr) {
1963 if (showCursor)
1964 node->setCursor(cursorRectangle(), d->color, nullptr);
1965 else
1966 node->clearCursor();
1967 } else {
1968 node->setRenderType(QSGTextNode::RenderType(d->renderType));
1969
1970 QSGInternalTextNode::RecycleBin recycleBin;
1971 node->recycle(&recycleBin);
1972 node->setMatrix(QMatrix4x4());
1973 node->setTextStyle(QSGInternalTextNode::Normal);
1974 node->setColor(d->color);
1975 node->setSelectionTextColor(d->selectedTextColor);
1976 node->setSelectionColor(d->selectionColor);
1977 node->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest);
1978
1979 if (flags().testFlag(ItemObservesViewport))
1980 node->setViewport(clipRect());
1981 else
1982 node->setViewport(QRectF{});
1983
1984 QPointF offset(leftPadding(), topPadding());
1985 offset -= QPointF(d->hscroll, d->vscroll);
1986
1987 if (!d->m_textLayout.text().isEmpty()
1988#if QT_CONFIG(im)
1989 || !d->m_textLayout.preeditAreaText().isEmpty()
1990#endif
1991 ) {
1992 node->addTextLayout(offset,
1993 &d->m_textLayout,
1994 &recycleBin,
1995 d->selectionStart(),
1996 d->selectionEnd() - 1); // selectionEnd() returns first char after
1997 // selection
1998 }
1999
2000 if (showCursor)
2001 node->setCursor(cursorRectangle(), d->color, &recycleBin);
2002 node->discardUnusedNodes(&recycleBin);
2003
2004 d->textLayoutDirty = false;
2005 }
2006
2007 d->containsUnscalableGlyphs = node->containsUnscalableGlyphs();
2008
2009 invalidateFontCaches();
2010
2011 return node;
2012}
2013
2014#if QT_CONFIG(im)
2015QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property) const
2016{
2017#ifdef Q_OS_ANDROID
2018 // QTBUG-61652
2019 if (property == Qt::ImEnterKeyType) {
2020 Q_D(const QQuickItem);
2021 // Do not change if type was set manually
2022 if (!d->extra.isAllocated()
2023 || d->extra->enterKeyAttached == nullptr
2024 || d->extra->enterKeyAttached->type() == Qt::EnterKeyDefault) {
2025
2026 QQuickItem *next = const_cast<QQuickTextInput*>(this)->nextItemInFocusChain();
2027 QQuickItem *originalNext = next;
2028 while (next && next != this && !next->activeFocusOnTab()) {
2029 next = next->nextItemInFocusChain();
2030 if (next == originalNext) {
2031 // There seems to be no suitable element in the focus chain
2032 next = nullptr;
2033 }
2034 }
2035 if (next) {
2036 const auto nextYPos = next->mapToGlobal(QPoint(0, 0)).y();
2037 const auto currentYPos = this->mapToGlobal(QPoint(0, 0)).y();
2038 if (currentYPos < nextYPos)
2039 // Set EnterKey to KeyNext type only if the next item
2040 // in the focus chain is below current QQuickTextInput
2041 return Qt::EnterKeyNext;
2042 }
2043 }
2044 }
2045#endif
2046 return inputMethodQuery(property, QVariant());
2047}
2048
2049QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property, const QVariant &argument) const
2050{
2051 Q_D(const QQuickTextInput);
2052 switch (property) {
2053 case Qt::ImEnabled:
2054 return QVariant((bool)(flags() & ItemAcceptsInputMethod));
2055 case Qt::ImHints:
2056 return QVariant((int) d->effectiveInputMethodHints());
2057 case Qt::ImCursorRectangle:
2058 return cursorRectangle();
2059 case Qt::ImAnchorRectangle:
2060 return d->anchorRectangle();
2061 case Qt::ImFont:
2062 return font();
2063 case Qt::ImCursorPosition: {
2064 const QPointF pt = argument.toPointF();
2065 if (!pt.isNull())
2066 return QVariant(d->positionAt(pt));
2067 return QVariant(d->m_cursor);
2068 }
2069 case Qt::ImSurroundingText:
2070 if (d->m_echoMode == PasswordEchoOnEdit && !d->m_passwordEchoEditing) {
2071 return QVariant(displayText());
2072 } else {
2073 return QVariant(d->realText());
2074 }
2075 case Qt::ImCurrentSelection:
2076 return QVariant(selectedText());
2077 case Qt::ImMaximumTextLength:
2078 return QVariant(maxLength());
2079 case Qt::ImAnchorPosition:
2080 if (d->selectionStart() == d->selectionEnd())
2081 return QVariant(d->m_cursor);
2082 else if (d->selectionStart() == d->m_cursor)
2083 return QVariant(d->selectionEnd());
2084 else
2085 return QVariant(d->selectionStart());
2086 case Qt::ImAbsolutePosition:
2087 return QVariant(d->m_cursor);
2088 case Qt::ImTextAfterCursor:
2089 if (argument.isValid())
2090 return QVariant(d->m_text.mid(d->m_cursor, argument.toInt()));
2091 return QVariant(d->m_text.mid(d->m_cursor));
2092 case Qt::ImTextBeforeCursor:
2093 if (argument.isValid())
2094 return QVariant(QStringView{d->m_text}.left(d->m_cursor).right(argument.toInt()).toString());
2095 return QVariant(d->m_text.left(d->m_cursor));
2096 case Qt::ImReadOnly:
2097 return QVariant(d->m_readOnly);
2098 default:
2099 return QQuickItem::inputMethodQuery(property);
2100 }
2101}
2102#endif // im
2103
2104/*!
2105 \qmlmethod void QtQuick::TextInput::deselect()
2106
2107 Removes active text selection.
2108*/
2109void QQuickTextInput::deselect()
2110{
2111 Q_D(QQuickTextInput);
2112 d->deselect();
2113}
2114
2115/*!
2116 \qmlmethod void QtQuick::TextInput::selectAll()
2117
2118 Causes all text to be selected.
2119*/
2120void QQuickTextInput::selectAll()
2121{
2122 Q_D(QQuickTextInput);
2123 d->setSelection(0, text().size());
2124}
2125
2126/*!
2127 \qmlmethod bool QtQuick::TextInput::isRightToLeft(int start, int end)
2128
2129 Returns \c true if the natural reading direction of the editor text
2130 found between positions \a start and \a end is right to left.
2131*/
2132bool QQuickTextInput::isRightToLeft(int start, int end)
2133{
2134 if (start > end) {
2135 qmlWarning(this) << "isRightToLeft(start, end) called with the end property being smaller than the start.";
2136 return false;
2137 } else {
2138 return QStringView{text()}.mid(start, end - start).isRightToLeft();
2139 }
2140}
2141
2142#if QT_CONFIG(clipboard)
2143/*!
2144 \qmlmethod void QtQuick::TextInput::cut()
2145
2146 Moves the currently selected text to the system clipboard.
2147
2148 \note If the echo mode is set to a mode other than Normal then cut
2149 will not work. This is to prevent using cut as a method of bypassing
2150 password features of the line control.
2151*/
2152void QQuickTextInput::cut()
2153{
2154 Q_D(QQuickTextInput);
2155 if (!d->m_readOnly && d->m_echoMode == QQuickTextInput::Normal) {
2156 d->copy();
2157 d->del();
2158 }
2159}
2160
2161/*!
2162 \qmlmethod void QtQuick::TextInput::copy()
2163
2164 Copies the currently selected text to the system clipboard.
2165
2166 \note If the echo mode is set to a mode other than Normal then copy
2167 will not work. This is to prevent using copy as a method of bypassing
2168 password features of the line control.
2169*/
2170void QQuickTextInput::copy()
2171{
2172 Q_D(QQuickTextInput);
2173 d->copy();
2174}
2175
2176/*!
2177 \qmlmethod void QtQuick::TextInput::paste()
2178
2179 Replaces the currently selected text by the contents of the system clipboard.
2180*/
2181void QQuickTextInput::paste()
2182{
2183 Q_D(QQuickTextInput);
2184 if (!d->m_readOnly)
2185 d->paste();
2186}
2187#endif // clipboard
2188
2189/*!
2190 \qmlmethod void QtQuick::TextInput::undo()
2191
2192 Undoes the last operation if undo is \l {canUndo}{available}. Deselects any
2193 current selection, and updates the selection start to the current cursor
2194 position.
2195*/
2196
2197void QQuickTextInput::undo()
2198{
2199 Q_D(QQuickTextInput);
2200 if (!d->m_readOnly) {
2201 d->cancelInput();
2202 d->internalUndo();
2203 d->finishChange(-1, true);
2204 }
2205}
2206
2207/*!
2208 \qmlmethod void QtQuick::TextInput::redo()
2209
2210 Redoes the last operation if redo is \l {canRedo}{available}.
2211*/
2212
2213void QQuickTextInput::redo()
2214{
2215 Q_D(QQuickTextInput);
2216 if (!d->m_readOnly) {
2217 d->cancelInput();
2218 d->internalRedo();
2219 d->finishChange();
2220 }
2221}
2222
2223/*!
2224 \qmlmethod void QtQuick::TextInput::insert(int position, string text)
2225
2226 Inserts \a text into the TextInput at \a position.
2227*/
2228
2229void QQuickTextInput::insert(int position, const QString &text)
2230{
2231 Q_D(QQuickTextInput);
2232 if (d->m_echoMode == QQuickTextInput::Password) {
2233 if (d->m_passwordMaskDelay > 0)
2234 d->m_passwordEchoTimer.start(d->m_passwordMaskDelay, this);
2235 }
2236 if (position < 0 || position > d->m_text.size())
2237 return;
2238
2239 const int priorState = d->m_undoState;
2240
2241 QString insertText = text;
2242
2243 if (d->hasSelectedText()) {
2244 d->addCommand(QQuickTextInputPrivate::Command(
2245 QQuickTextInputPrivate::SetSelection, d->m_cursor, u'\0', d->m_selstart, d->m_selend));
2246 }
2247 if (d->m_maskData) {
2248 insertText = d->maskString(position, insertText);
2249 for (int i = 0; i < insertText.size(); ++i) {
2250 d->addCommand(QQuickTextInputPrivate::Command(
2251 QQuickTextInputPrivate::DeleteSelection, position + i, d->m_text.at(position + i), -1, -1));
2252 d->addCommand(QQuickTextInputPrivate::Command(
2253 QQuickTextInputPrivate::Insert, position + i, insertText.at(i), -1, -1));
2254 }
2255 d->m_text.replace(position, insertText.size(), insertText);
2256 if (!insertText.isEmpty())
2257 d->m_textDirty = true;
2258 if (position < d->m_selend && position + insertText.size() > d->m_selstart)
2259 d->m_selDirty = true;
2260 } else {
2261 int remaining = d->m_maxLength - d->m_text.size();
2262 if (remaining != 0) {
2263 insertText = insertText.left(remaining);
2264 d->m_text.insert(position, insertText);
2265 for (int i = 0; i < insertText.size(); ++i)
2266 d->addCommand(QQuickTextInputPrivate::Command(
2267 QQuickTextInputPrivate::Insert, position + i, insertText.at(i), -1, -1));
2268 if (d->m_cursor >= position)
2269 d->m_cursor += insertText.size();
2270 if (d->m_selstart >= position)
2271 d->m_selstart += insertText.size();
2272 if (d->m_selend >= position)
2273 d->m_selend += insertText.size();
2274 d->m_textDirty = true;
2275 if (position >= d->m_selstart && position <= d->m_selend)
2276 d->m_selDirty = true;
2277 }
2278 }
2279
2280 d->addCommand(QQuickTextInputPrivate::Command(
2281 QQuickTextInputPrivate::SetSelection, d->m_cursor, u'\0', d->m_selstart, d->m_selend));
2282 d->finishChange(priorState);
2283
2284 if (d->lastSelectionStart != d->lastSelectionEnd) {
2285 if (d->m_selstart != d->lastSelectionStart) {
2286 d->lastSelectionStart = d->m_selstart;
2287 emit selectionStartChanged();
2288 }
2289 if (d->m_selend != d->lastSelectionEnd) {
2290 d->lastSelectionEnd = d->m_selend;
2291 emit selectionEndChanged();
2292 }
2293 }
2294}
2295
2296/*!
2297 \qmlmethod void QtQuick::TextInput::remove(int start, int end)
2298
2299 Removes the section of text that is between the \a start and \a end positions from the TextInput.
2300*/
2301
2302void QQuickTextInput::remove(int start, int end)
2303{
2304 Q_D(QQuickTextInput);
2305
2306 start = qBound(0, start, d->m_text.size());
2307 end = qBound(0, end, d->m_text.size());
2308
2309 if (start > end)
2310 qSwap(start, end);
2311 else if (start == end)
2312 return;
2313
2314 if (start < d->m_selend && end > d->m_selstart)
2315 d->m_selDirty = true;
2316
2317 const int priorState = d->m_undoState;
2318
2319 d->addCommand(QQuickTextInputPrivate::Command(
2320 QQuickTextInputPrivate::SetSelection, d->m_cursor, u'\0', d->m_selstart, d->m_selend));
2321
2322 if (start <= d->m_cursor && d->m_cursor < end) {
2323 // cursor is within the selection. Split up the commands
2324 // to be able to restore the correct cursor position
2325 for (int i = d->m_cursor; i >= start; --i) {
2326 d->addCommand(QQuickTextInputPrivate::Command(
2327 QQuickTextInputPrivate::DeleteSelection, i, d->m_text.at(i), -1, 1));
2328 }
2329 for (int i = end - 1; i > d->m_cursor; --i) {
2330 d->addCommand(QQuickTextInputPrivate::Command(
2331 QQuickTextInputPrivate::DeleteSelection, i - d->m_cursor + start - 1, d->m_text.at(i), -1, -1));
2332 }
2333 } else {
2334 for (int i = end - 1; i >= start; --i) {
2335 d->addCommand(QQuickTextInputPrivate::Command(
2336 QQuickTextInputPrivate::RemoveSelection, i, d->m_text.at(i), -1, -1));
2337 }
2338 }
2339 if (d->m_maskData) {
2340 d->m_text.replace(start, end - start, d->clearString(start, end - start));
2341 for (int i = 0; i < end - start; ++i) {
2342 d->addCommand(QQuickTextInputPrivate::Command(
2343 QQuickTextInputPrivate::Insert, start + i, d->m_text.at(start + i), -1, -1));
2344 }
2345 } else {
2346 d->m_text.remove(start, end - start);
2347
2348 if (d->m_cursor > start)
2349 d->m_cursor -= qMin(d->m_cursor, end) - start;
2350 if (d->m_selstart > start)
2351 d->m_selstart -= qMin(d->m_selstart, end) - start;
2352 if (d->m_selend >= end)
2353 d->m_selend -= end - start;
2354 }
2355 d->addCommand(QQuickTextInputPrivate::Command(
2356 QQuickTextInputPrivate::SetSelection, d->m_cursor, u'\0', d->m_selstart, d->m_selend));
2357
2358 d->m_textDirty = true;
2359 d->finishChange(priorState);
2360
2361 if (d->lastSelectionStart != d->lastSelectionEnd) {
2362 if (d->m_selstart != d->lastSelectionStart) {
2363 d->lastSelectionStart = d->m_selstart;
2364 emit selectionStartChanged();
2365 }
2366 if (d->m_selend != d->lastSelectionEnd) {
2367 d->lastSelectionEnd = d->m_selend;
2368 emit selectionEndChanged();
2369 }
2370 }
2371}
2372
2373
2374/*!
2375 \qmlmethod void QtQuick::TextInput::selectWord()
2376
2377 Causes the word closest to the current cursor position to be selected.
2378*/
2379void QQuickTextInput::selectWord()
2380{
2381 Q_D(QQuickTextInput);
2382 d->selectWordAtPos(d->m_cursor);
2383}
2384
2385/*!
2386 \qmlproperty string QtQuick::TextInput::passwordCharacter
2387
2388 This is the character displayed when echoMode is set to Password or
2389 PasswordEchoOnEdit. By default it is the password character used by
2390 the platform theme.
2391
2392 If this property is set to a string with more than one character,
2393 the first character is used. If the string is empty, the value
2394 is ignored and the property is not set.
2395*/
2396QString QQuickTextInput::passwordCharacter() const
2397{
2398 Q_D(const QQuickTextInput);
2399 return QString(d->m_passwordCharacter);
2400}
2401
2402void QQuickTextInput::setPasswordCharacter(const QString &str)
2403{
2404 Q_D(QQuickTextInput);
2405 if (str.size() < 1)
2406 return;
2407 d->m_passwordCharacter = str.constData()[0];
2408 if (d->m_echoMode == Password || d->m_echoMode == PasswordEchoOnEdit)
2409 d->updateDisplayText();
2410 emit passwordCharacterChanged();
2411}
2412
2413/*!
2414 \qmlproperty int QtQuick::TextInput::passwordMaskDelay
2415 \since 5.4
2416
2417 Sets the delay before visible character is masked with password character, in milliseconds.
2418
2419 The reset method will be called by assigning undefined.
2420*/
2421int QQuickTextInput::passwordMaskDelay() const
2422{
2423 Q_D(const QQuickTextInput);
2424 return d->m_passwordMaskDelay;
2425}
2426
2427void QQuickTextInput::setPasswordMaskDelay(int delay)
2428{
2429 Q_D(QQuickTextInput);
2430 if (d->m_passwordMaskDelay != delay) {
2431 d->m_passwordMaskDelay = delay;
2432 emit passwordMaskDelayChanged(delay);
2433 }
2434}
2435
2436void QQuickTextInput::resetPasswordMaskDelay()
2437{
2438 setPasswordMaskDelay(qGuiApp->styleHints()->passwordMaskDelay());
2439}
2440
2441/*!
2442 \qmlproperty string QtQuick::TextInput::displayText
2443
2444 This is the text displayed in the TextInput.
2445
2446 If \l echoMode is set to TextInput::Normal, this holds the
2447 same value as the TextInput::text property. Otherwise,
2448 this property holds the text visible to the user, while
2449 the \l text property holds the actual entered text.
2450
2451 \note Unlike the TextInput::text property, this contains
2452 partial text input from an input method.
2453
2454 \readonly
2455 \sa preeditText
2456*/
2457QString QQuickTextInput::displayText() const
2458{
2459 Q_D(const QQuickTextInput);
2460 return d->m_textLayout.text().insert(d->m_textLayout.preeditAreaPosition(), d->m_textLayout.preeditAreaText());
2461}
2462
2463/*!
2464 \qmlproperty string QtQuick::TextInput::preeditText
2465 \readonly
2466 \since 5.7
2467
2468 This property contains partial text input from an input method.
2469
2470 To turn off partial text that results from predictions, set the \c Qt.ImhNoPredictiveText
2471 flag in inputMethodHints.
2472
2473 \sa displayText, inputMethodHints
2474*/
2475QString QQuickTextInput::preeditText() const
2476{
2477 Q_D(const QQuickTextInput);
2478 return d->m_textLayout.preeditAreaText();
2479}
2480
2481/*!
2482 \qmlproperty bool QtQuick::TextInput::selectByMouse
2483
2484 Defaults to \c true.
2485
2486 If true, the user can use the mouse to select text in the usual way.
2487
2488 \note In versions prior to 6.4, the default was \c false; but if you
2489 enabled this property, you could also select text on a touchscreen by
2490 dragging your finger across it. This interfered with flicking when
2491 TextInput was used inside a Flickable. For consistency with TextField,
2492 selectByMouse now really means what it says: if \c true, you can select
2493 text by dragging \e only with a mouse. If this change does not suit your
2494 application, you can set \c selectByMouse to \c false, or import an older
2495 API version (for example \c {import QtQuick 6.3}) to revert to the previous
2496 behavior. The option to revert behavior by changing the import version will
2497 be removed in a later version of Qt.
2498*/
2499bool QQuickTextInput::selectByMouse() const
2500{
2501 Q_D(const QQuickTextInput);
2502 return d->selectByMouse;
2503}
2504
2505void QQuickTextInput::setSelectByMouse(bool on)
2506{
2507 Q_D(QQuickTextInput);
2508 if (d->selectByMouse != on) {
2509 d->selectByMouse = on;
2510 emit selectByMouseChanged(on);
2511 }
2512}
2513
2514/*!
2515 \qmlproperty enumeration QtQuick::TextInput::mouseSelectionMode
2516
2517 Specifies how text should be selected using a mouse.
2518
2519 \value TextInput.SelectCharacters (default) The selection is updated with individual characters.
2520 \value TextInput.SelectWords The selection is updated with whole words.
2521
2522 This property only applies when \l selectByMouse is true.
2523*/
2524
2525QQuickTextInput::SelectionMode QQuickTextInput::mouseSelectionMode() const
2526{
2527 Q_D(const QQuickTextInput);
2528 return d->mouseSelectionMode;
2529}
2530
2531void QQuickTextInput::setMouseSelectionMode(SelectionMode mode)
2532{
2533 Q_D(QQuickTextInput);
2534 if (d->mouseSelectionMode != mode) {
2535 d->mouseSelectionMode = mode;
2536 emit mouseSelectionModeChanged(mode);
2537 }
2538}
2539
2540/*!
2541 \qmlproperty bool QtQuick::TextInput::persistentSelection
2542
2543 Whether the TextInput should keep its selection when it loses active focus to another
2544 item in the scene. By default this is set to false;
2545*/
2546
2547bool QQuickTextInput::persistentSelection() const
2548{
2549 Q_D(const QQuickTextInput);
2550 return d->persistentSelection;
2551}
2552
2553void QQuickTextInput::setPersistentSelection(bool on)
2554{
2555 Q_D(QQuickTextInput);
2556 if (d->persistentSelection == on)
2557 return;
2558 d->persistentSelection = on;
2559 emit persistentSelectionChanged();
2560}
2561
2562/*!
2563 \qmlproperty bool QtQuick::TextInput::canPaste
2564 \readonly
2565
2566 Returns true if the TextInput is writable and the content of the clipboard is
2567 suitable for pasting into the TextInput.
2568*/
2569bool QQuickTextInput::canPaste() const
2570{
2571#if QT_CONFIG(clipboard)
2572 Q_D(const QQuickTextInput);
2573 if (!d->canPasteValid) {
2574 bool canPaste = false;
2575 if (!d->m_readOnly) {
2576 if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData())
2577 canPaste = mimeData->hasText();
2578 }
2579 const_cast<QQuickTextInputPrivate *>(d)->canPaste = canPaste;
2580 const_cast<QQuickTextInputPrivate *>(d)->canPasteValid = true;
2581 }
2582 return d->canPaste;
2583#else
2584 return false;
2585#endif
2586}
2587
2588/*!
2589 \qmlproperty bool QtQuick::TextInput::canUndo
2590 \readonly
2591
2592 Returns true if the TextInput is writable and there are previous operations
2593 that can be undone.
2594*/
2595
2596bool QQuickTextInput::canUndo() const
2597{
2598 Q_D(const QQuickTextInput);
2599 return d->canUndo;
2600}
2601
2602/*!
2603 \qmlproperty bool QtQuick::TextInput::canRedo
2604 \readonly
2605
2606 Returns true if the TextInput is writable and there are \l {undo}{undone}
2607 operations that can be redone.
2608*/
2609
2610bool QQuickTextInput::canRedo() const
2611{
2612 Q_D(const QQuickTextInput);
2613 return d->canRedo;
2614}
2615
2616/*!
2617 \qmlproperty real QtQuick::TextInput::contentWidth
2618 \readonly
2619
2620 Returns the width of the text, including the width past the width
2621 which is covered due to insufficient wrapping if \l wrapMode is set.
2622*/
2623
2624qreal QQuickTextInput::contentWidth() const
2625{
2626 Q_D(const QQuickTextInput);
2627 return d->contentSize.width();
2628}
2629
2630/*!
2631 \qmlproperty real QtQuick::TextInput::contentHeight
2632 \readonly
2633
2634 Returns the height of the text, including the height past the height
2635 that is covered if the text does not fit within the set height.
2636*/
2637
2638qreal QQuickTextInput::contentHeight() const
2639{
2640 Q_D(const QQuickTextInput);
2641 return d->contentSize.height();
2642}
2643
2644void QQuickTextInput::moveCursorSelection(int position)
2645{
2646 Q_D(QQuickTextInput);
2647 d->moveCursor(position, true);
2648}
2649
2650/*!
2651 \qmlmethod void QtQuick::TextInput::moveCursorSelection(int position, SelectionMode mode)
2652
2653 Moves the cursor to \a position and updates the selection according to the optional \a mode
2654 parameter. (To only move the cursor, set the \l cursorPosition property.)
2655
2656 When this method is called it additionally sets either the
2657 selectionStart or the selectionEnd (whichever was at the previous cursor position)
2658 to the specified position. This allows you to easily extend and contract the selected
2659 text range.
2660
2661 The selection mode specifies whether the selection is updated on a per character or a per word
2662 basis. If not specified the selection mode will default to \c {TextInput.SelectCharacters}.
2663
2664 \value TextInput.SelectCharacters
2665 Sets either the selectionStart or selectionEnd (whichever was at the previous cursor position)
2666 to the specified position.
2667 \value TextInput.SelectWords
2668 Sets the selectionStart and selectionEnd to include all words between the specified position
2669 and the previous cursor position. Words partially in the range are included.
2670
2671 For example, take this sequence of calls:
2672
2673 \code
2674 cursorPosition = 5
2675 moveCursorSelection(9, TextInput.SelectCharacters)
2676 moveCursorSelection(7, TextInput.SelectCharacters)
2677 \endcode
2678
2679 This moves the cursor to position 5, extend the selection end from 5 to 9
2680 and then retract the selection end from 9 to 7, leaving the text from position 5 to 7
2681 selected (the 6th and 7th characters).
2682
2683 The same sequence with TextInput.SelectWords will extend the selection start to a word boundary
2684 before or on position 5 and extend the selection end to a word boundary on or past position 9.
2685*/
2686void QQuickTextInput::moveCursorSelection(int pos, SelectionMode mode)
2687{
2688 Q_D(QQuickTextInput);
2689
2690 if (mode == SelectCharacters) {
2691 d->moveCursor(pos, true);
2692 } else if (pos != d->m_cursor) {
2693 const int cursor = d->m_cursor;
2694 int anchor;
2695 if (!d->hasSelectedText())
2696 anchor = d->m_cursor;
2697 else if (d->selectionStart() == d->m_cursor)
2698 anchor = d->selectionEnd();
2699 else
2700 anchor = d->selectionStart();
2701
2702 if (anchor < pos || (anchor == pos && cursor < pos)) {
2703 const QString text = this->text();
2704 QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text);
2705 finder.setPosition(anchor);
2706
2707 const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons();
2708 if (anchor < text.size() && (reasons == QTextBoundaryFinder::NotAtBoundary
2709 || (reasons & QTextBoundaryFinder::EndOfItem))) {
2710 finder.toPreviousBoundary();
2711 }
2712 anchor = finder.position() != -1 ? finder.position() : 0;
2713
2714 finder.setPosition(pos);
2715 if (pos > 0 && !finder.boundaryReasons())
2716 finder.toNextBoundary();
2717 const int cursor = finder.position() != -1 ? finder.position() : text.size();
2718
2719 d->setSelection(anchor, cursor - anchor);
2720 } else if (anchor > pos || (anchor == pos && cursor > pos)) {
2721 const QString text = this->text();
2722 QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text);
2723 finder.setPosition(anchor);
2724
2725 const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons();
2726 if (anchor > 0 && (reasons == QTextBoundaryFinder::NotAtBoundary
2727 || (reasons & QTextBoundaryFinder::StartOfItem))) {
2728 finder.toNextBoundary();
2729 }
2730 anchor = finder.position() != -1 ? finder.position() : text.size();
2731
2732 finder.setPosition(pos);
2733 if (pos < text.size() && !finder.boundaryReasons())
2734 finder.toPreviousBoundary();
2735 const int cursor = finder.position() != -1 ? finder.position() : 0;
2736
2737 d->setSelection(anchor, cursor - anchor);
2738 }
2739 }
2740}
2741
2742void QQuickTextInput::focusInEvent(QFocusEvent *event)
2743{
2744 Q_D(QQuickTextInput);
2745 d->handleFocusEvent(event);
2746 QQuickImplicitSizeItem::focusInEvent(event);
2747}
2748
2749void QQuickTextInputPrivate::handleFocusEvent(QFocusEvent *event)
2750{
2751 Q_Q(QQuickTextInput);
2752 bool focus = event->gotFocus();
2753 if (!m_readOnly) {
2754 q->setCursorVisible(focus);
2755 setBlinkingCursorEnabled(focus);
2756 }
2757 if (focus) {
2758 q->q_updateAlignment();
2759#if QT_CONFIG(im)
2760 if (focusOnPress && !m_readOnly)
2761 qGuiApp->inputMethod()->show();
2762 q->connect(QGuiApplication::inputMethod(), SIGNAL(inputDirectionChanged(Qt::LayoutDirection)),
2763 q, SLOT(q_updateAlignment()));
2764#endif
2765 } else {
2766 if ((m_passwordEchoEditing || m_passwordEchoTimer.isActive())) {
2767 updatePasswordEchoEditing(false);//QQuickTextInputPrivate sets it on key events, but doesn't deal with focus events
2768 }
2769
2770 if (event->reason() != Qt::ActiveWindowFocusReason
2771 && event->reason() != Qt::PopupFocusReason
2772 && hasSelectedText()
2773 && !persistentSelection)
2774 deselect();
2775
2776 if (hasAcceptableInput(m_text) == AcceptableInput || fixup())
2777 emit q->editingFinished();
2778
2779#if QT_CONFIG(im)
2780 q->disconnect(QGuiApplication::inputMethod(), SIGNAL(inputDirectionChanged(Qt::LayoutDirection)),
2781 q, SLOT(q_updateAlignment()));
2782#endif
2783 }
2784}
2785
2786void QQuickTextInput::focusOutEvent(QFocusEvent *event)
2787{
2788 Q_D(QQuickTextInput);
2789 d->handleFocusEvent(event);
2790 QQuickImplicitSizeItem::focusOutEvent(event);
2791}
2792
2793void QQuickTextInputPrivate::readOnlyChanged(bool isReadOnly)
2794{
2795 Q_UNUSED(isReadOnly);
2796#if QT_CONFIG(accessibility)
2797 if (QQuickAccessibleAttached *accessibleAttached =
2798 QQuickAccessibleAttached::attachedProperties(q_func()))
2799 accessibleAttached->set_readOnly(isReadOnly);
2800#endif
2801}
2802
2803void QQuickTextInputPrivate::echoModeChanged(QQuickTextInput::EchoMode echoMode)
2804{
2805#if QT_CONFIG(accessibility)
2806 if (!QAccessible::isActive())
2807 return;
2808
2809 if (QQuickAccessibleAttached *accessibleAttached =
2810 QQuickAccessibleAttached::attachedProperties(q_func()))
2811 accessibleAttached->set_passwordEdit((echoMode == QQuickTextInput::Password
2812 || echoMode == QQuickTextInput::PasswordEchoOnEdit)
2813 ? true
2814 : false);
2815#else
2816 Q_UNUSED(echoMode);
2817#endif
2818}
2819
2820#if QT_CONFIG(accessibility)
2821void QQuickTextInputPrivate::accessibilityActiveChanged(bool active)
2822{
2823 if (!active)
2824 return;
2825
2826 Q_Q(QQuickTextInput);
2827 QQuickAccessibleAttached *accessibleAttached = qobject_cast<QQuickAccessibleAttached *>(
2828 qmlAttachedPropertiesObject<QQuickAccessibleAttached>(q, true));
2829 Q_ASSERT(accessibleAttached);
2830 accessibleAttached->setRole(effectiveAccessibleRole());
2831 accessibleAttached->set_readOnly(m_readOnly);
2832 accessibleAttached->set_passwordEdit((m_echoMode == QQuickTextInput::Password
2833 || m_echoMode == QQuickTextInput::PasswordEchoOnEdit)
2834 ? true
2835 : false);
2836}
2837
2838QAccessible::Role QQuickTextInputPrivate::accessibleRole() const
2839{
2840 return QAccessible::EditableText;
2841}
2842#endif
2843
2844/*!
2845 \qmlproperty bool QtQuick::TextInput::inputMethodComposing
2846 \readonly
2847
2848 This property holds whether the TextInput has partial text input from an
2849 input method.
2850
2851 While it is composing an input method may rely on mouse or key events from
2852 the TextInput to edit or commit the partial text. This property can be
2853 used to determine when to disable events handlers that may interfere with
2854 the correct operation of an input method.
2855*/
2856bool QQuickTextInput::isInputMethodComposing() const
2857{
2858#if !QT_CONFIG(im)
2859 return false;
2860#else
2861 Q_D(const QQuickTextInput);
2862 return d->hasImState;
2863#endif
2864}
2865
2866QQuickTextInputPrivate::ExtraData::ExtraData()
2867 : padding(0)
2868 , topPadding(0)
2869 , leftPadding(0)
2870 , rightPadding(0)
2871 , bottomPadding(0)
2872 , explicitTopPadding(false)
2873 , explicitLeftPadding(false)
2874 , explicitRightPadding(false)
2875 , explicitBottomPadding(false)
2876 , implicitResize(true)
2877{
2878}
2879
2880void QQuickTextInputPrivate::init()
2881{
2882 Q_Q(QQuickTextInput);
2883#if QT_CONFIG(clipboard)
2884 if (QGuiApplication::clipboard()->supportsSelection())
2885 q->setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton);
2886 else
2887#endif
2888 q->setAcceptedMouseButtons(Qt::LeftButton);
2889
2890#if QT_CONFIG(im)
2891 q->setFlag(QQuickItem::ItemAcceptsInputMethod);
2892#endif
2893 q->setFlag(QQuickItem::ItemHasContents);
2894#if QT_CONFIG(clipboard)
2895 qmlobject_connect(QGuiApplication::clipboard(), QClipboard, SIGNAL(dataChanged()),
2896 q, QQuickTextInput, SLOT(q_canPasteChanged()));
2897#endif // clipboard
2898
2899 lastSelectionStart = 0;
2900 lastSelectionEnd = 0;
2901 determineHorizontalAlignment();
2902
2903 if (!qmlDisableDistanceField()) {
2904 QTextOption option = m_textLayout.textOption();
2905 option.setUseDesignMetrics(renderType != QQuickTextInput::NativeRendering);
2906 m_textLayout.setTextOption(option);
2907 }
2908
2909 m_inputControl = new QInputControl(QInputControl::LineEdit, q);
2910 setSizePolicy(QLayoutPolicy::Expanding, QLayoutPolicy::Fixed);
2911
2912 QObjectPrivate::connect(q, &QQuickTextInput::readOnlyChanged, this,
2913 &QQuickTextInputPrivate::readOnlyChanged);
2914 QObjectPrivate::connect(q, &QQuickTextInput::echoModeChanged, this,
2915 &QQuickTextInputPrivate::echoModeChanged);
2916}
2917
2918void QQuickTextInputPrivate::cancelInput()
2919{
2920#if QT_CONFIG(im)
2921 Q_Q(QQuickTextInput);
2922 if (!m_readOnly && q->hasActiveFocus() && qGuiApp)
2923 cancelPreedit();
2924#endif // im
2925}
2926
2927void QQuickTextInput::updateCursorRectangle(bool scroll)
2928{
2929 Q_D(QQuickTextInput);
2930 if (!isComponentComplete())
2931 return;
2932
2933 if (scroll) {
2934 d->updateHorizontalScroll();
2935 d->updateVerticalScroll();
2936 }
2937 d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
2938 polish();
2939 update();
2940 emit cursorRectangleChanged();
2941 if (d->cursorItem) {
2942 QRectF r = cursorRectangle();
2943 d->cursorItem->setPosition(r.topLeft());
2944 d->cursorItem->setHeight(r.height());
2945 }
2946#if QT_CONFIG(im)
2947 updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorRectangle);
2948#endif
2949}
2950
2951void QQuickTextInput::selectionChanged()
2952{
2953 Q_D(QQuickTextInput);
2954 d->textLayoutDirty = true; //TODO: Only update rect in selection
2955 d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
2956 polish();
2957 update();
2958 emit selectedTextChanged();
2959
2960 if (d->lastSelectionStart != d->selectionStart()) {
2961 d->lastSelectionStart = d->selectionStart();
2962 if (d->lastSelectionStart == -1)
2963 d->lastSelectionStart = d->m_cursor;
2964 emit selectionStartChanged();
2965 }
2966 if (d->lastSelectionEnd != d->selectionEnd()) {
2967 d->lastSelectionEnd = d->selectionEnd();
2968 if (d->lastSelectionEnd == -1)
2969 d->lastSelectionEnd = d->m_cursor;
2970 emit selectionEndChanged();
2971 }
2972}
2973
2974QRectF QQuickTextInput::boundingRect() const
2975{
2976 Q_D(const QQuickTextInput);
2977
2978 int cursorWidth = d->cursorItem ? 0 : 1;
2979
2980 qreal hscroll = d->hscroll;
2981 if (!d->autoScroll || d->contentSize.width() < width())
2982 hscroll -= QQuickTextUtil::alignedX(d->contentSize.width(), width(), effectiveHAlign());
2983
2984 // Could include font max left/right bearings to either side of rectangle.
2985 QRectF r(-hscroll, -d->vscroll, d->contentSize.width(), d->contentSize.height());
2986 r.setRight(r.right() + cursorWidth);
2987 return r;
2988}
2989
2990QRectF QQuickTextInput::clipRect() const
2991{
2992 Q_D(const QQuickTextInput);
2993
2994 int cursorWidth = d->cursorItem ? d->cursorItem->width() : 1;
2995
2996 // Could include font max left/right bearings to either side of rectangle.
2997 QRectF r = QQuickImplicitSizeItem::clipRect();
2998 r.setRight(r.right() + cursorWidth);
2999 return r;
3000}
3001
3002void QQuickTextInput::q_canPasteChanged()
3003{
3004 Q_D(QQuickTextInput);
3005 bool old = d->canPaste;
3006#if QT_CONFIG(clipboard)
3007 bool canPaste = false;
3008 if (!d->m_readOnly) {
3009 if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData())
3010 canPaste = mimeData->hasText();
3011 }
3012 d->canPaste = canPaste;
3013#endif
3014
3015 bool changed = d->canPaste != old || !d->canPasteValid;
3016 d->canPasteValid = true;
3017 if (changed)
3018 emit canPasteChanged();
3019
3020}
3021
3022void QQuickTextInput::q_updateAlignment()
3023{
3024 Q_D(QQuickTextInput);
3025 if (d->determineHorizontalAlignment()) {
3026 d->updateLayout();
3027 updateCursorRectangle();
3028 }
3029}
3030
3031/*!
3032 \internal
3033
3034 Updates the display text based of the current edit text
3035 If the text has changed will emit displayTextChanged()
3036*/
3037void QQuickTextInputPrivate::updateDisplayText(bool forceUpdate)
3038{
3039 QString orig = m_textLayout.text();
3040 QString str;
3041 if (m_echoMode == QQuickTextInput::NoEcho)
3042 str = QString::fromLatin1("");
3043 else
3044 str = m_text;
3045
3046 if (m_echoMode == QQuickTextInput::Password) {
3047 str.fill(m_passwordCharacter);
3048 if (m_passwordEchoTimer.isActive() && m_cursor > 0 && m_cursor <= m_text.size()) {
3049 int cursor = m_cursor - 1;
3050 QChar uc = m_text.at(cursor);
3051 str[cursor] = uc;
3052 if (cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) {
3053 // second half of a surrogate, check if we have the first half as well,
3054 // if yes restore both at once
3055 uc = m_text.at(cursor - 1);
3056 if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00)
3057 str[cursor - 1] = uc;
3058 }
3059 }
3060 } else if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing) {
3061 str.fill(m_passwordCharacter);
3062 }
3063
3064 // replace certain non-printable characters with spaces (to avoid
3065 // drawing boxes when using fonts that don't have glyphs for such
3066 // characters)
3067 QChar* uc = str.data();
3068 for (int i = 0; i < str.size(); ++i) {
3069 if (uc[i] == QChar::LineSeparator
3070 || uc[i] == QChar::ParagraphSeparator
3071 || uc[i] == QChar::ObjectReplacementCharacter)
3072 uc[i] = QChar(0x0020);
3073 }
3074
3075 if (str != orig || forceUpdate) {
3076 m_textLayout.setText(str);
3077 updateLayout(); // polish?
3078 emit q_func()->displayTextChanged();
3079 }
3080}
3081
3082qreal QQuickTextInputPrivate::calculateImplicitWidthForText(const QString &text) const
3083{
3084 Q_Q(const QQuickTextInput);
3085 QTextLayout layout(text);
3086
3087 QTextOption option = m_textLayout.textOption();
3088 option.setTextDirection(m_layoutDirection);
3089 option.setFlags(QTextOption::IncludeTrailingSpaces);
3090 option.setWrapMode(QTextOption::WrapMode(wrapMode));
3091 option.setAlignment(Qt::Alignment(q->effectiveHAlign()));
3092 layout.setTextOption(option);
3093 layout.setFont(font);
3094#if QT_CONFIG(im)
3095 layout.setPreeditArea(m_textLayout.preeditAreaPosition(), m_textLayout.preeditAreaText());
3096#endif
3097 layout.beginLayout();
3098
3099 QTextLine line = layout.createLine();
3100 line.setLineWidth(qreal(INT_MAX));
3101 const qreal theImplicitWidth = qCeil(line.naturalTextWidth()) + q->leftPadding() + q->rightPadding();
3102
3103 layout.endLayout();
3104 return theImplicitWidth;
3105}
3106
3107qreal QQuickTextInputPrivate::getImplicitWidth() const
3108{
3109 Q_Q(const QQuickTextInput);
3110 if (!requireImplicitWidth) {
3111 QQuickTextInputPrivate *d = const_cast<QQuickTextInputPrivate *>(this);
3112 d->requireImplicitWidth = true;
3113
3114 if (q->isComponentComplete())
3115 d->implicitWidth = calculateImplicitWidthForText(m_text);
3116 }
3117 return implicitWidth;
3118}
3119
3120void QQuickTextInputPrivate::setTopPadding(qreal value, bool reset)
3121{
3122 Q_Q(QQuickTextInput);
3123 qreal oldPadding = q->topPadding();
3124 if (!reset || extra.isAllocated()) {
3125 extra.value().topPadding = value;
3126 extra.value().explicitTopPadding = !reset;
3127 }
3128 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
3129 updateLayout();
3130 q->updateCursorRectangle();
3131 emit q->topPaddingChanged();
3132 }
3133}
3134
3135void QQuickTextInputPrivate::setLeftPadding(qreal value, bool reset)
3136{
3137 Q_Q(QQuickTextInput);
3138 qreal oldPadding = q->leftPadding();
3139 if (!reset || extra.isAllocated()) {
3140 extra.value().leftPadding = value;
3141 extra.value().explicitLeftPadding = !reset;
3142 }
3143 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
3144 updateLayout();
3145 q->updateCursorRectangle();
3146 emit q->leftPaddingChanged();
3147 }
3148}
3149
3150void QQuickTextInputPrivate::setRightPadding(qreal value, bool reset)
3151{
3152 Q_Q(QQuickTextInput);
3153 qreal oldPadding = q->rightPadding();
3154 if (!reset || extra.isAllocated()) {
3155 extra.value().rightPadding = value;
3156 extra.value().explicitRightPadding = !reset;
3157 }
3158 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
3159 updateLayout();
3160 q->updateCursorRectangle();
3161 emit q->rightPaddingChanged();
3162 }
3163}
3164
3165void QQuickTextInputPrivate::setBottomPadding(qreal value, bool reset)
3166{
3167 Q_Q(QQuickTextInput);
3168 qreal oldPadding = q->bottomPadding();
3169 if (!reset || extra.isAllocated()) {
3170 extra.value().bottomPadding = value;
3171 extra.value().explicitBottomPadding = !reset;
3172 }
3173 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
3174 updateLayout();
3175 q->updateCursorRectangle();
3176 emit q->bottomPaddingChanged();
3177 }
3178}
3179
3180bool QQuickTextInputPrivate::isImplicitResizeEnabled() const
3181{
3182 return !extra.isAllocated() || extra->implicitResize;
3183}
3184
3185void QQuickTextInputPrivate::setImplicitResizeEnabled(bool enabled)
3186{
3187 if (!enabled)
3188 extra.value().implicitResize = false;
3189 else if (extra.isAllocated())
3190 extra->implicitResize = true;
3191}
3192
3193void QQuickTextInputPrivate::updateLayout()
3194{
3195 Q_Q(QQuickTextInput);
3196
3197 if (!q->isComponentComplete())
3198 return;
3199
3200
3201 QTextOption option = m_textLayout.textOption();
3202 option.setTextDirection(layoutDirection());
3203 option.setWrapMode(QTextOption::WrapMode(wrapMode));
3204 option.setAlignment(Qt::Alignment(q->effectiveHAlign()));
3205 if (!qmlDisableDistanceField())
3206 option.setUseDesignMetrics(renderType != QQuickTextInput::NativeRendering);
3207
3208 m_textLayout.setTextOption(option);
3209 m_textLayout.setFont(font);
3210
3211 m_textLayout.beginLayout();
3212
3213 QTextLine line = m_textLayout.createLine();
3214 if (requireImplicitWidth) {
3215 line.setLineWidth(qreal(INT_MAX));
3216 const bool wasInLayout = inLayout;
3217 inLayout = true;
3218 if (isImplicitResizeEnabled())
3219 q->setImplicitWidth(qCeil(line.naturalTextWidth()) + q->leftPadding() + q->rightPadding());
3220 inLayout = wasInLayout;
3221 if (inLayout) // probably the result of a binding loop, but by letting it
3222 return; // get this far we'll get a warning to that effect.
3223 }
3224 qreal lineWidth = q->widthValid() || !isImplicitResizeEnabled() ? q->width() - q->leftPadding() - q->rightPadding() : qreal(INT_MAX);
3225 qreal height = 0;
3226 qreal width = 0;
3227 do {
3228 line.setLineWidth(lineWidth);
3229 line.setPosition(QPointF(0, height));
3230
3231 height += line.height();
3232 width = qMax(width, line.naturalTextWidth());
3233
3234 line = m_textLayout.createLine();
3235 } while (line.isValid());
3236 m_textLayout.endLayout();
3237
3238 option.setWrapMode(QTextOption::NoWrap);
3239 m_textLayout.setTextOption(option);
3240
3241 textLayoutDirty = true;
3242
3243 const QSizeF previousSize = contentSize;
3244 contentSize = QSizeF(width, height);
3245
3246 updateType = UpdatePaintNode;
3247 q->polish();
3248 q->update();
3249
3250 if (isImplicitResizeEnabled()) {
3251 if (!requireImplicitWidth && !q->widthValid())
3252 q->setImplicitSize(width + q->leftPadding() + q->rightPadding(), height + q->topPadding() + q->bottomPadding());
3253 else
3254 q->setImplicitHeight(height + q->topPadding() + q->bottomPadding());
3255 }
3256
3257 updateBaselineOffset();
3258
3259 if (previousSize != contentSize)
3260 emit q->contentSizeChanged();
3261}
3262
3263/*!
3264 \internal
3265 \brief QQuickTextInputPrivate::updateBaselineOffset
3266
3267 Assumes contentSize.height() is already calculated.
3268 */
3269void QQuickTextInputPrivate::updateBaselineOffset()
3270{
3271 Q_Q(QQuickTextInput);
3272 if (!q->isComponentComplete())
3273 return;
3274 QFontMetricsF fm(font);
3275 qreal yoff = 0;
3276 if (q->heightValid()) {
3277 const qreal surplusHeight = q->height() - contentSize.height() - q->topPadding() - q->bottomPadding();
3278 if (vAlign == QQuickTextInput::AlignBottom)
3279 yoff = surplusHeight;
3280 else if (vAlign == QQuickTextInput::AlignVCenter)
3281 yoff = surplusHeight/2;
3282 }
3283 qreal ascent;
3284 if (m_textLayout.lineCount() > 0) {
3285 QTextLine line = m_textLayout.lineAt(0);
3286 ascent = line.y() + line.ascent();
3287 } else {
3288 ascent = fm.ascent();
3289 }
3290 q->setBaselineOffset(ascent + yoff + q->topPadding());
3291}
3292
3293#if QT_CONFIG(clipboard)
3294/*!
3295 \internal
3296
3297 Copies the currently selected text into the clipboard using the given
3298 \a mode.
3299
3300 \note If the echo mode is set to a mode other than Normal then copy
3301 will not work. This is to prevent using copy as a method of bypassing
3302 password features of the line control.
3303*/
3304void QQuickTextInputPrivate::copy(QClipboard::Mode mode) const
3305{
3306 QString t = selectedText();
3307 if (!t.isEmpty() && m_echoMode == QQuickTextInput::Normal) {
3308 QGuiApplication::clipboard()->setText(t, mode);
3309 }
3310}
3311
3312/*!
3313 \internal
3314
3315 Inserts the text stored in the application clipboard into the line
3316 control.
3317
3318 \sa insert()
3319*/
3320void QQuickTextInputPrivate::paste(QClipboard::Mode clipboardMode)
3321{
3322 QString clip = QGuiApplication::clipboard()->text(clipboardMode);
3323 if (!clip.isEmpty() || hasSelectedText()) {
3324 separate(); //make it a separate undo/redo command
3325 insert(clip);
3326 separate();
3327 }
3328}
3329
3330#endif // clipboard
3331
3332#if QT_CONFIG(im)
3333/*!
3334 \internal
3335*/
3336void QQuickTextInputPrivate::commitPreedit()
3337{
3338 Q_Q(QQuickTextInput);
3339
3340 if (!hasImState)
3341 return;
3342
3343 QGuiApplication::inputMethod()->commit();
3344
3345 if (!hasImState)
3346 return;
3347
3348 QInputMethodEvent ev;
3349 QCoreApplication::sendEvent(q, &ev);
3350}
3351
3352void QQuickTextInputPrivate::cancelPreedit()
3353{
3354 Q_Q(QQuickTextInput);
3355
3356 if (!hasImState)
3357 return;
3358
3359 QGuiApplication::inputMethod()->reset();
3360
3361 QInputMethodEvent ev;
3362 QCoreApplication::sendEvent(q, &ev);
3363}
3364#endif // im
3365
3366/*!
3367 \internal
3368
3369 Handles the behavior for the backspace key or function.
3370 Removes the current selection if there is a selection, otherwise
3371 removes the character prior to the cursor position.
3372
3373 \sa del()
3374*/
3375void QQuickTextInputPrivate::backspace()
3376{
3377 int priorState = m_undoState;
3378 if (separateSelection()) {
3379 removeSelectedText();
3380 } else if (m_cursor) {
3381 --m_cursor;
3382 if (m_maskData)
3383 m_cursor = prevMaskBlank(m_cursor);
3384 QChar uc = m_text.at(m_cursor);
3385 if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) {
3386 // second half of a surrogate, check if we have the first half as well,
3387 // if yes delete both at once
3388 uc = m_text.at(m_cursor - 1);
3389 if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) {
3390 internalDelete(true);
3391 --m_cursor;
3392 }
3393 }
3394 internalDelete(true);
3395 }
3396 finishChange(priorState);
3397}
3398
3399/*!
3400 \internal
3401
3402 Handles the behavior for the delete key or function.
3403 Removes the current selection if there is a selection, otherwise
3404 removes the character after the cursor position.
3405
3406 \sa del()
3407*/
3408void QQuickTextInputPrivate::del()
3409{
3410 int priorState = m_undoState;
3411 if (separateSelection()) {
3412 removeSelectedText();
3413 } else {
3414 int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor;
3415 while (n--)
3416 internalDelete();
3417 }
3418 finishChange(priorState);
3419}
3420
3421/*!
3422 \internal
3423
3424 Inserts the given \a newText at the current cursor position.
3425 If there is any selected text it is removed prior to insertion of
3426 the new text.
3427*/
3428void QQuickTextInputPrivate::insert(const QString &newText)
3429{
3430 int priorState = m_undoState;
3431 if (separateSelection())
3432 removeSelectedText();
3433 internalInsert(newText);
3434 finishChange(priorState);
3435}
3436
3437/*!
3438 \internal
3439
3440 Clears the line control text.
3441*/
3442void QQuickTextInputPrivate::clear()
3443{
3444 int priorState = m_undoState;
3445 separateSelection();
3446 m_selstart = 0;
3447 m_selend = m_text.size();
3448 removeSelectedText();
3449 separate();
3450 finishChange(priorState, /*update*/false, /*edited*/false);
3451}
3452
3453/*!
3454 \internal
3455
3456 Sets \a length characters from the given \a start position as selected.
3457 The given \a start position must be within the current text for
3458 the line control. If \a length characters cannot be selected, then
3459 the selection will extend to the end of the current text.
3460*/
3461void QQuickTextInputPrivate::setSelection(int start, int length)
3462{
3463 Q_Q(QQuickTextInput);
3464#if QT_CONFIG(im)
3465 commitPreedit();
3466#endif
3467
3468 if (start < 0 || start > m_text.size()) {
3469 qWarning("QQuickTextInputPrivate::setSelection: Invalid start position");
3470 return;
3471 }
3472
3473 if (length > 0) {
3474 if (start == m_selstart && start + length == m_selend && m_cursor == m_selend)
3475 return;
3476 m_selstart = start;
3477 m_selend = qMin(start + length, m_text.size());
3478 m_cursor = m_selend;
3479 } else if (length < 0) {
3480 if (start == m_selend && start + length == m_selstart && m_cursor == m_selstart)
3481 return;
3482 m_selstart = qMax(start + length, 0);
3483 m_selend = start;
3484 m_cursor = m_selstart;
3485 } else if (m_selstart != m_selend) {
3486 m_selstart = 0;
3487 m_selend = 0;
3488 m_cursor = start;
3489 } else {
3490 m_cursor = start;
3491 emitCursorPositionChanged();
3492 return;
3493 }
3494 emit q->selectionChanged();
3495 emitCursorPositionChanged();
3496#if QT_CONFIG(im)
3497 q->updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorRectangle | Qt::ImCursorPosition | Qt::ImAnchorPosition
3498 | Qt::ImCurrentSelection);
3499#endif
3500}
3501
3502/*!
3503 \internal
3504
3505 Sets the password echo editing to \a editing. If password echo editing
3506 is true, then the text of the password is displayed even if the echo
3507 mode is set to QLineEdit::PasswordEchoOnEdit. Password echoing editing
3508 does not affect other echo modes.
3509*/
3510void QQuickTextInputPrivate::updatePasswordEchoEditing(bool editing)
3511{
3512 cancelPasswordEchoTimer();
3513 m_passwordEchoEditing = editing;
3514 updateDisplayText();
3515}
3516
3517/*!
3518 \internal
3519
3520 Fixes the current text so that it is valid given any set validators.
3521
3522 Returns true if the text was changed. Otherwise returns false.
3523*/
3524bool QQuickTextInputPrivate::fixup() // this function assumes that validate currently returns != Acceptable
3525{
3526#if QT_CONFIG(validator)
3527 if (m_validator) {
3528 QString textCopy = m_text;
3529 int cursorCopy = m_cursor;
3530 m_validator->fixup(textCopy);
3531 if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) {
3532 if (textCopy != m_text || cursorCopy != m_cursor)
3533 internalSetText(textCopy, cursorCopy);
3534 return true;
3535 }
3536 }
3537#endif
3538 return false;
3539}
3540
3541/*!
3542 \internal
3543
3544 Moves the cursor to the given position \a pos. If \a mark is true will
3545 adjust the currently selected text.
3546*/
3547void QQuickTextInputPrivate::moveCursor(int pos, bool mark)
3548{
3549 Q_Q(QQuickTextInput);
3550#if QT_CONFIG(im)
3551 commitPreedit();
3552#endif
3553
3554 if (pos != m_cursor) {
3555 separate();
3556 if (m_maskData)
3557 pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos);
3558 }
3559 if (mark) {
3560 int anchor;
3561 if (m_selend > m_selstart && m_cursor == m_selstart)
3562 anchor = m_selend;
3563 else if (m_selend > m_selstart && m_cursor == m_selend)
3564 anchor = m_selstart;
3565 else
3566 anchor = m_cursor;
3567 m_selstart = qMin(anchor, pos);
3568 m_selend = qMax(anchor, pos);
3569 } else {
3570 internalDeselect();
3571 }
3572 m_cursor = pos;
3573 if (mark || m_selDirty) {
3574 m_selDirty = false;
3575 emit q->selectionChanged();
3576 }
3577 emitCursorPositionChanged();
3578#if QT_CONFIG(im)
3579 q->updateInputMethod();
3580#endif
3581}
3582
3583#if QT_CONFIG(im)
3584/*!
3585 \internal
3586
3587 Applies the given input method event \a event to the text of the line
3588 control
3589*/
3590void QQuickTextInputPrivate::processInputMethodEvent(QInputMethodEvent *event)
3591{
3592 Q_Q(QQuickTextInput);
3593
3594 int priorState = -1;
3595 bool isGettingInput = !event->commitString().isEmpty()
3596 || event->preeditString() != preeditAreaText()
3597 || event->replacementLength() > 0;
3598 bool cursorPositionChanged = false;
3599 bool selectionChange = false;
3600 m_preeditDirty = event->preeditString() != preeditAreaText();
3601
3602 if (isGettingInput) {
3603 // If any text is being input, remove selected text.
3604 priorState = m_undoState;
3605 separateSelection();
3606 if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing) {
3607 updatePasswordEchoEditing(true);
3608 m_selstart = 0;
3609 m_selend = m_text.size();
3610 }
3611 removeSelectedText();
3612 }
3613
3614 int c = m_cursor; // cursor position after insertion of commit string
3615 if (event->replacementStart() <= 0)
3616 c += event->commitString().size() - qMin(-event->replacementStart(), event->replacementLength());
3617
3618 int cursorInsertPos = m_cursor + event->replacementStart();
3619 if (cursorInsertPos < 0)
3620 cursorInsertPos = 0;
3621
3622 // insert commit string
3623 if (event->replacementLength()) {
3624 m_selstart = cursorInsertPos;
3625 m_selend = m_selstart + event->replacementLength();
3626 m_selend = qMin(m_selend, m_text.size());
3627 removeSelectedText();
3628 }
3629 m_cursor = cursorInsertPos;
3630
3631 if (!event->commitString().isEmpty()) {
3632 internalInsert(event->commitString());
3633 cursorPositionChanged = true;
3634 } else {
3635 m_cursor = qBound(0, c, m_text.size());
3636 }
3637
3638 for (int i = 0; i < event->attributes().size(); ++i) {
3639 const QInputMethodEvent::Attribute &a = event->attributes().at(i);
3640 if (a.type == QInputMethodEvent::Selection) {
3641 // If we already called internalInsert(), the cursor position will
3642 // already be adjusted correctly. The attribute.start does
3643 // not seem to take the mask into account, so it will reset the cursor
3644 // to an invalid position in such case. However, when the input mask
3645 // is not active, we must apply the cursor position regardless of the
3646 // commit string.
3647 if (!cursorPositionChanged || !m_maskData)
3648 m_cursor = qBound(0, a.start + a.length, m_text.size());
3649 if (a.length) {
3650 m_selstart = qMax(0, qMin(a.start, m_text.size()));
3651 m_selend = m_cursor;
3652 if (m_selend < m_selstart) {
3653 qSwap(m_selstart, m_selend);
3654 }
3655 selectionChange = true;
3656 } else {
3657 selectionChange = m_selstart != m_selend;
3658 m_selstart = m_selend = 0;
3659 }
3660 cursorPositionChanged = true;
3661 }
3662 }
3663 QString oldPreeditString = m_textLayout.preeditAreaText();
3664 m_textLayout.setPreeditArea(m_cursor, event->preeditString());
3665 if (oldPreeditString != m_textLayout.preeditAreaText()) {
3666 emit q->preeditTextChanged();
3667 if (!event->preeditString().isEmpty() && m_undoPreeditState == -1)
3668 // Pre-edit text started. Remember state for undo purpose.
3669 m_undoPreeditState = priorState;
3670 }
3671 const int oldPreeditCursor = m_preeditCursor;
3672 m_preeditCursor = event->preeditString().size();
3673 hasImState = !event->preeditString().isEmpty();
3674 bool cursorVisible = true;
3675 QList<QTextLayout::FormatRange> formats;
3676 for (int i = 0; i < event->attributes().size(); ++i) {
3677 const QInputMethodEvent::Attribute &a = event->attributes().at(i);
3678 if (a.type == QInputMethodEvent::Cursor) {
3679 hasImState = true;
3680 m_preeditCursor = a.start;
3681 cursorVisible = a.length != 0;
3682 } else if (a.type == QInputMethodEvent::TextFormat) {
3683 hasImState = true;
3684 QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat();
3685 if (f.isValid()) {
3686 QTextLayout::FormatRange o;
3687 o.start = a.start + m_cursor;
3688 o.length = a.length;
3689 o.format = f;
3690 formats.append(o);
3691 }
3692 }
3693 }
3694 m_textLayout.setFormats(formats);
3695
3696 // Set cursor visible state. Do this before updating the text,
3697 // since user code connected to onTextChanged may set a different
3698 // cursor visible state (for instance by setting the focus), which
3699 // we don't want to overwrite.
3700 q->setCursorVisible(cursorVisible);
3701
3702 updateDisplayText(/*force*/ true);
3703 if (cursorPositionChanged && emitCursorPositionChanged())
3704 q->updateInputMethod(Qt::ImCursorPosition | Qt::ImAnchorPosition);
3705 else if (m_preeditCursor != oldPreeditCursor || isGettingInput)
3706 q->updateCursorRectangle();
3707
3708 if (isGettingInput)
3709 finishChange(priorState);
3710
3711 if (selectionChange) {
3712 emit q->selectionChanged();
3713 q->updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorRectangle
3714 | Qt::ImCurrentSelection);
3715 }
3716
3717 // Empty pre-edit text handled. Clean m_undoPreeditState
3718 if (event->preeditString().isEmpty())
3719 m_undoPreeditState = -1;
3720
3721}
3722#endif // im
3723
3724/*!
3725 \internal
3726
3727 Sets the selection to cover the word at the given cursor position.
3728 The word boundaries are defined by the behavior of QTextLayout::SkipWords
3729 cursor mode.
3730*/
3731void QQuickTextInputPrivate::selectWordAtPos(int cursor)
3732{
3733 int next = cursor + 1;
3734 if (next > end())
3735 --next;
3736 int c = m_textLayout.previousCursorPosition(next, QTextLayout::SkipWords);
3737 moveCursor(c, false);
3738 // ## text layout should support end of words.
3739 int end = m_textLayout.nextCursorPosition(c, QTextLayout::SkipWords);
3740 while (end > cursor && m_text.at(end - 1).isSpace())
3741 --end;
3742 moveCursor(end, true);
3743}
3744
3745/*!
3746 \internal
3747
3748 Completes a change to the line control text. If the change is not valid
3749 will undo the line control state back to the given \a validateFromState.
3750
3751 If \a edited is true and the change is valid, will emit textEdited() in
3752 addition to textChanged(). Otherwise only emits textChanged() on a valid
3753 change.
3754
3755 The \a update value is currently unused.
3756*/
3757bool QQuickTextInputPrivate::finishChange(int validateFromState, bool update, bool edited)
3758{
3759 Q_Q(QQuickTextInput);
3760
3761 Q_UNUSED(update);
3762#if QT_CONFIG(im)
3763 bool inputMethodAttributesChanged = m_textDirty || m_selDirty;
3764#endif
3765 bool alignmentChanged = false;
3766 bool textChanged = false;
3767
3768 if (m_textDirty) {
3769 // do validation
3770 bool wasValidInput = m_validInput;
3771 bool wasAcceptable = m_acceptableInput;
3772 m_validInput = true;
3773 m_acceptableInput = true;
3774#if QT_CONFIG(validator)
3775 if (m_validator) {
3776 QString textCopy = m_text;
3777 if (m_maskData)
3778 textCopy = maskString(0, m_text, true);
3779 int cursorCopy = m_cursor;
3780 QValidator::State state = m_validator->validate(textCopy, cursorCopy);
3781 if (m_maskData)
3782 textCopy = m_text;
3783 m_validInput = state != QValidator::Invalid;
3784 m_acceptableInput = state == QValidator::Acceptable;
3785 if (m_validInput && !m_maskData) {
3786 if (m_text != textCopy) {
3787 internalSetText(textCopy, cursorCopy);
3788 return true;
3789 }
3790 m_cursor = cursorCopy;
3791 }
3792 }
3793#endif
3794 if (m_maskData)
3795 checkIsValid();
3796
3797#if QT_CONFIG(im)
3798 // If we were during pre-edit, validateFromState should point to the state before pre-edit
3799 // has been started. Choose the correct oldest remembered state
3800 if (m_undoPreeditState >= 0 && (m_undoPreeditState < validateFromState || validateFromState < 0))
3801 validateFromState = m_undoPreeditState;
3802#endif
3803 if (validateFromState >= 0 && wasValidInput && !m_validInput) {
3804 if (m_transactions.size())
3805 return false;
3806 internalUndo(validateFromState);
3807 m_history.resize(m_undoState);
3808 m_validInput = true;
3809 m_acceptableInput = wasAcceptable;
3810 m_textDirty = false;
3811 }
3812
3813 if (m_textDirty) {
3814 textChanged = true;
3815 m_textDirty = false;
3816#if QT_CONFIG(im)
3817 m_preeditDirty = false;
3818#endif
3819 alignmentChanged = determineHorizontalAlignment();
3820 if (edited)
3821 emit q->textEdited();
3822 emit q->textChanged();
3823 }
3824
3825 updateDisplayText(alignmentChanged);
3826
3827 if (m_acceptableInput != wasAcceptable)
3828 emit q->acceptableInputChanged();
3829 }
3830#if QT_CONFIG(im)
3831 if (m_preeditDirty) {
3832 m_preeditDirty = false;
3833 if (determineHorizontalAlignment()) {
3834 alignmentChanged = true;
3835 updateLayout();
3836 }
3837 }
3838#endif
3839
3840 if (m_selDirty) {
3841 m_selDirty = false;
3842 emit q->selectionChanged();
3843 }
3844
3845#if QT_CONFIG(im)
3846 inputMethodAttributesChanged |= (m_cursor != m_lastCursorPos);
3847 if (inputMethodAttributesChanged)
3848 q->updateInputMethod();
3849#endif
3850 emitUndoRedoChanged();
3851
3852 if (!emitCursorPositionChanged() && (alignmentChanged || textChanged))
3853 q->updateCursorRectangle();
3854
3855 return true;
3856}
3857
3858/*!
3859 \internal
3860
3861 An internal function for setting the text of the line control.
3862*/
3863void QQuickTextInputPrivate::internalSetText(const QString &txt, int pos, bool edited)
3864{
3865 internalDeselect();
3866 QString oldText = m_text;
3867 if (m_maskData) {
3868 m_text = maskString(0, txt, true);
3869 m_text += clearString(m_text.size(), m_maxLength - m_text.size());
3870 } else {
3871 m_text = txt.isEmpty() ? txt : txt.left(m_maxLength);
3872 }
3873 m_history.clear();
3874 m_undoState = 0;
3875#if QT_CONFIG(im)
3876 m_undoPreeditState = -1;
3877#endif
3878 m_cursor = (pos < 0 || pos > m_text.size()) ? m_text.size() : pos;
3879 m_textDirty = (oldText != m_text);
3880
3881 bool changed = finishChange(-1, true, edited);
3882#if !QT_CONFIG(accessibility)
3883 Q_UNUSED(changed);
3884#else
3885 Q_Q(QQuickTextInput);
3886 if (changed && QAccessible::isActive()) {
3887 if (QObject *acc = QQuickAccessibleAttached::findAccessible(q, QAccessible::EditableText)) {
3888 QAccessibleTextUpdateEvent ev(acc, 0, oldText, m_text);
3889 QAccessible::updateAccessibility(&ev);
3890 }
3891 }
3892#endif
3893}
3894
3895
3896/*!
3897 \internal
3898
3899 Adds the given \a command to the undo history
3900 of the line control. Does not apply the command.
3901*/
3902void QQuickTextInputPrivate::addCommand(const Command &cmd)
3903{
3904 if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) {
3905 m_history.resize(m_undoState + 2);
3906 m_history[m_undoState++] = Command(Separator, m_cursor, u'\0', m_selstart, m_selend);
3907 } else {
3908 m_history.resize(m_undoState + 1);
3909 }
3910 m_separator = false;
3911 m_history[m_undoState++] = cmd;
3912}
3913
3914/*!
3915 \internal
3916
3917 Inserts the given string \a s into the line
3918 control.
3919
3920 Also adds the appropriate commands into the undo history.
3921 This function does not call finishChange(), and may leave the text
3922 in an invalid state.
3923*/
3924void QQuickTextInputPrivate::internalInsert(const QString &s)
3925{
3926 Q_Q(QQuickTextInput);
3927 if (m_echoMode == QQuickTextInput::Password) {
3928 if (m_passwordMaskDelay > 0)
3929 m_passwordEchoTimer.start(m_passwordMaskDelay, q);
3930 }
3931 Q_ASSERT(!hasSelectedText()); // insert(), processInputMethodEvent() call removeSelectedText() first.
3932 if (m_maskData) {
3933 QString ms = maskString(m_cursor, s);
3934 for (int i = 0; i < ms.size(); ++i) {
3935 addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1));
3936 addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1));
3937 }
3938 m_text.replace(m_cursor, ms.size(), ms);
3939 m_cursor += ms.size();
3940 m_cursor = nextMaskBlank(m_cursor);
3941 m_textDirty = true;
3942 } else {
3943 int remaining = m_maxLength - m_text.size();
3944 if (remaining != 0) {
3945 const QStringView remainingStr = QStringView{s}.left(remaining);
3946 m_text.insert(m_cursor, remainingStr);
3947 for (auto e : remainingStr)
3948 addCommand(Command(Insert, m_cursor++, e, -1, -1));
3949 m_textDirty = true;
3950 }
3951 }
3952}
3953
3954/*!
3955 \internal
3956
3957 deletes a single character from the current text. If \a wasBackspace,
3958 the character prior to the cursor is removed. Otherwise the character
3959 after the cursor is removed.
3960
3961 Also adds the appropriate commands into the undo history.
3962 This function does not call finishChange(), and may leave the text
3963 in an invalid state.
3964*/
3965void QQuickTextInputPrivate::internalDelete(bool wasBackspace)
3966{
3967 if (m_cursor < m_text.size()) {
3968 cancelPasswordEchoTimer();
3969 Q_ASSERT(!hasSelectedText()); // del(), backspace() call removeSelectedText() first.
3970 addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)),
3971 m_cursor, m_text.at(m_cursor), -1, -1));
3972 if (m_maskData) {
3973 m_text.replace(m_cursor, 1, clearString(m_cursor, 1));
3974 addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1));
3975 } else {
3976 m_text.remove(m_cursor, 1);
3977 }
3978 m_textDirty = true;
3979 }
3980}
3981
3982/*!
3983 \internal
3984
3985 removes the currently selected text from the line control.
3986
3987 Also adds the appropriate commands into the undo history.
3988 This function does not call finishChange(), and may leave the text
3989 in an invalid state.
3990*/
3991void QQuickTextInputPrivate::removeSelectedText()
3992{
3993 if (m_selstart < m_selend && m_selend <= m_text.size()) {
3994 cancelPasswordEchoTimer();
3995 int i ;
3996 if (m_selstart <= m_cursor && m_cursor < m_selend) {
3997 // cursor is within the selection. Split up the commands
3998 // to be able to restore the correct cursor position
3999 for (i = m_cursor; i >= m_selstart; --i)
4000 addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1));
4001 for (i = m_selend - 1; i > m_cursor; --i)
4002 addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1));
4003 } else {
4004 for (i = m_selend-1; i >= m_selstart; --i)
4005 addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1));
4006 }
4007 if (m_maskData) {
4008 m_text.replace(m_selstart, m_selend - m_selstart, clearString(m_selstart, m_selend - m_selstart));
4009 for (int i = 0; i < m_selend - m_selstart; ++i)
4010 addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1));
4011 } else {
4012 m_text.remove(m_selstart, m_selend - m_selstart);
4013 }
4014 if (m_cursor > m_selstart)
4015 m_cursor -= qMin(m_cursor, m_selend) - m_selstart;
4016 internalDeselect();
4017 m_textDirty = true;
4018 }
4019}
4020
4021/*!
4022 \internal
4023
4024 Adds the current selection to the undo history.
4025
4026 Returns true if there is a current selection and false otherwise.
4027*/
4028
4029bool QQuickTextInputPrivate::separateSelection()
4030{
4031 if (hasSelectedText()) {
4032 separate();
4033 addCommand(Command(SetSelection, m_cursor, u'\0', m_selstart, m_selend));
4034 return true;
4035 } else {
4036 return false;
4037 }
4038}
4039
4040/*!
4041 \internal
4042
4043 Parses the input mask specified by \a maskFields to generate
4044 the mask data used to handle input masks.
4045*/
4046void QQuickTextInputPrivate::parseInputMask(const QString &maskFields)
4047{
4048 int delimiter = maskFields.indexOf(QLatin1Char(';'));
4049 if (maskFields.isEmpty() || delimiter == 0) {
4050 if (m_maskData) {
4051 m_maskData.reset(nullptr);
4052 m_maxLength = 32767;
4053 internalSetText(QString());
4054 }
4055 return;
4056 }
4057
4058 if (delimiter == -1) {
4059 m_blank = QLatin1Char(' ');
4060 m_inputMask = maskFields;
4061 } else {
4062 m_inputMask = maskFields.left(delimiter);
4063 m_blank = (delimiter + 1 < maskFields.size()) ? maskFields[delimiter + 1] : QLatin1Char(' ');
4064 }
4065
4066 // calculate m_maxLength / m_maskData length
4067 m_maxLength = 0;
4068 QChar c = u'\0';
4069 for (int i=0; i<m_inputMask.size(); i++) {
4070 c = m_inputMask.at(i);
4071 if (i > 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) {
4072 m_maxLength++;
4073 continue;
4074 }
4075 if (c != QLatin1Char('\\') && c != QLatin1Char('!') &&
4076 c != QLatin1Char('<') && c != QLatin1Char('>') &&
4077 c != QLatin1Char('{') && c != QLatin1Char('}') &&
4078 c != QLatin1Char('[') && c != QLatin1Char(']'))
4079 m_maxLength++;
4080 }
4081
4082 m_maskData.reset(new MaskInputData[m_maxLength]);
4083
4084 MaskInputData::Casemode m = MaskInputData::NoCaseMode;
4085 c = u'\0';
4086 bool s;
4087 bool escape = false;
4088 int index = 0;
4089 for (int i = 0; i < m_inputMask.size(); i++) {
4090 c = m_inputMask.at(i);
4091 if (escape) {
4092 s = true;
4093 m_maskData[index].maskChar = c;
4094 m_maskData[index].separator = s;
4095 m_maskData[index].caseMode = m;
4096 index++;
4097 escape = false;
4098 } else if (c == QLatin1Char('<')) {
4099 m = MaskInputData::Lower;
4100 } else if (c == QLatin1Char('>')) {
4101 m = MaskInputData::Upper;
4102 } else if (c == QLatin1Char('!')) {
4103 m = MaskInputData::NoCaseMode;
4104 } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) {
4105 switch (c.unicode()) {
4106 case 'A':
4107 case 'a':
4108 case 'N':
4109 case 'n':
4110 case 'X':
4111 case 'x':
4112 case '9':
4113 case '0':
4114 case 'D':
4115 case 'd':
4116 case '#':
4117 case 'H':
4118 case 'h':
4119 case 'B':
4120 case 'b':
4121 s = false;
4122 break;
4123 case '\\':
4124 escape = true;
4125 Q_FALLTHROUGH();
4126 default:
4127 s = true;
4128 break;
4129 }
4130
4131 if (!escape) {
4132 m_maskData[index].maskChar = c;
4133 m_maskData[index].separator = s;
4134 m_maskData[index].caseMode = m;
4135 index++;
4136 }
4137 }
4138 }
4139 internalSetText(m_text);
4140}
4141
4142
4143/*!
4144 \internal
4145
4146 checks if the key is valid compared to the inputMask
4147*/
4148bool QQuickTextInputPrivate::isValidInput(QChar key, QChar mask) const
4149{
4150 switch (mask.unicode()) {
4151 case 'A':
4152 if (key.isLetter())
4153 return true;
4154 break;
4155 case 'a':
4156 if (key.isLetter() || key == m_blank)
4157 return true;
4158 break;
4159 case 'N':
4160 if (key.isLetterOrNumber())
4161 return true;
4162 break;
4163 case 'n':
4164 if (key.isLetterOrNumber() || key == m_blank)
4165 return true;
4166 break;
4167 case 'X':
4168 if (key.isPrint() && key != m_blank)
4169 return true;
4170 break;
4171 case 'x':
4172 if (key.isPrint() || key == m_blank)
4173 return true;
4174 break;
4175 case '9':
4176 if (key.isNumber())
4177 return true;
4178 break;
4179 case '0':
4180 if (key.isNumber() || key == m_blank)
4181 return true;
4182 break;
4183 case 'D':
4184 if (key.isNumber() && key.digitValue() > 0)
4185 return true;
4186 break;
4187 case 'd':
4188 if ((key.isNumber() && key.digitValue() > 0) || key == m_blank)
4189 return true;
4190 break;
4191 case '#':
4192 if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank)
4193 return true;
4194 break;
4195 case 'B':
4196 if (key == QLatin1Char('0') || key == QLatin1Char('1'))
4197 return true;
4198 break;
4199 case 'b':
4200 if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank)
4201 return true;
4202 break;
4203 case 'H':
4204 if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')))
4205 return true;
4206 break;
4207 case 'h':
4208 if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank)
4209 return true;
4210 break;
4211 default:
4212 break;
4213 }
4214 return false;
4215}
4216
4217/*!
4218 \internal
4219
4220 Returns true if the given text \a str is valid for any
4221 validator or input mask set for the line control.
4222
4223 Otherwise returns false
4224*/
4225QQuickTextInputPrivate::ValidatorState QQuickTextInputPrivate::hasAcceptableInput(const QString &str) const
4226{
4227#if QT_CONFIG(validator)
4228 QString textCopy = str;
4229 int cursorCopy = m_cursor;
4230 if (m_validator) {
4231 QValidator::State state = m_validator->validate(textCopy, cursorCopy);
4232 if (state != QValidator::Acceptable)
4233 return ValidatorState(state);
4234 }
4235#endif
4236
4237 if (!m_maskData)
4238 return AcceptableInput;
4239
4240 if (str.size() != m_maxLength)
4241 return InvalidInput;
4242
4243 for (int i=0; i < m_maxLength; ++i) {
4244 if (m_maskData[i].separator) {
4245 if (str.at(i) != m_maskData[i].maskChar)
4246 return InvalidInput;
4247 } else {
4248 if (!isValidInput(str.at(i), m_maskData[i].maskChar))
4249 return InvalidInput;
4250 }
4251 }
4252 return AcceptableInput;
4253}
4254
4255/*!
4256 \internal
4257
4258 Applies the inputMask on \a str starting from position \a pos in the mask. \a clear
4259 specifies from where characters should be gotten when a separator is met in \a str - true means
4260 that blanks will be used, false that previous input is used.
4261 Calling this when no inputMask is set is undefined.
4262*/
4263QString QQuickTextInputPrivate::maskString(uint pos, const QString &str, bool clear) const
4264{
4265 if (pos >= (uint)m_maxLength)
4266 return QString::fromLatin1("");
4267
4268 QString fill;
4269 fill = clear ? clearString(0, m_maxLength) : m_text;
4270
4271 int strIndex = 0;
4272 QString s = QString::fromLatin1("");
4273 int i = pos;
4274 while (i < m_maxLength) {
4275 if (strIndex < str.size()) {
4276 if (m_maskData[i].separator) {
4277 s += m_maskData[i].maskChar;
4278 if (str[strIndex] == m_maskData[i].maskChar)
4279 strIndex++;
4280 ++i;
4281 } else {
4282 if (isValidInput(str[strIndex], m_maskData[i].maskChar)) {
4283 switch (m_maskData[i].caseMode) {
4284 case MaskInputData::Upper:
4285 s += str[strIndex].toUpper();
4286 break;
4287 case MaskInputData::Lower:
4288 s += str[strIndex].toLower();
4289 break;
4290 default:
4291 s += str[strIndex];
4292 }
4293 ++i;
4294 } else {
4295 // search for separator first
4296 int n = findInMask(i, true, true, str[strIndex]);
4297 if (n != -1) {
4298 if (str.size() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[strIndex]))) {
4299 s += QStringView{fill}.mid(i, n-i+1);
4300 i = n + 1; // update i to find + 1
4301 }
4302 } else {
4303 // search for valid m_blank if not
4304 n = findInMask(i, true, false, str[strIndex]);
4305 if (n != -1) {
4306 s += QStringView{fill}.mid(i, n-i);
4307 switch (m_maskData[n].caseMode) {
4308 case MaskInputData::Upper:
4309 s += str[strIndex].toUpper();
4310 break;
4311 case MaskInputData::Lower:
4312 s += str[strIndex].toLower();
4313 break;
4314 default:
4315 s += str[strIndex];
4316 }
4317 i = n + 1; // updates i to find + 1
4318 }
4319 }
4320 }
4321 ++strIndex;
4322 }
4323 } else
4324 break;
4325 }
4326
4327 return s;
4328}
4329
4330
4331
4332/*!
4333 \internal
4334
4335 Returns a "cleared" string with only separators and blank chars.
4336 Calling this when no inputMask is set is undefined.
4337*/
4338QString QQuickTextInputPrivate::clearString(uint pos, uint len) const
4339{
4340 if (pos >= (uint)m_maxLength)
4341 return QString();
4342
4343 QString s;
4344 int end = qMin((uint)m_maxLength, pos + len);
4345 for (int i = pos; i < end; ++i)
4346 if (m_maskData[i].separator)
4347 s += m_maskData[i].maskChar;
4348 else
4349 s += m_blank;
4350
4351 return s;
4352}
4353
4354/*!
4355 \internal
4356
4357 Strips blank parts of the input in a QQuickTextInputPrivate when an inputMask is set,
4358 separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1".
4359*/
4360QString QQuickTextInputPrivate::stripString(const QString &str) const
4361{
4362 if (!m_maskData)
4363 return str;
4364
4365 QString s;
4366 int end = qMin(m_maxLength, str.size());
4367 for (int i = 0; i < end; ++i) {
4368 if (m_maskData[i].separator)
4369 s += m_maskData[i].maskChar;
4370 else if (str[i] != m_blank)
4371 s += str[i];
4372 }
4373
4374 return s;
4375}
4376
4377/*!
4378 \internal
4379 searches forward/backward in m_maskData for either a separator or a m_blank
4380*/
4381int QQuickTextInputPrivate::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const
4382{
4383 if (pos >= m_maxLength || pos < 0)
4384 return -1;
4385
4386 int end = forward ? m_maxLength : -1;
4387 int step = forward ? 1 : -1;
4388 int i = pos;
4389
4390 while (i != end) {
4391 if (findSeparator) {
4392 if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar)
4393 return i;
4394 } else {
4395 if (!m_maskData[i].separator) {
4396 if (searchChar.isNull())
4397 return i;
4398 else if (isValidInput(searchChar, m_maskData[i].maskChar))
4399 return i;
4400 }
4401 }
4402 i += step;
4403 }
4404 return -1;
4405}
4406
4407void QQuickTextInputPrivate::internalUndo(int until)
4408{
4409 if (!isUndoAvailable())
4410 return;
4411 cancelPasswordEchoTimer();
4412 internalDeselect();
4413 while (m_undoState && m_undoState > until) {
4414 Command& cmd = m_history[--m_undoState];
4415 switch (cmd.type) {
4416 case Insert:
4417 m_text.remove(cmd.pos, 1);
4418 m_cursor = cmd.pos;
4419 break;
4420 case SetSelection:
4421 m_selstart = cmd.selStart;
4422 m_selend = cmd.selEnd;
4423 m_cursor = cmd.pos;
4424 break;
4425 case Remove:
4426 case RemoveSelection:
4427 m_text.insert(cmd.pos, cmd.uc);
4428 m_cursor = cmd.pos + 1;
4429 break;
4430 case Delete:
4431 case DeleteSelection:
4432 m_text.insert(cmd.pos, cmd.uc);
4433 m_cursor = cmd.pos;
4434 break;
4435 case Separator:
4436 continue;
4437 }
4438 if (until < 0 && m_undoState) {
4439 Command& next = m_history[m_undoState-1];
4440 if (next.type != cmd.type
4441 && next.type < RemoveSelection
4442 && (cmd.type < RemoveSelection || next.type == Separator)) {
4443 break;
4444 }
4445 }
4446 }
4447 separate();
4448 m_textDirty = true;
4449}
4450
4451void QQuickTextInputPrivate::internalRedo()
4452{
4453 if (!isRedoAvailable())
4454 return;
4455 internalDeselect();
4456 while (m_undoState < m_history.size()) {
4457 Command& cmd = m_history[m_undoState++];
4458 switch (cmd.type) {
4459 case Insert:
4460 m_text.insert(cmd.pos, cmd.uc);
4461 m_cursor = cmd.pos + 1;
4462 break;
4463 case SetSelection:
4464 m_selstart = cmd.selStart;
4465 m_selend = cmd.selEnd;
4466 m_cursor = cmd.pos;
4467 break;
4468 case Remove:
4469 case Delete:
4470 case RemoveSelection:
4471 case DeleteSelection:
4472 m_text.remove(cmd.pos, 1);
4473 m_selstart = cmd.selStart;
4474 m_selend = cmd.selEnd;
4475 m_cursor = cmd.pos;
4476 break;
4477 case Separator:
4478 m_selstart = cmd.selStart;
4479 m_selend = cmd.selEnd;
4480 m_cursor = cmd.pos;
4481 break;
4482 }
4483 if (m_undoState < m_history.size()) {
4484 Command& next = m_history[m_undoState];
4485 if (next.type != cmd.type
4486 && cmd.type < RemoveSelection
4487 && next.type != Separator
4488 && (next.type < RemoveSelection || cmd.type == Separator)) {
4489 break;
4490 }
4491 }
4492 }
4493 m_textDirty = true;
4494}
4495
4496void QQuickTextInputPrivate::emitUndoRedoChanged()
4497{
4498 Q_Q(QQuickTextInput);
4499 const bool previousUndo = canUndo;
4500 const bool previousRedo = canRedo;
4501
4502 canUndo = isUndoAvailable();
4503 canRedo = isRedoAvailable();
4504
4505 if (previousUndo != canUndo)
4506 emit q->canUndoChanged();
4507 if (previousRedo != canRedo)
4508 emit q->canRedoChanged();
4509}
4510
4511/*!
4512 \internal
4513
4514 If the current cursor position differs from the last emitted cursor
4515 position, emits cursorPositionChanged().
4516*/
4517bool QQuickTextInputPrivate::emitCursorPositionChanged()
4518{
4519 Q_Q(QQuickTextInput);
4520 if (m_cursor != m_lastCursorPos) {
4521 m_lastCursorPos = m_cursor;
4522
4523 q->updateCursorRectangle();
4524 emit q->cursorPositionChanged();
4525
4526 if (!hasSelectedText()) {
4527 if (lastSelectionStart != m_cursor) {
4528 lastSelectionStart = m_cursor;
4529 emit q->selectionStartChanged();
4530 }
4531 if (lastSelectionEnd != m_cursor) {
4532 lastSelectionEnd = m_cursor;
4533 emit q->selectionEndChanged();
4534 }
4535 }
4536
4537#if QT_CONFIG(accessibility)
4538 if (QAccessible::isActive()) {
4539 if (QObject *acc = QQuickAccessibleAttached::findAccessible(q, QAccessible::EditableText)) {
4540 QAccessibleTextCursorEvent ev(acc, m_cursor);
4541 QAccessible::updateAccessibility(&ev);
4542 }
4543 }
4544#endif
4545
4546 return true;
4547 }
4548 return false;
4549}
4550
4551
4552void QQuickTextInputPrivate::setBlinkingCursorEnabled(bool enable)
4553{
4554 if (enable == m_blinkEnabled)
4555 return;
4556
4557 m_blinkEnabled = enable;
4558 updateCursorBlinking();
4559
4560 if (enable)
4561 connect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QQuickTextInputPrivate::updateCursorBlinking);
4562 else
4563 disconnect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QQuickTextInputPrivate::updateCursorBlinking);
4564}
4565
4566void QQuickTextInputPrivate::updateCursorBlinking()
4567{
4568 Q_Q(QQuickTextInput);
4569
4570 if (m_blinkTimer) {
4571 q->killTimer(m_blinkTimer);
4572 m_blinkTimer = 0;
4573 }
4574
4575 if (m_blinkEnabled && cursorVisible && !cursorItem && !m_readOnly) {
4576 int flashTime = QGuiApplication::styleHints()->cursorFlashTime();
4577 if (flashTime >= 2)
4578 m_blinkTimer = q->startTimer(flashTime / 2);
4579 }
4580
4581 m_blinkStatus = 1;
4582 updateType = UpdatePaintNode;
4583 q->polish();
4584 q->update();
4585}
4586
4587void QQuickTextInput::timerEvent(QTimerEvent *event)
4588{
4589 Q_D(QQuickTextInput);
4590 if (event->timerId() == d->m_blinkTimer) {
4591 d->m_blinkStatus = !d->m_blinkStatus;
4592 d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
4593 polish();
4594 update();
4595 } else if (event->timerId() == d->m_passwordEchoTimer.timerId()) {
4596 d->m_passwordEchoTimer.stop();
4597 d->updateDisplayText();
4598 updateCursorRectangle();
4599 }
4600}
4601
4602void QQuickTextInputPrivate::processKeyEvent(QKeyEvent* event)
4603{
4604 Q_Q(QQuickTextInput);
4605
4606 if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
4607 if (hasAcceptableInput(m_text) == AcceptableInput || fixup()) {
4608
4609 QInputMethod *inputMethod = QGuiApplication::inputMethod();
4610 inputMethod->commit();
4611
4612 if (activeFocus) {
4613 // If we lost focus after hiding the virtual keyboard, we've already emitted
4614 // editingFinished from handleFocusEvent. Otherwise we emit it now.
4615 emit q->editingFinished();
4616 }
4617
4618 emit q->accepted();
4619 }
4620 event->ignore();
4621 return;
4622 }
4623
4624 if (m_blinkEnabled)
4625 updateCursorBlinking();
4626
4627 if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit
4628 && !m_passwordEchoEditing
4629 && !m_readOnly
4630 && !event->text().isEmpty()
4631 && !(event->modifiers() & Qt::ControlModifier)) {
4632 // Clear the edit and reset to normal echo mode while editing; the
4633 // echo mode switches back when the edit loses focus
4634 // ### resets current content. dubious code; you can
4635 // navigate with keys up, down, back, and select(?), but if you press
4636 // "left" or "right" it clears?
4637 updatePasswordEchoEditing(true);
4638 clear();
4639 }
4640
4641 bool unknown = false;
4642#if QT_CONFIG(shortcut)
4643 bool visual = cursorMoveStyle() == Qt::VisualMoveStyle;
4644#endif
4645
4646 if (false) {
4647 }
4648#if QT_CONFIG(shortcut)
4649 else if (event == QKeySequence::Undo) {
4650 q->undo();
4651 }
4652 else if (event == QKeySequence::Redo) {
4653 q->redo();
4654 }
4655 else if (event == QKeySequence::SelectAll) {
4656 selectAll();
4657 }
4658#if QT_CONFIG(clipboard)
4659 else if (event == QKeySequence::Copy) {
4660 copy();
4661 }
4662 else if (event == QKeySequence::Paste) {
4663 if (!m_readOnly) {
4664 QClipboard::Mode mode = QClipboard::Clipboard;
4665 paste(mode);
4666 }
4667 }
4668 else if (event == QKeySequence::Cut) {
4669 q->cut();
4670 }
4671 else if (event == QKeySequence::DeleteEndOfLine) {
4672 if (!m_readOnly)
4673 deleteEndOfLine();
4674 }
4675#endif // clipboard
4676 else if (event == QKeySequence::MoveToStartOfLine || event == QKeySequence::MoveToStartOfBlock) {
4677 home(0);
4678 }
4679 else if (event == QKeySequence::MoveToEndOfLine || event == QKeySequence::MoveToEndOfBlock) {
4680 end(0);
4681 }
4682 else if (event == QKeySequence::SelectStartOfLine || event == QKeySequence::SelectStartOfBlock) {
4683 home(1);
4684 }
4685 else if (event == QKeySequence::SelectEndOfLine || event == QKeySequence::SelectEndOfBlock) {
4686 end(1);
4687 }
4688 else if (event == QKeySequence::MoveToNextChar) {
4689 if (hasSelectedText()) {
4690 moveCursor(selectionEnd(), false);
4691 } else {
4692 cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1));
4693 }
4694 }
4695 else if (event == QKeySequence::SelectNextChar) {
4696 cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1));
4697 }
4698 else if (event == QKeySequence::MoveToPreviousChar) {
4699 if (hasSelectedText()) {
4700 moveCursor(selectionStart(), false);
4701 } else {
4702 cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1));
4703 }
4704 }
4705 else if (event == QKeySequence::SelectPreviousChar) {
4706 cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1));
4707 }
4708 else if (event == QKeySequence::MoveToNextWord) {
4709 if (m_echoMode == QQuickTextInput::Normal)
4710 layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0);
4711 else
4712 layoutDirection() == Qt::LeftToRight ? end(0) : home(0);
4713 }
4714 else if (event == QKeySequence::MoveToPreviousWord) {
4715 if (m_echoMode == QQuickTextInput::Normal)
4716 layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0);
4717 else if (!m_readOnly) {
4718 layoutDirection() == Qt::LeftToRight ? home(0) : end(0);
4719 }
4720 }
4721 else if (event == QKeySequence::SelectNextWord) {
4722 if (m_echoMode == QQuickTextInput::Normal)
4723 layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1);
4724 else
4725 layoutDirection() == Qt::LeftToRight ? end(1) : home(1);
4726 }
4727 else if (event == QKeySequence::SelectPreviousWord) {
4728 if (m_echoMode == QQuickTextInput::Normal)
4729 layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1);
4730 else
4731 layoutDirection() == Qt::LeftToRight ? home(1) : end(1);
4732 }
4733 else if (event == QKeySequence::Delete) {
4734 if (!m_readOnly)
4735 del();
4736 }
4737 else if (event == QKeySequence::DeleteEndOfWord) {
4738 if (!m_readOnly)
4739 deleteEndOfWord();
4740 }
4741 else if (event == QKeySequence::DeleteStartOfWord) {
4742 if (!m_readOnly)
4743 deleteStartOfWord();
4744 } else if (event == QKeySequence::DeleteCompleteLine) {
4745 if (!m_readOnly) {
4746 selectAll();
4747#if QT_CONFIG(clipboard)
4748 copy();
4749#endif
4750 del();
4751 }
4752 }
4753#endif // shortcut
4754 else {
4755 bool handled = false;
4756 if (event->modifiers() & Qt::ControlModifier) {
4757 switch (event->key()) {
4758 case Qt::Key_Backspace:
4759 if (!m_readOnly)
4760 deleteStartOfWord();
4761 break;
4762 default:
4763 if (!handled)
4764 unknown = true;
4765 }
4766 } else { // ### check for *no* modifier
4767 switch (event->key()) {
4768 case Qt::Key_Backspace:
4769 if (!m_readOnly) {
4770 backspace();
4771 }
4772 break;
4773 default:
4774 if (!handled)
4775 unknown = true;
4776 }
4777 }
4778 }
4779
4780 if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) {
4781 setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft);
4782 unknown = false;
4783 }
4784
4785 if (unknown && !m_readOnly) {
4786 if (m_inputControl->isAcceptableInput(event)) {
4787 if (overwriteMode
4788 // no need to call del() if we have a selection, insert
4789 // does it already
4790 && !hasSelectedText()
4791 && !(m_cursor == q_func()->text().size())) {
4792 del();
4793 }
4794
4795 insert(event->text());
4796 event->accept();
4797 return;
4798 }
4799 }
4800
4801 if (unknown)
4802 event->ignore();
4803 else
4804 event->accept();
4805}
4806
4807/*!
4808 \internal
4809
4810 Deletes the portion of the word before the current cursor position.
4811*/
4812
4813void QQuickTextInputPrivate::deleteStartOfWord()
4814{
4815 int priorState = m_undoState;
4816
4817 if (!separateSelection()) {
4818 Command cmd(SetSelection, m_cursor, u'\0', m_selstart, m_selend);
4819 separate();
4820 cursorWordBackward(true);
4821 addCommand(cmd);
4822 }
4823
4824 removeSelectedText();
4825 finishChange(priorState);
4826}
4827
4828/*!
4829 \internal
4830
4831 Deletes the portion of the word after the current cursor position.
4832*/
4833
4834void QQuickTextInputPrivate::deleteEndOfWord()
4835{
4836 int priorState = m_undoState;
4837 Command cmd(SetSelection, m_cursor, u'\0', m_selstart, m_selend);
4838 separate();
4839 cursorWordForward(true);
4840 // moveCursor (sometimes) calls separate() so we need to add the command after that so the
4841 // cursor position and selection are restored in the same undo operation as the remove.
4842 addCommand(cmd);
4843 removeSelectedText();
4844 finishChange(priorState);
4845}
4846
4847/*!
4848 \internal
4849
4850 Deletes all text from the cursor position to the end of the line.
4851*/
4852
4853void QQuickTextInputPrivate::deleteEndOfLine()
4854{
4855 int priorState = m_undoState;
4856 Command cmd(SetSelection, m_cursor, u'\0', m_selstart, m_selend);
4857 separate();
4858 setSelection(m_cursor, end());
4859 addCommand(cmd);
4860 removeSelectedText();
4861 finishChange(priorState);
4862}
4863
4864/*!
4865 \qmlmethod void QtQuick::TextInput::ensureVisible(int position)
4866 \since 5.4
4867
4868 Scrolls the contents of the text input so that the specified character
4869 \a position is visible inside the boundaries of the text input.
4870
4871 \sa autoScroll
4872*/
4873void QQuickTextInput::ensureVisible(int position)
4874{
4875 Q_D(QQuickTextInput);
4876 d->ensureVisible(position);
4877 updateCursorRectangle(false);
4878}
4879
4880/*!
4881 \qmlmethod void QtQuick::TextInput::clear()
4882 \since 5.7
4883
4884 Clears the contents of the text input
4885 and resets partial text input from an input method.
4886
4887 Use this method instead of setting the \l text property to an empty string.
4888
4889 \sa QInputMethod::reset()
4890*/
4891void QQuickTextInput::clear()
4892{
4893 Q_D(QQuickTextInput);
4894 d->cancelInput();
4895 d->clear();
4896}
4897
4898/*!
4899 \since 5.6
4900 \qmlproperty real QtQuick::TextInput::padding
4901 \qmlproperty real QtQuick::TextInput::topPadding
4902 \qmlproperty real QtQuick::TextInput::leftPadding
4903 \qmlproperty real QtQuick::TextInput::bottomPadding
4904 \qmlproperty real QtQuick::TextInput::rightPadding
4905
4906 These properties hold the padding around the content. This space is reserved
4907 in addition to the contentWidth and contentHeight.
4908
4909 The individual padding properties assume the value of the \c padding
4910 property unless they are set explicitly. For example, if \c padding is
4911 set to \c 4 and \c leftPadding to \c 8, \c 8 will be used as the left
4912 padding.
4913
4914 \note If an explicit width or height is given to a TextInput, care must be
4915 taken to ensure it is large enough to accommodate the relevant padding
4916 values. For example: if \c topPadding and \c bottomPadding are set to
4917 \c 10, but the height of the TextInput is only set to \c 20, the text will
4918 not have enough vertical space in which to be rendered, and will appear
4919 clipped.
4920*/
4921qreal QQuickTextInput::padding() const
4922{
4923 Q_D(const QQuickTextInput);
4924 return d->padding();
4925}
4926
4927void QQuickTextInput::setPadding(qreal padding)
4928{
4929 Q_D(QQuickTextInput);
4930 if (qFuzzyCompare(d->padding(), padding))
4931 return;
4932
4933 d->extra.value().padding = padding;
4934 d->updateLayout();
4935 updateCursorRectangle();
4936 emit paddingChanged();
4937 if (!d->extra.isAllocated() || !d->extra->explicitTopPadding)
4938 emit topPaddingChanged();
4939 if (!d->extra.isAllocated() || !d->extra->explicitLeftPadding)
4940 emit leftPaddingChanged();
4941 if (!d->extra.isAllocated() || !d->extra->explicitRightPadding)
4942 emit rightPaddingChanged();
4943 if (!d->extra.isAllocated() || !d->extra->explicitBottomPadding)
4944 emit bottomPaddingChanged();
4945}
4946
4947void QQuickTextInput::resetPadding()
4948{
4949 setPadding(0);
4950}
4951
4952qreal QQuickTextInput::topPadding() const
4953{
4954 Q_D(const QQuickTextInput);
4955 if (d->extra.isAllocated() && d->extra->explicitTopPadding)
4956 return d->extra->topPadding;
4957 return d->padding();
4958}
4959
4960void QQuickTextInput::setTopPadding(qreal padding)
4961{
4962 Q_D(QQuickTextInput);
4963 d->setTopPadding(padding);
4964}
4965
4966void QQuickTextInput::resetTopPadding()
4967{
4968 Q_D(QQuickTextInput);
4969 d->setTopPadding(0, true);
4970}
4971
4972qreal QQuickTextInput::leftPadding() const
4973{
4974 Q_D(const QQuickTextInput);
4975 if (d->extra.isAllocated() && d->extra->explicitLeftPadding)
4976 return d->extra->leftPadding;
4977 return d->padding();
4978}
4979
4980void QQuickTextInput::setLeftPadding(qreal padding)
4981{
4982 Q_D(QQuickTextInput);
4983 d->setLeftPadding(padding);
4984}
4985
4986void QQuickTextInput::resetLeftPadding()
4987{
4988 Q_D(QQuickTextInput);
4989 d->setLeftPadding(0, true);
4990}
4991
4992qreal QQuickTextInput::rightPadding() const
4993{
4994 Q_D(const QQuickTextInput);
4995 if (d->extra.isAllocated() && d->extra->explicitRightPadding)
4996 return d->extra->rightPadding;
4997 return d->padding();
4998}
4999
5000void QQuickTextInput::setRightPadding(qreal padding)
5001{
5002 Q_D(QQuickTextInput);
5003 d->setRightPadding(padding);
5004}
5005
5006void QQuickTextInput::resetRightPadding()
5007{
5008 Q_D(QQuickTextInput);
5009 d->setRightPadding(0, true);
5010}
5011
5012qreal QQuickTextInput::bottomPadding() const
5013{
5014 Q_D(const QQuickTextInput);
5015 if (d->extra.isAllocated() && d->extra->explicitBottomPadding)
5016 return d->extra->bottomPadding;
5017 return d->padding();
5018}
5019
5020void QQuickTextInput::setBottomPadding(qreal padding)
5021{
5022 Q_D(QQuickTextInput);
5023 d->setBottomPadding(padding);
5024}
5025
5026void QQuickTextInput::resetBottomPadding()
5027{
5028 Q_D(QQuickTextInput);
5029 d->setBottomPadding(0, true);
5030}
5031
5032#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
5033void QQuickTextInput::setOldSelectionDefault()
5034{
5035 Q_D(QQuickTextInput);
5036 d->selectByMouse = false;
5037 d->selectByTouchDrag = true;
5038 qCDebug(lcQuickTextInput, "pre-6.4 behavior chosen: selectByMouse defaults false; if enabled, touchscreen acts like a mouse");
5039}
5040
5041// TODO in 6.7.0: remove the note about versions prior to 6.4 in selectByMouse() documentation
5042QQuickPre64TextInput::QQuickPre64TextInput(QQuickItem *parent)
5043 : QQuickTextInput(parent)
5044{
5045 setOldSelectionDefault();
5046}
5047#endif
5048
5049QT_END_NAMESPACE
5050
5051#include "moc_qquicktextinput_p.cpp"
Combined button and popup list for selecting options.