[Qt] Simplify QT_VERSION_CHECKS for Qt5 by introducing HAVE(QT5)
[WebKit-https.git] / Tools / DumpRenderTree / qt / DumpRenderTreeQt.cpp
1 /*
2  * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3  * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
4  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
5  * Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1.  Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  * 2.  Redistributions in binary form must reproduce the above copyright
14  *     notice, this list of conditions and the following disclaimer in the
15  *     documentation and/or other materials provided with the distribution.
16  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
17  *     its contributors may be used to endorse or promote products derived
18  *     from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
21  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
24  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include "config.h"
33
34 #include "DumpRenderTreeQt.h"
35 #include "DumpRenderTreeSupportQt.h"
36 #include "EventSenderQt.h"
37 #include "GCControllerQt.h"
38 #include "LayoutTestControllerQt.h"
39 #include "TextInputControllerQt.h"
40 #include "QtInitializeTestFonts.h"
41 #include "testplugin.h"
42 #include "WorkQueue.h"
43
44 #include <QApplication>
45 #include <QBuffer>
46 #include <QCryptographicHash>
47 #include <QDir>
48 #include <QFile>
49 #include <QFileInfo>
50 #include <QFocusEvent>
51 #include <QFontDatabase>
52 #include <QLabel>
53 #include <QLocale>
54 #include <QNetworkAccessManager>
55 #include <QNetworkReply>
56 #include <QNetworkRequest>
57 #include <QPaintDevice>
58 #include <QPaintEngine>
59 #ifndef QT_NO_PRINTER
60 #include <QPrinter>
61 #endif
62 #include <QProgressBar>
63 #include <QUndoStack>
64 #include <QUrl>
65
66 #include <qwebsettings.h>
67 #include <qwebsecurityorigin.h>
68
69 #include <limits.h>
70 #include <locale.h>
71
72 #ifndef Q_OS_WIN
73 #include <unistd.h>
74 #endif
75
76 #include <qdebug.h>
77
78 namespace WebCore {
79
80 const int databaseDefaultQuota = 5 * 1024 * 1024;
81
82 NetworkAccessManager::NetworkAccessManager(QObject* parent)
83     : QNetworkAccessManager(parent)
84 {
85 #ifndef QT_NO_OPENSSL
86     connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),
87             this, SLOT(sslErrorsEncountered(QNetworkReply*, const QList<QSslError>&)));
88 #endif
89 }
90
91 #ifndef QT_NO_OPENSSL
92 void NetworkAccessManager::sslErrorsEncountered(QNetworkReply* reply, const QList<QSslError>& errors)
93 {
94     if (reply->url().host() == "127.0.0.1" || reply->url().host() == "localhost") {
95         bool ignore = true;
96
97         // Accept any HTTPS certificate.
98         foreach (const QSslError& error, errors) {
99             if (error.error() < QSslError::UnableToGetIssuerCertificate || error.error() > QSslError::HostNameMismatch) {
100                 ignore = false;
101                 break;
102             }
103         }
104
105         if (ignore)
106             reply->ignoreSslErrors();
107     }
108 }
109 #endif
110
111
112 #ifndef QT_NO_PRINTER
113 class NullPrinter : public QPrinter {
114 public:
115     class NullPaintEngine : public QPaintEngine {
116     public:
117         virtual bool begin(QPaintDevice*) { return true; }
118         virtual bool end() { return true; }
119         virtual QPaintEngine::Type type() const { return QPaintEngine::User; }
120         virtual void drawPixmap(const QRectF& r, const QPixmap& pm, const QRectF& sr) { }
121         virtual void updateState(const QPaintEngineState& state) { }
122     };
123
124     virtual QPaintEngine* paintEngine() const { return const_cast<NullPaintEngine*>(&m_engine); }
125
126     NullPaintEngine m_engine;
127 };
128 #endif
129
130 WebPage::WebPage(QObject* parent, DumpRenderTree* drt)
131     : QWebPage(parent)
132     , m_webInspector(0)
133     , m_drt(drt)
134 {
135     QWebSettings* globalSettings = QWebSettings::globalSettings();
136
137     globalSettings->setFontSize(QWebSettings::MinimumFontSize, 0);
138     globalSettings->setFontSize(QWebSettings::MinimumLogicalFontSize, 5);
139     globalSettings->setFontSize(QWebSettings::DefaultFontSize, 16);
140     globalSettings->setFontSize(QWebSettings::DefaultFixedFontSize, 13);
141
142     globalSettings->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
143     globalSettings->setAttribute(QWebSettings::JavascriptCanAccessClipboard, true);
144     globalSettings->setAttribute(QWebSettings::LinksIncludedInFocusChain, false);
145     globalSettings->setAttribute(QWebSettings::PluginsEnabled, true);
146     globalSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
147     globalSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
148     globalSettings->setAttribute(QWebSettings::PrivateBrowsingEnabled, false);
149     globalSettings->setAttribute(QWebSettings::SpatialNavigationEnabled, false);
150
151     connect(this, SIGNAL(geometryChangeRequested(const QRect &)),
152             this, SLOT(setViewGeometry(const QRect & )));
153
154     setNetworkAccessManager(m_drt->networkAccessManager());
155     setPluginFactory(new TestPlugin(this));
156
157     connect(this, SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)), this, SLOT(requestPermission(QWebFrame*, QWebPage::Feature)));
158     connect(this, SIGNAL(featurePermissionRequestCanceled(QWebFrame*, QWebPage::Feature)), this, SLOT(cancelPermission(QWebFrame*, QWebPage::Feature)));
159 }
160
161 WebPage::~WebPage()
162 {
163     delete m_webInspector;
164 }
165
166 QWebInspector* WebPage::webInspector()
167 {
168     if (!m_webInspector) {
169         m_webInspector = new QWebInspector;
170         m_webInspector->setPage(this);
171     }
172     return m_webInspector;
173 }
174
175 void WebPage::resetSettings()
176 {
177     // After each layout test, reset the settings that may have been changed by
178     // layoutTestController.overridePreference() or similar.
179     settings()->resetFontSize(QWebSettings::DefaultFontSize);
180     settings()->resetAttribute(QWebSettings::JavascriptCanOpenWindows);
181     settings()->resetAttribute(QWebSettings::JavascriptEnabled);
182     settings()->resetAttribute(QWebSettings::PrivateBrowsingEnabled);
183     settings()->resetAttribute(QWebSettings::SpatialNavigationEnabled);
184     settings()->resetAttribute(QWebSettings::LinksIncludedInFocusChain);
185     settings()->resetAttribute(QWebSettings::OfflineWebApplicationCacheEnabled);
186     settings()->resetAttribute(QWebSettings::LocalContentCanAccessRemoteUrls);
187     settings()->resetAttribute(QWebSettings::LocalContentCanAccessFileUrls);
188     settings()->resetAttribute(QWebSettings::PluginsEnabled);
189     settings()->resetAttribute(QWebSettings::JavascriptCanAccessClipboard);
190     settings()->resetAttribute(QWebSettings::AutoLoadImages);
191     settings()->resetAttribute(QWebSettings::ZoomTextOnly);
192
193     m_drt->layoutTestController()->setCaretBrowsingEnabled(false);
194     m_drt->layoutTestController()->setAuthorAndUserStylesEnabled(true);
195     m_drt->layoutTestController()->setFrameFlatteningEnabled(false);
196     m_drt->layoutTestController()->setSmartInsertDeleteEnabled(true);
197     m_drt->layoutTestController()->setSelectTrailingWhitespaceEnabled(false);
198     m_drt->layoutTestController()->setDefersLoading(false);
199
200     // globalSettings must be reset explicitly.
201     m_drt->layoutTestController()->setXSSAuditorEnabled(false);
202
203     QWebSettings::setMaximumPagesInCache(0); // reset to default
204     settings()->setUserStyleSheetUrl(QUrl()); // reset to default
205
206     DumpRenderTreeSupportQt::setMinimumTimerInterval(this, DumpRenderTreeSupportQt::defaultMinimumTimerInterval());
207     DumpRenderTreeSupportQt::setHixie76WebSocketProtocolEnabled(this, DumpRenderTreeSupportQt::defaultHixie76WebSocketProtocolEnabled());
208
209     DumpRenderTreeSupportQt::resetInternalsObject(mainFrame());
210
211     m_pendingGeolocationRequests.clear();
212 }
213
214 QWebPage *WebPage::createWindow(QWebPage::WebWindowType)
215 {
216     return m_drt->createWindow();
217 }
218
219 void WebPage::javaScriptAlert(QWebFrame*, const QString& message)
220 {
221     if (!isTextOutputEnabled())
222         return;
223
224     fprintf(stdout, "ALERT: %s\n", message.toUtf8().constData());
225 }
226
227 void WebPage::requestPermission(QWebFrame* frame, QWebPage::Feature feature)
228 {
229     switch (feature) {
230     case Notifications:
231         if (!m_drt->layoutTestController()->ignoreReqestForPermission())
232             setFeaturePermission(frame, feature, PermissionGrantedByUser);
233         break;
234     case Geolocation:
235         if (m_drt->layoutTestController()->isGeolocationPermissionSet())
236             if (m_drt->layoutTestController()->geolocationPermission())
237                 setFeaturePermission(frame, feature, PermissionGrantedByUser);
238             else
239                 setFeaturePermission(frame, feature, PermissionDeniedByUser);
240         else
241             m_pendingGeolocationRequests.append(frame);
242         break;
243     default:
244         break;
245     }
246 }
247
248 void WebPage::cancelPermission(QWebFrame* frame, QWebPage::Feature feature)
249 {
250     switch (feature) {
251     case Geolocation:
252         m_pendingGeolocationRequests.removeOne(frame);
253         break;
254     default:
255         break;
256     }
257 }
258
259 void WebPage::permissionSet(QWebPage::Feature feature)
260 {
261     switch (feature) {
262     case Geolocation:
263         {
264         Q_ASSERT(m_drt->layoutTestController()->isGeolocationPermissionSet());
265         foreach (QWebFrame* frame, m_pendingGeolocationRequests)
266             if (m_drt->layoutTestController()->geolocationPermission())
267                 setFeaturePermission(frame, feature, PermissionGrantedByUser);
268             else
269                 setFeaturePermission(frame, feature, PermissionDeniedByUser);
270
271         m_pendingGeolocationRequests.clear();
272         break;
273         }
274     default:
275         break;
276     }
277 }
278
279 static QString urlSuitableForTestResult(const QString& url)
280 {
281     if (url.isEmpty() || !url.startsWith(QLatin1String("file://")))
282         return url;
283
284     return QFileInfo(url).fileName();
285 }
286
287 void WebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString&)
288 {
289     if (!isTextOutputEnabled())
290         return;
291
292     QString newMessage;
293     if (!message.isEmpty()) {
294         newMessage = message;
295
296         size_t fileProtocol = newMessage.indexOf(QLatin1String("file://"));
297         if (fileProtocol != -1) {
298             newMessage = newMessage.left(fileProtocol) + urlSuitableForTestResult(newMessage.mid(fileProtocol));
299         }
300     }
301
302     fprintf(stdout, "CONSOLE MESSAGE: ");
303     if (lineNumber)
304         fprintf(stdout, "line %d: ", lineNumber);
305     fprintf(stdout, "%s\n", newMessage.toUtf8().constData());
306 }
307
308 bool WebPage::javaScriptConfirm(QWebFrame*, const QString& msg)
309 {
310     if (!isTextOutputEnabled())
311         return true;
312
313     fprintf(stdout, "CONFIRM: %s\n", msg.toUtf8().constData());
314     return true;
315 }
316
317 bool WebPage::javaScriptPrompt(QWebFrame*, const QString& msg, const QString& defaultValue, QString* result)
318 {
319     if (!isTextOutputEnabled())
320         return true;
321
322     fprintf(stdout, "PROMPT: %s, default text: %s\n", msg.toUtf8().constData(), defaultValue.toUtf8().constData());
323     *result = defaultValue;
324     return true;
325 }
326
327 bool WebPage::acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest& request, NavigationType type)
328 {
329     if (m_drt->layoutTestController()->waitForPolicy())
330         m_drt->layoutTestController()->notifyDone();
331
332     return QWebPage::acceptNavigationRequest(frame, request, type);
333 }
334
335 bool WebPage::supportsExtension(QWebPage::Extension extension) const
336 {
337     if (extension == QWebPage::ErrorPageExtension)
338         return m_drt->layoutTestController()->shouldHandleErrorPages();
339
340     return false;
341 }
342
343 bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output)
344 {
345     const QWebPage::ErrorPageExtensionOption* info = static_cast<const QWebPage::ErrorPageExtensionOption*>(option);
346
347     // Lets handle error pages for the main frame for now.
348     if (info->frame != mainFrame())
349         return false;
350
351     QWebPage::ErrorPageExtensionReturn* errorPage = static_cast<QWebPage::ErrorPageExtensionReturn*>(output);
352
353     errorPage->content = QString("data:text/html,<body/>").toUtf8();
354
355     return true;
356 }
357
358 QObject* WebPage::createPlugin(const QString& classId, const QUrl& url, const QStringList& paramNames, const QStringList& paramValues)
359 {
360     Q_UNUSED(url);
361     Q_UNUSED(paramNames);
362     Q_UNUSED(paramValues);
363
364     if (classId == QLatin1String("QProgressBar"))
365         return new QProgressBar(view());
366     if (classId == QLatin1String("QLabel"))
367         return new QLabel(view());
368
369     return 0;
370 }
371
372 void WebPage::setViewGeometry(const QRect& rect)
373 {
374     if (WebViewGraphicsBased* v = qobject_cast<WebViewGraphicsBased*>(view()))
375         v->scene()->setSceneRect(QRectF(rect));
376     else if (QWidget *v = view())
377         v->setGeometry(rect);
378 }
379
380 WebViewGraphicsBased::WebViewGraphicsBased(QWidget* parent)
381     : m_item(new QGraphicsWebView)
382 {
383     setScene(new QGraphicsScene(this));
384     scene()->addItem(m_item);
385 }
386
387 DumpRenderTree::DumpRenderTree()
388     : m_dumpPixels(false)
389     , m_stdin(0)
390     , m_enableTextOutput(false)
391     , m_standAloneMode(false)
392     , m_graphicsBased(false)
393     , m_persistentStoragePath(QString(getenv("DUMPRENDERTREE_TEMP")))
394 {
395     QByteArray viewMode = getenv("QT_DRT_WEBVIEW_MODE");
396     if (viewMode == "graphics")
397         setGraphicsBased(true);
398
399     DumpRenderTreeSupportQt::initialize();
400
401     // Set running in DRT mode for qwebpage to create testable objects.
402     DumpRenderTreeSupportQt::setDumpRenderTreeModeEnabled(true);
403     DumpRenderTreeSupportQt::overwritePluginDirectories();
404     QWebSettings::enablePersistentStorage(m_persistentStoragePath);
405
406     m_networkAccessManager = new NetworkAccessManager(this);
407     // create our primary testing page/view.
408     if (isGraphicsBased()) {
409         WebViewGraphicsBased* view = new WebViewGraphicsBased(0);
410         m_page = new WebPage(view, this);
411         view->setPage(m_page);
412         m_mainView = view;
413     } else {
414         QWebView* view = new QWebView(0);
415         m_page = new WebPage(view, this);
416         view->setPage(m_page);
417         m_mainView = view;
418     }
419     // Use a frame group name for all pages created by DumpRenderTree to allow
420     // testing of cross-page frame lookup.
421     DumpRenderTreeSupportQt::webPageSetGroupName(m_page, "org.webkit.qt.DumpRenderTree");
422
423     m_mainView->setContextMenuPolicy(Qt::NoContextMenu);
424     m_mainView->resize(QSize(LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight));
425
426     // clean up cache by resetting quota.
427     qint64 quota = webPage()->settings()->offlineWebApplicationCacheQuota();
428     webPage()->settings()->setOfflineWebApplicationCacheQuota(quota);
429
430     // create our controllers. This has to be done before connectFrame,
431     // as it exports there to the JavaScript DOM window.
432     m_controller = new LayoutTestController(this);
433     connect(m_controller, SIGNAL(showPage()), this, SLOT(showPage()));
434     connect(m_controller, SIGNAL(hidePage()), this, SLOT(hidePage()));
435
436     // async geolocation permission set by controller
437     connect(m_controller, SIGNAL(geolocationPermissionSet()), this, SLOT(geolocationPermissionSet()));
438
439     connect(m_controller, SIGNAL(done()), this, SLOT(dump()));
440     m_eventSender = new EventSender(m_page);
441     m_textInputController = new TextInputController(m_page);
442     m_gcController = new GCController(m_page);
443
444     // now connect our different signals
445     connect(m_page, SIGNAL(frameCreated(QWebFrame *)),
446             this, SLOT(connectFrame(QWebFrame *)));
447     connectFrame(m_page->mainFrame());
448
449     connect(m_page, SIGNAL(loadFinished(bool)),
450             m_controller, SLOT(maybeDump(bool)));
451     // We need to connect to loadStarted() because notifyDone should only
452     // dump results itself when the last page loaded in the test has finished loading.
453     connect(m_page, SIGNAL(loadStarted()),
454             m_controller, SLOT(resetLoadFinished()));
455     connect(m_page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
456     connect(m_page, SIGNAL(printRequested(QWebFrame*)), this, SLOT(dryRunPrint(QWebFrame*)));
457
458     connect(m_page->mainFrame(), SIGNAL(titleChanged(const QString&)),
459             SLOT(titleChanged(const QString&)));
460     connect(m_page, SIGNAL(databaseQuotaExceeded(QWebFrame*,QString)),
461             this, SLOT(dumpDatabaseQuota(QWebFrame*,QString)));
462     connect(m_page, SIGNAL(applicationCacheQuotaExceeded(QWebSecurityOrigin *, quint64, quint64)),
463             this, SLOT(dumpApplicationCacheQuota(QWebSecurityOrigin *, quint64, quint64)));
464     connect(m_page, SIGNAL(statusBarMessage(const QString&)),
465             this, SLOT(statusBarMessage(const QString&)));
466
467     QObject::connect(this, SIGNAL(quit()), qApp, SLOT(quit()), Qt::QueuedConnection);
468
469     DumpRenderTreeSupportQt::setDumpRenderTreeModeEnabled(true);
470     DumpRenderTreeSupportQt::setInteractiveFormValidationEnabled(webPage(), true);
471     QFocusEvent event(QEvent::FocusIn, Qt::ActiveWindowFocusReason);
472     QApplication::sendEvent(m_mainView, &event);
473 }
474
475 DumpRenderTree::~DumpRenderTree()
476 {
477     if (!m_redirectOutputFileName.isEmpty())
478         fclose(stdout);
479     if (!m_redirectErrorFileName.isEmpty())
480         fclose(stderr);
481     delete m_mainView;
482     delete m_stdin;
483 }
484
485 static void clearHistory(QWebPage* page)
486 {
487     // QWebHistory::clear() leaves current page, so remove it as well by setting
488     // max item count to 0, and then setting it back to it's original value.
489
490     QWebHistory* history = page->history();
491     int itemCount = history->maximumItemCount();
492
493     history->clear();
494     history->setMaximumItemCount(0);
495     history->setMaximumItemCount(itemCount);
496 }
497
498 void DumpRenderTree::dryRunPrint(QWebFrame* frame)
499 {
500 #ifndef QT_NO_PRINTER
501     NullPrinter printer;
502     frame->print(&printer);
503 #endif
504 }
505
506 void DumpRenderTree::resetToConsistentStateBeforeTesting(const QUrl& url)
507 {
508     // reset so that any current loads are stopped
509     // NOTE: that this has to be done before the layoutTestController is
510     // reset or we get timeouts for some tests.
511     m_page->blockSignals(true);
512     m_page->triggerAction(QWebPage::Stop);
513     m_page->blockSignals(false);
514
515     QList<QWebSecurityOrigin> knownOrigins = QWebSecurityOrigin::allOrigins();
516     for (int i = 0; i < knownOrigins.size(); ++i)
517         knownOrigins[i].setDatabaseQuota(databaseDefaultQuota);
518
519     // reset the layoutTestController at this point, so that we under no
520     // circumstance dump (stop the waitUntilDone timer) during the reset
521     // of the DRT.
522     m_controller->reset();
523
524     // reset mouse clicks counter
525     m_eventSender->resetClickCount();
526
527     closeRemainingWindows();
528     
529     // Call setTextSizeMultiplier(1.0) to reset TextZoomFactor and PageZoomFactor too. 
530     // It should be done before resetSettings() to guarantee resetting QWebSettings::ZoomTextOnly correctly.
531     m_page->mainFrame()->setTextSizeMultiplier(1.0);
532
533     m_page->resetSettings();
534 #ifndef QT_NO_UNDOSTACK
535     m_page->undoStack()->clear();
536 #endif
537     
538     clearHistory(m_page);
539     DumpRenderTreeSupportQt::scalePageBy(m_page->mainFrame(), 1, QPoint(0, 0));
540     DumpRenderTreeSupportQt::clearFrameName(m_page->mainFrame());
541
542     m_page->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded);
543     m_page->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded);
544
545     if (url.scheme() == "http" || url.scheme() == "https") {
546         // credentials may exist from previous tests.
547         m_page->setNetworkAccessManager(0);
548         delete m_networkAccessManager;
549         m_networkAccessManager = new NetworkAccessManager(this);
550         m_page->setNetworkAccessManager(m_networkAccessManager);
551     }
552
553     WorkQueue::shared()->clear();
554     WorkQueue::shared()->setFrozen(false);
555
556     DumpRenderTreeSupportQt::resetOriginAccessWhiteLists();
557
558     DumpRenderTreeSupportQt::setWindowsBehaviorAsEditingBehavior(m_page);
559
560     QLocale::setDefault(QLocale::c());
561
562     layoutTestController()->setDeveloperExtrasEnabled(true);
563 #ifndef Q_OS_WINCE
564     setlocale(LC_ALL, "");
565 #endif
566
567     DumpRenderTreeSupportQt::clearOpener(m_page->mainFrame());
568 }
569
570 static bool isGlobalHistoryTest(const QUrl& url)
571 {
572     if (url.path().contains("globalhistory/"))
573         return true;
574     return false;
575 }
576
577 static bool isWebInspectorTest(const QUrl& url)
578 {
579     if (url.path().contains("inspector/"))
580         return true;
581     return false;
582 }
583
584 static bool isDumpAsTextTest(const QUrl& url)
585 {
586     if (url.path().contains("dumpAsText/"))
587         return true;
588     return false;
589 }
590
591
592 void DumpRenderTree::open(const QUrl& url)
593 {
594     DumpRenderTreeSupportQt::dumpResourceLoadCallbacksPath(QFileInfo(url.toString()).path());
595     resetToConsistentStateBeforeTesting(url);
596
597     if (isWebInspectorTest(m_page->mainFrame()->url()))
598         layoutTestController()->closeWebInspector();
599
600     if (isWebInspectorTest(url))
601         layoutTestController()->showWebInspector();
602
603     if (isDumpAsTextTest(url)) {
604         layoutTestController()->dumpAsText();
605         setDumpPixels(false);
606     }
607
608     if (isGlobalHistoryTest(url))
609         layoutTestController()->dumpHistoryCallbacks();
610
611     // W3C SVG tests expect to be 480x360
612     bool isW3CTest = url.toString().contains("svg/W3C-SVG-1.1");
613     int width = isW3CTest ? 480 : LayoutTestController::maxViewWidth;
614     int height = isW3CTest ? 360 : LayoutTestController::maxViewHeight;
615     m_mainView->resize(QSize(width, height));
616     m_page->setPreferredContentsSize(QSize());
617     m_page->setViewportSize(QSize(width, height));
618
619     QFocusEvent ev(QEvent::FocusIn);
620     m_page->event(&ev);
621
622     QWebSettings::clearMemoryCaches();
623     QFontDatabase::removeAllApplicationFonts();
624     WebKit::initializeTestFonts();
625
626     DumpRenderTreeSupportQt::dumpFrameLoader(url.toString().contains("loading/"));
627     setTextOutputEnabled(true);
628     m_page->mainFrame()->load(url);
629 }
630
631 void DumpRenderTree::readLine()
632 {
633     if (!m_stdin) {
634         m_stdin = new QFile;
635         m_stdin->open(stdin, QFile::ReadOnly);
636
637         if (!m_stdin->isReadable()) {
638             emit quit();
639             return;
640         }
641     }
642
643     QByteArray line = m_stdin->readLine().trimmed();
644
645     if (line.isEmpty()) {
646         emit quit();
647         return;
648     }
649
650     processLine(QString::fromLocal8Bit(line.constData(), line.length()));
651 }
652
653 void DumpRenderTree::processArgsLine(const QStringList &args)
654 {
655     setStandAloneMode(true);
656
657     m_standAloneModeTestList = args;
658
659     QFileInfo firstEntry(m_standAloneModeTestList.first());
660     if (firstEntry.isDir()) {
661         QDir folderEntry(m_standAloneModeTestList.first());
662         QStringList supportedExt;
663         // Check for all supported extensions (from Scripts/webkitpy/layout_tests/layout_package/test_files.py).
664         supportedExt << "*.html" << "*.shtml" << "*.xml" << "*.xhtml" << "*.xhtmlmp" << "*.pl" << "*.php" << "*.svg";
665         m_standAloneModeTestList = folderEntry.entryList(supportedExt, QDir::Files);
666         for (int i = 0; i < m_standAloneModeTestList.size(); ++i)
667             m_standAloneModeTestList[i] = folderEntry.absoluteFilePath(m_standAloneModeTestList[i]);
668     }
669     connect(this, SIGNAL(ready()), this, SLOT(loadNextTestInStandAloneMode()));
670
671     if (!m_standAloneModeTestList.isEmpty()) {
672         QString first = m_standAloneModeTestList.takeFirst();
673         processLine(first);
674     }
675 }
676
677 void DumpRenderTree::loadNextTestInStandAloneMode()
678 {
679     if (m_standAloneModeTestList.isEmpty()) {
680         emit quit();
681         return;
682     }
683     QString first = m_standAloneModeTestList.takeFirst();
684     processLine(first);
685 }
686
687 void DumpRenderTree::processLine(const QString &input)
688 {
689     QString line = input;
690
691     m_expectedHash = QString();
692     if (m_dumpPixels) {
693         // single quote marks the pixel dump hash
694         int i = line.indexOf('\'');
695         if (i > -1) {
696             m_expectedHash = line.mid(i + 1, line.length());
697             line.remove(i, line.length());
698         }
699     }
700
701     if (line.startsWith(QLatin1String("http:"))
702             || line.startsWith(QLatin1String("https:"))
703             || line.startsWith(QLatin1String("file:"))) {
704         open(QUrl(line));
705     } else {
706         QFileInfo fi(line);
707
708         if (!fi.exists()) {
709             QDir currentDir = QDir::currentPath();
710
711             // Try to be smart about where the test is located
712             if (currentDir.dirName() == QLatin1String("LayoutTests"))
713                 fi = QFileInfo(currentDir, line.replace(QRegExp(".*?LayoutTests/(.*)"), "\\1"));
714             else if (!line.contains(QLatin1String("LayoutTests")))
715                 fi = QFileInfo(currentDir, line.prepend(QLatin1String("LayoutTests/")));
716
717             if (!fi.exists()) {
718                 emit ready();
719                 return;
720             }
721         }
722
723         open(QUrl::fromLocalFile(fi.absoluteFilePath()));
724     }
725
726     fflush(stdout);
727 }
728
729 void DumpRenderTree::setDumpPixels(bool dump)
730 {
731     m_dumpPixels = dump;
732 }
733
734 void DumpRenderTree::closeRemainingWindows()
735 {
736     foreach (QObject* widget, windows)
737         delete widget;
738     windows.clear();
739 }
740
741 void DumpRenderTree::initJSObjects()
742 {
743     QWebFrame *frame = qobject_cast<QWebFrame*>(sender());
744     Q_ASSERT(frame);
745     frame->addToJavaScriptWindowObject(QLatin1String("layoutTestController"), m_controller);
746     frame->addToJavaScriptWindowObject(QLatin1String("eventSender"), m_eventSender);
747     frame->addToJavaScriptWindowObject(QLatin1String("textInputController"), m_textInputController);
748     frame->addToJavaScriptWindowObject(QLatin1String("GCController"), m_gcController);
749     DumpRenderTreeSupportQt::injectInternalsObject(frame);
750 }
751
752 void DumpRenderTree::showPage()
753 {
754     m_mainView->show();
755     // we need a paint event but cannot process all the events
756     QPixmap pixmap(m_mainView->size());
757     m_mainView->render(&pixmap);
758 }
759
760 void DumpRenderTree::hidePage()
761 {
762     m_mainView->hide();
763 }
764
765 QString DumpRenderTree::dumpFrameScrollPosition(QWebFrame* frame)
766 {
767     if (!frame || !DumpRenderTreeSupportQt::hasDocumentElement(frame))
768         return QString();
769
770     QString result;
771     QPoint pos = frame->scrollPosition();
772     if (pos.x() > 0 || pos.y() > 0) {
773         QWebFrame* parent = qobject_cast<QWebFrame *>(frame->parent());
774         if (parent)
775             result.append(QString("frame '%1' ").arg(frame->title()));
776         result.append(QString("scrolled to %1,%2\n").arg(pos.x()).arg(pos.y()));
777     }
778
779     if (m_controller->shouldDumpChildFrameScrollPositions()) {
780         QList<QWebFrame*> children = frame->childFrames();
781         for (int i = 0; i < children.size(); ++i)
782             result += dumpFrameScrollPosition(children.at(i));
783     }
784     return result;
785 }
786
787 QString DumpRenderTree::dumpFramesAsText(QWebFrame* frame)
788 {
789     if (!frame || !DumpRenderTreeSupportQt::hasDocumentElement(frame))
790         return QString();
791
792     QString result;
793     QWebFrame* parent = qobject_cast<QWebFrame*>(frame->parent());
794     if (parent) {
795         result.append(QLatin1String("\n--------\nFrame: '"));
796         result.append(frame->frameName());
797         result.append(QLatin1String("'\n--------\n"));
798     }
799
800     QString innerText = frame->toPlainText();
801     result.append(innerText);
802     result.append(QLatin1String("\n"));
803
804     if (m_controller->shouldDumpChildrenAsText()) {
805         QList<QWebFrame *> children = frame->childFrames();
806         for (int i = 0; i < children.size(); ++i)
807             result += dumpFramesAsText(children.at(i));
808     }
809
810     return result;
811 }
812
813 static QString dumpHistoryItem(const QWebHistoryItem& item, int indent, bool current)
814 {
815     QString result;
816
817     int start = 0;
818     if (current) {
819         result.append(QLatin1String("curr->"));
820         start = 6;
821     }
822     for (int i = start; i < indent; i++)
823         result.append(' ');
824
825     QString url = item.url().toString();
826     if (url.contains("file://")) {
827         static QString layoutTestsString("/LayoutTests/");
828         static QString fileTestString("(file test):");
829
830         QString res = url.mid(url.indexOf(layoutTestsString) + layoutTestsString.length());
831         if (res.isEmpty())
832             return result;
833
834         result.append(fileTestString);
835         result.append(res);
836     } else {
837         result.append(url);
838     }
839
840     QString target = DumpRenderTreeSupportQt::historyItemTarget(item);
841     if (!target.isEmpty())
842         result.append(QString(QLatin1String(" (in frame \"%1\")")).arg(target));
843
844     if (DumpRenderTreeSupportQt::isTargetItem(item))
845         result.append(QLatin1String("  **nav target**"));
846     result.append(QLatin1String("\n"));
847
848     QMap<QString, QWebHistoryItem> children = DumpRenderTreeSupportQt::getChildHistoryItems(item);
849     foreach (QWebHistoryItem item, children)
850         result += dumpHistoryItem(item, 12, false);
851
852     return result;
853 }
854
855 QString DumpRenderTree::dumpBackForwardList(QWebPage* page)
856 {
857     QWebHistory* history = page->history();
858
859     QString result;
860     result.append(QLatin1String("\n============== Back Forward List ==============\n"));
861
862     // FORMAT:
863     // "        (file test):fast/loader/resources/click-fragment-link.html  **nav target**"
864     // "curr->  (file test):fast/loader/resources/click-fragment-link.html#testfragment  **nav target**"
865
866     int maxItems = history->maximumItemCount();
867
868     foreach (const QWebHistoryItem item, history->backItems(maxItems)) {
869         if (!item.isValid())
870             continue;
871         result.append(dumpHistoryItem(item, 8, false));
872     }
873
874     QWebHistoryItem item = history->currentItem();
875     if (item.isValid())
876         result.append(dumpHistoryItem(item, 8, true));
877
878     foreach (const QWebHistoryItem item, history->forwardItems(maxItems)) {
879         if (!item.isValid())
880             continue;
881         result.append(dumpHistoryItem(item, 8, false));
882     }
883
884     result.append(QLatin1String("===============================================\n"));
885     return result;
886 }
887
888 static const char *methodNameStringForFailedTest(LayoutTestController *controller)
889 {
890     const char *errorMessage;
891     if (controller->shouldDumpAsText())
892         errorMessage = "[documentElement innerText]";
893     // FIXME: Add when we have support
894     //else if (controller->dumpDOMAsWebArchive())
895     //    errorMessage = "[[mainFrame DOMDocument] webArchive]";
896     //else if (controller->dumpSourceAsWebArchive())
897     //    errorMessage = "[[mainFrame dataSource] webArchive]";
898     else
899         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
900
901     return errorMessage;
902 }
903
904 void DumpRenderTree::dump()
905 {
906     // Prevent any further frame load or resource load callbacks from appearing after we dump the result.
907     DumpRenderTreeSupportQt::dumpFrameLoader(false);
908     DumpRenderTreeSupportQt::dumpResourceLoadCallbacks(false);
909
910     QWebFrame *mainFrame = m_page->mainFrame();
911
912     if (isStandAloneMode()) {
913         QString markup = mainFrame->toHtml();
914         fprintf(stdout, "Source:\n\n%s\n", markup.toUtf8().constData());
915     }
916
917     QString mimeType = DumpRenderTreeSupportQt::responseMimeType(mainFrame);
918     if (mimeType == "text/plain")
919         m_controller->dumpAsText();
920
921     // Dump render text...
922     QString resultString;
923     if (m_controller->shouldDumpAsText())
924         resultString = dumpFramesAsText(mainFrame);
925     else {
926         resultString = mainFrame->renderTreeDump();
927         resultString += dumpFrameScrollPosition(mainFrame);
928     }
929     if (!resultString.isEmpty()) {
930         fprintf(stdout, "Content-Type: text/plain\n");
931         fprintf(stdout, "%s", resultString.toUtf8().constData());
932
933         if (m_controller->shouldDumpBackForwardList()) {
934             fprintf(stdout, "%s", dumpBackForwardList(webPage()).toUtf8().constData());
935             foreach (QObject* widget, windows) {
936                 QWebPage* page = qobject_cast<QWebPage*>(widget->findChild<QWebPage*>());
937                 fprintf(stdout, "%s", dumpBackForwardList(page).toUtf8().constData());
938             }
939         }
940
941     } else
942         printf("ERROR: nil result from %s", methodNameStringForFailedTest(m_controller));
943
944     // signal end of text block
945     fputs("#EOF\n", stdout);
946     fputs("#EOF\n", stderr);
947
948     if (m_dumpPixels && !m_controller->shouldDumpAsText()) {
949         QImage image;
950         if (!m_controller->isPrinting()) {
951             image = QImage(m_page->viewportSize(), QImage::Format_ARGB32);
952             image.fill(Qt::white);
953             QPainter painter(&image);
954             mainFrame->render(&painter);
955             painter.end();
956         } else
957             image = DumpRenderTreeSupportQt::paintPagesWithBoundaries(mainFrame);
958
959         QCryptographicHash hash(QCryptographicHash::Md5);
960         for (int row = 0; row < image.height(); ++row)
961             hash.addData(reinterpret_cast<const char*>(image.scanLine(row)), image.width() * 4);
962         QString actualHash = hash.result().toHex();
963
964         fprintf(stdout, "\nActualHash: %s\n", qPrintable(actualHash));
965
966         bool dumpImage = true;
967
968         if (!m_expectedHash.isEmpty()) {
969             Q_ASSERT(m_expectedHash.length() == 32);
970             fprintf(stdout, "\nExpectedHash: %s\n", qPrintable(m_expectedHash));
971
972             if (m_expectedHash == actualHash)
973                 dumpImage = false;
974         }
975
976         if (dumpImage) {
977             image.setText("checksum", actualHash);
978
979             QBuffer buffer;
980             buffer.open(QBuffer::WriteOnly);
981             image.save(&buffer, "PNG");
982             buffer.close();
983             const QByteArray &data = buffer.data();
984
985             printf("Content-Type: %s\n", "image/png");
986             printf("Content-Length: %lu\n", static_cast<unsigned long>(data.length()));
987
988             const quint32 bytesToWriteInOneChunk = 1 << 15;
989             quint32 dataRemainingToWrite = data.length();
990             const char *ptr = data.data();
991             while (dataRemainingToWrite) {
992                 quint32 bytesToWriteInThisChunk = qMin(dataRemainingToWrite, bytesToWriteInOneChunk);
993                 quint32 bytesWritten = fwrite(ptr, 1, bytesToWriteInThisChunk, stdout);
994                 if (bytesWritten != bytesToWriteInThisChunk)
995                     break;
996                 dataRemainingToWrite -= bytesWritten;
997                 ptr += bytesWritten;
998             }
999         }
1000
1001         fflush(stdout);
1002     }
1003
1004     puts("#EOF");   // terminate the (possibly empty) pixels block
1005
1006     fflush(stdout);
1007     fflush(stderr);
1008
1009      emit ready();
1010 }
1011
1012 void DumpRenderTree::titleChanged(const QString &s)
1013 {
1014     if (m_controller->shouldDumpTitleChanges())
1015         printf("TITLE CHANGED: %s\n", s.toUtf8().data());
1016 }
1017
1018 void DumpRenderTree::connectFrame(QWebFrame *frame)
1019 {
1020     connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(initJSObjects()));
1021     connect(frame, SIGNAL(provisionalLoad()),
1022             layoutTestController(), SLOT(provisionalLoad()));
1023 }
1024
1025 void DumpRenderTree::dumpDatabaseQuota(QWebFrame* frame, const QString& dbName)
1026 {
1027     if (!m_controller->shouldDumpDatabaseCallbacks())
1028         return;
1029     QWebSecurityOrigin origin = frame->securityOrigin();
1030     printf("UI DELEGATE DATABASE CALLBACK: exceededDatabaseQuotaForSecurityOrigin:{%s, %s, %i} database:%s\n",
1031            origin.scheme().toUtf8().data(),
1032            origin.host().toUtf8().data(),
1033            origin.port(),
1034            dbName.toUtf8().data());
1035     origin.setDatabaseQuota(databaseDefaultQuota);
1036 }
1037
1038 void DumpRenderTree::dumpApplicationCacheQuota(QWebSecurityOrigin* origin, quint64 defaultOriginQuota, quint64 totalSpaceNeeded)
1039 {
1040     if (m_controller->shouldDumpApplicationCacheDelegateCallbacks()) {
1041         // For example, numbers from 30000 - 39999 will output as 30000.
1042         // Rounding up or down not really matter for these tests. It's
1043         // sufficient to just get a range of 10000 to determine if we were
1044         // above or below a threshold.
1045         quint64 truncatedSpaceNeeded = (totalSpaceNeeded / 10000) * 10000;
1046         printf("UI DELEGATE APPLICATION CACHE CALLBACK: exceededApplicationCacheOriginQuotaForSecurityOrigin:{%s, %s, %i} totalSpaceNeeded:~%llu\n",
1047                origin->scheme().toUtf8().data(),
1048                origin->host().toUtf8().data(),
1049                origin->port(),
1050                truncatedSpaceNeeded
1051                );
1052     }
1053
1054     if (m_controller->shouldDisallowIncreaseForApplicationCacheQuota())
1055         return;
1056
1057     origin->setApplicationCacheQuota(defaultOriginQuota);
1058 }
1059
1060 void DumpRenderTree::statusBarMessage(const QString& message)
1061 {
1062     if (!m_controller->shouldDumpStatusCallbacks())
1063         return;
1064
1065     printf("UI DELEGATE STATUS CALLBACK: setStatusText:%s\n", message.toUtf8().constData());
1066 }
1067
1068 QWebPage *DumpRenderTree::createWindow()
1069 {
1070     if (!m_controller->canOpenWindows())
1071         return 0;
1072
1073     // Create a dummy container object to track the page in DRT.
1074     // QObject is used instead of QWidget to prevent DRT from
1075     // showing the main view when deleting the container.
1076
1077     QObject* container = new QObject(m_mainView);
1078     // create a QWebPage we want to return
1079     QWebPage* page = static_cast<QWebPage*>(new WebPage(container, this));
1080     // gets cleaned up in closeRemainingWindows()
1081     windows.append(container);
1082
1083     // connect the needed signals to the page
1084     connect(page, SIGNAL(frameCreated(QWebFrame*)), this, SLOT(connectFrame(QWebFrame*)));
1085     connectFrame(page->mainFrame());
1086     connect(page, SIGNAL(loadFinished(bool)), m_controller, SLOT(maybeDump(bool)));
1087     connect(page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
1088
1089     // Use a frame group name for all pages created by DumpRenderTree to allow
1090     // testing of cross-page frame lookup.
1091     DumpRenderTreeSupportQt::webPageSetGroupName(page, "org.webkit.qt.DumpRenderTree");
1092
1093     return page;
1094 }
1095
1096 void DumpRenderTree::windowCloseRequested()
1097 {
1098     QWebPage* page = qobject_cast<QWebPage*>(sender());
1099     QObject* container = page->parent();
1100     windows.removeAll(container);
1101     container->deleteLater();
1102 }
1103
1104 int DumpRenderTree::windowCount() const
1105 {
1106 // include the main view in the count
1107     return windows.count() + 1;
1108 }
1109
1110 void DumpRenderTree::geolocationPermissionSet() 
1111 {
1112     m_page->permissionSet(QWebPage::Geolocation);
1113 }
1114
1115 void DumpRenderTree::switchFocus(bool focused)
1116 {
1117     QFocusEvent event((focused) ? QEvent::FocusIn : QEvent::FocusOut, Qt::ActiveWindowFocusReason);
1118     if (!isGraphicsBased())
1119         QApplication::sendEvent(m_mainView, &event);
1120     else {
1121         if (WebViewGraphicsBased* view = qobject_cast<WebViewGraphicsBased*>(m_mainView))
1122             view->scene()->sendEvent(view->graphicsView(), &event);
1123     }
1124
1125 }
1126
1127 QList<WebPage*> DumpRenderTree::getAllPages() const
1128 {
1129     QList<WebPage*> pages;
1130     pages.append(m_page);
1131     foreach (QObject* widget, windows) {
1132         if (WebPage* page = widget->findChild<WebPage*>())
1133             pages.append(page);
1134     }
1135     return pages;
1136 }
1137
1138 void DumpRenderTree::setTimeout(int timeout)
1139 {
1140     m_controller->setTimeout(timeout);
1141 }
1142
1143 void DumpRenderTree::setShouldTimeout(bool flag)
1144 {
1145     m_controller->setShouldTimeout(flag);
1146 }
1147
1148 }