Remove expected failure for qpa platform
[profile/ivi/qtdeclarative.git] / tests / auto / declarative / qsgtextinput / tst_qsgtextinput.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the test suite of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 #include <qtest.h>
42 #include <QtTest/QSignalSpy>
43 #include "../../../shared/util.h"
44 #include <QtDeclarative/qdeclarativeengine.h>
45 #include <QFile>
46 #include <QtDeclarative/qsgview.h>
47 #include <private/qsgtextinput_p.h>
48 #include <private/qsgtextinput_p_p.h>
49 #include <QDebug>
50 #include <QDir>
51 #include <QStyle>
52 #include <QInputContext>
53 #include <QtWidgets/5.0.0/QtWidgets/private/qapplication_p.h>
54 #include <private/qsgdistancefieldglyphcache_p.h>
55 #include <QtOpenGL/QGLShaderProgram>
56 #include <math.h>
57
58 #include "qplatformdefs.h"
59
60 #ifdef Q_OS_SYMBIAN
61 // In Symbian OS test data is located in applications private dir
62 #define SRCDIR "."
63 #endif
64
65 Q_DECLARE_METATYPE(QSGTextInput::SelectionMode)
66 DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)
67
68 QString createExpectedFileIfNotFound(const QString& filebasename, const QImage& actual)
69 {
70     // XXX This will be replaced by some clever persistent platform image store.
71     QString persistent_dir = SRCDIR "/data";
72     QString arch = "unknown-architecture"; // QTest needs to help with this.
73
74     QString expectfile = persistent_dir + QDir::separator() + filebasename + "-" + arch + ".png";
75
76     if (!QFile::exists(expectfile)) {
77         actual.save(expectfile);
78         qWarning() << "created" << expectfile;
79     }
80
81     return expectfile;
82 }
83
84 class tst_qsgtextinput : public QObject
85
86 {
87     Q_OBJECT
88 public:
89     tst_qsgtextinput();
90
91 private slots:
92     void initTestCase();
93     void cleanupTestCase();
94     void text();
95     void width();
96     void font();
97     void color();
98     void selection();
99     void isRightToLeft_data();
100     void isRightToLeft();
101     void moveCursorSelection_data();
102     void moveCursorSelection();
103     void moveCursorSelectionSequence_data();
104     void moveCursorSelectionSequence();
105     void dragMouseSelection();
106     void mouseSelectionMode_data();
107     void mouseSelectionMode();
108
109     void horizontalAlignment_data();
110     void horizontalAlignment();
111     void horizontalAlignment_RightToLeft();
112
113     void positionAt();
114
115     void maxLength();
116     void masks();
117     void validators();
118     void inputMethods();
119
120     void passwordCharacter();
121     void cursorDelegate();
122     void cursorVisible();
123     void cursorRectangle();
124     void navigation();
125     void navigation_RTL();
126     void copyAndPaste();
127     void canPasteEmpty();
128     void canPaste();
129     void readOnly();
130
131     void openInputPanelOnClick();
132     void openInputPanelOnFocus();
133     void setHAlignClearCache();
134     void focusOutClearSelection();
135
136     void echoMode();
137 #ifdef QT_GUI_PASSWORD_ECHO_DELAY
138     void passwordEchoDelay();
139 #endif
140     void geometrySignals();
141     void testQtQuick11Attributes();
142     void testQtQuick11Attributes_data();
143
144     void preeditAutoScroll();
145     void preeditMicroFocus();
146     void inputContextMouseHandler();
147     void inputMethodComposing();
148     void cursorRectangleSize();
149
150 private:
151     void simulateKey(QSGView *, int key);
152
153     QDeclarativeEngine engine;
154     QStringList standard;
155     QStringList colorStrings;
156 };
157 void tst_qsgtextinput::initTestCase()
158 {
159 }
160
161 void tst_qsgtextinput::cleanupTestCase()
162 {
163
164 }
165 tst_qsgtextinput::tst_qsgtextinput()
166 {
167     standard << "the quick brown fox jumped over the lazy dog"
168         << "It's supercalifragisiticexpialidocious!"
169         << "Hello, world!"
170         << "!dlrow ,olleH"
171         << " spacey   text ";
172
173     colorStrings << "aliceblue"
174                  << "antiquewhite"
175                  << "aqua"
176                  << "darkkhaki"
177                  << "darkolivegreen"
178                  << "dimgray"
179                  << "palevioletred"
180                  << "lightsteelblue"
181                  << "#000000"
182                  << "#AAAAAA"
183                  << "#FFFFFF"
184                  << "#2AC05F";
185 }
186
187 void tst_qsgtextinput::text()
188 {
189     {
190         QDeclarativeComponent textinputComponent(&engine);
191         textinputComponent.setData("import QtQuick 2.0\nTextInput {  text: \"\"  }", QUrl());
192         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
193
194         QVERIFY(textinputObject != 0);
195         QCOMPARE(textinputObject->text(), QString(""));
196
197         delete textinputObject;
198     }
199
200     for (int i = 0; i < standard.size(); i++)
201     {
202         QString componentStr = "import QtQuick 2.0\nTextInput { text: \"" + standard.at(i) + "\" }";
203         QDeclarativeComponent textinputComponent(&engine);
204         textinputComponent.setData(componentStr.toLatin1(), QUrl());
205         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
206
207         QVERIFY(textinputObject != 0);
208         QCOMPARE(textinputObject->text(), standard.at(i));
209
210         delete textinputObject;
211     }
212
213 }
214
215 void tst_qsgtextinput::width()
216 {
217     // uses Font metrics to find the width for standard
218     {
219         QDeclarativeComponent textinputComponent(&engine);
220         textinputComponent.setData("import QtQuick 2.0\nTextInput {  text: \"\" }", QUrl());
221         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
222
223         QVERIFY(textinputObject != 0);
224         QCOMPARE(textinputObject->width(), 0.0);
225
226         delete textinputObject;
227     }
228
229     bool requiresUnhintedMetrics = !qmlDisableDistanceField();
230
231     for (int i = 0; i < standard.size(); i++)
232     {
233         QFont f;
234         qreal metricWidth = 0.0;
235         if (requiresUnhintedMetrics) {
236             QString s = standard.at(i);
237             s.replace(QLatin1Char('\n'), QChar::LineSeparator);
238
239             QTextLayout layout(s);
240             layout.setFlags(Qt::TextExpandTabs | Qt::TextShowMnemonic);
241             {
242                 QTextOption option;
243                 option.setUseDesignMetrics(true);
244                 layout.setTextOption(option);
245             }
246
247             layout.beginLayout();
248             forever {
249                 QTextLine line = layout.createLine();
250                 if (!line.isValid())
251                     break;
252             }
253
254             layout.endLayout();
255
256             metricWidth = ceil(layout.boundingRect().width());
257         } else {
258             QFontMetricsF fm(f);
259             metricWidth = fm.width(standard.at(i));
260         }
261
262         QString componentStr = "import QtQuick 2.0\nTextInput { text: \"" + standard.at(i) + "\" }";
263         QDeclarativeComponent textinputComponent(&engine);
264         textinputComponent.setData(componentStr.toLatin1(), QUrl());
265         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
266
267         QVERIFY(textinputObject != 0);
268         int delta = abs(int(int(textinputObject->width()) - metricWidth));
269         QVERIFY(delta <= 3.0); // As best as we can hope for cross-platform.
270
271         delete textinputObject;
272     }
273 }
274
275 void tst_qsgtextinput::font()
276 {
277     //test size, then bold, then italic, then family
278     { 
279         QString componentStr = "import QtQuick 2.0\nTextInput {  font.pointSize: 40; text: \"Hello World\" }";
280         QDeclarativeComponent textinputComponent(&engine);
281         textinputComponent.setData(componentStr.toLatin1(), QUrl());
282         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
283
284         QVERIFY(textinputObject != 0);
285         QCOMPARE(textinputObject->font().pointSize(), 40);
286         QCOMPARE(textinputObject->font().bold(), false);
287         QCOMPARE(textinputObject->font().italic(), false);
288
289         delete textinputObject;
290     }
291
292     { 
293         QString componentStr = "import QtQuick 2.0\nTextInput {  font.bold: true; text: \"Hello World\" }";
294         QDeclarativeComponent textinputComponent(&engine);
295         textinputComponent.setData(componentStr.toLatin1(), QUrl());
296         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
297
298         QVERIFY(textinputObject != 0);
299         QCOMPARE(textinputObject->font().bold(), true);
300         QCOMPARE(textinputObject->font().italic(), false);
301
302         delete textinputObject;
303     }
304
305     { 
306         QString componentStr = "import QtQuick 2.0\nTextInput {  font.italic: true; text: \"Hello World\" }";
307         QDeclarativeComponent textinputComponent(&engine);
308         textinputComponent.setData(componentStr.toLatin1(), QUrl());
309         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
310
311         QVERIFY(textinputObject != 0);
312         QCOMPARE(textinputObject->font().italic(), true);
313         QCOMPARE(textinputObject->font().bold(), false);
314
315         delete textinputObject;
316     }
317  
318     { 
319         QString componentStr = "import QtQuick 2.0\nTextInput {  font.family: \"Helvetica\"; text: \"Hello World\" }";
320         QDeclarativeComponent textinputComponent(&engine);
321         textinputComponent.setData(componentStr.toLatin1(), QUrl());
322         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
323
324         QVERIFY(textinputObject != 0);
325         QCOMPARE(textinputObject->font().family(), QString("Helvetica"));
326         QCOMPARE(textinputObject->font().bold(), false);
327         QCOMPARE(textinputObject->font().italic(), false);
328
329         delete textinputObject;
330     }
331
332     { 
333         QString componentStr = "import QtQuick 2.0\nTextInput {  font.family: \"\"; text: \"Hello World\" }";
334         QDeclarativeComponent textinputComponent(&engine);
335         textinputComponent.setData(componentStr.toLatin1(), QUrl());
336         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
337
338         QVERIFY(textinputObject != 0);
339         QCOMPARE(textinputObject->font().family(), QString(""));
340
341         delete textinputObject;
342     }
343 }
344
345 void tst_qsgtextinput::color()
346 {
347     //test color
348     for (int i = 0; i < colorStrings.size(); i++)
349     { 
350         QString componentStr = "import QtQuick 2.0\nTextInput {  color: \"" + colorStrings.at(i) + "\"; text: \"Hello World\" }";
351         QDeclarativeComponent textinputComponent(&engine);
352         textinputComponent.setData(componentStr.toLatin1(), QUrl());
353         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
354         QVERIFY(textinputObject != 0);
355         QCOMPARE(textinputObject->color(), QColor(colorStrings.at(i)));
356
357         delete textinputObject;
358     }
359
360     //test selection color
361     for (int i = 0; i < colorStrings.size(); i++)
362     {
363         QString componentStr = "import QtQuick 2.0\nTextInput {  selectionColor: \"" + colorStrings.at(i) + "\"; text: \"Hello World\" }";
364         QDeclarativeComponent textinputComponent(&engine);
365         textinputComponent.setData(componentStr.toLatin1(), QUrl());
366         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
367         QVERIFY(textinputObject != 0);
368         QCOMPARE(textinputObject->selectionColor(), QColor(colorStrings.at(i)));
369
370         delete textinputObject;
371     }
372
373     //test selected text color
374     for (int i = 0; i < colorStrings.size(); i++)
375     { 
376         QString componentStr = "import QtQuick 2.0\nTextInput {  selectedTextColor: \"" + colorStrings.at(i) + "\"; text: \"Hello World\" }";
377         QDeclarativeComponent textinputComponent(&engine);
378         textinputComponent.setData(componentStr.toLatin1(), QUrl());
379         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
380         QVERIFY(textinputObject != 0);
381         QCOMPARE(textinputObject->selectedTextColor(), QColor(colorStrings.at(i)));
382
383         delete textinputObject;
384     }
385
386     {
387         QString colorStr = "#AA001234";
388         QColor testColor("#001234");
389         testColor.setAlpha(170);
390
391         QString componentStr = "import QtQuick 2.0\nTextInput {  color: \"" + colorStr + "\"; text: \"Hello World\" }";
392         QDeclarativeComponent textinputComponent(&engine);
393         textinputComponent.setData(componentStr.toLatin1(), QUrl());
394         QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
395
396         QVERIFY(textinputObject != 0);
397         QCOMPARE(textinputObject->color(), testColor);
398
399         delete textinputObject;
400     }
401 }
402
403 void tst_qsgtextinput::selection()
404 {
405     QString testStr = standard[0];
406     QString componentStr = "import QtQuick 2.0\nTextInput {  text: \""+ testStr +"\"; }";
407     QDeclarativeComponent textinputComponent(&engine);
408     textinputComponent.setData(componentStr.toLatin1(), QUrl());
409     QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
410     QVERIFY(textinputObject != 0);
411
412
413     //Test selection follows cursor
414     for(int i=0; i<= testStr.size(); i++) {
415         textinputObject->setCursorPosition(i);
416         QCOMPARE(textinputObject->cursorPosition(), i);
417         QCOMPARE(textinputObject->selectionStart(), i);
418         QCOMPARE(textinputObject->selectionEnd(), i);
419         QVERIFY(textinputObject->selectedText().isNull());
420     }
421
422     textinputObject->setCursorPosition(0);
423     QVERIFY(textinputObject->cursorPosition() == 0);
424     QVERIFY(textinputObject->selectionStart() == 0);
425     QVERIFY(textinputObject->selectionEnd() == 0);
426     QVERIFY(textinputObject->selectedText().isNull());
427
428     // Verify invalid positions are ignored.
429     textinputObject->setCursorPosition(-1);
430     QVERIFY(textinputObject->cursorPosition() == 0);
431     QVERIFY(textinputObject->selectionStart() == 0);
432     QVERIFY(textinputObject->selectionEnd() == 0);
433     QVERIFY(textinputObject->selectedText().isNull());
434
435     textinputObject->setCursorPosition(textinputObject->text().count()+1);
436     QVERIFY(textinputObject->cursorPosition() == 0);
437     QVERIFY(textinputObject->selectionStart() == 0);
438     QVERIFY(textinputObject->selectionEnd() == 0);
439     QVERIFY(textinputObject->selectedText().isNull());
440
441     //Test selection
442     for(int i=0; i<= testStr.size(); i++) {
443         textinputObject->select(0,i);
444         QCOMPARE(testStr.mid(0,i), textinputObject->selectedText());
445     }
446     for(int i=0; i<= testStr.size(); i++) {
447         textinputObject->select(i,testStr.size());
448         QCOMPARE(testStr.mid(i,testStr.size()-i), textinputObject->selectedText());
449     }
450
451     textinputObject->setCursorPosition(0);
452     QVERIFY(textinputObject->cursorPosition() == 0);
453     QVERIFY(textinputObject->selectionStart() == 0);
454     QVERIFY(textinputObject->selectionEnd() == 0);
455     QVERIFY(textinputObject->selectedText().isNull());
456
457     //Test Error Ignoring behaviour
458     textinputObject->setCursorPosition(0);
459     QVERIFY(textinputObject->selectedText().isNull());
460     textinputObject->select(-10,0);
461     QVERIFY(textinputObject->selectedText().isNull());
462     textinputObject->select(100,110);
463     QVERIFY(textinputObject->selectedText().isNull());
464     textinputObject->select(0,-10);
465     QVERIFY(textinputObject->selectedText().isNull());
466     textinputObject->select(0,100);
467     QVERIFY(textinputObject->selectedText().isNull());
468     textinputObject->select(0,10);
469     QVERIFY(textinputObject->selectedText().size() == 10);
470     textinputObject->select(-10,10);
471     QVERIFY(textinputObject->selectedText().size() == 10);
472     textinputObject->select(100,101);
473     QVERIFY(textinputObject->selectedText().size() == 10);
474     textinputObject->select(0,-10);
475     QVERIFY(textinputObject->selectedText().size() == 10);
476     textinputObject->select(0,100);
477     QVERIFY(textinputObject->selectedText().size() == 10);
478
479     textinputObject->deselect();
480     QVERIFY(textinputObject->selectedText().isNull());
481     textinputObject->select(0,10);
482     QVERIFY(textinputObject->selectedText().size() == 10);
483     textinputObject->deselect();
484     QVERIFY(textinputObject->selectedText().isNull());
485
486     delete textinputObject;
487 }
488
489 void tst_qsgtextinput::isRightToLeft_data()
490 {
491     QTest::addColumn<QString>("text");
492     QTest::addColumn<bool>("emptyString");
493     QTest::addColumn<bool>("firstCharacter");
494     QTest::addColumn<bool>("lastCharacter");
495     QTest::addColumn<bool>("middleCharacter");
496     QTest::addColumn<bool>("startString");
497     QTest::addColumn<bool>("midString");
498     QTest::addColumn<bool>("endString");
499
500     const quint16 arabic_str[] = { 0x0638, 0x0643, 0x00646, 0x0647, 0x0633, 0x0638, 0x0643, 0x00646, 0x0647, 0x0633, 0x0647};
501     QTest::newRow("Empty") << "" << false << false << false << false << false << false << false;
502     QTest::newRow("Neutral") << "23244242" << false << false << false << false << false << false << false;
503     QTest::newRow("LTR") << "Hello world" << false << false << false << false << false << false << false;
504     QTest::newRow("RTL") << QString::fromUtf16(arabic_str, 11) << false << true << true << true << true << true << true;
505     QTest::newRow("Bidi RTL + LTR + RTL") << QString::fromUtf16(arabic_str, 11) + QString("Hello world") + QString::fromUtf16(arabic_str, 11) << false << true << true << false << true << true << true;
506     QTest::newRow("Bidi LTR + RTL + LTR") << QString("Hello world") + QString::fromUtf16(arabic_str, 11) + QString("Hello world") << false << false << false << true << false << false << false;
507 }
508
509 void tst_qsgtextinput::isRightToLeft()
510 {
511     QFETCH(QString, text);
512     QFETCH(bool, emptyString);
513     QFETCH(bool, firstCharacter);
514     QFETCH(bool, lastCharacter);
515     QFETCH(bool, middleCharacter);
516     QFETCH(bool, startString);
517     QFETCH(bool, midString);
518     QFETCH(bool, endString);
519
520     QSGTextInput textInput;
521     textInput.setText(text);
522
523     // first test that the right string is delivered to the QString::isRightToLeft()
524     QCOMPARE(textInput.isRightToLeft(0,0), text.mid(0,0).isRightToLeft());
525     QCOMPARE(textInput.isRightToLeft(0,1), text.mid(0,1).isRightToLeft());
526     QCOMPARE(textInput.isRightToLeft(text.count()-2, text.count()-1), text.mid(text.count()-2, text.count()-1).isRightToLeft());
527     QCOMPARE(textInput.isRightToLeft(text.count()/2, text.count()/2 + 1), text.mid(text.count()/2, text.count()/2 + 1).isRightToLeft());
528     QCOMPARE(textInput.isRightToLeft(0,text.count()/4), text.mid(0,text.count()/4).isRightToLeft());
529     QCOMPARE(textInput.isRightToLeft(text.count()/4,3*text.count()/4), text.mid(text.count()/4,3*text.count()/4).isRightToLeft());
530     if (text.isEmpty())
531         QTest::ignoreMessage(QtWarningMsg, "<Unknown File>: QML TextInput: isRightToLeft(start, end) called with the end property being smaller than the start.");
532     QCOMPARE(textInput.isRightToLeft(3*text.count()/4,text.count()-1), text.mid(3*text.count()/4,text.count()-1).isRightToLeft());
533
534     // then test that the feature actually works
535     QCOMPARE(textInput.isRightToLeft(0,0), emptyString);
536     QCOMPARE(textInput.isRightToLeft(0,1), firstCharacter);
537     QCOMPARE(textInput.isRightToLeft(text.count()-2, text.count()-1), lastCharacter);
538     QCOMPARE(textInput.isRightToLeft(text.count()/2, text.count()/2 + 1), middleCharacter);
539     QCOMPARE(textInput.isRightToLeft(0,text.count()/4), startString);
540     QCOMPARE(textInput.isRightToLeft(text.count()/4,3*text.count()/4), midString);
541     if (text.isEmpty())
542         QTest::ignoreMessage(QtWarningMsg, "<Unknown File>: QML TextInput: isRightToLeft(start, end) called with the end property being smaller than the start.");
543     QCOMPARE(textInput.isRightToLeft(3*text.count()/4,text.count()-1), endString);
544 }
545
546 void tst_qsgtextinput::moveCursorSelection_data()
547 {
548     QTest::addColumn<QString>("testStr");
549     QTest::addColumn<int>("cursorPosition");
550     QTest::addColumn<int>("movePosition");
551     QTest::addColumn<QSGTextInput::SelectionMode>("mode");
552     QTest::addColumn<int>("selectionStart");
553     QTest::addColumn<int>("selectionEnd");
554     QTest::addColumn<bool>("reversible");
555
556     // () contains the text selected by the cursor.
557     // <> contains the actual selection.
558
559     QTest::newRow("(t)he|characters")
560             << standard[0] << 0 << 1 << QSGTextInput::SelectCharacters << 0 << 1 << true;
561     QTest::newRow("do(g)|characters")
562             << standard[0] << 43 << 44 << QSGTextInput::SelectCharacters << 43 << 44 << true;
563     QTest::newRow("jum(p)ed|characters")
564             << standard[0] << 23 << 24 << QSGTextInput::SelectCharacters << 23 << 24 << true;
565     QTest::newRow("jumped( )over|characters")
566             << standard[0] << 26 << 27 << QSGTextInput::SelectCharacters << 26 << 27 << true;
567     QTest::newRow("(the )|characters")
568             << standard[0] << 0 << 4 << QSGTextInput::SelectCharacters << 0 << 4 << true;
569     QTest::newRow("( dog)|characters")
570             << standard[0] << 40 << 44 << QSGTextInput::SelectCharacters << 40 << 44 << true;
571     QTest::newRow("( jumped )|characters")
572             << standard[0] << 19 << 27 << QSGTextInput::SelectCharacters << 19 << 27 << true;
573     QTest::newRow("th(e qu)ick|characters")
574             << standard[0] << 2 << 6 << QSGTextInput::SelectCharacters << 2 << 6 << true;
575     QTest::newRow("la(zy d)og|characters")
576             << standard[0] << 38 << 42 << QSGTextInput::SelectCharacters << 38 << 42 << true;
577     QTest::newRow("jum(ped ov)er|characters")
578             << standard[0] << 23 << 29 << QSGTextInput::SelectCharacters << 23 << 29 << true;
579     QTest::newRow("()the|characters")
580             << standard[0] << 0 << 0 << QSGTextInput::SelectCharacters << 0 << 0 << true;
581     QTest::newRow("dog()|characters")
582             << standard[0] << 44 << 44 << QSGTextInput::SelectCharacters << 44 << 44 << true;
583     QTest::newRow("jum()ped|characters")
584             << standard[0] << 23 << 23 << QSGTextInput::SelectCharacters << 23 << 23 << true;
585
586     QTest::newRow("<(t)he>|words")
587             << standard[0] << 0 << 1 << QSGTextInput::SelectWords << 0 << 3 << true;
588     QTest::newRow("<do(g)>|words")
589             << standard[0] << 43 << 44 << QSGTextInput::SelectWords << 41 << 44 << true;
590     QTest::newRow("<jum(p)ed>|words")
591             << standard[0] << 23 << 24 << QSGTextInput::SelectWords << 20 << 26 << true;
592     QTest::newRow("<jumped( )>over|words,ltr")
593             << standard[0] << 26 << 27 << QSGTextInput::SelectWords << 20 << 27 << false;
594     QTest::newRow("jumped<( )over>|words,rtl")
595             << standard[0] << 27 << 26 << QSGTextInput::SelectWords << 26 << 31 << false;
596     QTest::newRow("<(the )>quick|words,ltr")
597             << standard[0] << 0 << 4 << QSGTextInput::SelectWords << 0 << 4 << false;
598     QTest::newRow("<(the )quick>|words,rtl")
599             << standard[0] << 4 << 0 << QSGTextInput::SelectWords << 0 << 9 << false;
600     QTest::newRow("<lazy( dog)>|words,ltr")
601             << standard[0] << 40 << 44 << QSGTextInput::SelectWords << 36 << 44 << false;
602     QTest::newRow("lazy<( dog)>|words,rtl")
603             << standard[0] << 44 << 40 << QSGTextInput::SelectWords << 40 << 44 << false;
604     QTest::newRow("<fox( jumped )>over|words,ltr")
605             << standard[0] << 19 << 27 << QSGTextInput::SelectWords << 16 << 27 << false;
606     QTest::newRow("fox<( jumped )over>|words,rtl")
607             << standard[0] << 27 << 19 << QSGTextInput::SelectWords << 19 << 31 << false;
608     QTest::newRow("<th(e qu)ick>|words")
609             << standard[0] << 2 << 6 << QSGTextInput::SelectWords << 0 << 9 << true;
610     QTest::newRow("<la(zy d)og|words>")
611             << standard[0] << 38 << 42 << QSGTextInput::SelectWords << 36 << 44 << true;
612     QTest::newRow("<jum(ped ov)er>|words")
613             << standard[0] << 23 << 29 << QSGTextInput::SelectWords << 20 << 31 << true;
614     QTest::newRow("<()>the|words")
615             << standard[0] << 0 << 0 << QSGTextInput::SelectWords << 0 << 0 << true;
616     QTest::newRow("dog<()>|words")
617             << standard[0] << 44 << 44 << QSGTextInput::SelectWords << 44 << 44 << true;
618     QTest::newRow("jum<()>ped|words")
619             << standard[0] << 23 << 23 << QSGTextInput::SelectWords << 23 << 23 << true;
620
621     QTest::newRow("Hello<(,)> |words")
622             << standard[2] << 5 << 6 << QSGTextInput::SelectWords << 5 << 6 << true;
623     QTest::newRow("Hello<(, )>world|words,ltr")
624             << standard[2] << 5 << 7 << QSGTextInput::SelectWords << 5 << 7 << false;
625     QTest::newRow("Hello<(, )world>|words,rtl")
626             << standard[2] << 7 << 5 << QSGTextInput::SelectWords << 5 << 12 << false;
627     QTest::newRow("<Hel(lo, )>world|words,ltr")
628             << standard[2] << 3 << 7 << QSGTextInput::SelectWords << 0 << 7 << false;
629     QTest::newRow("<Hel(lo, )world>|words,rtl")
630             << standard[2] << 7 << 3 << QSGTextInput::SelectWords << 0 << 12 << false;
631     QTest::newRow("<Hel(lo)>,|words")
632             << standard[2] << 3 << 5 << QSGTextInput::SelectWords << 0 << 5 << true;
633     QTest::newRow("Hello<()>,|words")
634             << standard[2] << 5 << 5 << QSGTextInput::SelectWords << 5 << 5 << true;
635     QTest::newRow("Hello,<()>|words")
636             << standard[2] << 6 << 6 << QSGTextInput::SelectWords << 6 << 6 << true;
637     QTest::newRow("Hello<,( )>world|words,ltr")
638             << standard[2] << 6 << 7 << QSGTextInput::SelectWords << 5 << 7 << false;
639     QTest::newRow("Hello,<( )world>|words,rtl")
640             << standard[2] << 7 << 6 << QSGTextInput::SelectWords << 6 << 12 << false;
641     QTest::newRow("Hello<,( world)>|words,ltr")
642             << standard[2] << 6 << 12 << QSGTextInput::SelectWords << 5 << 12 << false;
643     QTest::newRow("Hello,<( world)>|words,rtl")
644             << standard[2] << 12 << 6 << QSGTextInput::SelectWords << 6 << 12 << false;
645     QTest::newRow("Hello<,( world!)>|words,ltr")
646             << standard[2] << 6 << 13 << QSGTextInput::SelectWords << 5 << 13 << false;
647     QTest::newRow("Hello,<( world!)>|words,rtl")
648             << standard[2] << 13 << 6 << QSGTextInput::SelectWords << 6 << 13 << false;
649     QTest::newRow("Hello<(, world!)>|words")
650             << standard[2] << 5 << 13 << QSGTextInput::SelectWords << 5 << 13 << true;
651     // Fails due to an issue with QTextBoundaryFinder and punctuation at the end of strings.
652     // QTBUG-11365
653     // QTest::newRow("world<(!)>|words")
654     //         << standard[2] << 12 << 13 << QSGTextInput::SelectWords << 12 << 13 << true;
655     QTest::newRow("world!<()>)|words")
656             << standard[2] << 13 << 13 << QSGTextInput::SelectWords << 13 << 13 << true;
657     QTest::newRow("world<()>!)|words")
658             << standard[2] << 12 << 12 << QSGTextInput::SelectWords << 12 << 12 << true;
659
660     QTest::newRow("<(,)>olleH |words")
661             << standard[3] << 7 << 8 << QSGTextInput::SelectWords << 7 << 8 << true;
662     QTest::newRow("<dlrow( ,)>olleH|words,ltr")
663             << standard[3] << 6 << 8 << QSGTextInput::SelectWords << 1 << 8 << false;
664     QTest::newRow("dlrow<( ,)>olleH|words,rtl")
665             << standard[3] << 8 << 6 << QSGTextInput::SelectWords << 6 << 8 << false;
666     QTest::newRow("<dlrow( ,ol)leH>|words,ltr")
667             << standard[3] << 6 << 10 << QSGTextInput::SelectWords << 1 << 13 << false;
668     QTest::newRow("dlrow<( ,ol)leH>|words,rtl")
669             << standard[3] << 10 << 6 << QSGTextInput::SelectWords << 6 << 13 << false;
670     QTest::newRow(",<(ol)leH>,|words")
671             << standard[3] << 8 << 10 << QSGTextInput::SelectWords << 8 << 13 << true;
672     QTest::newRow(",<()>olleH|words")
673             << standard[3] << 8 << 8 << QSGTextInput::SelectWords << 8 << 8 << true;
674     QTest::newRow("<()>,olleH|words")
675             << standard[3] << 7 << 7 << QSGTextInput::SelectWords << 7 << 7 << true;
676     QTest::newRow("<dlrow( )>,olleH|words,ltr")
677             << standard[3] << 6 << 7 << QSGTextInput::SelectWords << 1 << 7 << false;
678     QTest::newRow("dlrow<( ),>olleH|words,rtl")
679             << standard[3] << 7 << 6 << QSGTextInput::SelectWords << 6 << 8 << false;
680     QTest::newRow("<(dlrow )>,olleH|words,ltr")
681             << standard[3] << 1 << 7 << QSGTextInput::SelectWords << 1 << 7 << false;
682     QTest::newRow("<(dlrow ),>olleH|words,rtl")
683             << standard[3] << 7 << 1 << QSGTextInput::SelectWords << 1 << 8 << false;
684     QTest::newRow("<(!dlrow )>,olleH|words,ltr")
685             << standard[3] << 0 << 7 << QSGTextInput::SelectWords << 0 << 7 << false;
686     QTest::newRow("<(!dlrow ),>olleH|words,rtl")
687             << standard[3] << 7 << 0 << QSGTextInput::SelectWords << 0 << 8 << false;
688     QTest::newRow("(!dlrow ,)olleH|words")
689             << standard[3] << 0 << 8 << QSGTextInput::SelectWords << 0 << 8 << true;
690     QTest::newRow("<(!)>dlrow|words")
691             << standard[3] << 0 << 1 << QSGTextInput::SelectWords << 0 << 1 << true;
692     QTest::newRow("<()>!dlrow|words")
693             << standard[3] << 0 << 0 << QSGTextInput::SelectWords << 0 << 0 << true;
694     QTest::newRow("!<()>dlrow|words")
695             << standard[3] << 1 << 1 << QSGTextInput::SelectWords << 1 << 1 << true;
696
697     QTest::newRow(" <s(pac)ey>   text |words")
698             << standard[4] << 1 << 4 << QSGTextInput::SelectWords << 1 << 7 << true;
699     QTest::newRow(" spacey   <t(ex)t> |words")
700             << standard[4] << 11 << 13 << QSGTextInput::SelectWords << 10 << 14 << false; // Should be reversible. QTBUG-11365
701     QTest::newRow("<( )>spacey   text |words|ltr")
702             << standard[4] << 0 << 1 << QSGTextInput::SelectWords << 0 << 1 << false;
703     QTest::newRow("<( )spacey>   text |words|rtl")
704             << standard[4] << 1 << 0 << QSGTextInput::SelectWords << 0 << 7 << false;
705     QTest::newRow("spacey   <text( )>|words|ltr")
706             << standard[4] << 14 << 15 << QSGTextInput::SelectWords << 10 << 15 << false;
707 //    QTBUG-11365
708 //    QTest::newRow("spacey   text<( )>|words|rtl")
709 //            << standard[4] << 15 << 14 << QSGTextInput::SelectWords << 14 << 15 << false;
710     QTest::newRow("<()> spacey   text |words")
711             << standard[4] << 0 << 0 << QSGTextInput::SelectWords << 0 << 0 << false;
712     QTest::newRow(" spacey   text <()>|words")
713             << standard[4] << 15 << 15 << QSGTextInput::SelectWords << 15 << 15 << false;
714 }
715
716 void tst_qsgtextinput::moveCursorSelection()
717 {
718     QFETCH(QString, testStr);
719     QFETCH(int, cursorPosition);
720     QFETCH(int, movePosition);
721     QFETCH(QSGTextInput::SelectionMode, mode);
722     QFETCH(int, selectionStart);
723     QFETCH(int, selectionEnd);
724     QFETCH(bool, reversible);
725
726     QString componentStr = "import QtQuick 2.0\nTextInput {  text: \""+ testStr +"\"; }";
727     QDeclarativeComponent textinputComponent(&engine);
728     textinputComponent.setData(componentStr.toLatin1(), QUrl());
729     QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
730     QVERIFY(textinputObject != 0);
731
732     textinputObject->setCursorPosition(cursorPosition);
733     textinputObject->moveCursorSelection(movePosition, mode);
734
735     QCOMPARE(textinputObject->selectedText(), testStr.mid(selectionStart, selectionEnd - selectionStart));
736     QCOMPARE(textinputObject->selectionStart(), selectionStart);
737     QCOMPARE(textinputObject->selectionEnd(), selectionEnd);
738
739     if (reversible) {
740         textinputObject->setCursorPosition(movePosition);
741         textinputObject->moveCursorSelection(cursorPosition, mode);
742
743         QCOMPARE(textinputObject->selectedText(), testStr.mid(selectionStart, selectionEnd - selectionStart));
744         QCOMPARE(textinputObject->selectionStart(), selectionStart);
745         QCOMPARE(textinputObject->selectionEnd(), selectionEnd);
746     }
747
748     delete textinputObject;
749 }
750
751 void tst_qsgtextinput::moveCursorSelectionSequence_data()
752 {
753     QTest::addColumn<QString>("testStr");
754     QTest::addColumn<int>("cursorPosition");
755     QTest::addColumn<int>("movePosition1");
756     QTest::addColumn<int>("movePosition2");
757     QTest::addColumn<int>("selection1Start");
758     QTest::addColumn<int>("selection1End");
759     QTest::addColumn<int>("selection2Start");
760     QTest::addColumn<int>("selection2End");
761
762     // () contains the text selected by the cursor.
763     // <> contains the actual selection.
764     // ^ is the revised cursor position.
765     // {} contains the revised selection.
766
767     QTest::newRow("the {<quick( bro)wn> f^ox} jumped|ltr")
768             << standard[0]
769             << 9 << 13 << 17
770             << 4 << 15
771             << 4 << 19;
772     QTest::newRow("the quick<( {bro)wn> f^ox} jumped|rtl")
773             << standard[0]
774             << 13 << 9 << 17
775             << 9 << 15
776             << 10 << 19;
777     QTest::newRow("the {<quick( bro)wn> ^}fox jumped|ltr")
778             << standard[0]
779             << 9 << 13 << 16
780             << 4 << 15
781             << 4 << 16;
782     QTest::newRow("the quick<( {bro)wn> ^}fox jumped|rtl")
783             << standard[0]
784             << 13 << 9 << 16
785             << 9 << 15
786             << 10 << 16;
787     QTest::newRow("the {<quick( bro)wn^>} fox jumped|ltr")
788             << standard[0]
789             << 9 << 13 << 15
790             << 4 << 15
791             << 4 << 15;
792     QTest::newRow("the quick<( {bro)wn^>} f^ox jumped|rtl")
793             << standard[0]
794             << 13 << 9 << 15
795             << 9 << 15
796             << 10 << 15;
797     QTest::newRow("the {<quick() ^}bro)wn> fox|ltr")
798             << standard[0]
799             << 9 << 13 << 10
800             << 4 << 15
801             << 4 << 10;
802     QTest::newRow("the quick<( {^bro)wn>} fox|rtl")
803             << standard[0]
804             << 13 << 9 << 10
805             << 9 << 15
806             << 10 << 15;
807     QTest::newRow("the {<quick^}( bro)wn> fox|ltr")
808             << standard[0]
809             << 9 << 13 << 9
810             << 4 << 15
811             << 4 << 9;
812     QTest::newRow("the quick{<(^ bro)wn>} fox|rtl")
813             << standard[0]
814             << 13 << 9 << 9
815             << 9 << 15
816             << 9 << 15;
817     QTest::newRow("the {<qui^ck}( bro)wn> fox|ltr")
818             << standard[0]
819             << 9 << 13 << 7
820             << 4 << 15
821             << 4 << 9;
822     QTest::newRow("the {<qui^ck}( bro)wn> fox|rtl")
823             << standard[0]
824             << 13 << 9 << 7
825             << 9 << 15
826             << 4 << 15;
827     QTest::newRow("the {<^quick}( bro)wn> fox|ltr")
828             << standard[0]
829             << 9 << 13 << 4
830             << 4 << 15
831             << 4 << 9;
832     QTest::newRow("the {<^quick}( bro)wn> fox|rtl")
833             << standard[0]
834             << 13 << 9 << 4
835             << 9 << 15
836             << 4 << 15;
837     QTest::newRow("the{^ <quick}( bro)wn> fox|ltr")
838             << standard[0]
839             << 9 << 13 << 3
840             << 4 << 15
841             << 3 << 9;
842     QTest::newRow("the{^ <quick}( bro)wn> fox|rtl")
843             << standard[0]
844             << 13 << 9 << 3
845             << 9 << 15
846             << 3 << 15;
847     QTest::newRow("{t^he <quick}( bro)wn> fox|ltr")
848             << standard[0]
849             << 9 << 13 << 1
850             << 4 << 15
851             << 0 << 9;
852     QTest::newRow("{t^he <quick}( bro)wn> fox|rtl")
853             << standard[0]
854             << 13 << 9 << 1
855             << 9 << 15
856             << 0 << 15;
857
858     QTest::newRow("{<He(ll)o>, w^orld}!|ltr")
859             << standard[2]
860             << 2 << 4 << 8
861             << 0 << 5
862             << 0 << 12;
863     QTest::newRow("{<He(ll)o>, w^orld}!|rtl")
864             << standard[2]
865             << 4 << 2 << 8
866             << 0 << 5
867             << 0 << 12;
868
869     QTest::newRow("!{dlro^w ,<o(ll)eH>}|ltr")
870             << standard[3]
871             << 9 << 11 << 5
872             << 8 << 13
873             << 1 << 13;
874     QTest::newRow("!{dlro^w ,<o(ll)eH>}|rtl")
875             << standard[3]
876             << 11 << 9 << 5
877             << 8 << 13
878             << 1 << 13;
879
880     QTest::newRow("{<(^} sp)acey>   text |ltr")
881             << standard[4]
882             << 0 << 3 << 0
883             << 0 << 7
884             << 0 << 0;
885     QTest::newRow("{<( ^}sp)acey>   text |ltr")
886             << standard[4]
887             << 0 << 3 << 1
888             << 0 << 7
889             << 0 << 1;
890     QTest::newRow("<( {s^p)acey>}   text |rtl")
891             << standard[4]
892             << 3 << 0 << 2
893             << 0 << 7
894             << 1 << 7;
895     QTest::newRow("<( {^sp)acey>}   text |rtl")
896             << standard[4]
897             << 3 << 0 << 1
898             << 0 << 7
899             << 1 << 7;
900
901     QTest::newRow(" spacey   <te(xt {^)>}|rtl")
902             << standard[4]
903             << 15 << 12 << 15
904             << 10 << 15
905             << 15 << 15;
906 //    QTBUG-11365
907 //    QTest::newRow(" spacey   <te(xt{^ )>}|rtl")
908 //            << standard[4]
909 //            << 15 << 12 << 14
910 //            << 10 << 15
911 //            << 14 << 15;
912     QTest::newRow(" spacey   {<te(x^t} )>|ltr")
913             << standard[4]
914             << 12 << 15 << 13
915             << 10 << 15
916             << 10 << 14;
917 //    QTBUG-11365
918 //    QTest::newRow(" spacey   {<te(xt^} )>|ltr")
919 //            << standard[4]
920 //            << 12 << 15 << 14
921 //            << 10 << 15
922 //            << 10 << 14;
923 }
924
925 void tst_qsgtextinput::moveCursorSelectionSequence()
926 {
927     QFETCH(QString, testStr);
928     QFETCH(int, cursorPosition);
929     QFETCH(int, movePosition1);
930     QFETCH(int, movePosition2);
931     QFETCH(int, selection1Start);
932     QFETCH(int, selection1End);
933     QFETCH(int, selection2Start);
934     QFETCH(int, selection2End);
935
936     QString componentStr = "import QtQuick 2.0\nTextInput {  text: \""+ testStr +"\"; }";
937     QDeclarativeComponent textinputComponent(&engine);
938     textinputComponent.setData(componentStr.toLatin1(), QUrl());
939     QSGTextInput *textinputObject = qobject_cast<QSGTextInput*>(textinputComponent.create());
940     QVERIFY(textinputObject != 0);
941
942     textinputObject->setCursorPosition(cursorPosition);
943
944     textinputObject->moveCursorSelection(movePosition1, QSGTextInput::SelectWords);
945     QCOMPARE(textinputObject->selectedText(), testStr.mid(selection1Start, selection1End - selection1Start));
946     QCOMPARE(textinputObject->selectionStart(), selection1Start);
947     QCOMPARE(textinputObject->selectionEnd(), selection1End);
948
949     textinputObject->moveCursorSelection(movePosition2, QSGTextInput::SelectWords);
950     QCOMPARE(textinputObject->selectedText(), testStr.mid(selection2Start, selection2End - selection2Start));
951     QCOMPARE(textinputObject->selectionStart(), selection2Start);
952     QCOMPARE(textinputObject->selectionEnd(), selection2End);
953
954     delete textinputObject;
955 }
956
957 void tst_qsgtextinput::dragMouseSelection()
958 {
959     QString qmlfile = SRCDIR "/data/mouseselection_true.qml";
960
961     QSGView canvas(QUrl::fromLocalFile(qmlfile));
962
963     canvas.show();
964     canvas.requestActivateWindow();
965     QTest::qWaitForWindowShown(&canvas);
966
967     QTRY_COMPARE(canvas.windowState(), Qt::WindowActive);
968
969     QVERIFY(canvas.rootObject() != 0);
970     QSGTextInput *textInputObject = qobject_cast<QSGTextInput *>(canvas.rootObject());
971     QVERIFY(textInputObject != 0);
972
973     // press-and-drag-and-release from x1 to x2
974     int x1 = 10;
975     int x2 = 70;
976     int y = textInputObject->height()/2;
977     QTest::mousePress(&canvas, Qt::LeftButton, 0, QPoint(x1,y));
978     {
979         QMouseEvent mv(QEvent::MouseMove, QPoint(x2,y), Qt::LeftButton, Qt::LeftButton,Qt::NoModifier);
980         QApplication::sendEvent(&canvas, &mv);
981     }
982     QTest::mouseRelease(&canvas, Qt::LeftButton, 0, QPoint(x2,y));
983
984     QString str1 = textInputObject->selectedText();
985     QVERIFY(str1.length() > 3);
986
987     // press and drag the current selection.
988     x1 = 40;
989     x2 = 100;
990     QTest::mousePress(&canvas, Qt::LeftButton, 0, QPoint(x1,y));
991     {
992         QMouseEvent mv(QEvent::MouseMove, QPoint(x2,y), Qt::LeftButton, Qt::LeftButton,Qt::NoModifier);
993         QApplication::sendEvent(&canvas, &mv);
994     }
995         QTest::mouseRelease(&canvas, Qt::LeftButton, 0, QPoint(x2,y));
996     QString str2 = textInputObject->selectedText();
997     QVERIFY(str2.length() > 3);
998
999     QVERIFY(str1 != str2); // Verify the second press and drag is a new selection and doesn't not the first moved.
1000 }
1001
1002 void tst_qsgtextinput::mouseSelectionMode_data()
1003 {
1004     QTest::addColumn<QString>("qmlfile");
1005     QTest::addColumn<bool>("selectWords");
1006
1007     // import installed
1008     QTest::newRow("SelectWords") << SRCDIR "/data/mouseselectionmode_words.qml" << true;
1009     QTest::newRow("SelectCharacters") << SRCDIR "/data/mouseselectionmode_characters.qml" << false;
1010     QTest::newRow("default") << SRCDIR "/data/mouseselectionmode_default.qml" << false;
1011 }
1012
1013 void tst_qsgtextinput::mouseSelectionMode()
1014 {
1015     QFETCH(QString, qmlfile);
1016     QFETCH(bool, selectWords);
1017
1018     QString text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1019
1020     QSGView canvas(QUrl::fromLocalFile(qmlfile));
1021
1022     canvas.show();
1023     canvas.requestActivateWindow();
1024     QTest::qWaitForWindowShown(&canvas);
1025     QTRY_COMPARE(canvas.windowState(), Qt::WindowActive);
1026
1027     QVERIFY(canvas.rootObject() != 0);
1028     QSGTextInput *textInputObject = qobject_cast<QSGTextInput *>(canvas.rootObject());
1029     QVERIFY(textInputObject != 0);
1030
1031     // press-and-drag-and-release from x1 to x2
1032     int x1 = 10;
1033     int x2 = 70;
1034     int y = textInputObject->height()/2;
1035     QTest::mousePress(&canvas, Qt::LeftButton, 0, QPoint(x1,y));
1036     //QTest::mouseMove(&canvas, canvas.mapFromScene(QPoint(x2,y))); // doesn't work
1037     QMouseEvent mv(QEvent::MouseMove, QPoint(x2,y), Qt::LeftButton, Qt::LeftButton,Qt::NoModifier);
1038     QApplication::sendEvent(&canvas, &mv);
1039     QTest::mouseRelease(&canvas, Qt::LeftButton, 0, QPoint(x2,y));
1040     QString str = textInputObject->selectedText();
1041     if (selectWords) {
1042         QCOMPARE(str, text);
1043     } else {
1044         QVERIFY(str.length() > 3);
1045         QVERIFY(str != text);
1046     }
1047 }
1048
1049 void tst_qsgtextinput::horizontalAlignment_data()
1050 {
1051     QTest::addColumn<int>("hAlign");
1052     QTest::addColumn<QString>("expectfile");
1053
1054     QTest::newRow("L") << int(Qt::AlignLeft) << "halign_left";
1055     QTest::newRow("R") << int(Qt::AlignRight) << "halign_right";
1056     QTest::newRow("C") << int(Qt::AlignHCenter) << "halign_center";
1057 }
1058
1059 void tst_qsgtextinput::horizontalAlignment()
1060 {
1061     QFETCH(int, hAlign);
1062     QFETCH(QString, expectfile);
1063
1064     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/horizontalAlignment.qml"));
1065
1066     canvas.show();
1067     canvas.requestActivateWindow();
1068     QTest::qWaitForWindowShown(&canvas);
1069     QTRY_COMPARE(canvas.windowState(), Qt::WindowActive);
1070     QObject *ob = canvas.rootObject();
1071     QVERIFY(ob != 0);
1072     ob->setProperty("horizontalAlignment",hAlign);
1073     QImage actual = canvas.grabFrameBuffer();
1074
1075     expectfile = createExpectedFileIfNotFound(expectfile, actual);
1076
1077     QImage expect(expectfile);
1078
1079     QCOMPARE(actual,expect);
1080 }
1081
1082 void tst_qsgtextinput::horizontalAlignment_RightToLeft()
1083 {
1084     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/horizontalAlignment_RightToLeft.qml"));
1085     QSGTextInput *textInput = canvas.rootObject()->findChild<QSGTextInput*>("text");
1086     QVERIFY(textInput != 0);
1087     canvas.show();
1088
1089     const QString rtlText = textInput->text();
1090
1091     QSGTextInputPrivate *textInputPrivate = QSGTextInputPrivate::get(textInput);
1092     QVERIFY(textInputPrivate != 0);
1093     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1094
1095     // implicit alignment should follow the reading direction of RTL text
1096     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1097     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1098     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1099
1100     // explicitly left aligned
1101     textInput->setHAlign(QSGTextInput::AlignLeft);
1102     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignLeft);
1103     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1104     QVERIFY(-textInputPrivate->hscroll < canvas.width()/2);
1105
1106     // explicitly right aligned
1107     textInput->setHAlign(QSGTextInput::AlignRight);
1108     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1109     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1110     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1111
1112     // explicitly center aligned
1113     textInput->setHAlign(QSGTextInput::AlignHCenter);
1114     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1115     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignHCenter);
1116     QVERIFY(-textInputPrivate->hscroll < canvas.width()/2);
1117     QVERIFY(-textInputPrivate->hscroll + textInputPrivate->width > canvas.width()/2);
1118
1119     // reseted alignment should go back to following the text reading direction
1120     textInput->resetHAlign();
1121     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1122     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1123     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1124
1125     // mirror the text item
1126     QSGItemPrivate::get(textInput)->setLayoutMirror(true);
1127
1128     // mirrored implicit alignment should continue to follow the reading direction of the text
1129     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1130     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1131     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1132
1133     // explicitly right aligned behaves as left aligned
1134     textInput->setHAlign(QSGTextInput::AlignRight);
1135     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1136     QCOMPARE(textInput->effectiveHAlign(), QSGTextInput::AlignLeft);
1137     QVERIFY(-textInputPrivate->hscroll < canvas.width()/2);
1138
1139     // mirrored explicitly left aligned behaves as right aligned
1140     textInput->setHAlign(QSGTextInput::AlignLeft);
1141     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignLeft);
1142     QCOMPARE(textInput->effectiveHAlign(), QSGTextInput::AlignRight);
1143     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1144
1145     // disable mirroring
1146     QSGItemPrivate::get(textInput)->setLayoutMirror(false);
1147     QCOMPARE(textInput->effectiveHAlign(), textInput->hAlign());
1148     textInput->resetHAlign();
1149
1150     // English text should be implicitly left aligned
1151     textInput->setText("Hello world!");
1152     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignLeft);
1153     QVERIFY(-textInputPrivate->hscroll < canvas.width()/2);
1154
1155     QApplication::setActiveWindow(&canvas);
1156     QTest::qWaitForWindowShown(&canvas);
1157     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&canvas));
1158
1159     // If there is no commited text, the preedit text should determine the alignment.
1160     textInput->setText(QString());
1161     { QInputMethodEvent ev(rtlText, QList<QInputMethodEvent::Attribute>()); QApplication::sendEvent(&canvas, &ev); }
1162     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1163     { QInputMethodEvent ev("Hello world!", QList<QInputMethodEvent::Attribute>()); QApplication::sendEvent(&canvas, &ev); }
1164     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignLeft);
1165
1166 #ifndef Q_OS_MAC    // QTBUG-18040
1167     // empty text with implicit alignment follows the system locale-based
1168     // keyboard input direction from QApplication::keyboardInputDirection
1169     textInput->setText("");
1170     QCOMPARE(textInput->hAlign(), QApplication::keyboardInputDirection() == Qt::LeftToRight ?
1171                                   QSGTextInput::AlignLeft : QSGTextInput::AlignRight);
1172     if (QApplication::keyboardInputDirection() == Qt::LeftToRight)
1173         QVERIFY(-textInputPrivate->hscroll < canvas.width()/2);
1174     else
1175         QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1176     textInput->setHAlign(QSGTextInput::AlignRight);
1177     QCOMPARE(textInput->hAlign(), QSGTextInput::AlignRight);
1178     QVERIFY(-textInputPrivate->hscroll > canvas.width()/2);
1179 #endif
1180
1181 #ifndef Q_OS_MAC    // QTBUG-18040
1182     // alignment of TextInput with no text set to it
1183     QString componentStr = "import QtQuick 2.0\nTextInput {}";
1184     QDeclarativeComponent textComponent(&engine);
1185     textComponent.setData(componentStr.toLatin1(), QUrl::fromLocalFile(""));
1186     QSGTextInput *textObject = qobject_cast<QSGTextInput*>(textComponent.create());
1187     QCOMPARE(textObject->hAlign(), QApplication::keyboardInputDirection() == Qt::LeftToRight ?
1188                                   QSGTextInput::AlignLeft : QSGTextInput::AlignRight);
1189     delete textObject;
1190 #endif
1191 }
1192
1193 void tst_qsgtextinput::positionAt()
1194 {
1195     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/positionAt.qml"));
1196     QVERIFY(canvas.rootObject() != 0);
1197     canvas.show();
1198     canvas.requestActivateWindow();
1199     QTest::qWaitForWindowShown(&canvas);
1200
1201     QSGTextInput *textinputObject = qobject_cast<QSGTextInput *>(canvas.rootObject());
1202     QVERIFY(textinputObject != 0);
1203
1204     // Check autoscrolled...
1205     QFontMetrics fm(textinputObject->font());
1206
1207     int pos = textinputObject->positionAt(textinputObject->width()/2);
1208     int textWidth = 0;
1209     int textLeftWidth = 0;
1210     if (!qmlDisableDistanceField()) {
1211         {
1212             QTextLayout layout(textinputObject->text().left(pos));
1213
1214             {
1215                 QTextOption option;
1216                 option.setUseDesignMetrics(true);
1217                 layout.setTextOption(option);
1218             }
1219
1220             layout.beginLayout();
1221             QTextLine line = layout.createLine();
1222             layout.endLayout();
1223
1224             textLeftWidth = ceil(line.horizontalAdvance());
1225         }
1226         {
1227             QTextLayout layout(textinputObject->text());
1228
1229             {
1230                 QTextOption option;
1231                 option.setUseDesignMetrics(true);
1232                 layout.setTextOption(option);
1233             }
1234
1235             layout.beginLayout();
1236             QTextLine line = layout.createLine();
1237             layout.endLayout();
1238
1239             textWidth = ceil(line.horizontalAdvance());
1240         }
1241     } else {
1242         textWidth = fm.width(textinputObject->text());
1243         textLeftWidth = fm.width(textinputObject->text().left(pos));
1244     }
1245
1246     int diff = abs(textWidth - (textLeftWidth+textinputObject->width()/2));
1247
1248     // some tollerance for different fonts.
1249 #ifdef Q_OS_LINUX
1250     QVERIFY(diff < 2);
1251 #else
1252     QVERIFY(diff < 5);
1253 #endif
1254
1255     int x = textinputObject->positionToRectangle(pos + 1).x() - 1;
1256     QCOMPARE(textinputObject->positionAt(x, QSGTextInput::CursorBetweenCharacters), pos + 1);
1257     QCOMPARE(textinputObject->positionAt(x, QSGTextInput::CursorOnCharacter), pos);
1258
1259     // Check without autoscroll...
1260     textinputObject->setAutoScroll(false);
1261     pos = textinputObject->positionAt(textinputObject->width()/2);
1262
1263     if (!qmlDisableDistanceField()) {
1264         {
1265             QTextLayout layout(textinputObject->text().left(pos));
1266
1267             {
1268                 QTextOption option;
1269                 option.setUseDesignMetrics(true);
1270                 layout.setTextOption(option);
1271             }
1272
1273             layout.beginLayout();
1274             QTextLine line = layout.createLine();
1275             layout.endLayout();
1276
1277             textLeftWidth = ceil(line.horizontalAdvance());
1278         }
1279     } else {
1280         textLeftWidth = fm.width(textinputObject->text().left(pos));
1281     }
1282
1283     diff = abs(int(textLeftWidth-textinputObject->width()/2));
1284
1285     // some tollerance for different fonts.
1286 #ifdef Q_OS_LINUX
1287     QVERIFY(diff < 2);
1288 #else
1289     QVERIFY(diff < 5);
1290 #endif
1291
1292     x = textinputObject->positionToRectangle(pos + 1).x() - 1;
1293     QCOMPARE(textinputObject->positionAt(x, QSGTextInput::CursorBetweenCharacters), pos + 1);
1294     QCOMPARE(textinputObject->positionAt(x, QSGTextInput::CursorOnCharacter), pos);
1295
1296     const qreal x0 = textinputObject->positionToRectangle(pos).x();
1297     const qreal x1 = textinputObject->positionToRectangle(pos + 1).x();
1298
1299     QString preeditText = textinputObject->text().mid(0, pos);
1300     textinputObject->setText(textinputObject->text().mid(pos));
1301     textinputObject->setCursorPosition(0);
1302
1303     QInputMethodEvent inputEvent(preeditText, QList<QInputMethodEvent::Attribute>());
1304     QApplication::sendEvent(&canvas, &inputEvent);
1305
1306     // Check all points within the preedit text return the same position.
1307     QCOMPARE(textinputObject->positionAt(0), 0);
1308     QCOMPARE(textinputObject->positionAt(x0 / 2), 0);
1309     QCOMPARE(textinputObject->positionAt(x0), 0);
1310
1311     // Verify positioning returns to normal after the preedit text.
1312     QCOMPARE(textinputObject->positionAt(x1), 1);
1313     QCOMPARE(textinputObject->positionToRectangle(1).x(), x1);
1314 }
1315
1316 void tst_qsgtextinput::maxLength()
1317 {
1318     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/maxLength.qml"));
1319     QVERIFY(canvas.rootObject() != 0);
1320     canvas.show();
1321     canvas.requestActivateWindow();
1322     QTest::qWaitForWindowShown(&canvas);
1323
1324     QSGTextInput *textinputObject = qobject_cast<QSGTextInput *>(canvas.rootObject());
1325     QVERIFY(textinputObject != 0);
1326     QVERIFY(textinputObject->text().isEmpty());
1327     QVERIFY(textinputObject->maxLength() == 10);
1328     foreach(const QString &str, standard){
1329         QVERIFY(textinputObject->text().length() <= 10);
1330         textinputObject->setText(str);
1331         QVERIFY(textinputObject->text().length() <= 10);
1332     }
1333
1334     textinputObject->setText("");
1335     QTRY_VERIFY(textinputObject->hasActiveFocus() == true);
1336     for(int i=0; i<20; i++){
1337         QCOMPARE(textinputObject->text().length(), qMin(i,10));
1338         //simulateKey(&canvas, Qt::Key_A);
1339         QTest::keyPress(&canvas, Qt::Key_A);
1340         QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1341     }
1342 }
1343
1344 void tst_qsgtextinput::masks()
1345 {
1346     //Not a comprehensive test of the possible masks, that's done elsewhere (QLineEdit)
1347     //QString componentStr = "import QtQuick 2.0\nTextInput {  inputMask: 'HHHHhhhh'; }";
1348     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/masks.qml"));
1349     canvas.show();
1350     canvas.requestActivateWindow();
1351     QVERIFY(canvas.rootObject() != 0);
1352     QSGTextInput *textinputObject = qobject_cast<QSGTextInput *>(canvas.rootObject());
1353     QVERIFY(textinputObject != 0);
1354     QTRY_VERIFY(textinputObject->hasActiveFocus() == true);
1355     QVERIFY(textinputObject->text().length() == 0);
1356     QCOMPARE(textinputObject->inputMask(), QString("HHHHhhhh; "));
1357     for(int i=0; i<10; i++){
1358         QCOMPARE(qMin(i,8), textinputObject->text().length());
1359         QCOMPARE(i>=4, textinputObject->hasAcceptableInput());
1360         //simulateKey(&canvas, Qt::Key_A);
1361         QTest::keyPress(&canvas, Qt::Key_A);
1362         QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1363     }
1364 }
1365
1366 void tst_qsgtextinput::validators()
1367 {
1368     // Note that this test assumes that the validators are working properly
1369     // so you may need to run their tests first. All validators are checked
1370     // here to ensure that their exposure to QML is working.
1371
1372     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/validators.qml"));
1373     canvas.show();
1374     canvas.requestActivateWindow();
1375
1376     QVERIFY(canvas.rootObject() != 0);
1377
1378     QSGTextInput *intInput = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("intInput")));
1379     QVERIFY(intInput);
1380     intInput->setFocus(true);
1381     QTRY_VERIFY(intInput->hasActiveFocus());
1382     QTest::keyPress(&canvas, Qt::Key_1);
1383     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1384     QCOMPARE(intInput->text(), QLatin1String("1"));
1385     QCOMPARE(intInput->hasAcceptableInput(), false);
1386     QTest::keyPress(&canvas, Qt::Key_2);
1387     QTest::keyRelease(&canvas, Qt::Key_2, Qt::NoModifier ,10);
1388     QCOMPARE(intInput->text(), QLatin1String("1"));
1389     QCOMPARE(intInput->hasAcceptableInput(), false);
1390     QTest::keyPress(&canvas, Qt::Key_1);
1391     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1392     QCOMPARE(intInput->text(), QLatin1String("11"));
1393     QCOMPARE(intInput->hasAcceptableInput(), true);
1394     QTest::keyPress(&canvas, Qt::Key_0);
1395     QTest::keyRelease(&canvas, Qt::Key_0, Qt::NoModifier ,10);
1396     QCOMPARE(intInput->text(), QLatin1String("11"));
1397     QCOMPARE(intInput->hasAcceptableInput(), true);
1398
1399     QSGTextInput *dblInput = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("dblInput")));
1400     QTRY_VERIFY(dblInput);
1401     dblInput->setFocus(true);
1402     QVERIFY(dblInput->hasActiveFocus() == true);
1403     QTest::keyPress(&canvas, Qt::Key_1);
1404     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1405     QCOMPARE(dblInput->text(), QLatin1String("1"));
1406     QCOMPARE(dblInput->hasAcceptableInput(), false);
1407     QTest::keyPress(&canvas, Qt::Key_2);
1408     QTest::keyRelease(&canvas, Qt::Key_2, Qt::NoModifier ,10);
1409     QCOMPARE(dblInput->text(), QLatin1String("12"));
1410     QCOMPARE(dblInput->hasAcceptableInput(), true);
1411     QTest::keyPress(&canvas, Qt::Key_Period);
1412     QTest::keyRelease(&canvas, Qt::Key_Period, Qt::NoModifier ,10);
1413     QCOMPARE(dblInput->text(), QLatin1String("12."));
1414     QCOMPARE(dblInput->hasAcceptableInput(), true);
1415     QTest::keyPress(&canvas, Qt::Key_1);
1416     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1417     QCOMPARE(dblInput->text(), QLatin1String("12.1"));
1418     QCOMPARE(dblInput->hasAcceptableInput(), true);
1419     QTest::keyPress(&canvas, Qt::Key_1);
1420     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1421     QCOMPARE(dblInput->text(), QLatin1String("12.11"));
1422     QCOMPARE(dblInput->hasAcceptableInput(), true);
1423     QTest::keyPress(&canvas, Qt::Key_1);
1424     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1425     QCOMPARE(dblInput->text(), QLatin1String("12.11"));
1426     QCOMPARE(dblInput->hasAcceptableInput(), true);
1427
1428     QSGTextInput *strInput = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("strInput")));
1429     QTRY_VERIFY(strInput);
1430     strInput->setFocus(true);
1431     QVERIFY(strInput->hasActiveFocus() == true);
1432     QTest::keyPress(&canvas, Qt::Key_1);
1433     QTest::keyRelease(&canvas, Qt::Key_1, Qt::NoModifier ,10);
1434     QCOMPARE(strInput->text(), QLatin1String(""));
1435     QCOMPARE(strInput->hasAcceptableInput(), false);
1436     QTest::keyPress(&canvas, Qt::Key_A);
1437     QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1438     QCOMPARE(strInput->text(), QLatin1String("a"));
1439     QCOMPARE(strInput->hasAcceptableInput(), false);
1440     QTest::keyPress(&canvas, Qt::Key_A);
1441     QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1442     QCOMPARE(strInput->text(), QLatin1String("aa"));
1443     QCOMPARE(strInput->hasAcceptableInput(), true);
1444     QTest::keyPress(&canvas, Qt::Key_A);
1445     QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1446     QCOMPARE(strInput->text(), QLatin1String("aaa"));
1447     QCOMPARE(strInput->hasAcceptableInput(), true);
1448     QTest::keyPress(&canvas, Qt::Key_A);
1449     QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1450     QCOMPARE(strInput->text(), QLatin1String("aaaa"));
1451     QCOMPARE(strInput->hasAcceptableInput(), true);
1452     QTest::keyPress(&canvas, Qt::Key_A);
1453     QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1454     QCOMPARE(strInput->text(), QLatin1String("aaaa"));
1455     QCOMPARE(strInput->hasAcceptableInput(), true);
1456 }
1457
1458 void tst_qsgtextinput::inputMethods()
1459 {
1460     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/inputmethods.qml"));
1461     canvas.show();
1462     canvas.requestActivateWindow();
1463     QTest::qWaitForWindowShown(&canvas);
1464
1465     // test input method hints
1466     QVERIFY(canvas.rootObject() != 0);
1467     QSGTextInput *input = qobject_cast<QSGTextInput *>(canvas.rootObject());
1468     QVERIFY(input != 0);
1469     QVERIFY(input->inputMethodHints() & Qt::ImhNoPredictiveText);
1470     input->setInputMethodHints(Qt::ImhUppercaseOnly);
1471     QVERIFY(input->inputMethodHints() & Qt::ImhUppercaseOnly);
1472
1473     input->setFocus(true);
1474     QVERIFY(input->hasActiveFocus() == true);
1475     // test that input method event is committed
1476     QInputMethodEvent event;
1477     event.setCommitString( "My ", -12, 0);
1478     QApplication::sendEvent(&canvas, &event);
1479     QCOMPARE(input->text(), QString("My Hello world!"));
1480
1481     input->setCursorPosition(2);
1482     event.setCommitString("Your", -2, 2);
1483     QApplication::sendEvent(&canvas, &event);
1484     QCOMPARE(input->text(), QString("Your Hello world!"));
1485     QCOMPARE(input->cursorPosition(), 4);
1486
1487     input->setCursorPosition(7);
1488     event.setCommitString("Goodbye", -2, 5);
1489     QApplication::sendEvent(&canvas, &event);
1490     QCOMPARE(input->text(), QString("Your Goodbye world!"));
1491     QCOMPARE(input->cursorPosition(), 12);
1492
1493     input->setCursorPosition(8);
1494     event.setCommitString("Our", -8, 4);
1495     QApplication::sendEvent(&canvas, &event);
1496     QCOMPARE(input->text(), QString("Our Goodbye world!"));
1497     QCOMPARE(input->cursorPosition(), 7);
1498 }
1499
1500 /*
1501 TextInput element should only handle left/right keys until the cursor reaches
1502 the extent of the text, then they should ignore the keys.
1503
1504 */
1505 void tst_qsgtextinput::navigation()
1506 {
1507     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/navigation.qml"));
1508     canvas.show();
1509     canvas.requestActivateWindow();
1510
1511     QVERIFY(canvas.rootObject() != 0);
1512
1513     QSGTextInput *input = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("myInput")));
1514
1515     QVERIFY(input != 0);
1516     input->setCursorPosition(0);
1517     QTRY_VERIFY(input->hasActiveFocus() == true);
1518     simulateKey(&canvas, Qt::Key_Left);
1519     QVERIFY(input->hasActiveFocus() == false);
1520     simulateKey(&canvas, Qt::Key_Right);
1521     QVERIFY(input->hasActiveFocus() == true);
1522     //QT-2944: If text is selected, ensure we deselect upon cursor motion
1523     input->setCursorPosition(input->text().length());
1524     input->select(0,input->text().length());
1525     QVERIFY(input->selectionStart() != input->selectionEnd());
1526     simulateKey(&canvas, Qt::Key_Right);
1527     QVERIFY(input->selectionStart() == input->selectionEnd());
1528     QVERIFY(input->selectionStart() == input->text().length());
1529     QVERIFY(input->hasActiveFocus() == true);
1530     simulateKey(&canvas, Qt::Key_Right);
1531     QVERIFY(input->hasActiveFocus() == false);
1532     simulateKey(&canvas, Qt::Key_Left);
1533     QVERIFY(input->hasActiveFocus() == true);
1534
1535     // Up and Down should NOT do Home/End, even on Mac OS X (QTBUG-10438).
1536     input->setCursorPosition(2);
1537     QCOMPARE(input->cursorPosition(),2);
1538     simulateKey(&canvas, Qt::Key_Up);
1539     QCOMPARE(input->cursorPosition(),2);
1540     simulateKey(&canvas, Qt::Key_Down);
1541     QCOMPARE(input->cursorPosition(),2);
1542 }
1543
1544 void tst_qsgtextinput::navigation_RTL()
1545 {
1546     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/navigation.qml"));
1547     canvas.show();
1548     canvas.requestActivateWindow();
1549
1550     QVERIFY(canvas.rootObject() != 0);
1551
1552     QSGTextInput *input = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("myInput")));
1553
1554     QVERIFY(input != 0);
1555     const quint16 arabic_str[] = { 0x0638, 0x0643, 0x00646, 0x0647, 0x0633, 0x0638, 0x0643, 0x00646, 0x0647, 0x0633, 0x0647};
1556     input->setText(QString::fromUtf16(arabic_str, 11));
1557
1558     input->setCursorPosition(0);
1559     QTRY_VERIFY(input->hasActiveFocus() == true);
1560
1561     // move off
1562     simulateKey(&canvas, Qt::Key_Right);
1563     QVERIFY(input->hasActiveFocus() == false);
1564
1565     // move back
1566     simulateKey(&canvas, Qt::Key_Left);
1567     QVERIFY(input->hasActiveFocus() == true);
1568
1569     input->setCursorPosition(input->text().length());
1570     QVERIFY(input->hasActiveFocus() == true);
1571
1572     // move off
1573     simulateKey(&canvas, Qt::Key_Left);
1574     QVERIFY(input->hasActiveFocus() == false);
1575
1576     // move back
1577     simulateKey(&canvas, Qt::Key_Right);
1578     QVERIFY(input->hasActiveFocus() == true);
1579 }
1580
1581 void tst_qsgtextinput::copyAndPaste() {
1582 #ifndef QT_NO_CLIPBOARD
1583
1584 #ifdef Q_WS_MAC
1585     {
1586         PasteboardRef pasteboard;
1587         OSStatus status = PasteboardCreate(0, &pasteboard);
1588         if (status == noErr)
1589             CFRelease(pasteboard);
1590         else
1591             QSKIP("This machine doesn't support the clipboard", SkipAll);
1592     }
1593 #endif
1594
1595     QString componentStr = "import QtQuick 2.0\nTextInput { text: \"Hello world!\" }";
1596     QDeclarativeComponent textInputComponent(&engine);
1597     textInputComponent.setData(componentStr.toLatin1(), QUrl());
1598     QSGTextInput *textInput = qobject_cast<QSGTextInput*>(textInputComponent.create());
1599     QVERIFY(textInput != 0);
1600
1601     // copy and paste
1602     QCOMPARE(textInput->text().length(), 12);
1603     textInput->select(0, textInput->text().length());;
1604     textInput->copy();
1605     QCOMPARE(textInput->selectedText(), QString("Hello world!"));
1606     QCOMPARE(textInput->selectedText().length(), 12);
1607     textInput->setCursorPosition(0);
1608     QVERIFY(textInput->canPaste());
1609     textInput->paste();
1610     QCOMPARE(textInput->text(), QString("Hello world!Hello world!"));
1611     QCOMPARE(textInput->text().length(), 24);
1612
1613     // can paste
1614     QVERIFY(textInput->canPaste());
1615     textInput->setReadOnly(true);
1616     QVERIFY(!textInput->canPaste());
1617     textInput->setReadOnly(false);
1618     QVERIFY(textInput->canPaste());
1619
1620     // select word
1621     textInput->setCursorPosition(0);
1622     textInput->selectWord();
1623     QCOMPARE(textInput->selectedText(), QString("Hello"));
1624
1625     // select all and cut
1626     textInput->selectAll();
1627     textInput->cut();
1628     QCOMPARE(textInput->text().length(), 0);
1629     textInput->paste();
1630     QCOMPARE(textInput->text(), QString("Hello world!Hello world!"));
1631     QCOMPARE(textInput->text().length(), 24);
1632
1633     // clear copy buffer
1634     QClipboard *clipboard = QApplication::clipboard();
1635     QVERIFY(clipboard);
1636     clipboard->clear();
1637     QVERIFY(!textInput->canPaste());
1638
1639     // test that copy functionality is disabled
1640     // when echo mode is set to hide text/password mode
1641     int index = 0;
1642     while (index < 4) {
1643         QSGTextInput::EchoMode echoMode = QSGTextInput::EchoMode(index);
1644         textInput->setEchoMode(echoMode);
1645         textInput->setText("My password");
1646         textInput->select(0, textInput->text().length());;
1647         textInput->copy();
1648         if (echoMode == QSGTextInput::Normal) {
1649             QVERIFY(!clipboard->text().isEmpty());
1650             QCOMPARE(clipboard->text(), QString("My password"));
1651             clipboard->clear();
1652         } else {
1653             QVERIFY(clipboard->text().isEmpty());
1654         }
1655         index++;
1656     }
1657
1658     delete textInput;
1659 #endif
1660 }
1661
1662 void tst_qsgtextinput::canPasteEmpty() {
1663 #ifndef QT_NO_CLIPBOARD
1664
1665     QApplication::clipboard()->clear();
1666
1667     QString componentStr = "import QtQuick 2.0\nTextInput { text: \"Hello world!\" }";
1668     QDeclarativeComponent textInputComponent(&engine);
1669     textInputComponent.setData(componentStr.toLatin1(), QUrl());
1670     QSGTextInput *textInput = qobject_cast<QSGTextInput*>(textInputComponent.create());
1671     QVERIFY(textInput != 0);
1672
1673     QLineControl lc;
1674     bool cp = !lc.isReadOnly() && QApplication::clipboard()->text().length() != 0;
1675     QCOMPARE(textInput->canPaste(), cp);
1676
1677 #endif
1678 }
1679
1680 void tst_qsgtextinput::canPaste() {
1681 #ifndef QT_NO_CLIPBOARD
1682
1683     QApplication::clipboard()->setText("Some text");
1684
1685     QString componentStr = "import QtQuick 2.0\nTextInput { text: \"Hello world!\" }";
1686     QDeclarativeComponent textInputComponent(&engine);
1687     textInputComponent.setData(componentStr.toLatin1(), QUrl());
1688     QSGTextInput *textInput = qobject_cast<QSGTextInput*>(textInputComponent.create());
1689     QVERIFY(textInput != 0);
1690
1691     QLineControl lc;
1692     bool cp = !lc.isReadOnly() && QApplication::clipboard()->text().length() != 0;
1693     QCOMPARE(textInput->canPaste(), cp);
1694
1695 #endif
1696 }
1697
1698 void tst_qsgtextinput::passwordCharacter()
1699 {
1700     QString componentStr = "import QtQuick 2.0\nTextInput { text: \"Hello world!\"; font.family: \"Helvetica\"; echoMode: TextInput.Password }";
1701     QDeclarativeComponent textInputComponent(&engine);
1702     textInputComponent.setData(componentStr.toLatin1(), QUrl());
1703     QSGTextInput *textInput = qobject_cast<QSGTextInput*>(textInputComponent.create());
1704     QVERIFY(textInput != 0);
1705
1706     textInput->setPasswordCharacter("X");
1707     qreal implicitWidth = textInput->implicitWidth();
1708     textInput->setPasswordCharacter(".");
1709
1710     // QTBUG-12383 content is updated and redrawn
1711     QVERIFY(textInput->implicitWidth() < implicitWidth);
1712
1713     delete textInput;
1714 }
1715
1716 void tst_qsgtextinput::cursorDelegate()
1717 {
1718     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/cursorTest.qml"));
1719     view.show();
1720     view.requestActivateWindow();
1721     QSGTextInput *textInputObject = view.rootObject()->findChild<QSGTextInput*>("textInputObject");
1722     QVERIFY(textInputObject != 0);
1723     QVERIFY(textInputObject->findChild<QSGItem*>("cursorInstance"));
1724     //Test Delegate gets created
1725     textInputObject->setFocus(true);
1726     QSGItem* delegateObject = textInputObject->findChild<QSGItem*>("cursorInstance");
1727     QVERIFY(delegateObject);
1728     //Test Delegate gets moved
1729     for(int i=0; i<= textInputObject->text().length(); i++){
1730         textInputObject->setCursorPosition(i);
1731         QCOMPARE(textInputObject->cursorRectangle().x(), qRound(delegateObject->x()));
1732         QCOMPARE(textInputObject->cursorRectangle().y(), qRound(delegateObject->y()));
1733     }
1734     textInputObject->setCursorPosition(0);
1735     QCOMPARE(textInputObject->cursorRectangle().x(), qRound(delegateObject->x()));
1736     QCOMPARE(textInputObject->cursorRectangle().y(), qRound(delegateObject->y()));
1737     //Test Delegate gets deleted
1738     textInputObject->setCursorDelegate(0);
1739     QVERIFY(!textInputObject->findChild<QSGItem*>("cursorInstance"));
1740 }
1741
1742 void tst_qsgtextinput::cursorVisible()
1743 {
1744     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/cursorVisible.qml"));
1745     view.show();
1746     view.requestActivateWindow();
1747     QTest::qWaitForWindowShown(&view);
1748     QTRY_COMPARE(view.windowState(), Qt::WindowActive);
1749
1750     QSGTextInput input;
1751     QSignalSpy spy(&input, SIGNAL(cursorVisibleChanged(bool)));
1752
1753     QCOMPARE(input.isCursorVisible(), false);
1754
1755     input.setCursorVisible(true);
1756     QCOMPARE(input.isCursorVisible(), true);
1757     QCOMPARE(spy.count(), 1);
1758
1759     input.setCursorVisible(false);
1760     QCOMPARE(input.isCursorVisible(), false);
1761     QCOMPARE(spy.count(), 2);
1762
1763     input.setFocus(true);
1764     QCOMPARE(input.isCursorVisible(), false);
1765     QCOMPARE(spy.count(), 2);
1766
1767     input.setParentItem(view.rootObject());
1768     QCOMPARE(input.isCursorVisible(), true);
1769     QCOMPARE(spy.count(), 3);
1770
1771     input.setFocus(false);
1772     QCOMPARE(input.isCursorVisible(), false);
1773     QCOMPARE(spy.count(), 4);
1774
1775     input.setFocus(true);
1776     QCOMPARE(input.isCursorVisible(), true);
1777     QCOMPARE(spy.count(), 5);
1778
1779     view.setWindowState(Qt::WindowNoState);
1780     QCOMPARE(input.isCursorVisible(), false);
1781     QCOMPARE(spy.count(), 6);
1782
1783     view.requestActivateWindow();
1784     QCOMPARE(input.isCursorVisible(), true);
1785     QCOMPARE(spy.count(), 7);
1786
1787     // on mac, setActiveWindow(0) on mac does not deactivate the current application
1788     // (you have to switch to a different app or hide the current app to trigger this)
1789 #if !defined(Q_WS_MAC)
1790     QApplication::setActiveWindow(0);
1791     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(0));
1792     QCOMPARE(input.isCursorVisible(), false);
1793     QCOMPARE(spy.count(), 8);
1794
1795     view.requestActivateWindow();
1796     QTRY_COMPARE(view.windowState(), Qt::WindowActive);
1797     QCOMPARE(input.isCursorVisible(), true);
1798     QCOMPARE(spy.count(), 9);
1799 #endif
1800 }
1801
1802 void tst_qsgtextinput::cursorRectangle()
1803 {
1804     QString text = "Hello World!";
1805
1806     QSGTextInput input;
1807     input.setText(text);
1808     QFontMetricsF fm(input.font());
1809     input.setWidth(fm.width(text.mid(0, 5)));
1810
1811     QRect r;
1812
1813     // some tolerance for different fonts.
1814 #ifdef Q_OS_LINUX
1815     const int error = 2;
1816 #else
1817     const int error = 5;
1818 #endif
1819
1820
1821     for (int i = 0; i <= 5; ++i) {
1822         input.setCursorPosition(i);
1823         r = input.cursorRectangle();
1824         int textWidth = fm.width(text.mid(0, i));
1825
1826         QVERIFY(r.left() < textWidth + error);
1827         QVERIFY(r.right() > textWidth - error);
1828         QCOMPARE(input.inputMethodQuery(Qt::ImMicroFocus).toRect(), r);
1829     }
1830
1831     // Check the cursor rectangle remains within the input bounding rect when auto scrolling.
1832     QVERIFY(r.left() < input.boundingRect().width());
1833     QVERIFY(r.right() >= input.width() - error);
1834
1835     for (int i = 6; i < text.length(); ++i) {
1836         input.setCursorPosition(i);
1837         QCOMPARE(r, input.cursorRectangle());
1838         QCOMPARE(input.inputMethodQuery(Qt::ImMicroFocus).toRect(), r);
1839     }
1840
1841     for (int i = text.length() - 2; i >= 0; --i) {
1842         input.setCursorPosition(i);
1843         r = input.cursorRectangle();
1844         QVERIFY(r.right() >= 0);
1845         QCOMPARE(input.inputMethodQuery(Qt::ImMicroFocus).toRect(), r);
1846     }
1847
1848     input.setText("Hi!");
1849     input.setHAlign(QSGTextInput::AlignRight);
1850     r = input.cursorRectangle();
1851     QVERIFY(r.left() < input.boundingRect().width());
1852     QVERIFY(r.right() >= input.width() - error);
1853 }
1854
1855 void tst_qsgtextinput::readOnly()
1856 {
1857     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/readOnly.qml"));
1858     canvas.show();
1859     canvas.requestActivateWindow();
1860
1861     QVERIFY(canvas.rootObject() != 0);
1862
1863     QSGTextInput *input = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("myInput")));
1864
1865     QVERIFY(input != 0);
1866     QTRY_VERIFY(input->hasActiveFocus() == true);
1867     QVERIFY(input->isReadOnly() == true);
1868     QString initial = input->text();
1869     for(int k=Qt::Key_0; k<=Qt::Key_Z; k++)
1870         simulateKey(&canvas, k);
1871     simulateKey(&canvas, Qt::Key_Return);
1872     simulateKey(&canvas, Qt::Key_Space);
1873     simulateKey(&canvas, Qt::Key_Escape);
1874     QCOMPARE(input->text(), initial);
1875
1876     input->setCursorPosition(3);
1877     input->setReadOnly(false);
1878     QCOMPARE(input->isReadOnly(), false);
1879     QCOMPARE(input->cursorPosition(), input->text().length());
1880 }
1881
1882 void tst_qsgtextinput::echoMode()
1883 {
1884     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/echoMode.qml"));
1885     canvas.show();
1886     canvas.requestActivateWindow();
1887     QTest::qWaitForWindowShown(&canvas);
1888     QTRY_COMPARE(canvas.windowState(), Qt::WindowActive);
1889
1890     QVERIFY(canvas.rootObject() != 0);
1891
1892     QSGTextInput *input = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("myInput")));
1893
1894     QVERIFY(input != 0);
1895     QTRY_VERIFY(input->hasActiveFocus() == true);
1896     QString initial = input->text();
1897     Qt::InputMethodHints ref;
1898     QCOMPARE(initial, QLatin1String("ABCDefgh"));
1899     QCOMPARE(input->echoMode(), QSGTextInput::Normal);
1900     QCOMPARE(input->displayText(), input->text());
1901     //Normal
1902     ref &= ~Qt::ImhHiddenText;
1903     ref &= ~(Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
1904     QCOMPARE(input->inputMethodHints(), ref);
1905     input->setEchoMode(QSGTextInput::NoEcho);
1906     QCOMPARE(input->text(), initial);
1907     QCOMPARE(input->displayText(), QLatin1String(""));
1908     QCOMPARE(input->passwordCharacter(), QLatin1String("*"));
1909     //NoEcho
1910     ref |= Qt::ImhHiddenText;
1911     ref |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
1912     QCOMPARE(input->inputMethodHints(), ref);
1913     input->setEchoMode(QSGTextInput::Password);
1914     //Password
1915     ref |= Qt::ImhHiddenText;
1916     ref |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
1917     QCOMPARE(input->text(), initial);
1918     QCOMPARE(input->displayText(), QLatin1String("********"));
1919     QCOMPARE(input->inputMethodHints(), ref);
1920     input->setPasswordCharacter(QChar('Q'));
1921     QCOMPARE(input->passwordCharacter(), QLatin1String("Q"));
1922     QCOMPARE(input->text(), initial);
1923     QCOMPARE(input->displayText(), QLatin1String("QQQQQQQQ"));
1924     input->setEchoMode(QSGTextInput::PasswordEchoOnEdit);
1925     //PasswordEchoOnEdit
1926     ref &= ~Qt::ImhHiddenText;
1927     ref |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
1928     QCOMPARE(input->inputMethodHints(), ref);
1929     QCOMPARE(input->text(), initial);
1930     QCOMPARE(input->displayText(), QLatin1String("QQQQQQQQ"));
1931     QCOMPARE(input->inputMethodQuery(Qt::ImSurroundingText).toString(), QLatin1String("QQQQQQQQ"));
1932     QTest::keyPress(&canvas, Qt::Key_A);//Clearing previous entry is part of PasswordEchoOnEdit
1933     QTest::keyRelease(&canvas, Qt::Key_A, Qt::NoModifier ,10);
1934     QCOMPARE(input->text(), QLatin1String("a"));
1935     QCOMPARE(input->displayText(), QLatin1String("a"));
1936     QCOMPARE(input->inputMethodQuery(Qt::ImSurroundingText).toString(), QLatin1String("a"));
1937     input->setFocus(false);
1938     QVERIFY(input->hasActiveFocus() == false);
1939     QCOMPARE(input->displayText(), QLatin1String("Q"));
1940     QCOMPARE(input->inputMethodQuery(Qt::ImSurroundingText).toString(), QLatin1String("Q"));
1941     input->setFocus(true);
1942     QInputMethodEvent inputEvent;
1943     inputEvent.setCommitString(initial);
1944     QApplication::sendEvent(&canvas, &inputEvent);
1945     QCOMPARE(input->text(), initial);
1946     QCOMPARE(input->displayText(), initial);
1947     QCOMPARE(input->inputMethodQuery(Qt::ImSurroundingText).toString(), initial);
1948 }
1949
1950 #ifdef QT_GUI_PASSWORD_ECHO_DELAY
1951 void tst_qdeclarativetextinput::passwordEchoDelay()
1952 {
1953     QSGView canvas(QUrl::fromLocalFile(SRCDIR "/data/echoMode.qml"));
1954     canvas.show();
1955     canvas.setFocus();
1956     QApplication::setActiveWindow(&canvas);
1957     QTest::qWaitForWindowShown(&canvas);
1958     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&canvas));
1959
1960     QVERIFY(canvas.rootObject() != 0);
1961
1962     QSGTextInput *input = qobject_cast<QSGTextInput *>(qvariant_cast<QObject *>(canvas.rootObject()->property("myInput")));
1963
1964     QChar fillChar = QLatin1Char('*');
1965
1966     input->setEchoMode(QDeclarativeTextInput::Password);
1967     QCOMPARE(input->displayText(), QString(8, fillChar));
1968     input->setText(QString());
1969     QCOMPARE(input->displayText(), QString());
1970
1971     QTest::keyPress(&canvas, '0');
1972     QTest::keyPress(&canvas, '1');
1973     QTest::keyPress(&canvas, '2');
1974     QCOMPARE(input->displayText(), QString(2, fillChar) + QLatin1Char('2'));
1975     QTest::keyPress(&canvas, '3');
1976     QTest::keyPress(&canvas, '4');
1977     QCOMPARE(input->displayText(), QString(4, fillChar) + QLatin1Char('4'));
1978     QTest::keyPress(&canvas, Qt::Key_Backspace);
1979     QCOMPARE(input->displayText(), QString(4, fillChar));
1980     QTest::keyPress(&canvas, '4');
1981     QCOMPARE(input->displayText(), QString(4, fillChar) + QLatin1Char('4'));
1982     QTest::qWait(QT_GUI_PASSWORD_ECHO_DELAY);
1983     QTRY_COMPARE(input->displayText(), QString(5, fillChar));
1984     QTest::keyPress(&canvas, '5');
1985     QCOMPARE(input->displayText(), QString(5, fillChar) + QLatin1Char('5'));
1986     input->setFocus(false);
1987     QVERIFY(!input->hasFocus());
1988     QCOMPARE(input->displayText(), QString(6, fillChar));
1989     input->setFocus(true);
1990     QTRY_VERIFY(input->hasFocus());
1991     QCOMPARE(input->displayText(), QString(6, fillChar));
1992     QTest::keyPress(&canvas, '6');
1993     QCOMPARE(input->displayText(), QString(6, fillChar) + QLatin1Char('6'));
1994
1995     QInputMethodEvent ev;
1996     ev.setCommitString(QLatin1String("7"));
1997     QApplication::sendEvent(&canvas, &ev);
1998     QCOMPARE(input->displayText(), QString(7, fillChar) + QLatin1Char('7'));
1999 }
2000 #endif
2001
2002
2003 void tst_qsgtextinput::simulateKey(QSGView *view, int key)
2004 {
2005     QKeyEvent press(QKeyEvent::KeyPress, key, 0);
2006     QKeyEvent release(QKeyEvent::KeyRelease, key, 0);
2007
2008     QApplication::sendEvent(view, &press);
2009     QApplication::sendEvent(view, &release);
2010 }
2011
2012 class MyInputContext : public QInputContext
2013 {
2014 public:
2015     MyInputContext() : openInputPanelReceived(false), closeInputPanelReceived(false), updateReceived(false), eventType(QEvent::None) {}
2016     ~MyInputContext() {}
2017
2018     QString identifierName() { return QString(); }
2019     QString language() { return QString(); }
2020
2021     void reset() {}
2022
2023     bool isComposing() const { return false; }
2024
2025     bool filterEvent( const QEvent *event )
2026     {
2027         if (event->type() == QEvent::RequestSoftwareInputPanel)
2028             openInputPanelReceived = true;
2029         if (event->type() == QEvent::CloseSoftwareInputPanel)
2030             closeInputPanelReceived = true;
2031         return QInputContext::filterEvent(event);
2032     }
2033
2034     void update() { updateReceived = true; }
2035
2036     void mouseHandler(int x, QMouseEvent *event)
2037     {
2038         cursor = x;
2039         eventType = event->type();
2040         eventPosition = event->pos();
2041         eventGlobalPosition = event->globalPos();
2042         eventButton = event->button();
2043         eventButtons = event->buttons();
2044         eventModifiers = event->modifiers();
2045     }
2046
2047     void sendPreeditText(const QString &text, int cursor)
2048     {
2049         QList<QInputMethodEvent::Attribute> attributes;
2050         attributes.append(QInputMethodEvent::Attribute(
2051                 QInputMethodEvent::Cursor, cursor, text.length(), QVariant()));
2052
2053         QInputMethodEvent event(text, attributes);
2054         sendEvent(event);
2055     }
2056
2057     bool openInputPanelReceived;
2058     bool closeInputPanelReceived;
2059     bool updateReceived;
2060     int cursor;
2061     QEvent::Type eventType;
2062     QPoint eventPosition;
2063     QPoint eventGlobalPosition;
2064     Qt::MouseButton eventButton;
2065     Qt::MouseButtons eventButtons;
2066     Qt::KeyboardModifiers eventModifiers;
2067 };
2068
2069 void tst_qsgtextinput::openInputPanelOnClick()
2070 {
2071     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/openInputPanel.qml"));
2072     MyInputContext ic;
2073     // QSGCanvas won't set the Qt::WA_InputMethodEnabled flag unless a suitable item has focus
2074     // and QWidget won't allow an input context to be set when the flag is not set.
2075     view.setAttribute(Qt::WA_InputMethodEnabled, true);
2076     view.setInputContext(&ic);
2077     view.setAttribute(Qt::WA_InputMethodEnabled, false);
2078     view.show();
2079     QApplication::setActiveWindow(&view);
2080     QTest::qWaitForWindowShown(&view);
2081     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2082     QSGTextInput *input = qobject_cast<QSGTextInput *>(view.rootObject());
2083     QVERIFY(input);
2084
2085     QSGItemPrivate* pri = QSGItemPrivate::get(input);
2086     QSGTextInputPrivate *inputPrivate = static_cast<QSGTextInputPrivate*>(pri);
2087
2088     // input panel on click
2089     inputPrivate->showInputPanelOnFocus = false;
2090
2091     QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel(
2092             view.style()->styleHint(QStyle::SH_RequestSoftwareInputPanel));
2093     QTest::mouseClick(&view, Qt::LeftButton, 0, input->pos().toPoint());
2094     QApplication::processEvents();
2095     if (behavior == QStyle::RSIP_OnMouseClickAndAlreadyFocused) {
2096         QCOMPARE(ic.openInputPanelReceived, false);
2097         QTest::mouseClick(&view, Qt::LeftButton, 0, input->pos().toPoint());
2098         QApplication::processEvents();
2099         QCOMPARE(ic.openInputPanelReceived, true);
2100     } else if (behavior == QStyle::RSIP_OnMouseClick) {
2101         QCOMPARE(ic.openInputPanelReceived, true);
2102     }
2103     ic.openInputPanelReceived = false;
2104
2105     // focus should not cause input panels to open or close
2106     input->setFocus(false);
2107     input->setFocus(true);
2108     input->setFocus(false);
2109     input->setFocus(true);
2110     input->setFocus(false);
2111     QCOMPARE(ic.openInputPanelReceived, false);
2112     QCOMPARE(ic.closeInputPanelReceived, false);
2113 }
2114
2115 void tst_qsgtextinput::openInputPanelOnFocus()
2116 {
2117     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/openInputPanel.qml"));
2118     MyInputContext ic;
2119     // QSGCanvas won't set the Qt::WA_InputMethodEnabled flag unless a suitable item has focus
2120     // and QWidget won't allow an input context to be set when the flag is not set.
2121     view.setAttribute(Qt::WA_InputMethodEnabled, true);
2122     view.setInputContext(&ic);
2123     view.setAttribute(Qt::WA_InputMethodEnabled, false);
2124     view.show();
2125     QApplication::setActiveWindow(&view);
2126     QTest::qWaitForWindowShown(&view);
2127     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2128     QSGTextInput *input = qobject_cast<QSGTextInput *>(view.rootObject());
2129     QVERIFY(input);
2130     QSignalSpy focusOnPressSpy(input, SIGNAL(activeFocusOnPressChanged(bool)));
2131
2132     QSGItemPrivate* pri = QSGItemPrivate::get(input);
2133     QSGTextInputPrivate *inputPrivate = static_cast<QSGTextInputPrivate*>(pri);
2134     inputPrivate->showInputPanelOnFocus = true;
2135
2136     // test default values
2137     QVERIFY(input->focusOnPress());
2138     QCOMPARE(ic.openInputPanelReceived, false);
2139     QCOMPARE(ic.closeInputPanelReceived, false);
2140
2141     // focus on press, input panel on focus
2142     QTest::mousePress(&view, Qt::LeftButton, 0, input->pos().toPoint());
2143     QApplication::processEvents();
2144     QVERIFY(input->hasActiveFocus());
2145     QCOMPARE(ic.openInputPanelReceived, true);
2146     ic.openInputPanelReceived = false;
2147
2148     // no events on release
2149     QTest::mouseRelease(&view, Qt::LeftButton, 0, input->pos().toPoint());
2150     QCOMPARE(ic.openInputPanelReceived, false);
2151     ic.openInputPanelReceived = false;
2152
2153     // if already focused, input panel can be opened on press
2154     QVERIFY(input->hasActiveFocus());
2155     QTest::mousePress(&view, Qt::LeftButton, 0, input->pos().toPoint());
2156     QApplication::processEvents();
2157     QCOMPARE(ic.openInputPanelReceived, true);
2158     ic.openInputPanelReceived = false;
2159
2160     // input method should stay enabled if focus
2161     // is lost to an item that also accepts inputs
2162     QSGTextInput anotherInput;
2163     anotherInput.setParentItem(view.rootItem());
2164     anotherInput.setFocus(true);
2165     QApplication::processEvents();
2166     QCOMPARE(ic.openInputPanelReceived, true);
2167     ic.openInputPanelReceived = false;
2168     QCOMPARE(view.inputContext(), (QInputContext*)&ic);
2169     QVERIFY(view.testAttribute(Qt::WA_InputMethodEnabled));
2170
2171     // input method should be disabled if focus
2172     // is lost to an item that doesn't accept inputs
2173     QSGItem item;
2174     item.setParentItem(view.rootItem());
2175     item.setFocus(true);
2176     QApplication::processEvents();
2177     QCOMPARE(ic.openInputPanelReceived, false);
2178     QVERIFY(view.inputContext() == 0);
2179     QVERIFY(!view.testAttribute(Qt::WA_InputMethodEnabled));
2180
2181     // no automatic input panel events should
2182     // be sent if activeFocusOnPress is false
2183     input->setFocusOnPress(false);
2184     QCOMPARE(focusOnPressSpy.count(),1);
2185     input->setFocusOnPress(false);
2186     QCOMPARE(focusOnPressSpy.count(),1);
2187     input->setFocus(false);
2188     input->setFocus(true);
2189     QTest::mousePress(&view, Qt::LeftButton, 0, input->pos().toPoint());
2190     QTest::mouseRelease(&view, Qt::LeftButton, 0, input->pos().toPoint());
2191     QApplication::processEvents();
2192     QCOMPARE(ic.openInputPanelReceived, false);
2193     QCOMPARE(ic.closeInputPanelReceived, false);
2194
2195     // one show input panel event should
2196     // be set when openSoftwareInputPanel is called
2197     input->openSoftwareInputPanel();
2198     QCOMPARE(ic.openInputPanelReceived, true);
2199     QCOMPARE(ic.closeInputPanelReceived, false);
2200     ic.openInputPanelReceived = false;
2201
2202     // one close input panel event should
2203     // be sent when closeSoftwareInputPanel is called
2204     input->closeSoftwareInputPanel();
2205     QCOMPARE(ic.openInputPanelReceived, false);
2206     QCOMPARE(ic.closeInputPanelReceived, true);
2207     ic.closeInputPanelReceived = false;
2208
2209     // set activeFocusOnPress back to true
2210     input->setFocusOnPress(true);
2211     QCOMPARE(focusOnPressSpy.count(),2);
2212     input->setFocusOnPress(true);
2213     QCOMPARE(focusOnPressSpy.count(),2);
2214     input->setFocus(false);
2215     QApplication::processEvents();
2216     QCOMPARE(ic.openInputPanelReceived, false);
2217     QCOMPARE(ic.closeInputPanelReceived, false);
2218     ic.closeInputPanelReceived = false;
2219
2220     // input panel should not re-open
2221     // if focus has already been set
2222     input->setFocus(true);
2223     QCOMPARE(ic.openInputPanelReceived, true);
2224     ic.openInputPanelReceived = false;
2225     input->setFocus(true);
2226     QCOMPARE(ic.openInputPanelReceived, false);
2227
2228     // input method should be disabled
2229     // if TextInput loses focus
2230     input->setFocus(false);
2231     QApplication::processEvents();
2232     QVERIFY(view.inputContext() == 0);
2233     QVERIFY(!view.testAttribute(Qt::WA_InputMethodEnabled));
2234
2235     // input method should not be enabled
2236     // if TextEdit is read only.
2237     input->setReadOnly(true);
2238     ic.openInputPanelReceived = false;
2239     input->setFocus(true);
2240     QApplication::processEvents();
2241     QCOMPARE(ic.openInputPanelReceived, false);
2242     QVERIFY(view.inputContext() == 0);
2243     QVERIFY(!view.testAttribute(Qt::WA_InputMethodEnabled));
2244 }
2245
2246 class MyTextInput : public QSGTextInput
2247 {
2248 public:
2249     MyTextInput(QSGItem *parent = 0) : QSGTextInput(parent)
2250     {
2251         nbPaint = 0;
2252     }
2253     virtual QSGNode *updatePaintNode(QSGNode *node, UpdatePaintNodeData *data)
2254     {
2255        nbPaint++;
2256        return QSGTextInput::updatePaintNode(node, data);
2257     }
2258     int nbPaint;
2259 };
2260
2261 void tst_qsgtextinput::setHAlignClearCache()
2262 {
2263     QSGView view;
2264     MyTextInput input;
2265     input.setText("Hello world");
2266     input.setParentItem(view.rootItem());
2267     view.show();
2268     QApplication::setActiveWindow(&view);
2269     QTest::qWaitForWindowShown(&view);
2270     QTRY_COMPARE(input.nbPaint, 1);
2271     input.setHAlign(QSGTextInput::AlignRight);
2272     //Changing the alignment should trigger a repaint
2273     QTRY_COMPARE(input.nbPaint, 2);
2274 }
2275
2276 void tst_qsgtextinput::focusOutClearSelection()
2277 {
2278     QSGView view;
2279     QSGTextInput input;
2280     QSGTextInput input2;
2281     input.setText(QLatin1String("Hello world"));
2282     input.setFocus(true);
2283     input2.setParentItem(view.rootItem());
2284     input.setParentItem(view.rootItem());
2285     view.show();
2286     QApplication::setActiveWindow(&view);
2287     QTest::qWaitForWindowShown(&view);
2288     input.select(2,5);
2289     //The selection should work
2290     QTRY_COMPARE(input.selectedText(), QLatin1String("llo"));
2291     input2.setFocus(true);
2292     QApplication::processEvents();
2293     //The input lost the focus selection should be cleared
2294     QTRY_COMPARE(input.selectedText(), QLatin1String(""));
2295 }
2296
2297 void tst_qsgtextinput::geometrySignals()
2298 {
2299     QDeclarativeComponent component(&engine, SRCDIR "/data/geometrySignals.qml");
2300     QObject *o = component.create();
2301     QVERIFY(o);
2302     QCOMPARE(o->property("bindingWidth").toInt(), 400);
2303     QCOMPARE(o->property("bindingHeight").toInt(), 500);
2304     delete o;
2305 }
2306
2307 void tst_qsgtextinput::testQtQuick11Attributes()
2308 {
2309     QFETCH(QString, code);
2310     QFETCH(QString, warning);
2311     QFETCH(QString, error);
2312
2313     QDeclarativeEngine engine;
2314     QObject *obj;
2315
2316     QDeclarativeComponent valid(&engine);
2317     valid.setData("import QtQuick 2.0; TextInput { " + code.toUtf8() + " }", QUrl(""));
2318     obj = valid.create();
2319     QVERIFY(obj);
2320     QVERIFY(valid.errorString().isEmpty());
2321     delete obj;
2322
2323     QDeclarativeComponent invalid(&engine);
2324     invalid.setData("import QtQuick 1.0; TextInput { " + code.toUtf8() + " }", QUrl(""));
2325     QTest::ignoreMessage(QtWarningMsg, warning.toUtf8());
2326     obj = invalid.create();
2327     QCOMPARE(invalid.errorString(), error);
2328     delete obj;
2329 }
2330
2331 void tst_qsgtextinput::testQtQuick11Attributes_data()
2332 {
2333     QTest::addColumn<QString>("code");
2334     QTest::addColumn<QString>("warning");
2335     QTest::addColumn<QString>("error");
2336
2337     QTest::newRow("canPaste") << "property bool foo: canPaste"
2338         << "<Unknown File>:1: ReferenceError: Can't find variable: canPaste"
2339         << "";
2340
2341     QTest::newRow("moveCursorSelection") << "Component.onCompleted: moveCursorSelection(0, TextEdit.SelectCharacters)"
2342         << "<Unknown File>:1: ReferenceError: Can't find variable: moveCursorSelection"
2343         << "";
2344
2345     QTest::newRow("deselect") << "Component.onCompleted: deselect()"
2346         << "<Unknown File>:1: ReferenceError: Can't find variable: deselect"
2347         << "";
2348 }
2349
2350 void tst_qsgtextinput::preeditAutoScroll()
2351 {
2352     QString preeditText = "califragisiticexpialidocious!";
2353
2354     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/preeditAutoScroll.qml"));
2355     MyInputContext ic;
2356     // QSGCanvas won't set the Qt::WA_InputMethodEnabled flag unless a suitable item has active focus
2357     // and QWidget won't allow an input context to be set when the flag is not set.
2358     view.setAttribute(Qt::WA_InputMethodEnabled, true);
2359     view.setInputContext(&ic);
2360     view.setAttribute(Qt::WA_InputMethodEnabled, false);
2361     view.show();
2362     QApplication::setActiveWindow(&view);
2363     QTest::qWaitForWindowShown(&view);
2364     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2365     QSGTextInput *input = qobject_cast<QSGTextInput *>(view.rootObject());
2366     QVERIFY(input);
2367
2368     QSignalSpy cursorRectangleSpy(input, SIGNAL(cursorRectangleChanged()));
2369     int cursorRectangleChanges = 0;
2370
2371     QFontMetricsF fm(input->font());
2372     input->setWidth(fm.width(input->text()));
2373
2374     // test the text is scrolled so the preedit is visible.
2375     ic.sendPreeditText(preeditText.mid(0, 3), 1);
2376     QVERIFY(input->positionAt(0) != 0);
2377     QVERIFY(input->cursorRectangle().left() < input->boundingRect().width());
2378     QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2379
2380     // test the text is scrolled back when the preedit is removed.
2381     ic.sendEvent(QInputMethodEvent());
2382     QCOMPARE(input->positionAt(0), 0);
2383     QCOMPARE(input->positionAt(input->width()), 5);
2384     QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2385
2386     // some tolerance for different fonts.
2387 #ifdef Q_OS_LINUX
2388     const int error = 2;
2389 #else
2390     const int error = 5;
2391 #endif
2392
2393     // test if the preedit is larger than the text input that the
2394     // character preceding the cursor is still visible.
2395     qreal x = input->positionToRectangle(0).x();
2396     for (int i = 0; i < 3; ++i) {
2397         ic.sendPreeditText(preeditText, i + 1);
2398         QVERIFY(input->cursorRectangle().right() >= fm.width(preeditText.at(i)) - error);
2399         QVERIFY(input->positionToRectangle(0).x() < x);
2400         QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2401         x = input->positionToRectangle(0).x();
2402     }
2403     for (int i = 1; i >= 0; --i) {
2404         ic.sendPreeditText(preeditText, i + 1);
2405         QVERIFY(input->cursorRectangle().right() >= fm.width(preeditText.at(i)) - error);
2406         QVERIFY(input->positionToRectangle(0).x() > x);
2407         QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2408         x = input->positionToRectangle(0).x();
2409     }
2410
2411     // Test incrementing the preedit cursor doesn't cause further
2412     // scrolling when right most text is visible.
2413     ic.sendPreeditText(preeditText, preeditText.length() - 3);
2414     QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2415     x = input->positionToRectangle(0).x();
2416     for (int i = 2; i >= 0; --i) {
2417         ic.sendPreeditText(preeditText, preeditText.length() - i);
2418         QCOMPARE(input->positionToRectangle(0).x(), x);
2419         QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2420     }
2421     for (int i = 1; i <  3; ++i) {
2422         ic.sendPreeditText(preeditText, preeditText.length() - i);
2423         QCOMPARE(input->positionToRectangle(0).x(), x);
2424         QCOMPARE(cursorRectangleSpy.count(), ++cursorRectangleChanges);
2425     }
2426
2427     // Test disabling auto scroll.
2428     ic.sendEvent(QInputMethodEvent());
2429
2430     input->setAutoScroll(false);
2431     ic.sendPreeditText(preeditText.mid(0, 3), 1);
2432     QCOMPARE(input->positionAt(0), 0);
2433     QCOMPARE(input->positionAt(input->width()), 5);
2434 }
2435
2436 void tst_qsgtextinput::preeditMicroFocus()
2437 {
2438     QString preeditText = "super";
2439
2440     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/inputMethodEvent.qml"));
2441     MyInputContext ic;
2442     // QSGCanvas won't set the Qt::WA_InputMethodEnabled flag unless a suitable item has active focus
2443     // and QWidget won't allow an input context to be set when the flag is not set.
2444     view.setAttribute(Qt::WA_InputMethodEnabled, true);
2445     view.setInputContext(&ic);
2446     view.setAttribute(Qt::WA_InputMethodEnabled, false);
2447     view.show();
2448     QApplication::setActiveWindow(&view);
2449     QTest::qWaitForWindowShown(&view);
2450     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2451     QSGTextInput *input = qobject_cast<QSGTextInput *>(view.rootObject());
2452     QVERIFY(input);
2453
2454     QRect currentRect;
2455     QRect previousRect = input->inputMethodQuery(Qt::ImMicroFocus).toRect();
2456
2457     // Verify that the micro focus rect is positioned the same for position 0 as
2458     // it would be if there was no preedit text.
2459     ic.updateReceived = false;
2460     ic.sendPreeditText(preeditText, 0);
2461     currentRect = input->inputMethodQuery(Qt::ImMicroFocus).toRect();
2462     QCOMPARE(currentRect, previousRect);
2463 #if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
2464     QCOMPARE(ic.updateReceived, true);
2465 #endif
2466
2467     // Verify that the micro focus rect moves to the left as the cursor position
2468     // is incremented.
2469     for (int i = 1; i <= 5; ++i) {
2470         ic.updateReceived = false;
2471         ic.sendPreeditText(preeditText, i);
2472         currentRect = input->inputMethodQuery(Qt::ImMicroFocus).toRect();
2473         QVERIFY(previousRect.left() < currentRect.left());
2474 #if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
2475         QCOMPARE(ic.updateReceived, true);
2476 #endif
2477         previousRect = currentRect;
2478     }
2479
2480     // Verify that if there is no preedit cursor then the micro focus rect is the
2481     // same as it would be if it were positioned at the end of the preedit text.
2482     ic.sendPreeditText(preeditText, 0);
2483     ic.updateReceived = false;
2484     ic.sendEvent(QInputMethodEvent(preeditText, QList<QInputMethodEvent::Attribute>()));
2485     currentRect = input->inputMethodQuery(Qt::ImMicroFocus).toRect();
2486     QCOMPARE(currentRect, previousRect);
2487 #if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
2488     QCOMPARE(ic.updateReceived, true);
2489 #endif
2490 }
2491
2492 void tst_qsgtextinput::inputContextMouseHandler()
2493 {
2494     QString text = "supercalifragisiticexpialidocious!";
2495
2496     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/inputContext.qml"));
2497     MyInputContext ic;
2498     // QSGCanvas won't set the Qt::WA_InputMethodEnabled flag unless a suitable item has active focus
2499     // and QWidget won't allow an input context to be set when the flag is not set.
2500     view.setAttribute(Qt::WA_InputMethodEnabled, true);
2501     view.setInputContext(&ic);
2502     view.setAttribute(Qt::WA_InputMethodEnabled, false);
2503     view.show();
2504     QApplication::setActiveWindow(&view);
2505     QTest::qWaitForWindowShown(&view);
2506     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2507     QSGTextInput *input = qobject_cast<QSGTextInput *>(view.rootObject());
2508     QVERIFY(input);
2509
2510     QFontMetricsF fm(input->font());
2511     const qreal y = fm.height() / 2;
2512
2513     QPoint position2 = input->mapToScene(QPointF(fm.width(text.mid(0, 2)), y)).toPoint();
2514     QPoint position8 = input->mapToScene(QPointF(fm.width(text.mid(0, 8)), y)).toPoint();
2515     QPoint position20 = input->mapToScene(QPointF(fm.width(text.mid(0, 20)), y)).toPoint();
2516     QPoint position27 = input->mapToScene(QPointF(fm.width(text.mid(0, 27)), y)).toPoint();
2517     QPoint globalPosition2 = view.mapToGlobal(position2);
2518     QPoint globalposition8 = view.mapToGlobal(position8);
2519     QPoint globalposition20 = view.mapToGlobal(position20);
2520     QPoint globalposition27 = view.mapToGlobal(position27);
2521
2522     ic.sendEvent(QInputMethodEvent(text.mid(12), QList<QInputMethodEvent::Attribute>()));
2523
2524     QTest::mouseDClick(&view, Qt::LeftButton, Qt::NoModifier, position2);
2525     QCOMPARE(ic.eventType, QEvent::MouseButtonDblClick);
2526     QCOMPARE(ic.eventPosition, position2);
2527     QCOMPARE(ic.eventGlobalPosition, globalPosition2);
2528     QCOMPARE(ic.eventButton, Qt::LeftButton);
2529     QCOMPARE(ic.eventModifiers, Qt::NoModifier);
2530     QVERIFY(ic.cursor < 0);
2531     ic.eventType = QEvent::None;
2532
2533     QTest::mousePress(&view, Qt::LeftButton, Qt::NoModifier, position2);
2534     QCOMPARE(ic.eventType, QEvent::MouseButtonPress);
2535     QCOMPARE(ic.eventPosition, position2);
2536     QCOMPARE(ic.eventGlobalPosition, globalPosition2);
2537     QCOMPARE(ic.eventButton, Qt::LeftButton);
2538     QCOMPARE(ic.eventModifiers, Qt::NoModifier);
2539     QVERIFY(ic.cursor < 0);
2540     ic.eventType = QEvent::None;
2541
2542     {   QMouseEvent mv(QEvent::MouseMove, position8, globalposition8, Qt::LeftButton, Qt::LeftButton,Qt::NoModifier);
2543         QApplication::sendEvent(&view, &mv); }
2544     QCOMPARE(ic.eventType, QEvent::None);
2545
2546     {   QMouseEvent mv(QEvent::MouseMove, position27, globalposition27, Qt::LeftButton, Qt::LeftButton,Qt::NoModifier);
2547         QApplication::sendEvent(&view, &mv); }
2548     QCOMPARE(ic.eventType, QEvent::MouseMove);
2549     QCOMPARE(ic.eventPosition, position27);
2550     QCOMPARE(ic.eventGlobalPosition, globalposition27);
2551     QCOMPARE(ic.eventButton, Qt::LeftButton);
2552     QCOMPARE(ic.eventModifiers, Qt::NoModifier);
2553     QVERIFY(ic.cursor >= 14 && ic.cursor <= 16);    // 15 is expected but some platforms may be off by one.
2554     ic.eventType = QEvent::None;
2555
2556     QTest::mouseRelease(&view, Qt::LeftButton, Qt::NoModifier, position27);
2557     QCOMPARE(ic.eventType, QEvent::MouseButtonRelease);
2558     QCOMPARE(ic.eventPosition, position27);
2559     QCOMPARE(ic.eventGlobalPosition, globalposition27);
2560     QCOMPARE(ic.eventButton, Qt::LeftButton);
2561     QCOMPARE(ic.eventModifiers, Qt::NoModifier);
2562     QVERIFY(ic.cursor >= 14 && ic.cursor <= 16);
2563     ic.eventType = QEvent::None;
2564
2565     // And in the other direction.
2566     QTest::mouseDClick(&view, Qt::LeftButton, Qt::ControlModifier, position27);
2567     QCOMPARE(ic.eventType, QEvent::MouseButtonDblClick);
2568     QCOMPARE(ic.eventPosition, position27);
2569     QCOMPARE(ic.eventGlobalPosition, globalposition27);
2570     QCOMPARE(ic.eventButton, Qt::LeftButton);
2571     QCOMPARE(ic.eventModifiers, Qt::ControlModifier);
2572     QVERIFY(ic.cursor >= 14 && ic.cursor <= 16);
2573     ic.eventType = QEvent::None;
2574
2575     QTest::mousePress(&view, Qt::RightButton, Qt::ControlModifier, position27);
2576     QCOMPARE(ic.eventType, QEvent::MouseButtonPress);
2577     QCOMPARE(ic.eventPosition, position27);
2578     QCOMPARE(ic.eventGlobalPosition, globalposition27);
2579     QCOMPARE(ic.eventButton, Qt::RightButton);
2580     QCOMPARE(ic.eventModifiers, Qt::ControlModifier);
2581     QVERIFY(ic.cursor >= 14 && ic.cursor <= 16);
2582     ic.eventType = QEvent::None;
2583
2584     {   QMouseEvent mv(QEvent::MouseMove, position20, globalposition20, Qt::RightButton, Qt::RightButton,Qt::ControlModifier);
2585         QApplication::sendEvent(&view, &mv); }
2586     QCOMPARE(ic.eventType, QEvent::MouseMove);
2587     QCOMPARE(ic.eventPosition, position20);
2588     QCOMPARE(ic.eventGlobalPosition, globalposition20);
2589     QCOMPARE(ic.eventButton, Qt::RightButton);
2590     QCOMPARE(ic.eventModifiers, Qt::ControlModifier);
2591     QVERIFY(ic.cursor >= 7 && ic.cursor <= 9);
2592     ic.eventType = QEvent::None;
2593
2594     {   QMouseEvent mv(QEvent::MouseMove, position2, globalPosition2, Qt::RightButton, Qt::RightButton,Qt::ControlModifier);
2595         QApplication::sendEvent(&view, &mv); }
2596     QCOMPARE(ic.eventType, QEvent::None);
2597
2598     QTest::mouseRelease(&view, Qt::RightButton, Qt::ControlModifier, position2);
2599     QCOMPARE(ic.eventType, QEvent::MouseButtonRelease);
2600     QCOMPARE(ic.eventPosition, position2);
2601     QCOMPARE(ic.eventGlobalPosition, globalPosition2);
2602     QCOMPARE(ic.eventButton, Qt::RightButton);
2603     QCOMPARE(ic.eventModifiers, Qt::ControlModifier);
2604     QVERIFY(ic.cursor < 0);
2605     ic.eventType = QEvent::None;
2606 }
2607
2608 void tst_qsgtextinput::inputMethodComposing()
2609 {
2610     QString text = "supercalifragisiticexpialidocious!";
2611
2612     QSGView view(QUrl::fromLocalFile(SRCDIR "/data/inputContext.qml"));
2613     view.show();
2614     QApplication::setActiveWindow(&view);
2615     QTest::qWaitForWindowShown(&view);
2616     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2617     QSGTextInput *input = qobject_cast<QSGTextInput *>(view.rootObject());
2618     QVERIFY(input);
2619     QSignalSpy spy(input, SIGNAL(inputMethodComposingChanged()));
2620
2621     QCOMPARE(input->isInputMethodComposing(), false);
2622     {
2623         QInputMethodEvent event(text.mid(3), QList<QInputMethodEvent::Attribute>());
2624         QApplication::sendEvent(&view, &event);
2625     }
2626     QCOMPARE(input->isInputMethodComposing(), true);
2627     QCOMPARE(spy.count(), 1);
2628
2629     {
2630         QInputMethodEvent event(text.mid(12), QList<QInputMethodEvent::Attribute>());
2631         QApplication::sendEvent(&view, &event);
2632     }
2633     QCOMPARE(spy.count(), 1);
2634
2635     {
2636         QInputMethodEvent event;
2637         QApplication::sendEvent(&view, &event);
2638     }
2639     QCOMPARE(input->isInputMethodComposing(), false);
2640     QCOMPARE(spy.count(), 2);
2641 }
2642
2643 void tst_qsgtextinput::cursorRectangleSize()
2644 {
2645     QSGView *canvas = new QSGView(QUrl::fromLocalFile(SRCDIR "/data/positionAt.qml"));
2646     QVERIFY(canvas->rootObject() != 0);
2647     canvas->show();
2648     canvas->setFocus();
2649     QApplication::setActiveWindow(canvas);
2650     QTest::qWaitForWindowShown(canvas);
2651
2652     QSGTextInput *textInput = qobject_cast<QSGTextInput *>(canvas->rootObject());
2653     QVERIFY(textInput != 0);
2654     textInput->setFocus(Qt::OtherFocusReason);
2655     QRectF cursorRect = textInput->positionToRectangle(textInput->cursorPosition());
2656     QRectF microFocusFromScene = canvas->inputMethodQuery(Qt::ImMicroFocus).toRectF();
2657     QRectF microFocusFromApp= QApplication::focusWidget()->inputMethodQuery(Qt::ImMicroFocus).toRectF();
2658
2659     QCOMPARE(microFocusFromScene.size(), cursorRect.size());
2660     QCOMPARE(microFocusFromApp.size(), cursorRect.size());
2661
2662     delete canvas;
2663 }
2664
2665 QTEST_MAIN(tst_qsgtextinput)
2666
2667 #include "tst_qsgtextinput.moc"