OSDN Git Service

10a6af08fe960f79d69978c4b6f44d77c284743b
[android-x86/external-webkit.git] / WebKitTools / 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 "../../../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, 5);
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
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(statusBarMessage(const QString&)),
484             this, SLOT(statusBarMessage(const QString&)));
485
486     QObject::connect(this, SIGNAL(quit()), qApp, SLOT(quit()), Qt::QueuedConnection);
487
488     DumpRenderTreeSupportQt::setDumpRenderTreeModeEnabled(true);
489     QFocusEvent event(QEvent::FocusIn, Qt::ActiveWindowFocusReason);
490     QApplication::sendEvent(m_mainView, &event);
491 }
492
493 DumpRenderTree::~DumpRenderTree()
494 {
495     delete m_mainView;
496     delete m_stdin;
497 }
498
499 static void clearHistory(QWebPage* page)
500 {
501     // QWebHistory::clear() leaves current page, so remove it as well by setting
502     // max item count to 0, and then setting it back to it's original value.
503
504     QWebHistory* history = page->history();
505     int itemCount = history->maximumItemCount();
506
507     history->clear();
508     history->setMaximumItemCount(0);
509     history->setMaximumItemCount(itemCount);
510 }
511
512 void DumpRenderTree::dryRunPrint(QWebFrame* frame)
513 {
514 #ifndef QT_NO_PRINTER
515     NullPrinter printer;
516     frame->print(&printer);
517 #endif
518 }
519
520 void DumpRenderTree::resetToConsistentStateBeforeTesting()
521 {
522     // reset so that any current loads are stopped
523     // NOTE: that this has to be done before the layoutTestController is
524     // reset or we get timeouts for some tests.
525     m_page->blockSignals(true);
526     m_page->triggerAction(QWebPage::Stop);
527     m_page->blockSignals(false);
528
529     // reset the layoutTestController at this point, so that we under no
530     // circumstance dump (stop the waitUntilDone timer) during the reset
531     // of the DRT.
532     m_controller->reset();
533
534     // reset mouse clicks counter
535     m_eventSender->resetClickCount();
536
537     closeRemainingWindows();
538
539     m_page->resetSettings();
540     m_page->undoStack()->clear();
541     m_page->mainFrame()->setZoomFactor(1.0);
542     clearHistory(m_page);
543     DumpRenderTreeSupportQt::clearFrameName(m_page->mainFrame());
544
545     m_page->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded);
546     m_page->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded);
547
548     WorkQueue::shared()->clear();
549     WorkQueue::shared()->setFrozen(false);
550
551     DumpRenderTreeSupportQt::resetOriginAccessWhiteLists();
552
553     // Qt defaults to Windows editing behavior.
554     DumpRenderTreeSupportQt::setEditingBehavior(m_page, "win");
555
556     QLocale::setDefault(QLocale::c());
557
558 #ifndef Q_OS_WINCE
559     setlocale(LC_ALL, "");
560 #endif
561 }
562
563 static bool isGlobalHistoryTest(const QUrl& url)
564 {
565     if (url.path().contains("globalhistory/"))
566         return true;
567     return false;
568 }
569
570 static bool isWebInspectorTest(const QUrl& url)
571 {
572     if (url.path().contains("inspector/"))
573         return true;
574     return false;
575 }
576
577 static bool shouldEnableDeveloperExtras(const QUrl& url)
578 {
579     return true;
580 }
581
582 void DumpRenderTree::open(const QUrl& url)
583 {
584     DumpRenderTreeSupportQt::dumpResourceLoadCallbacksPath(QFileInfo(url.toString()).path());
585     resetToConsistentStateBeforeTesting();
586
587     if (shouldEnableDeveloperExtras(m_page->mainFrame()->url())) {
588         layoutTestController()->closeWebInspector();
589         layoutTestController()->setDeveloperExtrasEnabled(false);
590     }
591
592     if (shouldEnableDeveloperExtras(url)) {
593         layoutTestController()->setDeveloperExtrasEnabled(true);
594         if (isWebInspectorTest(url))
595             layoutTestController()->showWebInspector();
596     }
597
598     if (isGlobalHistoryTest(url))
599         layoutTestController()->dumpHistoryCallbacks();
600
601     // W3C SVG tests expect to be 480x360
602     bool isW3CTest = url.toString().contains("svg/W3C-SVG-1.1");
603     int width = isW3CTest ? 480 : LayoutTestController::maxViewWidth;
604     int height = isW3CTest ? 360 : LayoutTestController::maxViewHeight;
605     m_mainView->resize(QSize(width, height));
606     m_page->setPreferredContentsSize(QSize());
607     m_page->setViewportSize(QSize(width, height));
608
609     QFocusEvent ev(QEvent::FocusIn);
610     m_page->event(&ev);
611
612     QWebSettings::clearMemoryCaches();
613 #if !(defined(Q_OS_SYMBIAN) && QT_VERSION <= QT_VERSION_CHECK(4, 6, 2))
614     QFontDatabase::removeAllApplicationFonts();
615 #endif
616 #if defined(Q_WS_X11)
617     initializeFonts();
618 #endif
619
620     DumpRenderTreeSupportQt::dumpFrameLoader(url.toString().contains("loading/"));
621     setTextOutputEnabled(true);
622     m_page->mainFrame()->load(url);
623 }
624
625 void DumpRenderTree::readLine()
626 {
627     if (!m_stdin) {
628         m_stdin = new QFile;
629         m_stdin->open(stdin, QFile::ReadOnly);
630
631         if (!m_stdin->isReadable()) {
632             emit quit();
633             return;
634         }
635     }
636
637     QByteArray line = m_stdin->readLine().trimmed();
638
639     if (line.isEmpty()) {
640         emit quit();
641         return;
642     }
643
644     processLine(QString::fromLocal8Bit(line.constData(), line.length()));
645 }
646
647 void DumpRenderTree::processArgsLine(const QStringList &args)
648 {
649     setStandAloneMode(true);
650
651     for (int i = 1; i < args.size(); ++i)
652         if (!args.at(i).startsWith('-'))
653             m_standAloneModeTestList.append(args[i]);
654
655     QFileInfo firstEntry(m_standAloneModeTestList.first());
656     if (firstEntry.isDir()) {
657         QDir folderEntry(m_standAloneModeTestList.first());
658         QStringList supportedExt;
659         // Check for all supported extensions (from Scripts/webkitpy/layout_tests/layout_package/test_files.py).
660         supportedExt << "*.html" << "*.shtml" << "*.xml" << "*.xhtml" << "*.xhtmlmp" << "*.pl" << "*.php" << "*.svg";
661         m_standAloneModeTestList = folderEntry.entryList(supportedExt, QDir::Files);
662         for (int i = 0; i < m_standAloneModeTestList.size(); ++i)
663             m_standAloneModeTestList[i] = folderEntry.absoluteFilePath(m_standAloneModeTestList[i]);
664     }
665
666     processLine(m_standAloneModeTestList.first());
667     m_standAloneModeTestList.removeFirst();
668
669     connect(this, SIGNAL(ready()), this, SLOT(loadNextTestInStandAloneMode()));
670 }
671
672 void DumpRenderTree::loadNextTestInStandAloneMode()
673 {
674     if (m_standAloneModeTestList.isEmpty()) {
675         emit quit();
676         return;
677     }
678
679     processLine(m_standAloneModeTestList.first());
680     m_standAloneModeTestList.removeFirst();
681 }
682
683 void DumpRenderTree::processLine(const QString &input)
684 {
685     QString line = input;
686
687     m_expectedHash = QString();
688     if (m_dumpPixels) {
689         // single quote marks the pixel dump hash
690         int i = line.indexOf('\'');
691         if (i > -1) {
692             m_expectedHash = line.mid(i + 1, line.length());
693             line.remove(i, line.length());
694         }
695     }
696
697     if (line.startsWith(QLatin1String("http:"))
698             || line.startsWith(QLatin1String("https:"))
699             || line.startsWith(QLatin1String("file:"))) {
700         open(QUrl(line));
701     } else {
702         QFileInfo fi(line);
703
704         if (!fi.exists()) {
705             QDir currentDir = QDir::currentPath();
706
707             // Try to be smart about where the test is located
708             if (currentDir.dirName() == QLatin1String("LayoutTests"))
709                 fi = QFileInfo(currentDir, line.replace(QRegExp(".*?LayoutTests/(.*)"), "\\1"));
710             else if (!line.contains(QLatin1String("LayoutTests")))
711                 fi = QFileInfo(currentDir, line.prepend(QLatin1String("LayoutTests/")));
712
713             if (!fi.exists()) {
714                 emit ready();
715                 return;
716             }
717         }
718
719         open(QUrl::fromLocalFile(fi.absoluteFilePath()));
720     }
721
722     fflush(stdout);
723 }
724
725 void DumpRenderTree::setDumpPixels(bool dump)
726 {
727     m_dumpPixels = dump;
728 }
729
730 void DumpRenderTree::closeRemainingWindows()
731 {
732     foreach (QObject* widget, windows)
733         delete widget;
734     windows.clear();
735 }
736
737 void DumpRenderTree::initJSObjects()
738 {
739     QWebFrame *frame = qobject_cast<QWebFrame*>(sender());
740     Q_ASSERT(frame);
741     frame->addToJavaScriptWindowObject(QLatin1String("layoutTestController"), m_controller);
742     frame->addToJavaScriptWindowObject(QLatin1String("eventSender"), m_eventSender);
743     frame->addToJavaScriptWindowObject(QLatin1String("textInputController"), m_textInputController);
744     frame->addToJavaScriptWindowObject(QLatin1String("GCController"), m_gcController);
745     frame->addToJavaScriptWindowObject(QLatin1String("plainText"), m_plainTextController);
746 }
747
748 void DumpRenderTree::showPage()
749 {
750     m_mainView->show();
751     // we need a paint event but cannot process all the events
752     QPixmap pixmap(m_mainView->size());
753     m_mainView->render(&pixmap);
754 }
755
756 void DumpRenderTree::hidePage()
757 {
758     m_mainView->hide();
759 }
760
761 QString DumpRenderTree::dumpFrameScrollPosition(QWebFrame* frame)
762 {
763     if (!frame || !DumpRenderTreeSupportQt::hasDocumentElement(frame))
764         return QString();
765
766     QString result;
767     QPoint pos = frame->scrollPosition();
768     if (pos.x() > 0 || pos.y() > 0) {
769         QWebFrame* parent = qobject_cast<QWebFrame *>(frame->parent());
770         if (parent)
771             result.append(QString("frame '%1' ").arg(frame->title()));
772         result.append(QString("scrolled to %1,%2\n").arg(pos.x()).arg(pos.y()));
773     }
774
775     if (m_controller->shouldDumpChildFrameScrollPositions()) {
776         QList<QWebFrame*> children = frame->childFrames();
777         for (int i = 0; i < children.size(); ++i)
778             result += dumpFrameScrollPosition(children.at(i));
779     }
780     return result;
781 }
782
783 QString DumpRenderTree::dumpFramesAsText(QWebFrame* frame)
784 {
785     if (!frame || !DumpRenderTreeSupportQt::hasDocumentElement(frame))
786         return QString();
787
788     QString result;
789     QWebFrame* parent = qobject_cast<QWebFrame*>(frame->parent());
790     if (parent) {
791         result.append(QLatin1String("\n--------\nFrame: '"));
792         result.append(frame->frameName());
793         result.append(QLatin1String("'\n--------\n"));
794     }
795
796     QString innerText = frame->toPlainText();
797     result.append(innerText);
798     result.append(QLatin1String("\n"));
799
800     if (m_controller->shouldDumpChildrenAsText()) {
801         QList<QWebFrame *> children = frame->childFrames();
802         for (int i = 0; i < children.size(); ++i)
803             result += dumpFramesAsText(children.at(i));
804     }
805
806     return result;
807 }
808
809 static QString dumpHistoryItem(const QWebHistoryItem& item, int indent, bool current)
810 {
811     QString result;
812
813     int start = 0;
814     if (current) {
815         result.append(QLatin1String("curr->"));
816         start = 6;
817     }
818     for (int i = start; i < indent; i++)
819         result.append(' ');
820
821     QString url = item.url().toEncoded();
822     if (url.contains("file://")) {
823         static QString layoutTestsString("/LayoutTests/");
824         static QString fileTestString("(file test):");
825
826         QString res = url.mid(url.indexOf(layoutTestsString) + layoutTestsString.length());
827         if (res.isEmpty())
828             return result;
829
830         result.append(fileTestString);
831         result.append(res);
832     } else {
833         result.append(url);
834     }
835
836     QString target = DumpRenderTreeSupportQt::historyItemTarget(item);
837     if (!target.isEmpty())
838         result.append(QString(QLatin1String(" (in frame \"%1\")")).arg(target));
839
840     if (DumpRenderTreeSupportQt::isTargetItem(item))
841         result.append(QLatin1String("  **nav target**"));
842     result.append(QLatin1String("\n"));
843
844     QMap<QString, QWebHistoryItem> children = DumpRenderTreeSupportQt::getChildHistoryItems(item);
845     foreach (QWebHistoryItem item, children)
846         result += dumpHistoryItem(item, 12, false);
847
848     return result;
849 }
850
851 QString DumpRenderTree::dumpBackForwardList(QWebPage* page)
852 {
853     QWebHistory* history = page->history();
854
855     QString result;
856     result.append(QLatin1String("\n============== Back Forward List ==============\n"));
857
858     // FORMAT:
859     // "        (file test):fast/loader/resources/click-fragment-link.html  **nav target**"
860     // "curr->  (file test):fast/loader/resources/click-fragment-link.html#testfragment  **nav target**"
861
862     int maxItems = history->maximumItemCount();
863
864     foreach (const QWebHistoryItem item, history->backItems(maxItems)) {
865         if (!item.isValid())
866             continue;
867         result.append(dumpHistoryItem(item, 8, false));
868     }
869
870     QWebHistoryItem item = history->currentItem();
871     if (item.isValid())
872         result.append(dumpHistoryItem(item, 8, true));
873
874     foreach (const QWebHistoryItem item, history->forwardItems(maxItems)) {
875         if (!item.isValid())
876             continue;
877         result.append(dumpHistoryItem(item, 8, false));
878     }
879
880     result.append(QLatin1String("===============================================\n"));
881     return result;
882 }
883
884 static const char *methodNameStringForFailedTest(LayoutTestController *controller)
885 {
886     const char *errorMessage;
887     if (controller->shouldDumpAsText())
888         errorMessage = "[documentElement innerText]";
889     // FIXME: Add when we have support
890     //else if (controller->dumpDOMAsWebArchive())
891     //    errorMessage = "[[mainFrame DOMDocument] webArchive]";
892     //else if (controller->dumpSourceAsWebArchive())
893     //    errorMessage = "[[mainFrame dataSource] webArchive]";
894     else
895         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
896
897     return errorMessage;
898 }
899
900 void DumpRenderTree::dump()
901 {
902     // Prevent any further frame load or resource load callbacks from appearing after we dump the result.
903     DumpRenderTreeSupportQt::dumpFrameLoader(false);
904     DumpRenderTreeSupportQt::dumpResourceLoadCallbacks(false);
905
906     QWebFrame *mainFrame = m_page->mainFrame();
907
908     if (isStandAloneMode()) {
909         QString markup = mainFrame->toHtml();
910         fprintf(stdout, "Source:\n\n%s\n", markup.toUtf8().constData());
911     }
912
913     // Dump render text...
914     QString resultString;
915     if (m_controller->shouldDumpAsText())
916         resultString = dumpFramesAsText(mainFrame);
917     else {
918         resultString = mainFrame->renderTreeDump();
919         resultString += dumpFrameScrollPosition(mainFrame);
920     }
921     if (!resultString.isEmpty()) {
922         fprintf(stdout, "Content-Type: text/plain\n");
923         fprintf(stdout, "%s", resultString.toUtf8().constData());
924
925         if (m_controller->shouldDumpBackForwardList()) {
926             fprintf(stdout, "%s", dumpBackForwardList(webPage()).toUtf8().constData());
927             foreach (QObject* widget, windows) {
928                 QWebPage* page = qobject_cast<QWebPage*>(widget->findChild<QWebPage*>());
929                 fprintf(stdout, "%s", dumpBackForwardList(page).toUtf8().constData());
930             }
931         }
932
933     } else
934         printf("ERROR: nil result from %s", methodNameStringForFailedTest(m_controller));
935
936     // signal end of text block
937     fputs("#EOF\n", stdout);
938     fputs("#EOF\n", stderr);
939
940     // FIXME: All other ports don't dump pixels, if generatePixelResults is false.
941     if (m_dumpPixels) {
942         QImage image(m_page->viewportSize(), QImage::Format_ARGB32);
943         image.fill(Qt::white);
944         QPainter painter(&image);
945         mainFrame->render(&painter);
946         painter.end();
947
948         QCryptographicHash hash(QCryptographicHash::Md5);
949         for (int row = 0; row < image.height(); ++row)
950             hash.addData(reinterpret_cast<const char*>(image.scanLine(row)), image.width() * 4);
951         QString actualHash = hash.result().toHex();
952
953         fprintf(stdout, "\nActualHash: %s\n", qPrintable(actualHash));
954
955         bool dumpImage = true;
956
957         if (!m_expectedHash.isEmpty()) {
958             Q_ASSERT(m_expectedHash.length() == 32);
959             fprintf(stdout, "\nExpectedHash: %s\n", qPrintable(m_expectedHash));
960
961             if (m_expectedHash == actualHash)
962                 dumpImage = false;
963         }
964
965         if (dumpImage) {
966             QBuffer buffer;
967             buffer.open(QBuffer::WriteOnly);
968             image.save(&buffer, "PNG");
969             buffer.close();
970             const QByteArray &data = buffer.data();
971
972             printf("Content-Type: %s\n", "image/png");
973             printf("Content-Length: %lu\n", static_cast<unsigned long>(data.length()));
974
975             const quint32 bytesToWriteInOneChunk = 1 << 15;
976             quint32 dataRemainingToWrite = data.length();
977             const char *ptr = data.data();
978             while (dataRemainingToWrite) {
979                 quint32 bytesToWriteInThisChunk = qMin(dataRemainingToWrite, bytesToWriteInOneChunk);
980                 quint32 bytesWritten = fwrite(ptr, 1, bytesToWriteInThisChunk, stdout);
981                 if (bytesWritten != bytesToWriteInThisChunk)
982                     break;
983                 dataRemainingToWrite -= bytesWritten;
984                 ptr += bytesWritten;
985             }
986         }
987
988         fflush(stdout);
989     }
990
991     puts("#EOF");   // terminate the (possibly empty) pixels block
992
993     fflush(stdout);
994     fflush(stderr);
995
996      emit ready();
997 }
998
999 void DumpRenderTree::titleChanged(const QString &s)
1000 {
1001     if (m_controller->shouldDumpTitleChanges())
1002         printf("TITLE CHANGED: %s\n", s.toUtf8().data());
1003 }
1004
1005 void DumpRenderTree::connectFrame(QWebFrame *frame)
1006 {
1007     connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(initJSObjects()));
1008     connect(frame, SIGNAL(provisionalLoad()),
1009             layoutTestController(), SLOT(provisionalLoad()));
1010 }
1011
1012 void DumpRenderTree::dumpDatabaseQuota(QWebFrame* frame, const QString& dbName)
1013 {
1014     if (!m_controller->shouldDumpDatabaseCallbacks())
1015         return;
1016     QWebSecurityOrigin origin = frame->securityOrigin();
1017     printf("UI DELEGATE DATABASE CALLBACK: exceededDatabaseQuotaForSecurityOrigin:{%s, %s, %i} database:%s\n",
1018            origin.scheme().toUtf8().data(),
1019            origin.host().toUtf8().data(),
1020            origin.port(),
1021            dbName.toUtf8().data());
1022     origin.setDatabaseQuota(5 * 1024 * 1024);
1023 }
1024
1025 void DumpRenderTree::statusBarMessage(const QString& message)
1026 {
1027     if (!m_controller->shouldDumpStatusCallbacks())
1028         return;
1029
1030     printf("UI DELEGATE STATUS CALLBACK: setStatusText:%s\n", message.toUtf8().constData());
1031 }
1032
1033 QWebPage *DumpRenderTree::createWindow()
1034 {
1035     if (!m_controller->canOpenWindows())
1036         return 0;
1037
1038     // Create a dummy container object to track the page in DRT.
1039     // QObject is used instead of QWidget to prevent DRT from
1040     // showing the main view when deleting the container.
1041
1042     QObject* container = new QObject(m_mainView);
1043     // create a QWebPage we want to return
1044     QWebPage* page = static_cast<QWebPage*>(new WebPage(container, this));
1045     // gets cleaned up in closeRemainingWindows()
1046     windows.append(container);
1047
1048     // connect the needed signals to the page
1049     connect(page, SIGNAL(frameCreated(QWebFrame*)), this, SLOT(connectFrame(QWebFrame*)));
1050     connectFrame(page->mainFrame());
1051     connect(page, SIGNAL(loadFinished(bool)), m_controller, SLOT(maybeDump(bool)));
1052     connect(page, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
1053
1054     // Use a frame group name for all pages created by DumpRenderTree to allow
1055     // testing of cross-page frame lookup.
1056     DumpRenderTreeSupportQt::webPageSetGroupName(page, "org.webkit.qt.DumpRenderTree");
1057
1058     return page;
1059 }
1060
1061 void DumpRenderTree::windowCloseRequested()
1062 {
1063     QWebPage* page = qobject_cast<QWebPage*>(sender());
1064     QObject* container = page->parent();
1065     windows.removeAll(container);
1066     // Our use of container->deleteLater() means we need to remove closed pages
1067     // from the org.webkit.qt.DumpRenderTree group explicitly.
1068     DumpRenderTreeSupportQt::webPageSetGroupName(page, "");
1069     container->deleteLater();
1070 }
1071
1072 int DumpRenderTree::windowCount() const
1073 {
1074 // include the main view in the count
1075     return windows.count() + 1;
1076 }
1077
1078 void DumpRenderTree::geolocationPermissionSet() 
1079 {
1080     m_page->permissionSet(QWebPage::Geolocation);
1081 }
1082
1083 void DumpRenderTree::switchFocus(bool focused)
1084 {
1085     QFocusEvent event((focused) ? QEvent::FocusIn : QEvent::FocusOut, Qt::ActiveWindowFocusReason);
1086     if (!isGraphicsBased())
1087         QApplication::sendEvent(m_mainView, &event);
1088     else {
1089         if (WebViewGraphicsBased* view = qobject_cast<WebViewGraphicsBased*>(m_mainView))
1090             view->scene()->sendEvent(view->graphicsView(), &event);
1091     }
1092
1093 }
1094
1095 #if defined(Q_WS_X11)
1096 void DumpRenderTree::initializeFonts()
1097 {
1098     static int numFonts = -1;
1099
1100     // Some test cases may add or remove application fonts (via @font-face).
1101     // Make sure to re-initialize the font set if necessary.
1102     FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication);
1103     if (appFontSet && numFonts >= 0 && appFontSet->nfont == numFonts)
1104         return;
1105
1106     QByteArray fontDir = getenv("WEBKIT_TESTFONTS");
1107     if (fontDir.isEmpty() || !QDir(fontDir).exists()) {
1108         fprintf(stderr,
1109                 "\n\n"
1110                 "----------------------------------------------------------------------\n"
1111                 "WEBKIT_TESTFONTS environment variable is not set correctly.\n"
1112                 "This variable has to point to the directory containing the fonts\n"
1113                 "you can clone from git://gitorious.org/qtwebkit/testfonts.git\n"
1114                 "----------------------------------------------------------------------\n"
1115                );
1116         exit(1);
1117     }
1118     char currentPath[PATH_MAX+1];
1119     if (!getcwd(currentPath, PATH_MAX))
1120         qFatal("Couldn't get current working directory");
1121     QByteArray configFile = currentPath;
1122     FcConfig *config = FcConfigCreate();
1123     configFile += "/WebKitTools/DumpRenderTree/qt/fonts.conf";
1124     if (!FcConfigParseAndLoad (config, (FcChar8*) configFile.data(), true))
1125         qFatal("Couldn't load font configuration file");
1126     if (!FcConfigAppFontAddDir (config, (FcChar8*) fontDir.data()))
1127         qFatal("Couldn't add font dir!");
1128     FcConfigSetCurrent(config);
1129
1130     appFontSet = FcConfigGetFonts(config, FcSetApplication);
1131     numFonts = appFontSet->nfont;
1132 }
1133 #endif
1134
1135 }