summaryrefslogtreecommitdiff
path: root/Tools/DumpRenderTree/qt/DumpRenderTreeQt.cpp
blob: db09ad713f89fe575bbcbb97b833bdb0fab7bb4e (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
/*
 * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
 * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "DumpRenderTree.h"

#include "DumpRenderTreeQt.h"
#include "DumpRenderTreeSupportQt.h"
#include "EventSenderQt.h"
#include "GCControllerQt.h"
#include "TestRunnerQt.h"
#include "TextInputControllerQt.h"
#include "QtInitializeTestFonts.h"
#include "testplugin.h"
#include "WorkQueue.h"

#include <QApplication>
#include <QBuffer>
#include <QCryptographicHash>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFocusEvent>
#include <QFontDatabase>
#include <QLabel>
#include <QLocale>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPaintDevice>
#include <QPaintEngine>
#if !defined(QT_NO_PRINTER) && HAVE(QTPRINTSUPPORT)
#include <QPrinter>
#endif
#include <QProgressBar>
#include <QUndoStack>
#include <QUrl>

#include <qwebsettings.h>
#include <qwebsecurityorigin.h>

#include <limits.h>
#include <locale.h>

#ifndef Q_OS_WIN
#include <unistd.h>
#endif

#include <qdebug.h>

namespace WebCore {

const int databaseDefaultQuota = 5 * 1024 * 1024;

NetworkAccessManager::NetworkAccessManager(QObject* parent)
    : QNetworkAccessManager(parent)
{
#ifndef QT_NO_OPENSSL
    connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),
            this, SLOT(sslErrorsEncountered(QNetworkReply*, const QList<QSslError>&)));
#endif
}

#ifndef QT_NO_OPENSSL
void NetworkAccessManager::sslErrorsEncountered(QNetworkReply* reply, const QList<QSslError>& errors)
{
    if (reply->url().host() == "127.0.0.1" || reply->url().host() == "localhost") {
        bool ignore = true;

        // Accept any HTTPS certificate.
        foreach (const QSslError& error, errors) {
            if (error.error() < QSslError::UnableToGetIssuerCertificate || error.error() > QSslError::HostNameMismatch) {
                ignore = false;
                break;
            }
        }

        if (ignore)
            reply->ignoreSslErrors();
    }
}
#endif


#if !defined(QT_NO_PRINTER) && HAVE(QTPRINTSUPPORT)
class NullPrinter : public QPrinter {
public:
    class NullPaintEngine : public QPaintEngine {
    public:
        virtual bool begin(QPaintDevice*) { return true; }
        virtual bool end() { return true; }
        virtual QPaintEngine::Type type() const { return QPaintEngine::User; }
        virtual void drawPixmap(const QRectF& r, const QPixmap& pm, const QRectF& sr) { }
        virtual void updateState(const QPaintEngineState& state) { }
    };

    virtual QPaintEngine* paintEngine() const { return const_cast<NullPaintEngine*>(&m_engine); }

    NullPaintEngine m_engine;
};
#endif

WebPage::WebPage(QObject* parent, DumpRenderTree* drt)
    : QWebPage(parent)
    , m_webInspector(0)
    , m_drt(drt)
{
    QWebSettings* globalSettings = QWebSettings::globalSettings();

    globalSettings->setFontSize(QWebSettings::MinimumFontSize, 0);
    globalSettings->setFontSize(QWebSettings::MinimumLogicalFontSize, 5);
    globalSettings->setFontSize(QWebSettings::DefaultFontSize, 16);
    globalSettings->setFontSize(QWebSettings::DefaultFixedFontSize, 13);

    globalSettings->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
    globalSettings->setAttribute(QWebSettings::JavascriptCanAccessClipboard, true);
    globalSettings->setAttribute(QWebSettings::LinksIncludedInFocusChain, false);
    globalSettings->setAttribute(QWebSettings::PluginsEnabled, true);
    globalSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
    globalSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
    globalSettings->setAttribute(QWebSettings::PrivateBrowsingEnabled, false);
    globalSettings->setAttribute(QWebSettings::SpatialNavigationEnabled, false);

    connect(this, SIGNAL(geometryChangeRequested(const QRect &)),
            this, SLOT(setViewGeometry(const QRect & )));

    setNetworkAccessManager(m_drt->networkAccessManager());
    setPluginFactory(new TestPlugin(this));

    connect(this, SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)), this, SLOT(requestPermission(QWebFrame*, QWebPage::Feature)));
    connect(this, SIGNAL(featurePermissionRequestCanceled(QWebFrame*, QWebPage::Feature)), this, SLOT(cancelPermission(QWebFrame*, QWebPage::Feature)));
}

WebPage::~WebPage()
{
    delete m_webInspector;
}

QWebInspector* WebPage::webInspector()
{
    if (!m_webInspector) {
        m_webInspector = new QWebInspector;
        m_webInspector->setPage(this);
    }
    return m_webInspector;
}

void WebPage::resetSettings()
{
    // After each layout test, reset the settings that may have been changed by
    // testRunner.overridePreference() or similar.
    settings()->resetFontSize(QWebSettings::DefaultFontSize);
    settings()->resetAttribute(QWebSettings::JavascriptCanOpenWindows);
    settings()->resetAttribute(QWebSettings::JavascriptEnabled);
    settings()->resetAttribute(QWebSettings::PrivateBrowsingEnabled);
    settings()->resetAttribute(QWebSettings::SpatialNavigationEnabled);
    settings()->resetAttribute(QWebSettings::LinksIncludedInFocusChain);
    settings()->resetAttribute(QWebSettings::OfflineWebApplicationCacheEnabled);
    settings()->resetAttribute(QWebSettings::LocalContentCanAccessRemoteUrls);
    settings()->resetAttribute(QWebSettings::LocalContentCanAccessFileUrls);
    settings()->resetAttribute(QWebSettings::PluginsEnabled);
    settings()->resetAttribute(QWebSettings::JavascriptCanAccessClipboard);
    settings()->resetAttribute(QWebSettings::AutoLoadImages);
    settings()->resetAttribute(QWebSettings::ZoomTextOnly);
    settings()->resetAttribute(QWebSettings::CSSRegionsEnabled);
    settings()->resetAttribute(QWebSettings::CSSGridLayoutEnabled);
    settings()->resetAttribute(QWebSettings::AcceleratedCompositingEnabled);

    m_drt->testRunner()->setCaretBrowsingEnabled(false);
    m_drt->testRunner()->setAuthorAndUserStylesEnabled(true);
    m_drt->testRunner()->setFrameFlatteningEnabled(false);
    m_drt->testRunner()->setMockScrollbarsEnabled(false);
    m_drt->testRunner()->setSmartInsertDeleteEnabled(true);
    m_drt->testRunner()->setSelectTrailingWhitespaceEnabled(false);
    m_drt->testRunner()->setDefersLoading(false);

    // globalSettings must be reset explicitly.
    m_drt->testRunner()->setXSSAuditorEnabled(false);

    QWebSettings::setMaximumPagesInCache(0); // reset to default
    settings()->setUserStyleSheetUrl(QUrl()); // reset to default

    DumpRenderTreeSupportQt::setMinimumTimerInterval(this, DumpRenderTreeSupportQt::defaultMinimumTimerInterval());

    DumpRenderTreeSupportQt::resetInternalsObject(mainFrame());

    m_pendingGeolocationRequests.clear();
}

QWebPage *WebPage::createWindow(QWebPage::WebWindowType)
{
    return m_drt->createWindow();
}

void WebPage::javaScriptAlert(QWebFrame*, const QString& message)
{
    if (!isTextOutputEnabled())
        return;

    fprintf(stdout, "ALERT: %s\n", message.toUtf8().constData());
}

void WebPage::requestPermission(QWebFrame* frame, QWebPage::Feature feature)
{
    switch (feature) {
    case Notifications:
        if (!m_drt->testRunner()->ignoreReqestForPermission())
            setFeaturePermission(frame, feature, PermissionGrantedByUser);
        break;
    case Geolocation:
        if (m_drt->testRunner()->isGeolocationPermissionSet())
            if (m_drt->testRunner()->geolocationPermission())
                setFeaturePermission(frame, feature, PermissionGrantedByUser);
            else
                setFeaturePermission(frame, feature, PermissionDeniedByUser);
        else
            m_pendingGeolocationRequests.append(frame);
        break;
    default:
        break;
    }
}

void WebPage::cancelPermission(QWebFrame* frame, QWebPage::Feature feature)
{
    switch (feature) {
    case Geolocation:
        m_pendingGeolocationRequests.removeOne(frame);
        break;
    default:
        break;
    }
}

void WebPage::permissionSet(QWebPage::Feature feature)
{
    switch (feature) {
    case Geolocation:
        {
        Q_ASSERT(m_drt->testRunner()->isGeolocationPermissionSet());
        foreach (QWebFrame* frame, m_pendingGeolocationRequests)
            if (m_drt->testRunner()->geolocationPermission())
                setFeaturePermission(frame, feature, PermissionGrantedByUser);
            else
                setFeaturePermission(frame, feature, PermissionDeniedByUser);

        m_pendingGeolocationRequests.clear();
        break;
        }
    default:
        break;
    }
}

static QString urlSuitableForTestResult(const QString& url)
{
    if (url.isEmpty() || !url.startsWith(QLatin1String("file://")))
        return url;

    return QFileInfo(url).fileName();
}

void WebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString&)
{
    if (!isTextOutputEnabled())
        return;

    QString newMessage;
    if (!message.isEmpty()) {
        newMessage = message;

        size_t fileProtocol = newMessage.indexOf(QLatin1String("file://"));
        if (fileProtocol != -1) {
            newMessage = newMessage.left(fileProtocol) + urlSuitableForTestResult(newMessage.mid(fileProtocol));
        }
    }

    fprintf(stdout, "CONSOLE MESSAGE: ");
    if (lineNumber)
        fprintf(stdout, "line %d: ", lineNumber);
    fprintf(stdout, "%s\n", newMessage.toUtf8().constData());
}

bool WebPage::javaScriptConfirm(QWebFrame*, const QString& msg)
{
    if (!isTextOutputEnabled())
        return true;

    fprintf(stdout, "CONFIRM: %s\n", msg.toUtf8().constData());
    return true;
}

bool WebPage::javaScriptPrompt(QWebFrame*, const QString& msg, const QString& defaultValue, QString* result)
{
    if (!isTextOutputEnabled())
        return true;

    fprintf(stdout, "PROMPT: %s, default text: %s\n", msg.toUtf8().constData(), defaultValue.toUtf8().constData());
    *result = defaultValue;
    return true;
}

bool WebPage::acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest& request, NavigationType type)
{
    if (m_drt->testRunner()->waitForPolicy())
        m_drt->testRunner()->notifyDone();

    return QWebPage::acceptNavigationRequest(frame, request, type);
}

bool WebPage::supportsExtension(QWebPage::Extension extension) const
{
    if (extension == QWebPage::ErrorPageExtension)
        return m_drt->testRunner()->shouldHandleErrorPages();

    return false;
}

bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output)
{
    const QWebPage::ErrorPageExtensionOption* info = static_cast<const QWebPage::ErrorPageExtensionOption*>(option);

    // Lets handle error pages for the main frame for now.
    if (info->frame != mainFrame())
        return false;

    QWebPage::ErrorPageExtensionReturn* errorPage = static_cast<QWebPage::ErrorPageExtensionReturn*>(output);

    errorPage->content = QString("data:text/html,<body/>").toUtf8();

    return true;
}

QObject* WebPage::createPlugin(const QString& classId, const QUrl& url, const QStringList& paramNames, const QStringList& paramValues)
{
    Q_UNUSED(url);
    Q_UNUSED(paramNames);
    Q_UNUSED(paramValues);

    if (classId == QLatin1String("QProgressBar"))
        return new QProgressBar(view());
    if (classId == QLatin1String("QLabel"))
        return new QLabel(view());

    return 0;
}

void WebPage::setViewGeometry(const QRect& rect)
{
    if (WebViewGraphicsBased* v = qobject_cast<WebViewGraphicsBased*>(view()))
        v->scene()->setSceneRect(QRectF(rect));
    else if (QWidget *v = view())
        v->setGeometry(rect);
}

WebViewGraphicsBased::WebViewGraphicsBased(QWidget* parent)
    : m_item(new QGraphicsWebView)
{
    setScene(new QGraphicsScene(this));
    scene()->addItem(m_item);
}

DumpRenderTree::DumpRenderTree()
    : m_stdin(0)
    , m_enableTextOutput(false)
    , m_standAloneMode(false)
    , m_graphicsBased(false)
    , m_persistentStoragePath(QString(getenv("DUMPRENDERTREE_TEMP")))
{
    QByteArray viewMode = getenv("QT_DRT_WEBVIEW_MODE");
    if (viewMode == "graphics")
        setGraphicsBased(true);

    DumpRenderTreeSupportQt::initialize();

    // Set running in DRT mode for qwebpage to create testable objects.
    DumpRenderTreeSupportQt::setDumpRenderTreeModeEnabled(true);
    DumpRenderTreeSupportQt::overwritePluginDirectories();
    QWebSettings::enablePersistentStorage(m_persistentStoragePath);

    m_networkAccessManager = new NetworkAccessManager(this);
    // create our primary testing page/view.
    if (isGraphicsBased()) {
        WebViewGraphicsBased* view = new WebViewGraphicsBased(0);
        m_page = new WebPage(view, this);
        view->setPage(m_page);
        m_mainView = view;
    } else {
        QWebView* view = new QWebView(0);
        m_page = new WebPage(view, this);
        view->setPage(m_page);
        m_mainView = view;
    }
    // Use a frame group name for all pages created by DumpRenderTree to allow
    // testing of cross-page frame lookup.
    DumpRenderTreeSupportQt::webPageSetGroupName(m_page, "org.webkit.qt.DumpRenderTree");

    m_mainView->setContextMenuPolicy(Qt::NoContextMenu);
    m_mainView->resize(QSize(TestRunner::maxViewWidth, TestRunner::maxViewHeight));

    // clean up cache by resetting quota.
    qint64 quota = webPage()->settings()->offlineWebApplicationCacheQuota();
    webPage()->settings()->setOfflineWebApplicationCacheQuota(quota);

    // create our controllers. This has to be done before connectFrame,
    // as it exports there to the JavaScript DOM window.
    m_controller = new TestRunner(this);
    connect(m_controller, SIGNAL(showPage()), this, SLOT(showPage()));
    connect(m_controller, SIGNAL(hidePage()), this, SLOT(hidePage()));

    // async geolocation permission set by controller
    connect(m_controller, SIGNAL(geolocationPermissionSet()), this, SLOT(geolocationPermissionSet()));

    connect(m_controller, SIGNAL(done()), this, SLOT(dump()));
    m_eventSender = new EventSender(m_page);
    m_textInputController = new TextInputController(m_page);
    m_gcController = new GCController(m_page);

    // now connect our different signals
    connect(m_page, SIGNAL(frameCreated(QWebFrame *)),
            this, SLOT(connectFrame(QWebFrame *)));
    connectFrame(m_page->mainFrame());

    connect(m_page, SIGNAL(loadFinished(bool)),
            m_controller, SLOT(maybeDump(bool)));
    // We need to connect to loadStarted() because notifyDone should only
    // dump results itself when the last page loaded in the test has finished loading.
    connect(m_page, SIGNAL(loadStarted()),
            m_controller, SLOT(resetLoadFinished()));
    connect(m_page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
    connect(m_page, SIGNAL(printRequested(QWebFrame*)), this, SLOT(dryRunPrint(QWebFrame*)));

    connect(m_page->mainFrame(), SIGNAL(titleChanged(const QString&)),
            SLOT(titleChanged(const QString&)));
    connect(m_page, SIGNAL(databaseQuotaExceeded(QWebFrame*,QString)),
            this, SLOT(dumpDatabaseQuota(QWebFrame*,QString)));
    connect(m_page, SIGNAL(applicationCacheQuotaExceeded(QWebSecurityOrigin *, quint64, quint64)),
            this, SLOT(dumpApplicationCacheQuota(QWebSecurityOrigin *, quint64, quint64)));
    connect(m_page, SIGNAL(statusBarMessage(const QString&)),
            this, SLOT(statusBarMessage(const QString&)));

    QObject::connect(this, SIGNAL(quit()), qApp, SLOT(quit()), Qt::QueuedConnection);

    DumpRenderTreeSupportQt::setDumpRenderTreeModeEnabled(true);
    DumpRenderTreeSupportQt::setInteractiveFormValidationEnabled(webPage(), true);
    QFocusEvent event(QEvent::FocusIn, Qt::ActiveWindowFocusReason);
    QApplication::sendEvent(m_mainView, &event);
}

DumpRenderTree::~DumpRenderTree()
{
    if (!m_redirectOutputFileName.isEmpty())
        fclose(stdout);
    if (!m_redirectErrorFileName.isEmpty())
        fclose(stderr);
    delete m_mainView;
    delete m_stdin;
}

static void clearHistory(QWebPage* page)
{
    // QWebHistory::clear() leaves current page, so remove it as well by setting
    // max item count to 0, and then setting it back to it's original value.

    QWebHistory* history = page->history();
    int itemCount = history->maximumItemCount();

    history->clear();
    history->setMaximumItemCount(0);
    history->setMaximumItemCount(itemCount);
}

void DumpRenderTree::dryRunPrint(QWebFrame* frame)
{
#if !defined(QT_NO_PRINTER) && HAVE(QTPRINTSUPPORT)
    NullPrinter printer;
    frame->print(&printer);
#endif
}

void DumpRenderTree::resetToConsistentStateBeforeTesting(const QUrl& url)
{
    // reset so that any current loads are stopped
    // NOTE: that this has to be done before the testRunner is
    // reset or we get timeouts for some tests.
    m_page->blockSignals(true);
    m_page->triggerAction(QWebPage::Stop);
    m_page->blockSignals(false);

    QList<QWebSecurityOrigin> knownOrigins = QWebSecurityOrigin::allOrigins();
    for (int i = 0; i < knownOrigins.size(); ++i)
        knownOrigins[i].setDatabaseQuota(databaseDefaultQuota);

    // reset the testRunner at this point, so that we under no
    // circumstance dump (stop the waitUntilDone timer) during the reset
    // of the DRT.
    m_controller->reset();

    // reset mouse clicks counter
    m_eventSender->resetClickCount();

    closeRemainingWindows();
    
    // Call setTextSizeMultiplier(1.0) to reset TextZoomFactor and PageZoomFactor too. 
    // It should be done before resetSettings() to guarantee resetting QWebSettings::ZoomTextOnly correctly.
    m_page->mainFrame()->setTextSizeMultiplier(1.0);

    m_page->resetSettings();
#ifndef QT_NO_UNDOSTACK
    m_page->undoStack()->clear();
#endif

    clearHistory(m_page);
    DumpRenderTreeSupportQt::scalePageBy(m_page->mainFrame(), 1, QPoint(0, 0));
    DumpRenderTreeSupportQt::clearFrameName(m_page->mainFrame());
    DumpRenderTreeSupportQt::removeUserStyleSheets(m_page);

    m_page->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded);
    m_page->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded);

    if (url.scheme() == "http" || url.scheme() == "https") {
        // credentials may exist from previous tests.
        m_page->setNetworkAccessManager(0);
        delete m_networkAccessManager;
        m_networkAccessManager = new NetworkAccessManager(this);
        m_page->setNetworkAccessManager(m_networkAccessManager);
    }

    WorkQueue::shared()->clear();
    WorkQueue::shared()->setFrozen(false);

    DumpRenderTreeSupportQt::resetOriginAccessWhiteLists();

    DumpRenderTreeSupportQt::setWindowsBehaviorAsEditingBehavior(m_page);

    QLocale::setDefault(QLocale::c());

    testRunner()->setDeveloperExtrasEnabled(true);
#ifndef Q_OS_WINCE
    setlocale(LC_ALL, "");
#endif

    DumpRenderTreeSupportQt::clearOpener(m_page->mainFrame());
}

static bool isGlobalHistoryTest(const QUrl& url)
{
    if (url.path().contains("globalhistory/"))
        return true;
    return false;
}

static bool isWebInspectorTest(const QUrl& url)
{
    if (url.path().contains("inspector/"))
        return true;
    return false;
}

static bool isDumpAsTextTest(const QUrl& url)
{
    if (url.path().contains("dumpAsText/"))
        return true;
    return false;
}


void DumpRenderTree::open(const QUrl& url)
{
    DumpRenderTreeSupportQt::dumpResourceLoadCallbacksPath(QFileInfo(url.toString()).path());
    resetToConsistentStateBeforeTesting(url);

    if (isWebInspectorTest(m_page->mainFrame()->url()))
        testRunner()->closeWebInspector();

    if (isWebInspectorTest(url))
        testRunner()->showWebInspector();

    if (isDumpAsTextTest(url))
        testRunner()->dumpAsText();

    if (isGlobalHistoryTest(url))
        testRunner()->dumpHistoryCallbacks();

    // W3C SVG tests expect to be 480x360
    bool isW3CTest = url.toString().contains("svg/W3C-SVG-1.1");
    int width = isW3CTest ? 480 : TestRunner::maxViewWidth;
    int height = isW3CTest ? 360 : TestRunner::maxViewHeight;
    m_mainView->resize(QSize(width, height));
    m_page->setPreferredContentsSize(QSize());
    m_page->setViewportSize(QSize(width, height));

    QFocusEvent ev(QEvent::FocusIn);
    m_page->event(&ev);

    QWebSettings::clearMemoryCaches();
    QFontDatabase::removeAllApplicationFonts();
    WebKit::initializeTestFonts();

    DumpRenderTreeSupportQt::dumpFrameLoader(url.toString().contains("loading/"));
    setTextOutputEnabled(true);
    m_page->mainFrame()->load(url);
}

void DumpRenderTree::readLine()
{
    if (!m_stdin) {
        m_stdin = new QFile;
        m_stdin->open(stdin, QFile::ReadOnly);

        if (!m_stdin->isReadable()) {
            emit quit();
            return;
        }
    }

    QByteArray line = m_stdin->readLine().trimmed();

    if (line.isEmpty()) {
        emit quit();
        return;
    }

    processLine(QString::fromLocal8Bit(line.constData(), line.length()));
}

void DumpRenderTree::processArgsLine(const QStringList &args)
{
    setStandAloneMode(true);

    m_standAloneModeTestList = args;

    QFileInfo firstEntry(m_standAloneModeTestList.first());
    if (firstEntry.isDir()) {
        QDir folderEntry(m_standAloneModeTestList.first());
        QStringList supportedExt;
        // Check for all supported extensions (from Scripts/webkitpy/layout_tests/layout_package/test_files.py).
        supportedExt << "*.html" << "*.shtml" << "*.xml" << "*.xhtml" << "*.xhtmlmp" << "*.pl" << "*.php" << "*.svg";
        m_standAloneModeTestList = folderEntry.entryList(supportedExt, QDir::Files);
        for (int i = 0; i < m_standAloneModeTestList.size(); ++i)
            m_standAloneModeTestList[i] = folderEntry.absoluteFilePath(m_standAloneModeTestList[i]);
    }
    connect(this, SIGNAL(ready()), this, SLOT(loadNextTestInStandAloneMode()), Qt::QueuedConnection);

    if (!m_standAloneModeTestList.isEmpty()) {
        QString first = m_standAloneModeTestList.takeFirst();
        processLine(first);
    }
}

void DumpRenderTree::loadNextTestInStandAloneMode()
{
    if (m_standAloneModeTestList.isEmpty()) {
        emit quit();
        return;
    }
    QString first = m_standAloneModeTestList.takeFirst();
    processLine(first);
}

void DumpRenderTree::processLine(const QString &input)
{
    TestCommand command = parseInputLine(std::string(input.toLatin1().constData()));
    QString pathOrURL = QLatin1String(command.pathOrURL.c_str());
    m_dumpPixelsForCurrentTest = command.shouldDumpPixels;
    m_expectedHash = QLatin1String(command.expectedPixelHash.c_str());

    if (pathOrURL.startsWith(QLatin1String("http:"))
            || pathOrURL.startsWith(QLatin1String("https:"))
            || pathOrURL.startsWith(QLatin1String("file:"))
            || pathOrURL == QLatin1String("about:blank")) {
        open(QUrl(pathOrURL));
    } else {
        QFileInfo fi(pathOrURL);

        if (!fi.exists()) {
            QDir currentDir = QDir::currentPath();

            // Try to be smart about where the test is located
            if (currentDir.dirName() == QLatin1String("LayoutTests"))
                fi = QFileInfo(currentDir, pathOrURL.replace(QRegExp(".*?LayoutTests/(.*)"), "\\1"));
            else if (!pathOrURL.contains(QLatin1String("LayoutTests")))
                fi = QFileInfo(currentDir, pathOrURL.prepend(QLatin1String("LayoutTests/")));

            if (!fi.exists()) {
                emit ready();
                return;
            }
        }

        open(QUrl::fromLocalFile(fi.absoluteFilePath()));
    }

    fflush(stdout);
}

void DumpRenderTree::closeRemainingWindows()
{
    foreach (QObject* widget, windows)
        delete widget;
    windows.clear();
}

void DumpRenderTree::initJSObjects()
{
    QWebFrame *frame = qobject_cast<QWebFrame*>(sender());
    Q_ASSERT(frame);
    frame->addToJavaScriptWindowObject(QLatin1String("testRunner"), m_controller);
    frame->addToJavaScriptWindowObject(QLatin1String("eventSender"), m_eventSender);
    frame->addToJavaScriptWindowObject(QLatin1String("textInputController"), m_textInputController);
    frame->addToJavaScriptWindowObject(QLatin1String("GCController"), m_gcController);
    DumpRenderTreeSupportQt::injectInternalsObject(frame);
}

void DumpRenderTree::showPage()
{
    m_mainView->show();
    // we need a paint event but cannot process all the events
    QPixmap pixmap(m_mainView->size());
    m_mainView->render(&pixmap);
}

void DumpRenderTree::hidePage()
{
    m_mainView->hide();
}

QString DumpRenderTree::dumpFrameScrollPosition(QWebFrame* frame)
{
    if (!frame || !DumpRenderTreeSupportQt::hasDocumentElement(frame))
        return QString();

    QString result;
    QPoint pos = frame->scrollPosition();
    if (pos.x() > 0 || pos.y() > 0) {
        QWebFrame* parent = qobject_cast<QWebFrame *>(frame->parent());
        if (parent)
            result.append(QString("frame '%1' ").arg(frame->title()));
        result.append(QString("scrolled to %1,%2\n").arg(pos.x()).arg(pos.y()));
    }

    if (m_controller->shouldDumpChildFrameScrollPositions()) {
        QList<QWebFrame*> children = frame->childFrames();
        for (int i = 0; i < children.size(); ++i)
            result += dumpFrameScrollPosition(children.at(i));
    }
    return result;
}

QString DumpRenderTree::dumpFramesAsText(QWebFrame* frame)
{
    if (!frame || !DumpRenderTreeSupportQt::hasDocumentElement(frame))
        return QString();

    QString result;
    QWebFrame* parent = qobject_cast<QWebFrame*>(frame->parent());
    if (parent) {
        result.append(QLatin1String("\n--------\nFrame: '"));
        result.append(frame->frameName());
        result.append(QLatin1String("'\n--------\n"));
    }

    QString innerText = frame->toPlainText();
    result.append(innerText);
    result.append(QLatin1String("\n"));

    if (m_controller->shouldDumpChildrenAsText()) {
        QList<QWebFrame *> children = frame->childFrames();
        for (int i = 0; i < children.size(); ++i)
            result += dumpFramesAsText(children.at(i));
    }

    return result;
}

static QString dumpHistoryItem(const QWebHistoryItem& item, int indent, bool current)
{
    QString result;

    int start = 0;
    if (current) {
        result.append(QLatin1String("curr->"));
        start = 6;
    }
    for (int i = start; i < indent; i++)
        result.append(' ');

    QString url = item.url().toString();
    if (url.contains("file://")) {
        static QString layoutTestsString("/LayoutTests/");
        static QString fileTestString("(file test):");

        QString res = url.mid(url.indexOf(layoutTestsString) + layoutTestsString.length());
        if (res.isEmpty())
            return result;

        result.append(fileTestString);
        result.append(res);
    } else {
        result.append(url);
    }

    QString target = DumpRenderTreeSupportQt::historyItemTarget(item);
    if (!target.isEmpty())
        result.append(QString(QLatin1String(" (in frame \"%1\")")).arg(target));

    if (DumpRenderTreeSupportQt::isTargetItem(item))
        result.append(QLatin1String("  **nav target**"));
    result.append(QLatin1String("\n"));

    QMap<QString, QWebHistoryItem> children = DumpRenderTreeSupportQt::getChildHistoryItems(item);
    foreach (QWebHistoryItem item, children)
        result += dumpHistoryItem(item, 12, false);

    return result;
}

QString DumpRenderTree::dumpBackForwardList(QWebPage* page)
{
    QWebHistory* history = page->history();

    QString result;
    result.append(QLatin1String("\n============== Back Forward List ==============\n"));

    // FORMAT:
    // "        (file test):fast/loader/resources/click-fragment-link.html  **nav target**"
    // "curr->  (file test):fast/loader/resources/click-fragment-link.html#testfragment  **nav target**"

    int maxItems = history->maximumItemCount();

    foreach (const QWebHistoryItem item, history->backItems(maxItems)) {
        if (!item.isValid())
            continue;
        result.append(dumpHistoryItem(item, 8, false));
    }

    QWebHistoryItem item = history->currentItem();
    if (item.isValid())
        result.append(dumpHistoryItem(item, 8, true));

    foreach (const QWebHistoryItem item, history->forwardItems(maxItems)) {
        if (!item.isValid())
            continue;
        result.append(dumpHistoryItem(item, 8, false));
    }

    result.append(QLatin1String("===============================================\n"));
    return result;
}

static const char *methodNameStringForFailedTest(TestRunner *controller)
{
    const char *errorMessage;
    if (controller->shouldDumpAsText())
        errorMessage = "[documentElement innerText]";
    // FIXME: Add when we have support
    //else if (controller->dumpDOMAsWebArchive())
    //    errorMessage = "[[mainFrame DOMDocument] webArchive]";
    //else if (controller->dumpSourceAsWebArchive())
    //    errorMessage = "[[mainFrame dataSource] webArchive]";
    else
        errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";

    return errorMessage;
}

void DumpRenderTree::dump()
{
    // Prevent any further frame load or resource load callbacks from appearing after we dump the result.
    DumpRenderTreeSupportQt::dumpFrameLoader(false);
    DumpRenderTreeSupportQt::dumpResourceLoadCallbacks(false);

    QWebFrame *mainFrame = m_page->mainFrame();

    if (isStandAloneMode()) {
        QString markup = mainFrame->toHtml();
        fprintf(stdout, "Source:\n\n%s\n", markup.toUtf8().constData());
    }

    QString mimeType = DumpRenderTreeSupportQt::responseMimeType(mainFrame);
    if (mimeType == "text/plain")
        m_controller->dumpAsText();

    // Dump render text...
    QString resultString;
    if (m_controller->shouldDumpAsText())
        resultString = dumpFramesAsText(mainFrame);
    else {
        resultString = mainFrame->renderTreeDump();
        resultString += dumpFrameScrollPosition(mainFrame);
    }
    if (!resultString.isEmpty()) {
        fprintf(stdout, "Content-Type: text/plain\n");
        fprintf(stdout, "%s", resultString.toUtf8().constData());

        if (m_controller->shouldDumpBackForwardList()) {
            fprintf(stdout, "%s", dumpBackForwardList(webPage()).toUtf8().constData());
            foreach (QObject* widget, windows) {
                QWebPage* page = qobject_cast<QWebPage*>(widget->findChild<QWebPage*>());
                fprintf(stdout, "%s", dumpBackForwardList(page).toUtf8().constData());
            }
        }

    } else
        printf("ERROR: nil result from %s", methodNameStringForFailedTest(m_controller));

    // signal end of text block
    fputs("#EOF\n", stdout);
    fputs("#EOF\n", stderr);

    if (m_dumpPixelsForCurrentTest && !m_controller->shouldDumpAsText()) {
        QImage image;
        if (!m_controller->isPrinting()) {
            image = QImage(m_page->viewportSize(), QImage::Format_ARGB32);
            image.fill(Qt::white);
            QPainter painter(&image);
            mainFrame->render(&painter);
            painter.end();
        } else
            image = DumpRenderTreeSupportQt::paintPagesWithBoundaries(mainFrame);

        QCryptographicHash hash(QCryptographicHash::Md5);
        for (int row = 0; row < image.height(); ++row)
            hash.addData(reinterpret_cast<const char*>(image.scanLine(row)), image.width() * 4);
        QString actualHash = hash.result().toHex();

        fprintf(stdout, "\nActualHash: %s\n", qPrintable(actualHash));

        bool dumpImage = true;

        if (!m_expectedHash.isEmpty()) {
            Q_ASSERT(m_expectedHash.length() == 32);
            fprintf(stdout, "\nExpectedHash: %s\n", qPrintable(m_expectedHash));

            if (m_expectedHash == actualHash)
                dumpImage = false;
        }

        if (dumpImage) {
            image.setText("checksum", actualHash);

            QBuffer buffer;
            buffer.open(QBuffer::WriteOnly);
            image.save(&buffer, "PNG");
            buffer.close();
            const QByteArray &data = buffer.data();

            printf("Content-Type: %s\n", "image/png");
            printf("Content-Length: %lu\n", static_cast<unsigned long>(data.length()));

            const quint32 bytesToWriteInOneChunk = 1 << 15;
            quint32 dataRemainingToWrite = data.length();
            const char *ptr = data.data();
            while (dataRemainingToWrite) {
                quint32 bytesToWriteInThisChunk = qMin(dataRemainingToWrite, bytesToWriteInOneChunk);
                quint32 bytesWritten = fwrite(ptr, 1, bytesToWriteInThisChunk, stdout);
                if (bytesWritten != bytesToWriteInThisChunk)
                    break;
                dataRemainingToWrite -= bytesWritten;
                ptr += bytesWritten;
            }
        }

        fflush(stdout);
    }

    puts("#EOF");   // terminate the (possibly empty) pixels block

    fflush(stdout);
    fflush(stderr);

     emit ready();
}

void DumpRenderTree::titleChanged(const QString &s)
{
    if (m_controller->shouldDumpTitleChanges())
        printf("TITLE CHANGED: %s\n", s.toUtf8().data());
}

void DumpRenderTree::connectFrame(QWebFrame *frame)
{
    connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(initJSObjects()));
    connect(frame, SIGNAL(provisionalLoad()),
            testRunner(), SLOT(provisionalLoad()));
}

void DumpRenderTree::dumpDatabaseQuota(QWebFrame* frame, const QString& dbName)
{
    if (!m_controller->shouldDumpDatabaseCallbacks())
        return;
    QWebSecurityOrigin origin = frame->securityOrigin();
    printf("UI DELEGATE DATABASE CALLBACK: exceededDatabaseQuotaForSecurityOrigin:{%s, %s, %i} database:%s\n",
           origin.scheme().toUtf8().data(),
           origin.host().toUtf8().data(),
           origin.port(),
           dbName.toUtf8().data());
    origin.setDatabaseQuota(databaseDefaultQuota);
}

void DumpRenderTree::dumpApplicationCacheQuota(QWebSecurityOrigin* origin, quint64 defaultOriginQuota, quint64 totalSpaceNeeded)
{
    if (m_controller->shouldDumpApplicationCacheDelegateCallbacks()) {
        // For example, numbers from 30000 - 39999 will output as 30000.
        // Rounding up or down not really matter for these tests. It's
        // sufficient to just get a range of 10000 to determine if we were
        // above or below a threshold.
        quint64 truncatedSpaceNeeded = (totalSpaceNeeded / 10000) * 10000;
        printf("UI DELEGATE APPLICATION CACHE CALLBACK: exceededApplicationCacheOriginQuotaForSecurityOrigin:{%s, %s, %i} totalSpaceNeeded:~%llu\n",
               origin->scheme().toUtf8().data(),
               origin->host().toUtf8().data(),
               origin->port(),
               truncatedSpaceNeeded
               );
    }

    if (m_controller->shouldDisallowIncreaseForApplicationCacheQuota())
        return;

    origin->setApplicationCacheQuota(defaultOriginQuota);
}

void DumpRenderTree::statusBarMessage(const QString& message)
{
    if (!m_controller->shouldDumpStatusCallbacks())
        return;

    printf("UI DELEGATE STATUS CALLBACK: setStatusText:%s\n", message.toUtf8().constData());
}

QWebPage *DumpRenderTree::createWindow()
{
    if (!m_controller->canOpenWindows())
        return 0;

    // Create a dummy container object to track the page in DRT.
    // QObject is used instead of QWidget to prevent DRT from
    // showing the main view when deleting the container.

    QObject* container = new QObject(m_mainView);
    // create a QWebPage we want to return
    QWebPage* page = static_cast<QWebPage*>(new WebPage(container, this));
    // gets cleaned up in closeRemainingWindows()
    windows.append(container);

    // connect the needed signals to the page
    connect(page, SIGNAL(frameCreated(QWebFrame*)), this, SLOT(connectFrame(QWebFrame*)));
    connectFrame(page->mainFrame());
    connect(page, SIGNAL(loadFinished(bool)), m_controller, SLOT(maybeDump(bool)));
    connect(page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));

    // Use a frame group name for all pages created by DumpRenderTree to allow
    // testing of cross-page frame lookup.
    DumpRenderTreeSupportQt::webPageSetGroupName(page, "org.webkit.qt.DumpRenderTree");

    return page;
}

void DumpRenderTree::windowCloseRequested()
{
    QWebPage* page = qobject_cast<QWebPage*>(sender());
    QObject* container = page->parent();
    windows.removeAll(container);
    container->deleteLater();
}

int DumpRenderTree::windowCount() const
{
// include the main view in the count
    return windows.count() + 1;
}

void DumpRenderTree::geolocationPermissionSet() 
{
    m_page->permissionSet(QWebPage::Geolocation);
}

void DumpRenderTree::switchFocus(bool focused)
{
    QFocusEvent event((focused) ? QEvent::FocusIn : QEvent::FocusOut, Qt::ActiveWindowFocusReason);
    if (!isGraphicsBased())
        QApplication::sendEvent(m_mainView, &event);
    else {
        if (WebViewGraphicsBased* view = qobject_cast<WebViewGraphicsBased*>(m_mainView))
            view->scene()->sendEvent(view->graphicsView(), &event);
    }

}

QList<WebPage*> DumpRenderTree::getAllPages() const
{
    QList<WebPage*> pages;
    pages.append(m_page);
    foreach (QObject* widget, windows) {
        if (WebPage* page = widget->findChild<WebPage*>())
            pages.append(page);
    }
    return pages;
}

void DumpRenderTree::setTimeout(int timeout)
{
    m_controller->setTimeout(timeout);
}

void DumpRenderTree::setShouldTimeout(bool flag)
{
    m_controller->setShouldTimeout(flag);
}

}