b27a426f092f611197d77b1d2d110be8cdf5049c
[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 "../../../Source/WebKit/qt/WebCoreSupport/DumpRenderTreeSupportQt.h"
36 #include "EventSenderQt.h"
37 #include "GCControllerQt.h"
38 #include "LayoutTestControllerQt.h"
39 #include "TextInputControllerQt.h"
40 #include "PlainTextControllerQt.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 <QLocale>
53 #include <QNetworkAccessManager>
54 #include <QNetworkReply>
55 #include <QNetworkRequest>
56 #include <QPaintDevice>
57 #include <QPaintEngine>
58 #ifndef QT_NO_PRINTER
59 #include <QPrinter>
60 #endif
61 #include <QUndoStack>
62 #include <QUrl>
63
64 #include <qwebsettings.h>
65 #include <qwebsecurityorigin.h>
66
67 #ifndef QT_NO_UITOOLS
68 #include <QtUiTools/QUiLoader>
69 #endif
70
71 #ifdef Q_WS_X11
72 #include <fontconfig/fontconfig.h>
73 #endif
74
75 #include <limits.h>
76 #include <locale.h>
77
78 #ifndef Q_OS_WIN
79 #include <unistd.h>
80 #endif
81
82 #include <qdebug.h>
83
84 namespace WebCore {
85
86 NetworkAccessManager::NetworkAccessManager(QObject* parent)
87     : QNetworkAccessManager(parent)
88 {
89 #ifndef QT_NO_OPENSSL
90     connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),
91             this, SLOT(sslErrorsEncountered(QNetworkReply*, const QList<QSslError>&)));
92 #endif
93 }
94
95 #ifndef QT_NO_OPENSSL
96 void NetworkAccessManager::sslErrorsEncountered(QNetworkReply* reply, const QList<QSslError>& errors)
97 {
98     if (reply->url().host() == "127.0.0.1" || reply->url().host() == "localhost") {
99         bool ignore = true;
100
101         // Accept any HTTPS certificate.
102         foreach (const QSslError& error, errors) {
103             if (error.error() < QSslError::UnableToGetIssuerCertificate || error.error() > QSslError::HostNameMismatch) {
104                 ignore = false;
105                 break;
106             }
107         }
108
109         if (ignore)
110             reply->ignoreSslErrors();
111     }
112 }
113 #endif
114
115
116 #ifndef QT_NO_PRINTER
117 class NullPrinter : public QPrinter {
118 public:
119     class NullPaintEngine : public QPaintEngine {
120     public:
121         virtual bool begin(QPaintDevice*) { return true; }
122         virtual bool end() { return true; }
123         virtual QPaintEngine::Type type() const { return QPaintEngine::User; }
124         virtual void drawPixmap(const QRectF& r, const QPixmap& pm, const QRectF& sr) { }
125         virtual void updateState(const QPaintEngineState& state) { }
126     };
127
128     virtual QPaintEngine* paintEngine() const { return const_cast<NullPaintEngine*>(&m_engine); }
129
130     NullPaintEngine m_engine;
131 };
132 #endif
133
134 WebPage::WebPage(QObject* parent, DumpRenderTree* drt)
135     : QWebPage(parent)
136     , m_webInspector(0)
137     , m_drt(drt)
138 {
139     QWebSettings* globalSettings = QWebSettings::globalSettings();
140
141     globalSettings->setFontSize(QWebSettings::MinimumFontSize, 0);
142     globalSettings->setFontSize(QWebSettings::MinimumLogicalFontSize, 5);
143     globalSettings->setFontSize(QWebSettings::DefaultFontSize, 16);
144     globalSettings->setFontSize(QWebSettings::DefaultFixedFontSize, 13);
145
146     globalSettings->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
147     globalSettings->setAttribute(QWebSettings::JavascriptCanAccessClipboard, true);
148     globalSettings->setAttribute(QWebSettings::LinksIncludedInFocusChain, false);
149     globalSettings->setAttribute(QWebSettings::PluginsEnabled, true);
150     globalSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
151     globalSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
152     globalSettings->setAttribute(QWebSettings::PrivateBrowsingEnabled, false);
153     globalSettings->setAttribute(QWebSettings::SpatialNavigationEnabled, false);
154
155     connect(this, SIGNAL(geometryChangeRequested(const QRect &)),
156             this, SLOT(setViewGeometry(const QRect & )));
157
158     setNetworkAccessManager(m_drt->networkAccessManager());
159     setPluginFactory(new TestPlugin(this));
160
161     connect(this, SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)), this, SLOT(requestPermission(QWebFrame*, QWebPage::Feature)));
162     connect(this, SIGNAL(featurePermissionRequestCanceled(QWebFrame*, QWebPage::Feature)), this, SLOT(cancelPermission(QWebFrame*, QWebPage::Feature)));
163 }
164
165 WebPage::~WebPage()
166 {
167     delete m_webInspector;
168 }
169
170 QWebInspector* WebPage::webInspector()
171 {
172     if (!m_webInspector) {
173         m_webInspector = new QWebInspector;
174         m_webInspector->setPage(this);
175     }
176     return m_webInspector;
177 }
178
179 void WebPage::resetSettings()
180 {
181     // After each layout test, reset the settings that may have been changed by
182     // layoutTestController.overridePreference() or similar.
183     settings()->resetFontSize(QWebSettings::DefaultFontSize);
184     settings()->resetAttribute(QWebSettings::JavascriptCanOpenWindows);
185     settings()->resetAttribute(QWebSettings::JavascriptEnabled);
186     settings()->resetAttribute(QWebSettings::PrivateBrowsingEnabled);
187     settings()->resetAttribute(QWebSettings::SpatialNavigationEnabled);
188     settings()->resetAttribute(QWebSettings::LinksIncludedInFocusChain);
189     settings()->resetAttribute(QWebSettings::OfflineWebApplicationCacheEnabled);
190     settings()->resetAttribute(QWebSettings::LocalContentCanAccessRemoteUrls);
191     settings()->resetAttribute(QWebSettings::PluginsEnabled);
192     settings()->resetAttribute(QWebSettings::JavascriptCanAccessClipboard);
193     settings()->resetAttribute(QWebSettings::AutoLoadImages);
194
195     m_drt->layoutTestController()->setCaretBrowsingEnabled(false);
196     m_drt->layoutTestController()->setFrameFlatteningEnabled(false);
197     m_drt->layoutTestController()->setSmartInsertDeleteEnabled(true);
198     m_drt->layoutTestController()->setSelectTrailingWhitespaceEnabled(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     m_pendingGeolocationRequests.clear();
207 }
208
209 QWebPage *WebPage::createWindow(QWebPage::WebWindowType)
210 {
211     return m_drt->createWindow();
212 }
213
214 void WebPage::javaScriptAlert(QWebFrame*, const QString& message)
215 {
216     if (!isTextOutputEnabled())
217         return;
218
219     fprintf(stdout, "ALERT: %s\n", message.toUtf8().constData());
220 }
221
222 void WebPage::requestPermission(QWebFrame* frame, QWebPage::Feature feature)
223 {
224     switch (feature) {
225     case Notifications:
226         if (!m_drt->layoutTestController()->ignoreReqestForPermission())
227             setFeaturePermission(frame, feature, PermissionGrantedByUser);
228         break;
229     case Geolocation:
230         if (m_drt->layoutTestController()->isGeolocationPermissionSet())
231             if (m_drt->layoutTestController()->geolocationPermission())
232                 setFeaturePermission(frame, feature, PermissionGrantedByUser);
233             else
234                 setFeaturePermission(frame, feature, PermissionDeniedByUser);
235         else
236             m_pendingGeolocationRequests.append(frame);
237         break;
238     default:
239         break;
240     }
241 }
242
243 void WebPage::cancelPermission(QWebFrame* frame, QWebPage::Feature feature)
244 {
245     switch (feature) {
246     case Geolocation:
247         m_pendingGeolocationRequests.removeOne(frame);
248         break;
249     default:
250         break;
251     }
252 }
253
254 void WebPage::permissionSet(QWebPage::Feature feature)
255 {
256     switch (feature) {
257     case Geolocation:
258         {
259         Q_ASSERT(m_drt->layoutTestController()->isGeolocationPermissionSet());
260         foreach (QWebFrame* frame, m_pendingGeolocationRequests)
261             if (m_drt->layoutTestController()->geolocationPermission())
262                 setFeaturePermission(frame, feature, PermissionGrantedByUser);
263             else
264                 setFeaturePermission(frame, feature, PermissionDeniedByUser);
265
266         m_pendingGeolocationRequests.clear();
267         break;
268         }
269     default:
270         break;
271     }
272 }
273
274 static QString urlSuitableForTestResult(const QString& url)
275 {
276     if (url.isEmpty() || !url.startsWith(QLatin1String("file://")))
277         return url;
278
279     return QFileInfo(url).fileName();
280 }
281
282 void WebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString&)
283 {
284     if (!isTextOutputEnabled())
285         return;
286
287     QString newMessage;
288     if (!message.isEmpty()) {
289         newMessage = message;
290
291         size_t fileProtocol = newMessage.indexOf(QLatin1String("file://"));
292         if (fileProtocol != -1) {
293             newMessage = newMessage.left(fileProtocol) + urlSuitableForTestResult(newMessage.mid(fileProtocol));
294         }
295     }
296
297     fprintf (stdout, "CONSOLE MESSAGE: line %d: %s\n", lineNumber, newMessage.toUtf8().constData());
298 }
299
300 bool WebPage::javaScriptConfirm(QWebFrame*, const QString& msg)
301 {
302     if (!isTextOutputEnabled())
303         return true;
304
305     fprintf(stdout, "CONFIRM: %s\n", msg.toUtf8().constData());
306     return true;
307 }
308
309 bool WebPage::javaScriptPrompt(QWebFrame*, const QString& msg, const QString& defaultValue, QString* result)
310 {
311     if (!isTextOutputEnabled())
312         return true;
313
314     fprintf(stdout, "PROMPT: %s, default text: %s\n", msg.toUtf8().constData(), defaultValue.toUtf8().constData());
315     *result = defaultValue;
316     return true;
317 }
318
319 bool WebPage::acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest& request, NavigationType type)
320 {
321     if (m_drt->layoutTestController()->waitForPolicy()) {
322         QString url = QString::fromUtf8(request.url().toEncoded());
323         QString typeDescription;
324
325         switch (type) {
326         case NavigationTypeLinkClicked:
327             typeDescription = "link clicked";
328             break;
329         case NavigationTypeFormSubmitted:
330             typeDescription = "form submitted";
331             break;
332         case NavigationTypeBackOrForward:
333             typeDescription = "back/forward";
334             break;
335         case NavigationTypeReload:
336             typeDescription = "reload";
337             break;
338         case NavigationTypeFormResubmitted:
339             typeDescription = "form resubmitted";
340             break;
341         case NavigationTypeOther:
342             typeDescription = "other";
343             break;
344         default:
345             typeDescription = "illegal value";
346         }
347
348         if (isTextOutputEnabled())
349             fprintf(stdout, "Policy delegate: attempt to load %s with navigation type '%s'\n",
350                     url.toUtf8().constData(), typeDescription.toUtf8().constData());
351
352         m_drt->layoutTestController()->notifyDone();
353     }
354     return QWebPage::acceptNavigationRequest(frame, request, type);
355 }
356
357 bool WebPage::supportsExtension(QWebPage::Extension extension) const
358 {
359     if (extension == QWebPage::ErrorPageExtension)
360         return m_drt->layoutTestController()->shouldHandleErrorPages();
361
362     return false;
363 }
364
365 bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output)
366 {
367     const QWebPage::ErrorPageExtensionOption* info = static_cast<const QWebPage::ErrorPageExtensionOption*>(option);
368
369     // Lets handle error pages for the main frame for now.
370     if (info->frame != mainFrame())
371         return false;
372
373     QWebPage::ErrorPageExtensionReturn* errorPage = static_cast<QWebPage::ErrorPageExtensionReturn*>(output);
374
375     errorPage->content = QString("data:text/html,<body/>").toUtf8();
376
377     return true;
378 }
379
380 QObject* WebPage::createPlugin(const QString& classId, const QUrl& url, const QStringList& paramNames, const QStringList& paramValues)
381 {
382     Q_UNUSED(url);
383     Q_UNUSED(paramNames);
384     Q_UNUSED(paramValues);
385 #ifndef QT_NO_UITOOLS
386     QUiLoader loader;
387     return loader.createWidget(classId, view());
388 #else
389     Q_UNUSED(classId);
390     return 0;
391 #endif
392 }
393
394 void WebPage::setViewGeometry(const QRect& rect)
395 {
396     if (WebViewGraphicsBased* v = qobject_cast<WebViewGraphicsBased*>(view()))
397         v->scene()->setSceneRect(QRectF(rect));
398     else if (QWidget *v = view())
399         v->setGeometry(rect);
400 }
401
402 WebViewGraphicsBased::WebViewGraphicsBased(QWidget* parent)
403     : m_item(new QGraphicsWebView)
404 {
405     setScene(new QGraphicsScene(this));
406     scene()->addItem(m_item);
407 }
408
409 DumpRenderTree::DumpRenderTree()
410     : m_dumpPixels(false)
411     , m_stdin(0)
412     , m_enableTextOutput(false)
413     , m_standAloneMode(false)
414     , m_graphicsBased(false)
415     , m_persistentStoragePath(QString(getenv("DUMPRENDERTREE_TEMP")))
416 {
417
418     QByteArray viewMode = getenv("QT_DRT_WEBVIEW_MODE");
419     if (viewMode == "graphics")
420         setGraphicsBased(true);
421
422     DumpRenderTreeSupportQt::overwritePluginDirectories();
423     DumpRenderTreeSupportQt::activeMockDeviceOrientationClient(true);
424     QWebSettings::enablePersistentStorage(m_persistentStoragePath);
425
426     m_networkAccessManager = new NetworkAccessManager(this);
427     // create our primary testing page/view.
428     if (isGraphicsBased()) {
429         WebViewGraphicsBased* view = new WebViewGraphicsBased(0);
430         m_page = new WebPage(view, this);
431         view->setPage(m_page);
432         m_mainView = view;
433     } else {
434         QWebView* view = new QWebView(0);
435         m_page = new WebPage(view, this);
436         view->setPage(m_page);
437         m_mainView = view;
438     }
439     // Use a frame group name for all pages created by DumpRenderTree to allow
440     // testing of cross-page frame lookup.
441     DumpRenderTreeSupportQt::webPageSetGroupName(m_page, "org.webkit.qt.DumpRenderTree");
442
443     m_mainView->setContextMenuPolicy(Qt::NoContextMenu);
444     m_mainView->resize(QSize(LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight));
445
446     // clean up cache by resetting quota.
447     qint64 quota = webPage()->settings()->offlineWebApplicationCacheQuota();
448     webPage()->settings()->setOfflineWebApplicationCacheQuota(quota);
449
450     // create our controllers. This has to be done before connectFrame,
451     // as it exports there to the JavaScript DOM window.
452     m_controller = new LayoutTestController(this);
453     connect(m_controller, SIGNAL(showPage()), this, SLOT(showPage()));
454     connect(m_controller, SIGNAL(hidePage()), this, SLOT(hidePage()));
455
456     // async geolocation permission set by controller
457     connect(m_controller, SIGNAL(geolocationPermissionSet()), this, SLOT(geolocationPermissionSet()));
458
459     connect(m_controller, SIGNAL(done()), this, SLOT(dump()));
460     m_eventSender = new EventSender(m_page);
461     m_textInputController = new TextInputController(m_page);
462     m_plainTextController = new PlainTextController(m_page);
463     m_gcController = new GCController(m_page);
464
465     // now connect our different signals
466     connect(m_page, SIGNAL(frameCreated(QWebFrame *)),
467             this, SLOT(connectFrame(QWebFrame *)));
468     connectFrame(m_page->mainFrame());
469
470     connect(m_page, SIGNAL(loadFinished(bool)),
471             m_controller, SLOT(maybeDump(bool)));
472     // We need to connect to loadStarted() because notifyDone should only
473     // dump results itself when the last page loaded in the test has finished loading.
474     connect(m_page, SIGNAL(loadStarted()),
475             m_controller, SLOT(resetLoadFinished()));
476     connect(m_page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
477     connect(m_page, SIGNAL(printRequested(QWebFrame*)), this, SLOT(dryRunPrint(QWebFrame*)));
478
479     connect(m_page->mainFrame(), SIGNAL(titleChanged(const QString&)),
480             SLOT(titleChanged(const QString&)));
481     connect(m_page, SIGNAL(databaseQuotaExceeded(QWebFrame*,QString)),
482             this, SLOT(dumpDatabaseQuota(QWebFrame*,QString)));
483     connect(m_page, SIGNAL(applicationCacheQuotaExceeded(QWebSecurityOrigin *, quint64)),
484             this, SLOT(dumpApplicationCacheQuota(QWebSecurityOrigin *, quint64)));
485     connect(m_page, SIGNAL(statusBarMessage(const QString&)),
486             this, SLOT(statusBarMessage(const QString&)));
487
488     QObject::connect(this, SIGNAL(quit()), qApp, SLOT(quit()), Qt::QueuedConnection);
489
490     DumpRenderTreeSupportQt::setDumpRenderTreeModeEnabled(true);
491     QFocusEvent event(QEvent::FocusIn, Qt::ActiveWindowFocusReason);
492     QApplication::sendEvent(m_mainView, &event);
493 }
494
495 DumpRenderTree::~DumpRenderTree()
496 {
497     delete m_mainView;
498     delete m_stdin;
499     DumpRenderTreeSupportQt::removeMockDeviceOrientation();
500 }
501
502 static void clearHistory(QWebPage* page)
503 {
504     // QWebHistory::clear() leaves current page, so remove it as well by setting
505     // max item count to 0, and then setting it back to it's original value.
506
507     QWebHistory* history = page->history();
508     int itemCount = history->maximumItemCount();
509
510     history->clear();
511     history->setMaximumItemCount(0);
512     history->setMaximumItemCount(itemCount);
513 }
514
515 void DumpRenderTree::dryRunPrint(QWebFrame* frame)
516 {
517 #ifndef QT_NO_PRINTER
518     NullPrinter printer;
519     frame->print(&printer);
520 #endif
521 }
522
523 void DumpRenderTree::resetToConsistentStateBeforeTesting(const QUrl& url)
524 {
525     // reset so that any current loads are stopped
526     // NOTE: that this has to be done before the layoutTestController is
527     // reset or we get timeouts for some tests.
528     m_page->blockSignals(true);
529     m_page->triggerAction(QWebPage::Stop);
530     m_page->blockSignals(false);
531
532     // reset the layoutTestController at this point, so that we under no
533     // circumstance dump (stop the waitUntilDone timer) during the reset
534     // of the DRT.
535     m_controller->reset();
536
537     // reset mouse clicks counter
538     m_eventSender->resetClickCount();
539
540     closeRemainingWindows();
541
542     m_page->resetSettings();
543 #ifndef QT_NO_UNDOSTACK
544     m_page->undoStack()->clear();
545 #endif
546     m_page->mainFrame()->setZoomFactor(1.0);
547     clearHistory(m_page);
548     DumpRenderTreeSupportQt::clearFrameName(m_page->mainFrame());
549
550     m_page->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded);
551     m_page->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded);
552
553     if (url.scheme() == "http" || url.scheme() == "https") {
554         // credentials may exist from previous tests.
555         m_page->setNetworkAccessManager(0);
556         delete m_networkAccessManager;
557         m_networkAccessManager = new NetworkAccessManager(this);
558         m_page->setNetworkAccessManager(m_networkAccessManager);
559     }
560
561     WorkQueue::shared()->clear();
562     WorkQueue::shared()->setFrozen(false);
563
564     DumpRenderTreeSupportQt::resetOriginAccessWhiteLists();
565
566     // Qt defaults to Windows editing behavior.
567     DumpRenderTreeSupportQt::setEditingBehavior(m_page, "win");
568
569     QLocale::setDefault(QLocale::c());
570
571     layoutTestController()->setDeveloperExtrasEnabled(true);
572 #ifndef Q_OS_WINCE
573     setlocale(LC_ALL, "");
574 #endif
575 }
576
577 static bool isGlobalHistoryTest(const QUrl& url)
578 {
579     if (url.path().contains("globalhistory/"))
580         return true;
581     return false;
582 }
583
584 static bool isWebInspectorTest(const QUrl& url)
585 {
586     if (url.path().contains("inspector/"))
587         return true;
588     return false;
589 }
590
591 void DumpRenderTree::open(const QUrl& url)
592 {
593     DumpRenderTreeSupportQt::dumpResourceLoadCallbacksPath(QFileInfo(url.toString()).path());
594     resetToConsistentStateBeforeTesting(url);
595
596     if (isWebInspectorTest(m_page->mainFrame()->url()))
597         layoutTestController()->closeWebInspector();
598
599     if (isWebInspectorTest(url))
600         layoutTestController()->showWebInspector();
601
602     if (isGlobalHistoryTest(url))
603         layoutTestController()->dumpHistoryCallbacks();
604
605     // W3C SVG tests expect to be 480x360
606     bool isW3CTest = url.toString().contains("svg/W3C-SVG-1.1");
607     int width = isW3CTest ? 480 : LayoutTestController::maxViewWidth;
608     int height = isW3CTest ? 360 : LayoutTestController::maxViewHeight;
609     m_mainView->resize(QSize(width, height));
610     m_page->setPreferredContentsSize(QSize());
611     m_page->setViewportSize(QSize(width, height));
612
613     QFocusEvent ev(QEvent::FocusIn);
614     m_page->event(&ev);
615
616     QWebSettings::clearMemoryCaches();
617 #if !(defined(Q_OS_SYMBIAN) && QT_VERSION <= QT_VERSION_CHECK(4, 6, 2))
618     QFontDatabase::removeAllApplicationFonts();
619 #endif
620 #if defined(Q_WS_X11)
621     initializeFonts();
622 #endif
623
624     DumpRenderTreeSupportQt::dumpFrameLoader(url.toString().contains("loading/"));
625     setTextOutputEnabled(true);
626     m_page->mainFrame()->load(url);
627 }
628
629 void DumpRenderTree::readLine()
630 {
631     if (!m_stdin) {
632         m_stdin = new QFile;
633         m_stdin->open(stdin, QFile::ReadOnly);
634
635         if (!m_stdin->isReadable()) {
636             emit quit();
637             return;
638         }
639     }
640
641     QByteArray line = m_stdin->readLine().trimmed();
642
643     if (line.isEmpty()) {
644         emit quit();
645         return;
646     }
647
648     processLine(QString::fromLocal8Bit(line.constData(), line.length()));
649 }
650
651 void DumpRenderTree::processArgsLine(const QStringList &args)
652 {
653     setStandAloneMode(true);
654
655     for (int i = 1; i < args.size(); ++i)
656         if (!args.at(i).startsWith('-'))
657             m_standAloneModeTestList.append(args[i]);
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
670     processLine(m_standAloneModeTestList.first());
671     m_standAloneModeTestList.removeFirst();
672
673     connect(this, SIGNAL(ready()), this, SLOT(loadNextTestInStandAloneMode()));
674 }
675
676 void DumpRenderTree::loadNextTestInStandAloneMode()
677 {
678     if (m_standAloneModeTestList.isEmpty()) {
679         emit quit();
680         return;
681     }
682
683     processLine(m_standAloneModeTestList.first());
684     m_standAloneModeTestList.removeFirst();
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     frame->addToJavaScriptWindowObject(QLatin1String("plainText"), m_plainTextController);
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().toEncoded();
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     // FIXME: All other ports don't dump pixels, if generatePixelResults is false.
949     if (m_dumpPixels) {
950         QImage image(m_page->viewportSize(), QImage::Format_ARGB32);
951         image.fill(Qt::white);
952         QPainter painter(&image);
953         mainFrame->render(&painter);
954         painter.end();
955
956         QCryptographicHash hash(QCryptographicHash::Md5);
957         for (int row = 0; row < image.height(); ++row)
958             hash.addData(reinterpret_cast<const char*>(image.scanLine(row)), image.width() * 4);
959         QString actualHash = hash.result().toHex();
960
961         fprintf(stdout, "\nActualHash: %s\n", qPrintable(actualHash));
962
963         bool dumpImage = true;
964
965         if (!m_expectedHash.isEmpty()) {
966             Q_ASSERT(m_expectedHash.length() == 32);
967             fprintf(stdout, "\nExpectedHash: %s\n", qPrintable(m_expectedHash));
968
969             if (m_expectedHash == actualHash)
970                 dumpImage = false;
971         }
972
973         if (dumpImage) {
974             QBuffer buffer;
975             buffer.open(QBuffer::WriteOnly);
976             image.save(&buffer, "PNG");
977             buffer.close();
978             const QByteArray &data = buffer.data();
979
980             printf("Content-Type: %s\n", "image/png");
981             printf("Content-Length: %lu\n", static_cast<unsigned long>(data.length()));
982
983             const quint32 bytesToWriteInOneChunk = 1 << 15;
984             quint32 dataRemainingToWrite = data.length();
985             const char *ptr = data.data();
986             while (dataRemainingToWrite) {
987                 quint32 bytesToWriteInThisChunk = qMin(dataRemainingToWrite, bytesToWriteInOneChunk);
988                 quint32 bytesWritten = fwrite(ptr, 1, bytesToWriteInThisChunk, stdout);
989                 if (bytesWritten != bytesToWriteInThisChunk)
990                     break;
991                 dataRemainingToWrite -= bytesWritten;
992                 ptr += bytesWritten;
993             }
994         }
995
996         fflush(stdout);
997     }
998
999     puts("#EOF");   // terminate the (possibly empty) pixels block
1000
1001     fflush(stdout);
1002     fflush(stderr);
1003
1004      emit ready();
1005 }
1006
1007 void DumpRenderTree::titleChanged(const QString &s)
1008 {
1009     if (m_controller->shouldDumpTitleChanges())
1010         printf("TITLE CHANGED: %s\n", s.toUtf8().data());
1011 }
1012
1013 void DumpRenderTree::connectFrame(QWebFrame *frame)
1014 {
1015     connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(initJSObjects()));
1016     connect(frame, SIGNAL(provisionalLoad()),
1017             layoutTestController(), SLOT(provisionalLoad()));
1018 }
1019
1020 void DumpRenderTree::dumpDatabaseQuota(QWebFrame* frame, const QString& dbName)
1021 {
1022     if (!m_controller->shouldDumpDatabaseCallbacks())
1023         return;
1024     QWebSecurityOrigin origin = frame->securityOrigin();
1025     printf("UI DELEGATE DATABASE CALLBACK: exceededDatabaseQuotaForSecurityOrigin:{%s, %s, %i} database:%s\n",
1026            origin.scheme().toUtf8().data(),
1027            origin.host().toUtf8().data(),
1028            origin.port(),
1029            dbName.toUtf8().data());
1030     origin.setDatabaseQuota(5 * 1024 * 1024);
1031 }
1032
1033 void DumpRenderTree::dumpApplicationCacheQuota(QWebSecurityOrigin* origin, quint64 defaultOriginQuota)
1034 {
1035     if (!m_controller->shouldDumpApplicationCacheDelegateCallbacks())
1036         return;
1037
1038     printf("UI DELEGATE APPLICATION CACHE CALLBACK: exceededApplicationCacheOriginQuotaForSecurityOrigin:{%s, %s, %i}\n",
1039            origin->scheme().toUtf8().data(),
1040            origin->host().toUtf8().data(),
1041            origin->port()
1042            );
1043     origin->setApplicationCacheQuota(defaultOriginQuota);
1044 }
1045
1046 void DumpRenderTree::statusBarMessage(const QString& message)
1047 {
1048     if (!m_controller->shouldDumpStatusCallbacks())
1049         return;
1050
1051     printf("UI DELEGATE STATUS CALLBACK: setStatusText:%s\n", message.toUtf8().constData());
1052 }
1053
1054 QWebPage *DumpRenderTree::createWindow()
1055 {
1056     if (!m_controller->canOpenWindows())
1057         return 0;
1058
1059     // Create a dummy container object to track the page in DRT.
1060     // QObject is used instead of QWidget to prevent DRT from
1061     // showing the main view when deleting the container.
1062
1063     QObject* container = new QObject(m_mainView);
1064     // create a QWebPage we want to return
1065     QWebPage* page = static_cast<QWebPage*>(new WebPage(container, this));
1066     // gets cleaned up in closeRemainingWindows()
1067     windows.append(container);
1068
1069     // connect the needed signals to the page
1070     connect(page, SIGNAL(frameCreated(QWebFrame*)), this, SLOT(connectFrame(QWebFrame*)));
1071     connectFrame(page->mainFrame());
1072     connect(page, SIGNAL(loadFinished(bool)), m_controller, SLOT(maybeDump(bool)));
1073     connect(page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
1074
1075     // Use a frame group name for all pages created by DumpRenderTree to allow
1076     // testing of cross-page frame lookup.
1077     DumpRenderTreeSupportQt::webPageSetGroupName(page, "org.webkit.qt.DumpRenderTree");
1078
1079     return page;
1080 }
1081
1082 void DumpRenderTree::windowCloseRequested()
1083 {
1084     QWebPage* page = qobject_cast<QWebPage*>(sender());
1085     QObject* container = page->parent();
1086     windows.removeAll(container);
1087     container->deleteLater();
1088 }
1089
1090 int DumpRenderTree::windowCount() const
1091 {
1092 // include the main view in the count
1093     return windows.count() + 1;
1094 }
1095
1096 void DumpRenderTree::geolocationPermissionSet() 
1097 {
1098     m_page->permissionSet(QWebPage::Geolocation);
1099 }
1100
1101 void DumpRenderTree::switchFocus(bool focused)
1102 {
1103     QFocusEvent event((focused) ? QEvent::FocusIn : QEvent::FocusOut, Qt::ActiveWindowFocusReason);
1104     if (!isGraphicsBased())
1105         QApplication::sendEvent(m_mainView, &event);
1106     else {
1107         if (WebViewGraphicsBased* view = qobject_cast<WebViewGraphicsBased*>(m_mainView))
1108             view->scene()->sendEvent(view->graphicsView(), &event);
1109     }
1110
1111 }
1112
1113 #if defined(Q_WS_X11)
1114 void DumpRenderTree::initializeFonts()
1115 {
1116     static int numFonts = -1;
1117
1118     // Some test cases may add or remove application fonts (via @font-face).
1119     // Make sure to re-initialize the font set if necessary.
1120     FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication);
1121     if (appFontSet && numFonts >= 0 && appFontSet->nfont == numFonts)
1122         return;
1123
1124     QByteArray fontDir = getenv("WEBKIT_TESTFONTS");
1125     if (fontDir.isEmpty() || !QDir(fontDir).exists()) {
1126         fprintf(stderr,
1127                 "\n\n"
1128                 "----------------------------------------------------------------------\n"
1129                 "WEBKIT_TESTFONTS environment variable is not set correctly.\n"
1130                 "This variable has to point to the directory containing the fonts\n"
1131                 "you can clone from git://gitorious.org/qtwebkit/testfonts.git\n"
1132                 "----------------------------------------------------------------------\n"
1133                );
1134         exit(1);
1135     }
1136     char currentPath[PATH_MAX+1];
1137     if (!getcwd(currentPath, PATH_MAX))
1138         qFatal("Couldn't get current working directory");
1139     QByteArray configFile = currentPath;
1140     FcConfig *config = FcConfigCreate();
1141     configFile += "/Tools/DumpRenderTree/qt/fonts.conf";
1142     if (!FcConfigParseAndLoad (config, (FcChar8*) configFile.data(), true))
1143         qFatal("Couldn't load font configuration file");
1144     if (!FcConfigAppFontAddDir (config, (FcChar8*) fontDir.data()))
1145         qFatal("Couldn't add font dir!");
1146     FcConfigSetCurrent(config);
1147
1148     appFontSet = FcConfigGetFonts(config, FcSetApplication);
1149     numFonts = appFontSet->nfont;
1150 }
1151 #endif
1152
1153 }