summaryrefslogtreecommitdiffstats
path: root/tests/auto/qapplication/tst_qapplication.cpp
blob: a11b159ac232becfb860b65a06aea1a207eceb6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/


//#define QT_TST_QAPP_DEBUG
#include <qdebug.h>

#include <QtTest/QtTest>

#include "qabstracteventdispatcher.h"
#include <QtGui>

#include "private/qstylesheetstyle_p.h"
#ifdef Q_OS_WINCE
#include <windows.h>
#endif

//TESTED_CLASS=
//TESTED_FILES=

class tst_QApplication : public QObject
{
Q_OBJECT

public:
    tst_QApplication();
    virtual ~tst_QApplication();

public slots:
    void init();
    void cleanup();
private slots:
    void getSetCheck();
    void staticSetup();

    void alert();

    void multiple_data();
    void multiple();

    void nonGui();

    void setFont_data();
    void setFont();

    void args_data();
    void args();

    void lastWindowClosed();
    void quitOnLastWindowClosed();
    void testDeleteLater();
    void testDeleteLaterProcessEvents();

    void libraryPaths();
    void libraryPaths_qt_plugin_path();
    void libraryPaths_qt_plugin_path_2();

    void sendPostedEvents();

    void thread();
    void desktopSettingsAware();

    void setActiveWindow();

    void focusChanged();
    void focusOut();

    void execAfterExit();

    void wheelScrollLines();

    void task109149();

    void style();

    void allWidgets();

    void setAttribute();

    void windowsCommandLine_data();
    void windowsCommandLine();
};

class MyInputContext : public QInputContext
{
public:
    MyInputContext() : QInputContext() {}
    QString identifierName() { return QString("NoName"); }
    QString language() { return QString("NoLanguage"); }
    void reset() {}
    bool isComposing() const { return false; }
};

// Testing get/set functions
void tst_QApplication::getSetCheck()
{
    int argc = 0;
    QApplication obj1(argc, 0, QApplication::GuiServer);
    // QInputContext * QApplication::inputContext()
    // void QApplication::setInputContext(QInputContext *)
    MyInputContext *var1 = new MyInputContext;
    obj1.setInputContext(var1);
    QCOMPARE((QInputContext *)var1, obj1.inputContext());
    QTest::ignoreMessage(QtWarningMsg, "QApplication::setInputContext: called with 0 input context");
    obj1.setInputContext((QInputContext *)0);
    QCOMPARE((QInputContext *)var1, obj1.inputContext());
    // delete var1; // No delete, since QApplication takes ownership
}

class CloseEventTestWindow : public QWidget
{
public:
    CloseEventTestWindow(QWidget *parent = 0)
        : QWidget(parent)
    {
    }

    void closeEvent(QCloseEvent *event)
    {
        QWidget dialog;
        dialog.show();
        dialog.close();

        hide();
        event->ignore();
    }
};

static  char *argv0;

tst_QApplication::tst_QApplication()
{
#ifdef Q_OS_WINCE
    // Clean up environment previously to launching test
    qputenv("QT_PLUGIN_PATH", QByteArray());
#endif
}

tst_QApplication::~tst_QApplication()
{

}

void tst_QApplication::init()
{
// TODO: Add initialization code here.
// This will be executed immediately before each test is run.
}

void tst_QApplication::cleanup()
{
// TODO: Add cleanup code here.
// This will be executed immediately after each test is run.
}

void tst_QApplication::staticSetup()
{
    QVERIFY(!qApp);

    QStyle *style = QStyleFactory::create(QLatin1String("Windows"));
    QVERIFY(style);
    QApplication::setStyle(style);

    QPalette pal;
    QApplication::setPalette(pal);

    /*QFont font;
    QApplication::setFont(font);*/

    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);
}


// QApp subclass that exits the event loop after 150ms
class TestApplication : public QApplication
{
public:
    TestApplication( int &argc, char **argv )
	: QApplication( argc, argv, QApplication::GuiServer )
    {
	startTimer( 150 );
    }

    void timerEvent( QTimerEvent * )
    {
        quit();
    }
};

void tst_QApplication::alert()
{
    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);
    app.alert(0, 0);

    QWidget widget;
    QWidget widget2;
    app.alert(&widget, 100);
    widget.show();
    widget2.show();
#ifdef Q_WS_X11
    qt_x11_wait_for_window_manager(&widget);
    qt_x11_wait_for_window_manager(&widget2);
#endif
    QTest::qWait(100);
    app.alert(&widget, -1);
    app.alert(&widget, 250);
    widget2.activateWindow();
    QApplication::setActiveWindow(&widget2);
    app.alert(&widget, 0);
    widget.activateWindow();
    QApplication::setActiveWindow(&widget);
    app.alert(&widget, 200);
    app.syncX();
}

void tst_QApplication::multiple_data()
{
    QTest::addColumn<QStringList>("features");

    // return a list of things to try
    QTest::newRow( "data0" ) << QStringList( "" );
    QTest::newRow( "data1" ) << QStringList( "QFont" );
    QTest::newRow( "data2" ) << QStringList( "QPixmap" );
    QTest::newRow( "data3" ) << QStringList( "QWidget" );
}

void tst_QApplication::multiple()
{
    QFETCH(QStringList,features);

    int i = 0;
    int argc = 0;
    while ( i++ < 5 ) {
	TestApplication app( argc, 0 );

	if ( features.contains( "QFont" ) ) {
	    // create font and force loading
	    QFont font( "Arial", 12 );
	    QFontInfo finfo( font );
	    finfo.exactMatch();
	}
	if ( features.contains( "QPixmap" ) ) {
	    QPixmap pix( 100, 100 );
	    pix.fill( Qt::black );
	}
	if ( features.contains( "QWidget" ) ) {
	    QWidget widget;
	}

	QVERIFY(!app.exec());
    }
}

void tst_QApplication::nonGui()
{
#ifdef Q_OS_HPUX
    // ### This is only to allow us to generate a test report for now.
    QSKIP("This test shuts down the window manager on HP-UX.", SkipAll);
#endif

    int argc = 0;
    QApplication app(argc, 0, false);
    QCOMPARE(qApp, &app);
}

void tst_QApplication::setFont_data()
{
    QTest::addColumn<QString>("family");
    QTest::addColumn<int>("pointsize");
    QTest::addColumn<bool>("beforeAppConstructor");

    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer); // Needed for QFontDatabase

    int cnt = 0;
    QFontDatabase fdb;
    QStringList families = fdb.families();
    for (QStringList::const_iterator itr = families.begin();
	 itr != families.end();
	 ++itr) {
	if (cnt < 3) {
	    QString family = *itr;
	    QStringList styles = fdb.styles(family);
	    if (styles.size() > 0) {
		QString style = styles.first();
		QList<int> sizes = fdb.pointSizes(family, style);
		if (!sizes.size())
		    sizes = fdb.standardSizes();
		if (sizes.size() > 0) {
		    QTest::newRow(QString("data%1a").arg(cnt).toLatin1().constData())
			<< family
			<< sizes.first()
                        << false;
		    QTest::newRow(QString("data%1b").arg(cnt).toLatin1().constData())
			<< family
			<< sizes.first()
                        << true;
                }
	    }
	}
	++cnt;
    }

    QTest::newRow("nonexistingfont") << "nosuchfont_probably_quiteunlikely"
        << 0 << false;
    QTest::newRow("nonexistingfont") << "nosuchfont_probably_quiteunlikely"
        << 0 << true;

    QTest::newRow("largescaleable") << "smoothtimes" << 100 << false;
    QTest::newRow("largescaleable") << "smoothtimes" << 100 << true;

    QTest::newRow("largeunscaleale") << "helvetica" << 100 << false;
    QTest::newRow("largeunscaleale") << "helvetica" << 100 << true;
}

void tst_QApplication::setFont()
{
    QFETCH( QString, family );
    QFETCH( int, pointsize );
    QFETCH( bool, beforeAppConstructor );

    QFont font( family, pointsize );
    if (beforeAppConstructor) {
        QApplication::setFont( font );
        QCOMPARE(QApplication::font(), font);
    }

    int argc = 0;
    QApplication app( argc, 0, QApplication::GuiServer );
    if (!beforeAppConstructor)
        QApplication::setFont( font );

    QCOMPARE( app.font(), font );
}

void tst_QApplication::args_data()
{
    QTest::addColumn<int>("argc_in");
    QTest::addColumn<QString>("args_in");
    QTest::addColumn<int>("argc_out");
    QTest::addColumn<QString>("args_out");

    QTest::newRow( "App name" ) << 1 << "/usr/bin/appname" << 1 << "/usr/bin/appname";
    QTest::newRow( "No arguments" ) << 0 << QString() << 0 << QString();
    QTest::newRow( "App name, style" ) << 3 << "/usr/bin/appname -style motif" << 1 << "/usr/bin/appname";
    QTest::newRow( "App name, style, arbitrary, reverse" ) << 5 << "/usr/bin/appname -style motif -arbitrary -reverse"
							<< 2 << "/usr/bin/appname -arbitrary";
}

void tst_QApplication::task109149()
{
    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);
    QApplication::setFont(QFont("helvetica", 100));

    QWidget w;
    w.setWindowTitle("hello");
    w.show();

    app.processEvents();
}

static char ** QString2cstrings( const QString &args )
{
    static QList<QByteArray> cache;

    int i;
    char **argarray = 0;
    QStringList list = args.split(' ');;
    argarray = new char*[list.count()+1];

    for (i = 0; i < (int)list.count(); ++i ) {
        QByteArray l1 = list[i].toLatin1();
        argarray[i] = l1.data();
        cache.append(l1);
    }
    argarray[i] = 0;

    return argarray;
}

static QString cstrings2QString( char **args )
{
    QString string;
    if ( !args )
	return string;

    int i = 0;
    while ( args[i] ) {
	string += args[i];
	if ( args[i+1] )
	    string += " ";
	++i;
    }
    return string;
}

void tst_QApplication::args()
{
    QFETCH( int, argc_in );
    QFETCH( QString, args_in );
    QFETCH( int, argc_out );
    QFETCH( QString, args_out );

    char **argv = QString2cstrings( args_in );

    QApplication app( argc_in, argv, QApplication::GuiServer );
    QString argv_out = cstrings2QString(argv);

    QCOMPARE( argc_in, argc_out );
    QCOMPARE( argv_out, args_out );

    delete [] argv;
}

class CloseWidget : public QWidget
{
    Q_OBJECT
public:
    CloseWidget()
    {
        startTimer(500);
    }

protected:
    void timerEvent(QTimerEvent *)
    {
        close();
    }

};

void tst_QApplication::lastWindowClosed()
{
    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);

    QSignalSpy spy(&app, SIGNAL(lastWindowClosed()));

    QPointer<QDialog> dialog = new QDialog;
    QVERIFY(dialog->testAttribute(Qt::WA_QuitOnClose));
    QTimer::singleShot(1000, dialog, SLOT(accept()));
    dialog->exec();
    QVERIFY(dialog);
    QCOMPARE(spy.count(), 0);

    QPointer<CloseWidget>widget = new CloseWidget;
    QVERIFY(widget->testAttribute(Qt::WA_QuitOnClose));
    QObject::connect(&app, SIGNAL(lastWindowClosed()), widget, SLOT(deleteLater()));
    app.exec();
    QVERIFY(!widget);
    QCOMPARE(spy.count(), 1);
    spy.clear();

#if 0
    // everything is closed, so doing this should not emit lastWindowClosed() again
    QMetaObject::invokeMethod(dialog, "close", Qt::QueuedConnection);
    QTimer::singleShot(1000, &app, SLOT(quit()));
    app.exec();
    QCOMPARE(spy.count(), 0);
#endif

    delete dialog;

    // show 3 windows, close them, should only get lastWindowClosed once
    QWidget w1;
    QWidget w2;
    QWidget w3;
    w1.show();
    w2.show();
    w3.show();

    QTimer::singleShot(1000, &app, SLOT(closeAllWindows()));
    app.exec();
    QCOMPARE(spy.count(), 1);
}

class QuitOnLastWindowClosedDialog : public QDialog
{
    Q_OBJECT
public:
    QPushButton *okButton;

    QuitOnLastWindowClosedDialog()
    {
        QHBoxLayout *hbox = new QHBoxLayout(this);
        okButton = new QPushButton("&ok", this);

        hbox->addWidget(okButton);
        connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
        connect(okButton, SIGNAL(clicked()), this, SLOT(ok_clicked()));
    }

public slots:
    void ok_clicked()
    {
        QDialog other;

        QTimer timer;
        connect(&timer, SIGNAL(timeout()), &other, SLOT(accept()));
        QSignalSpy spy(&timer, SIGNAL(timeout()));
        QSignalSpy appSpy(qApp, SIGNAL(lastWindowClosed()));

        timer.start(1000);
        other.exec();

        // verify that the eventloop ran and let the timer fire
        QCOMPARE(spy.count(), 1);
        QCOMPARE(appSpy.count(), 1);
    }
};

class QuitOnLastWindowClosedWindow : public QWidget
{
    Q_OBJECT

public:
    QuitOnLastWindowClosedWindow()
    { }

public slots:
    void execDialogThenShow()
    {
        QDialog dialog;
        QTimer timer1;
        connect(&timer1, SIGNAL(timeout()), &dialog, SLOT(accept()));
        QSignalSpy spy1(&timer1, SIGNAL(timeout()));
        timer1.setSingleShot(true);
        timer1.start(1000);
        dialog.exec();
        QCOMPARE(spy1.count(), 1);

        show();
    }
};

void tst_QApplication::quitOnLastWindowClosed()
{
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);

        QuitOnLastWindowClosedDialog d;
        d.show();
        QTimer::singleShot(1000, d.okButton, SLOT(animateClick()));

        QSignalSpy appSpy(&app, SIGNAL(lastWindowClosed()));
        app.exec();

        // lastWindowClosed() signal should only be sent after the last dialog is closed
        QCOMPARE(appSpy.count(), 2);
    }
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);
        QSignalSpy appSpy(&app, SIGNAL(lastWindowClosed()));

        QDialog dialog;
        QTimer timer1;
        connect(&timer1, SIGNAL(timeout()), &dialog, SLOT(accept()));
        QSignalSpy spy1(&timer1, SIGNAL(timeout()));
        timer1.setSingleShot(true);
        timer1.start(1000);
        dialog.exec();
        QCOMPARE(spy1.count(), 1);
        QCOMPARE(appSpy.count(), 0);

        QTimer timer2;
        connect(&timer2, SIGNAL(timeout()), &app, SLOT(quit()));
        QSignalSpy spy2(&timer2, SIGNAL(timeout()));
        timer2.setSingleShot(true);
        timer2.start(1000);
        int returnValue = app.exec();
        QCOMPARE(returnValue, 0);
        QCOMPARE(spy2.count(), 1);
        QCOMPARE(appSpy.count(), 0);
    }
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);
        QTimer timer;
        timer.setInterval(100);

        QSignalSpy spy(&app, SIGNAL(aboutToQuit()));
        QSignalSpy spy2(&timer, SIGNAL(timeout()));

        QPointer<QMainWindow> mainWindow = new QMainWindow;
        QPointer<QDialog> dialog = new QDialog(mainWindow);

        QVERIFY(app.quitOnLastWindowClosed());
        QVERIFY(mainWindow->testAttribute(Qt::WA_QuitOnClose));
        QVERIFY(dialog->testAttribute(Qt::WA_QuitOnClose));

        mainWindow->show();
        dialog->show();

        timer.start();
        QTimer::singleShot(1000, mainWindow, SLOT(close())); // This should quit the application
        QTimer::singleShot(2000, &app, SLOT(quit()));        // This makes sure we quit even if it didn't

        app.exec();

        QCOMPARE(spy.count(), 1);
        QVERIFY(spy2.count() < 15);      // Should be around 10 if closing caused the quit
    }
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);
        QTimer timer;
        timer.setInterval(100);

        QSignalSpy spy(&app, SIGNAL(aboutToQuit()));
        QSignalSpy spy2(&timer, SIGNAL(timeout()));

        QPointer<QMainWindow> mainWindow = new QMainWindow;
        QPointer<QWidget> invisibleTopLevelWidget = new QWidget;
        invisibleTopLevelWidget->setAttribute(Qt::WA_DontShowOnScreen);

        QVERIFY(app.quitOnLastWindowClosed());
        QVERIFY(mainWindow->testAttribute(Qt::WA_QuitOnClose));
        QVERIFY(invisibleTopLevelWidget->testAttribute(Qt::WA_QuitOnClose));
        QVERIFY(invisibleTopLevelWidget->testAttribute(Qt::WA_DontShowOnScreen));

        mainWindow->show();
        invisibleTopLevelWidget->show();

        timer.start();
        QTimer::singleShot(1000, mainWindow, SLOT(close())); // This should quit the application
        QTimer::singleShot(2000, &app, SLOT(quit()));        // This makes sure we quit even if it didn't

        app.exec();

        QCOMPARE(spy.count(), 1);
        QVERIFY(spy2.count() < 15);      // Should be around 10 if closing caused the quit
    }
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);
        QTimer timer;
        timer.setInterval(100);

        QSignalSpy spy(&app, SIGNAL(aboutToQuit()));
        QSignalSpy spy2(&timer, SIGNAL(timeout()));

        QPointer<CloseEventTestWindow> mainWindow = new CloseEventTestWindow;

        QVERIFY(app.quitOnLastWindowClosed());
        QVERIFY(mainWindow->testAttribute(Qt::WA_QuitOnClose));

        mainWindow->show();

        timer.start();
        QTimer::singleShot(1000, mainWindow, SLOT(close())); // This should quit the application
        QTimer::singleShot(2000, &app, SLOT(quit()));        // This makes sure we quit even if it didn't

        app.exec();

        QCOMPARE(spy.count(), 1);
        QVERIFY(spy2.count() > 15);      // Should be around 20 if closing did not caused the quit
    }
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);
        QSignalSpy appSpy(&app, SIGNAL(lastWindowClosed()));

        // exec a dialog for 1 second, then show the window
        QuitOnLastWindowClosedWindow window;
        QTimer::singleShot(0, &window, SLOT(execDialogThenShow()));

        QTimer timer;
        QSignalSpy timerSpy(&timer, SIGNAL(timeout()));
        connect(&timer, SIGNAL(timeout()), &window, SLOT(close()));
        timer.setSingleShot(true);
        timer.start(2000);
        int returnValue = app.exec();
        QCOMPARE(returnValue, 0);
        // failure here means the timer above didn't fire, and the
        // quit was caused the the dialog being closed (not the window)
        QCOMPARE(timerSpy.count(), 1);
        QCOMPARE(appSpy.count(), 2);
    }
}

bool isPathListIncluded(const QStringList &l, const QStringList &r)
{
    int size = r.count();
    if (size > l.count())
        return false;
#if defined (Q_OS_WIN)
    Qt::CaseSensitivity cs = Qt::CaseInsensitive;
#else
    Qt::CaseSensitivity cs = Qt::CaseSensitive;
#endif
    int i = 0, j = 0;
    for ( ; i < l.count() && j < r.count(); ++i) {
        if (QDir::toNativeSeparators(l[i]).compare(QDir::toNativeSeparators(r[j]), cs) == 0) {
            ++j;
            i = -1;
        }
    }
    return j == r.count();
}

#define QT_TST_QAPP_DEBUG
void tst_QApplication::libraryPaths()
{
    {
#ifndef Q_OS_WINCE
        QString testDir = QDir::current().canonicalPath() + "/test";
#else
        // On Windows CE we need QApplication object to have valid
        // current Path. Therefore we need to identify it ourselves
        // here for the test.
        QFileInfo filePath;
        wchar_t module_name[256];
        GetModuleFileNameW(0, module_name, sizeof(module_name) / sizeof(wchar_t));
        filePath = QString::fromUtf16((ushort *)module_name);
        QString testDir = filePath.path() + "/test";
#endif
        QApplication::setLibraryPaths(QStringList() << testDir);
        QCOMPARE(QApplication::libraryPaths(), (QStringList() << testDir));

        // creating QApplication adds the applicationDirPath to the libraryPath
        int argc = 1;
        QApplication app(argc, &argv0, QApplication::GuiServer);
        QString appDirPath = QDir(app.applicationDirPath()).canonicalPath();

        QStringList actual = QApplication::libraryPaths();
        actual.sort();
        QStringList expected = QSet<QString>::fromList((QStringList() << testDir << appDirPath)).toList();
        expected.sort();

        QVERIFY2(isPathListIncluded(actual, expected),
                 qPrintable("actual:\n - " + actual.join("\n - ") +
                            "\nexpected:\n - " + expected.join("\n - ")));
    }
    {
        // creating QApplication adds the applicationDirPath and plugin install path to the libraryPath
        int argc = 1;
        QApplication app(argc, &argv0, QApplication::GuiServer);
        QString appDirPath = app.applicationDirPath();
        QString installPathPlugins =  QLibraryInfo::location(QLibraryInfo::PluginsPath);

        QStringList actual = QApplication::libraryPaths();
        actual.sort();

        QStringList expected = QSet<QString>::fromList((QStringList() << installPathPlugins << appDirPath)).toList();
        expected.sort();

        QVERIFY2(isPathListIncluded(actual, expected),
                 qPrintable("actual:\n - " + actual.join("\n - ") +
                            "\nexpected:\n - " + expected.join("\n - ")));

        // setting the library paths overrides everything
        QString testDir = QDir::currentPath() + "/test";
        QApplication::setLibraryPaths(QStringList() << testDir);
        QVERIFY2(isPathListIncluded(QApplication::libraryPaths(), (QStringList() << testDir)),
                 qPrintable("actual:\n - " + QApplication::libraryPaths().join("\n - ") +
                            "\nexpected:\n - " + testDir));
    }
    {
#ifdef QT_TST_QAPP_DEBUG
        qDebug() << "Initial library path:" << QApplication::libraryPaths();
#endif

        int count = QApplication::libraryPaths().count();
#if 0
        // this test doesn't work if KDE 4 is installed
        QCOMPARE(count, 1); // before creating QApplication, only the PluginsPath is in the libraryPaths()
#endif
        QString installPathPlugins =  QLibraryInfo::location(QLibraryInfo::PluginsPath);
        QApplication::addLibraryPath(installPathPlugins);
#ifdef QT_TST_QAPP_DEBUG
        qDebug() << "installPathPlugins" << installPathPlugins;
        qDebug() << "After adding plugins path:" << QApplication::libraryPaths();
#endif
        QCOMPARE(QApplication::libraryPaths().count(), count);

        QApplication::addLibraryPath(QDir::currentPath() + "/test");
        QCOMPARE(QApplication::libraryPaths().count(), count + 1);

        // creating QApplication adds the applicationDirPath to the libraryPath
        int argc = 1;
        QApplication app(argc, &argv0, QApplication::GuiServer);
        QString appDirPath = app.applicationDirPath();
        qDebug() << QApplication::libraryPaths();
        // On Windows CE these are identical and might also be the case for other
        // systems too
        if (appDirPath != installPathPlugins)
            QCOMPARE(QApplication::libraryPaths().count(), count + 2);
    }
    {
        int argc = 1;
        QApplication app(argc, &argv0, QApplication::GuiServer);

#ifdef QT_TST_QAPP_DEBUG
        qDebug() << "Initial library path:" << app.libraryPaths();
#endif
        int count = app.libraryPaths().count();
        QString installPathPlugins =  QLibraryInfo::location(QLibraryInfo::PluginsPath);
        app.addLibraryPath(installPathPlugins);
#ifdef QT_TST_QAPP_DEBUG
        qDebug() << "installPathPlugins" << installPathPlugins;
        qDebug() << "After adding plugins path:" << app.libraryPaths();
#endif
        QCOMPARE(app.libraryPaths().count(), count);

        QString appDirPath = app.applicationDirPath();

        app.addLibraryPath(appDirPath);
#ifdef Q_OS_WINCE
        app.addLibraryPath(appDirPath + "/../..");
#else
        app.addLibraryPath(appDirPath + "/..");
#endif
#ifdef QT_TST_QAPP_DEBUG
        qDebug() << "appDirPath" << appDirPath;
        qDebug() << "After adding appDirPath && appDirPath + /..:" << app.libraryPaths();
#endif
        QCOMPARE(app.libraryPaths().count(), count + 1);
#ifdef Q_OS_MAC
        app.addLibraryPath(appDirPath + "/../MacOS");
#else
        app.addLibraryPath(appDirPath + "/tmp/..");
#endif
#ifdef QT_TST_QAPP_DEBUG
        qDebug() << "After adding appDirPath + /tmp/..:" << app.libraryPaths();
#endif
        QCOMPARE(app.libraryPaths().count(), count + 1);
    }
}

void tst_QApplication::libraryPaths_qt_plugin_path()
{
    int argc = 1;

    QApplication app(argc, &argv0, QApplication::GuiServer);
    QString appDirPath = app.applicationDirPath();

    // Our hook into libraryPaths() initialization: Set the QT_PLUGIN_PATH environment variable
    QString installPathPluginsDeCanon = appDirPath + QString::fromLatin1("/tmp/..");
    QByteArray ascii = installPathPluginsDeCanon.toAscii();
    qputenv("QT_PLUGIN_PATH", ascii);

    QVERIFY(!app.libraryPaths().contains(appDirPath + QString::fromLatin1("/tmp/..")));
}

void tst_QApplication::libraryPaths_qt_plugin_path_2()
{
#ifdef Q_OS_UNIX
    QByteArray validPath = QDir("/tmp").canonicalPath().toLatin1();
    QByteArray nonExistentPath = "/nonexistent";
    QByteArray pluginPath = validPath + ":" + nonExistentPath;
#elif defined(Q_OS_WIN)
# ifdef Q_OS_WINCE
    QByteArray validPath = "/Temp";
    QByteArray nonExistentPath = "/nonexistent";
    QByteArray pluginPath = validPath + ";" + nonExistentPath;
# else
    QByteArray validPath = "C:\\windows";
    QByteArray nonExistentPath = "Z:\\nonexistent";
    QByteArray pluginPath = validPath + ";" + nonExistentPath;
# endif
#endif

    {
        // Our hook into libraryPaths() initialization: Set the QT_PLUGIN_PATH environment variable
        qputenv("QT_PLUGIN_PATH", pluginPath);

        int argc = 1;

        QApplication app(argc, &argv0, QApplication::GuiServer);

        // library path list should contain the default plus the one valid path
        QStringList expected =
            QStringList()
            << QLibraryInfo::location(QLibraryInfo::PluginsPath)
            << QDir(app.applicationDirPath()).canonicalPath()
            << QDir(QDir::fromNativeSeparators(QString::fromLatin1(validPath))).canonicalPath();
#ifdef Q_OS_WINCE
        expected = QSet<QString>::fromList(expected).toList();
#endif
        QVERIFY2(isPathListIncluded(app.libraryPaths(), expected),
                 qPrintable("actual:\n - " + app.libraryPaths().join("\n - ") +
                            "\nexpected:\n - " + expected.join("\n - ")));

        qputenv("QT_PLUGIN_PATH", QByteArray());
    }

    {
        int argc = 1;

        QApplication app(argc, &argv0, QApplication::GuiServer);

        // library paths are initialized by the QApplication, setting
        // the environment variable here doesn't work
        qputenv("QT_PLUGIN_PATH", pluginPath);

        // library path list should contain the default plus the one valid path
        QStringList expected =
            QStringList()
            << QLibraryInfo::location(QLibraryInfo::PluginsPath)
            << app.applicationDirPath();
#ifdef Q_OS_WINCE
        expected = QSet<QString>::fromList(expected).toList();
#endif
        QVERIFY(isPathListIncluded(app.libraryPaths(), expected));

        qputenv("QT_PLUGIN_PATH", QByteArray());
    }
}

class SendPostedEventsTester : public QObject
{
    Q_OBJECT
public:
    QList<int> eventSpy;
    bool event(QEvent *e);
private slots:
    void doTest();
};

bool SendPostedEventsTester::event(QEvent *e)
{
    eventSpy.append(e->type());
    return QObject::event(e);
}

void SendPostedEventsTester::doTest()
{
    QPointer<SendPostedEventsTester> p = this;
    QApplication::postEvent(this, new QEvent(QEvent::User));
    // DeferredDelete should not be delivered until returning from this function
    QApplication::postEvent(this, new QEvent(QEvent::DeferredDelete));

    QEventLoop eventLoop;
    QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
    eventLoop.exec();
    QVERIFY(p != 0);

    QCOMPARE(eventSpy.count(), 2);
    QCOMPARE(eventSpy.at(0), int(QEvent::MetaCall));
    QCOMPARE(eventSpy.at(1), int(QEvent::User));
    eventSpy.clear();
}

void tst_QApplication::sendPostedEvents()
{
    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);
    SendPostedEventsTester *tester = new SendPostedEventsTester;
    QMetaObject::invokeMethod(tester, "doTest", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
    QPointer<SendPostedEventsTester> p = tester;
    (void) app.exec();
    QVERIFY(p == 0);
}

void tst_QApplication::thread()
{
    QThread *currentThread = QThread::currentThread();
    // no app, but still have a valid thread
    QVERIFY(currentThread != 0);

    // the thread should be running and not finished
    QVERIFY(currentThread->isRunning());
    QVERIFY(!currentThread->isFinished());

    // this should probably be in the tst_QObject::thread() test, but
    // we put it here since we want to make sure that objects created
    // *before* the QApplication has a thread
    QObject object;
    QObject child(&object);
    QVERIFY(object.thread() == currentThread);
    QVERIFY(child.thread() == currentThread);

    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);

        // current thread still valid
        QVERIFY(QThread::currentThread() != 0);
        // thread should be the same as before
        QCOMPARE(QThread::currentThread(), currentThread);

        // app's thread should be the current thread
        QCOMPARE(app.thread(), currentThread);

        // the thread should still be running and not finished
        QVERIFY(currentThread->isRunning());
        QVERIFY(!currentThread->isFinished());

        QTestEventLoop::instance().enterLoop(1);
    }

    // app dead, current thread still valid
    QVERIFY(QThread::currentThread() != 0);
    QCOMPARE(QThread::currentThread(), currentThread);

    // the thread should still be running and not finished
    QVERIFY(currentThread->isRunning());
    QVERIFY(!currentThread->isFinished());

    // should still have a thread
    QVERIFY(object.thread() == currentThread);
    QVERIFY(child.thread() == currentThread);

    // do the test again, making sure that the thread is the same as
    // before
    {
        int argc = 0;
        QApplication app(argc, 0, QApplication::GuiServer);

        // current thread still valid
        QVERIFY(QThread::currentThread() != 0);
        // thread should be the same as before
        QCOMPARE(QThread::currentThread(), currentThread);

        // app's thread should be the current thread
        QCOMPARE(app.thread(), currentThread);

        // the thread should be running and not finished
        QVERIFY(currentThread->isRunning());
        QVERIFY(!currentThread->isFinished());

        // should still have a thread
        QVERIFY(object.thread() == currentThread);
        QVERIFY(child.thread() == currentThread);

        QTestEventLoop::instance().enterLoop(1);
    }

    // app dead, current thread still valid
    QVERIFY(QThread::currentThread() != 0);
    QCOMPARE(QThread::currentThread(), currentThread);

    // the thread should still be running and not finished
    QVERIFY(currentThread->isRunning());
    QVERIFY(!currentThread->isFinished());

    // should still have a thread
    QVERIFY(object.thread() == currentThread);
    QVERIFY(child.thread() == currentThread);
}

class DeleteLaterWidget : public QWidget
{
    Q_OBJECT
public:
    DeleteLaterWidget(QApplication *_app, QWidget *parent = 0)
        : QWidget(parent) { app = _app; child_deleted = false; }

    bool child_deleted;
    QApplication *app;

public slots:
    void runTest();
    void checkDeleteLater();
    void childDeleted() { child_deleted = true; }
};


void DeleteLaterWidget::runTest()
{
    QObject *stillAlive = qFindChild<QObject*>(this, "deleteLater");

    QWidget *w = new QWidget(this);
    connect(w, SIGNAL(destroyed()), this, SLOT(childDeleted()));

    w->deleteLater();
    Q_ASSERT(!child_deleted);

    QDialog dlg;
    QTimer::singleShot(500, &dlg, SLOT(reject()));
    dlg.exec();

    Q_ASSERT(!child_deleted);
    app->processEvents();
    Q_ASSERT(!child_deleted);

    QTimer::singleShot(500, this, SLOT(checkDeleteLater()));

    app->processEvents();

    QVERIFY(!stillAlive); // verify at the end to make test terminate
}

void DeleteLaterWidget::checkDeleteLater()
{
    Q_ASSERT(child_deleted);

    close();
}

void tst_QApplication::testDeleteLater()
{
    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);
    connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));

    DeleteLaterWidget *wgt = new DeleteLaterWidget(&app);
    QTimer::singleShot(500, wgt, SLOT(runTest()));

    QObject *object = new QObject(wgt);
    object->setObjectName("deleteLater");
    object->deleteLater();

    QObject *stillAlive = qFindChild<QObject*>(wgt, "deleteLater");
    QVERIFY(stillAlive);

    app.exec();

    delete wgt;

}

class EventLoopNester : public QObject
{
    Q_OBJECT
public slots:
    void deleteLaterAndEnterLoop()
    {
        QEventLoop eventLoop;
        QPointer<QObject> p(this);
        deleteLater();
        /*
          DeferredDelete events are compressed, meaning this second
          deleteLater() will *not* delete the object in the nested
          event loop
        */
        QMetaObject::invokeMethod(this, "deleteLater", Qt::QueuedConnection);
        QTimer::singleShot(1000, &eventLoop, SLOT(quit()));
        eventLoop.exec();
        QVERIFY(p);
    }
    void deleteLaterAndExitLoop()
    {
        QEventLoop eventLoop;
        QPointer<QObject> p(this);
        QMetaObject::invokeMethod(this, "deleteLater", Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p); // not dead yet
    }

    void processEventsOnly()
    {
        QApplication::processEvents();
    }
    void processEventsWithDeferredDeletion()
    {
        QApplication::processEvents(QEventLoop::DeferredDeletion);
    }
    void sendPostedEventsWithDeferredDelete()
    {
        QApplication::sendPostedEvents(0, QEvent::DeferredDelete);
    }
    void deleteLaterAndProcessEvents1()
    {
        QEventLoop eventLoop;

        QPointer<QObject> p = this;
        deleteLater();

        // trying to delete this object in a deeper eventloop just won't work
        QMetaObject::invokeMethod(this,
                                  "processEventsOnly",
                                  Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p);
        QMetaObject::invokeMethod(this,
                                  "processEventsWithDeferredDeletion",
                                  Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p);
        QMetaObject::invokeMethod(this,
                                  "sendPostedEventsWithDeferredDelete",
                                  Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p);

        // trying to delete it from this eventloop still doesn't work
        QApplication::processEvents();
        QVERIFY(p);

        // however, it *will* work with this magic incantation
        QApplication::processEvents(QEventLoop::DeferredDeletion);
        QVERIFY(!p);
    }

    void deleteLaterAndProcessEvents2()
    {
        QEventLoop eventLoop;

        QPointer<QObject> p = this;
        deleteLater();

        // trying to delete this object in a deeper eventloop just won't work
        QMetaObject::invokeMethod(this,
                                  "processEventsOnly",
                                  Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p);
        QMetaObject::invokeMethod(this,
                                  "processEventsWithDeferredDeletion",
                                  Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p);
        QMetaObject::invokeMethod(this,
                                  "sendPostedEventsWithDeferredDelete",
                                  Qt::QueuedConnection);
        QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
        eventLoop.exec();
        QVERIFY(p);

        // trying to delete it from this eventloop still doesn't work
        QApplication::processEvents();
        QVERIFY(p);

        // however, it *will* work with this magic incantation
        QApplication::sendPostedEvents(0, QEvent::DeferredDelete);
        QVERIFY(!p);
    }
};

void tst_QApplication::testDeleteLaterProcessEvents()
{
    int argc = 0;

    // Calling processEvents() with no event dispatcher does nothing.
    QObject *object = new QObject;
    QPointer<QObject> p(object);
    object->deleteLater();
    QApplication::processEvents();
    QVERIFY(p);
    delete object;

    {
        QApplication app(argc, 0, QApplication::GuiServer);
        // If you call processEvents() with an event dispatcher present, but
        // outside any event loops, deferred deletes are not processed unless
        // QEventLoop::DeferredDeletion is passed.
        object = new QObject;
        p = object;
        object->deleteLater();
        app.processEvents();
        QVERIFY(p);
        app.processEvents(QEventLoop::ProcessEventsFlag(0x10)); // 0x10 == QEventLoop::DeferredDeletion
        QVERIFY(!p);

        // sendPostedEvents(0, DeferredDelete); also works
        object = new QObject;
        p = object;
        object->deleteLater();
        app.processEvents();
        QVERIFY(p);
        QApplication::sendPostedEvents(0, QEvent::DeferredDelete);
        QVERIFY(!p);

        // If you call deleteLater() on an object when there is no parent
        // event loop, and then enter an event loop, the object will get
        // deleted.
        object = new QObject;
        p = object;
        object->deleteLater();
        QEventLoop loop;
        QTimer::singleShot(1000, &loop, SLOT(quit()));
        loop.exec();
        QVERIFY(!p);
    }
    {
        // When an object is in an event loop, then calls deleteLater() and enters
        // an event loop recursively, it should not die until the parent event
        // loop continues.
        QApplication app(argc, 0, QApplication::GuiServer);
        QEventLoop loop;
        EventLoopNester *nester = new EventLoopNester;
        p = nester;
        QTimer::singleShot(3000, &loop, SLOT(quit()));
        QTimer::singleShot(0, nester, SLOT(deleteLaterAndEnterLoop()));

        loop.exec();
        QVERIFY(!p);
    }

    {
        // When the event loop that calls deleteLater() is exited
        // immediately, the object should die when returning to the
        // parent event loop
        QApplication app(argc, 0, QApplication::GuiServer);
        QEventLoop loop;
        EventLoopNester *nester = new EventLoopNester;
        p = nester;
        QTimer::singleShot(3000, &loop, SLOT(quit()));
        QTimer::singleShot(0, nester, SLOT(deleteLaterAndExitLoop()));

        loop.exec();
        QVERIFY(!p);
    }

    {
        // when the event loop that calls deleteLater() also calls
        // processEvents() immediately afterwards, the object should
        // not die until the parent loop continues
        QApplication app(argc, 0, QApplication::GuiServer);
        QEventLoop loop;
        EventLoopNester *nester = new EventLoopNester();
        p = nester;
        QTimer::singleShot(3000, &loop, SLOT(quit()));
        QTimer::singleShot(0, nester, SLOT(deleteLaterAndProcessEvents1()));

        loop.exec();
        QVERIFY(!p);
    }

    {
        // when the event loop that calls deleteLater() also calls
        // processEvents() immediately afterwards, the object should
        // not die until the parent loop continues
        QApplication app(argc, 0, QApplication::GuiServer);
        QEventLoop loop;
        EventLoopNester *nester = new EventLoopNester();
        p = nester;
        QTimer::singleShot(3000, &loop, SLOT(quit()));
        QTimer::singleShot(0, nester, SLOT(deleteLaterAndProcessEvents2()));

        loop.exec();
        QVERIFY(!p);
    }
}

/*
    Test for crash whith QApplication::setDesktopSettingsAware(false).
*/
void tst_QApplication::desktopSettingsAware()
{
    QProcess testProcess;
#ifdef Q_OS_WINCE
    int argc = 0;
    QApplication tmpApp(argc, 0, QApplication::GuiServer);
    testProcess.start("desktopsettingsaware/desktopsettingsaware");
#else
#if defined(Q_OS_WIN) && defined(QT_DEBUG)
    testProcess.start("desktopsettingsaware/debug/desktopsettingsaware");
#elif defined(Q_OS_WIN)
    testProcess.start("desktopsettingsaware/release/desktopsettingsaware");
#else
    testProcess.start("desktopsettingsaware/desktopsettingsaware");
#endif
#endif
    QVERIFY(testProcess.waitForFinished(10000));
    QCOMPARE(int(testProcess.state()), int(QProcess::NotRunning));
    QVERIFY(int(testProcess.error()) != int(QProcess::Crashed));
}

void tst_QApplication::setActiveWindow()
{
    int argc = 0;
    QApplication MyApp(argc, 0, QApplication::GuiServer);

    QWidget* w = new QWidget;
    QVBoxLayout* layout = new QVBoxLayout(w);

    QLineEdit* pb1 = new QLineEdit("Testbutton1", w);
    QLineEdit* pb2 = new QLineEdit("Test Line Edit", w);

    layout->addWidget(pb1);
    layout->addWidget(pb2);

    pb2->setFocus();
    pb2->setParent(0);
    delete pb2;

    w->show();
    QApplication::setActiveWindow(w); // needs this on twm (focus follows mouse)
    QVERIFY(pb1->hasFocus());
    delete w;
}


/* This might fail on some X11 window managers? */
void tst_QApplication::focusChanged()
{
    int argc = 0;
    QApplication app(argc, 0, QApplication::GuiServer);

    QSignalSpy spy(&app, SIGNAL(focusChanged(QWidget *, QWidget *)));
    QWidget *now = 0;
    QWidget *old = 0;

    QWidget parent1;
    QHBoxLayout hbox1(&parent1);
    QLabel lb1(&parent1);
    QLineEdit le1(&parent1);
    QPushButton pb1(&parent1);
    hbox1.addWidget(&lb1);
    hbox1.addWidget(&le1);
    hbox1.addWidget(&pb1);

    QCOMPARE(spy.count(), 0);

    parent1.show();
    QApplication::setActiveWindow(&parent1); // needs this on twm (focus follows mouse)
    QCOMPARE(spy.count(), 1);
    QCOMPARE(spy.at(0).count(), 2);
    old = qVariantValue<QWidget*>(spy.at(0).at(0));
    now = qVariantValue<QWidget*>(spy.at(0).at(1));
    QVERIFY(now == &le1);
    QVERIFY(now == QApplication::focusWidget());
    QVERIFY(old == 0);
    spy.clear();
    QCOMPARE(spy.count(), 0);

    pb1.setFocus();
    QCOMPARE(spy.count(), 1);
    old = qVariantValue<QWidget*>(spy.at(0).at(0));
    now = qVariantValue<QWidget*>(spy.at(0).at(1));
    QVERIFY(now == &pb1);
    QVERIFY(now == QApplication::focusWidget());
    QVERIFY(old == &le1);
    spy.clear();

    lb1.setFocus();
    QCOMPARE(spy.count(), 1);
    old = qVariantValue<QWidget*>(spy.at(0).at(0));
    now = qVariantValue<QWidget*>(spy.at(0).at(1));
    QVERIFY(now == &lb1);
    QVERIFY(now == QApplication::focusWidget());
    QVERIFY(old == &pb1);
    spy.clear();

    lb1.clearFocus();
    QCOMPARE(spy.count(), 1);
    old = qVariantValue<QWidget*>(spy.at(0).at(0));
    now = qVariantValue<QWidget*>(spy.at(0).at(1));
    QVERIFY(now == 0);
    QVERIFY(now == QApplication::focusWidget());
    QVERIFY(old == &lb1);
    spy.clear();

    QWidget parent2;
    QHBoxLayout hbox2(&parent2);
    QLabel lb2(&parent2);
    QLineEdit le2(&parent2);
    QPushButton pb2(&parent2);
    hbox2.addWidget(&lb2);
    hbox2.addWidget(&le2);
    hbox2.addWidget(&pb2);

    parent2.show();
    QApplication::setActiveWindow(&parent2); // needs this on twm (focus follows mouse)
    QVERIFY(spy.count() > 0); // one for deactivation, one for activation on Windows
    old = qVariantValue<QWidget*>(spy.at(spy.count()-1).at(0));
    now = qVariantValue<QWidget*>(spy.at(spy.count()-1).at(1));
    QVERIFY(now == &le2);
    QVERIFY(now == QApplication::focusWidget());
    QVERIFY(old == 0);
    spy.clear();

    QTestKeyEvent tab(QTest::Press, Qt::Key_Tab, 0, 0);
    QTestKeyEvent backtab(QTest::Press, Qt::Key_Backtab, 0, 0);
    QTestMouseEvent click(QTest::MouseClick, Qt::LeftButton, 0, QPoint(5, 5), 0);

    bool tabAllControls = true;
#ifdef Q_WS_MAC
    // Mac has two modes, one where you tab to everything, one where you can
    // only tab to input controls, here's what we get. Determine which ones we
    // should get.
    QSettings appleSettings(QLatin1String("apple.com"));
    QVariant appleValue = appleSettings.value(QLatin1String("AppleKeyboardUIMode"), 0);
    tabAllControls = (appleValue.toInt() & 0x2);
#endif

    tab.simulate(now);
    if (!tabAllControls) {
        QVERIFY(spy.count() == 0);
        QVERIFY(now == QApplication::focusWidget());
    } else {
        QVERIFY(spy.count() > 0);
        old = qVariantValue<QWidget*>(spy.at(0).at(0));
        now = qVariantValue<QWidget*>(spy.at(0).at(1));
        QVERIFY(now == &pb2);
        QVERIFY(now == QApplication::focusWidget());
        QVERIFY(old == &le2);
        spy.clear();
    }

    if (!tabAllControls) {
        QVERIFY(spy.count() == 0);
        QVERIFY(now == QApplication::focusWidget());
    } else {
        tab.simulate(now);
        QVERIFY(spy.count() > 0);
        old = qVariantValue<QWidget*>(spy.at(0).at(0));
        now = qVariantValue<QWidget*>(spy.at(0).at(1));
        QVERIFY(now == &le2);
        QVERIFY(now == QApplication::focusWidget());
        QVERIFY(old == &pb2);
        spy.clear();
    }

    if (!tabAllControls) {
        QVERIFY(spy.count() == 0);
        QVERIFY(now == QApplication::focusWidget());
    } else {
        backtab.simulate(now);
        QVERIFY(spy.count() > 0);
        old = qVariantValue<QWidget*>(spy.at(0).at(0));
        now = qVariantValue<QWidget*>(spy.at(0).at(1));
        QVERIFY(now == &pb2);
        QVERIFY(now == QApplication::focusWidget());
        QVERIFY(old == &le2);
        spy.clear();
    }


    if (!tabAllControls) {
        QVERIFY(spy.count() == 0);
        QVERIFY(now == QApplication::focusWidget());
        old = &pb2;
    } else {
        backtab.simulate(now);
        QVERIFY(spy.count() > 0);
        old = qVariantValue<QWidget*>(spy.at(0).at(0));
        now = qVariantValue<QWidget*>(spy.at(0).at(1));
        QVERIFY(now == &le2);
        QVERIFY(now == QApplication::focusWidget());
        QVERIFY(old == &pb2);
        spy.clear();
    }

    click.simulate(old);
    if (!(pb2.focusPolicy() & Qt::ClickFocus)) {
        QVERIFY(spy.count() == 0);
        QVERIFY(now == QApplication::focusWidget());
    } else {
        QVERIFY(spy.count() > 0);
        old = qVariantValue<QWidget*>(spy.at(0).at(0));
        now = qVariantValue<QWidget*>(spy.at(0).at(1));
        QVERIFY(now == &pb2);
        QVERIFY(now == QApplication::focusWidget());
        QVERIFY(old == &le2);
        spy.clear();

        click.simulate(old);
        QVERIFY(spy.count() > 0);
        old = qVariantValue<QWidget*>(spy.at(0).at(0));
        now = qVariantValue<QWidget*>(spy.at(0).at(1));
        QVERIFY(now == &le2);
        QVERIFY(now == QApplication::focusWidget());
        QVERIFY(old == &pb2);
        spy.clear();
    }

    parent1.activateWindow();
    QApplication::setActiveWindow(&parent1); // needs this on twm (focus follows mouse)
    QVERIFY(spy.count() == 1 || spy.count() == 2); // one for deactivation, one for activation on Windows

    //on windows, the change of focus is made in 2 steps
    //(the focusChanged SIGNAL is emitted twice)
    if (spy.count()==1)
        old = qVariantValue<QWidget*>(spy.at(spy.count()-1).at(0));
    else
        old = qVariantValue<QWidget*>(spy.at(spy.count()-2).at(0));
    now = qVariantValue<QWidget*>(spy.at(spy.count()-1).at(1));
    QVERIFY(now == &le1);
    QVERIFY(now == QApplication::focusWidget());
    QVERIFY(old == &le2);
    spy.clear();
}

class LineEdit : public QLineEdit
{
public:
    LineEdit(QWidget *parent = 0) : QLineEdit(parent) { }

protected:
    void focusOutEvent(QFocusEvent *e) {
        QLineEdit::focusOutEvent(e);
        if (objectName() == "le1")
            setStyleSheet("");
    }

    void focusInEvent(QFocusEvent *e) {
        QLineEdit::focusInEvent(e);
        if (objectName() == "le2")
            setStyleSheet("");
    }
};

void tst_QApplication::focusOut()
{
    int argc = 1;
    QApplication app(argc, &argv0, QApplication::GuiServer);

    // Tests the case where the style pointer changes when on focus in/out
    // (the above is the case when the stylesheet changes)
    QWidget w;
    QLineEdit *le1 = new LineEdit(&w);
    le1->setObjectName("le1");
    le1->setStyleSheet("background: #fee");
    le1->setFocus();

    QLineEdit *le2 = new LineEdit(&w);
    le2->setObjectName("le2");
    le2->setStyleSheet("background: #fee");
    le2->move(100, 100);
    w.show();

    QTest::qWait(2000);
    le2->setFocus();
    QTest::qWait(2000);
}

void tst_QApplication::execAfterExit()
{
    int argc = 1;
    QApplication app(argc, &argv0, QApplication::GuiServer);
    QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
    // this should be ignored, as exec() will reset the exitCode
    QApplication::exit(1);
    int exitCode = app.exec();
    QCOMPARE(exitCode, 0);

    // the quitNow flag should have been reset, so we can spin an
    // eventloop after QApplication::exec() returns
    QEventLoop eventLoop;
    QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection);
    exitCode = eventLoop.exec();
    QCOMPARE(exitCode, 0);
}

void tst_QApplication::wheelScrollLines()
{
    int argc = 1;
    QApplication app(argc, &argv0, QApplication::GuiServer);
    // If wheelScrollLines returns 0, the mose wheel will be disabled.
    QVERIFY(app.wheelScrollLines() > 0);
}

void tst_QApplication::style()
{
    int argc = 1;

    {
        QApplication app(argc, &argv0, QApplication::GuiServer);
        QPointer<QStyle> style = app.style();
        app.setStyle(new QWindowsStyle);
        QVERIFY(style.isNull());
    }

    QApplication app(argc, &argv0, QApplication::GuiServer);

    // qApp style can never be 0
    QVERIFY(QApplication::style() != 0);
}

void tst_QApplication::allWidgets()
{
    int argc = 1;
    QApplication app(argc, &argv0, QApplication::GuiServer);
    QWidget *w = new QWidget;
    QVERIFY(app.allWidgets().contains(w)); // uncreate widget test
    QVERIFY(app.allWidgets().contains(w)); // created widget test
    delete w;
    w = 0;
    QVERIFY(!app.allWidgets().contains(w)); // removal test
}


void tst_QApplication::setAttribute()
{
    int argc = 1;
    QApplication app(argc, &argv0, QApplication::GuiServer);
    QVERIFY(!QApplication::testAttribute(Qt::AA_ImmediateWidgetCreation));
    QWidget  *w = new QWidget;
    QVERIFY(!w->testAttribute(Qt::WA_WState_Created));
    delete w;

    QApplication::setAttribute(Qt::AA_ImmediateWidgetCreation);
    QVERIFY(QApplication::testAttribute(Qt::AA_ImmediateWidgetCreation));
    w = new QWidget;
    QVERIFY(w->testAttribute(Qt::WA_WState_Created));
    QWidget *w2 = new QWidget(w);
    w2->setParent(0);
    QVERIFY(w2->testAttribute(Qt::WA_WState_Created));
    delete w;
    delete w2;

    QApplication::setAttribute(Qt::AA_ImmediateWidgetCreation, false);
    QVERIFY(!QApplication::testAttribute(Qt::AA_ImmediateWidgetCreation));
    w = new QWidget;
    QVERIFY(!w->testAttribute(Qt::WA_WState_Created));
    delete w;
}

void tst_QApplication::windowsCommandLine_data()
{
#if defined(Q_OS_WIN)
    QTest::addColumn<QString>("args");
    QTest::addColumn<QString>("expected");

    QTest::newRow("hello world")
        << QString("Hello \"World\"")
        << QString("Hello \"World\"");
    QTest::newRow("sql")
        << QString("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PNR' AND TABLE_TYPE = 'VIEW' ORDER BY TABLE_NAME")
        << QString("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PNR' AND TABLE_TYPE = 'VIEW' ORDER BY TABLE_NAME");
#endif
}

void tst_QApplication::windowsCommandLine()
{
#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
    QFETCH(QString, args);
    QFETCH(QString, expected);

    QProcess testProcess;
#if defined(QT_DEBUG)
    testProcess.start("wincmdline/debug/wincmdline", QStringList(args));
#else
    testProcess.start("wincmdline/release/wincmdline", QStringList(args));
#endif
    QVERIFY(testProcess.waitForFinished(10000));
    QByteArray error = testProcess.readAllStandardError();
    QString procError(error);
    QCOMPARE(procError, expected);
#endif
}

//QTEST_APPLESS_MAIN(tst_QApplication)
int main(int argc, char *argv[])
{
    tst_QApplication tc;
    argv0 = argv[0];
    return QTest::qExec(&tc, argc, argv);
}

#include "tst_qapplication.moc"