tizen beta release
[framework/web/webkit-efl.git] / Tools / DumpRenderTree / qt / LayoutTestControllerQt.cpp
1 /*
2  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
3  * Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 #include "config.h"
30 #include "LayoutTestControllerQt.h"
31 #include "DumpRenderTreeSupportQt.h"
32
33 #include "DumpRenderTreeQt.h"
34 #include "WorkQueue.h"
35 #include "WorkQueueItemQt.h"
36 #include <QCoreApplication>
37 #include <QDir>
38 #include <QLocale>
39 #include <qwebsettings.h>
40
41 LayoutTestController::LayoutTestController(WebCore::DumpRenderTree* drt)
42     : QObject()
43     , m_drt(drt)
44 {
45     reset();
46     DumpRenderTreeSupportQt::dumpNotification(true);
47 }
48
49 void LayoutTestController::reset()
50 {
51     m_hasDumped = false;
52     m_loadFinished = false;
53     m_textDump = false;
54     m_dumpBackForwardList = false;
55     m_dumpChildrenAsText = false;
56     m_dumpChildFrameScrollPositions = false;
57     m_canOpenWindows = false;
58     m_waitForDone = false;
59     m_disallowIncreaseForApplicationCacheQuota = false;
60     m_dumpTitleChanges = false;
61     m_dumpDatabaseCallbacks = false;
62     m_dumpApplicationCacheDelegateCallbacks = false;
63     m_dumpStatusCallbacks = false;
64     m_timeoutTimer.stop();
65     m_topLoadingFrame = 0;
66     m_waitForPolicy = false;
67     m_handleErrorPages = false;
68     m_webHistory = 0;
69     m_globalFlag = false;
70     m_userStyleSheetEnabled = false;
71     m_desktopNotificationAllowedOrigins.clear();
72     m_ignoreDesktopNotification = false;
73     m_isGeolocationPermissionSet = false;
74     m_isPrinting = false;
75     m_geolocationPermission = false;
76
77     DumpRenderTreeSupportQt::dumpEditingCallbacks(false);
78     DumpRenderTreeSupportQt::dumpFrameLoader(false);
79     DumpRenderTreeSupportQt::dumpProgressFinishedCallback(false);
80     DumpRenderTreeSupportQt::dumpUserGestureInFrameLoader(false);
81     DumpRenderTreeSupportQt::dumpResourceLoadCallbacks(false);
82     DumpRenderTreeSupportQt::dumpResourceResponseMIMETypes(false);
83     DumpRenderTreeSupportQt::setDeferMainResourceDataLoad(true);
84     DumpRenderTreeSupportQt::setWillSendRequestReturnsNullOnRedirect(false);
85     DumpRenderTreeSupportQt::setWillSendRequestReturnsNull(false);
86     DumpRenderTreeSupportQt::setWillSendRequestClearHeaders(QStringList());
87     DumpRenderTreeSupportQt::clearScriptWorlds();
88     DumpRenderTreeSupportQt::setCustomPolicyDelegate(false, false);
89     DumpRenderTreeSupportQt::dumpHistoryCallbacks(false);
90     DumpRenderTreeSupportQt::dumpVisitedLinksCallbacks(false);
91     DumpRenderTreeSupportQt::resetGeolocationMock(m_drt->webPage());
92     setIconDatabaseEnabled(false);
93     clearAllDatabases();
94 #if QT_VERSION >= 0x040800
95     // The default state for DRT is to block third-party cookies, mimicing the Mac port
96     setAlwaysAcceptCookies(false);
97 #endif
98     emit hidePage();
99 }
100
101 void LayoutTestController::processWork()
102 {
103     // qDebug() << ">>>processWork";
104
105     // if we didn't start a new load, then we finished all the commands, so we're ready to dump state
106     if (WorkQueue::shared()->processWork() && !shouldWaitUntilDone()) {
107         emit done();
108         m_hasDumped = true;
109     }
110 }
111
112 // Called on loadFinished on WebPage
113 void LayoutTestController::maybeDump(bool /*success*/)
114 {
115
116     // This can happen on any of the http/tests/security/window-events-*.html tests, where the test opens
117     // a new window, calls the unload and load event handlers on the window's page, and then immediately
118     // issues a notifyDone. Needs investigation.
119     if (!m_topLoadingFrame)
120         return;
121
122     // It is possible that we get called by windows created from the main page that have finished
123     // loading, so we don't ASSERT here. At the moment we do not gather results from such windows,
124     // but may need to in future.
125     if (sender() != m_topLoadingFrame->page())
126         return;
127
128     m_loadFinished = true;
129     // as the function is called on loadFinished, the test might
130     // already have dumped and thus no longer be active, thus
131     // bail out here.
132     if (m_hasDumped)
133         return;
134
135     WorkQueue::shared()->setFrozen(true); // first complete load freezes the queue for the rest of this test
136     if (WorkQueue::shared()->count())
137         QTimer::singleShot(0, this, SLOT(processWork()));
138     else if (!shouldWaitUntilDone()) {
139         emit done();
140         m_hasDumped = true;
141     }
142 }
143
144 void LayoutTestController::waitUntilDone()
145 {
146     //qDebug() << ">>>>waitForDone";
147     m_waitForDone = true;
148     m_timeoutTimer.start(30000, this);
149 }
150
151 QString LayoutTestController::counterValueForElementById(const QString& id)
152 {
153     return DumpRenderTreeSupportQt::counterValueForElementById(m_drt->webPage()->mainFrame(), id);
154 }
155
156 void LayoutTestController::setViewModeMediaFeature(const QString& mode)
157 {
158     m_drt->webPage()->setProperty("_q_viewMode", mode);
159 }
160
161 int LayoutTestController::webHistoryItemCount()
162 {
163     if (!m_webHistory)
164         return -1;
165
166     // Subtract one here as our QWebHistory::count() includes the actual page,
167     // which is not considered in the DRT tests.
168     return m_webHistory->count() - 1;
169 }
170
171 void LayoutTestController::keepWebHistory()
172 {
173     m_webHistory = m_drt->webPage()->history();
174 }
175
176 void LayoutTestController::notifyDone()
177 {
178     qDebug() << ">>>>notifyDone";
179
180     if (!m_timeoutTimer.isActive())
181         return;
182
183     m_timeoutTimer.stop();
184     m_waitForDone = false;
185
186     // If the page has not finished loading (i.e. loadFinished() has not been emitted) then
187     // content created by the likes of document.write() JS methods will not be available yet.
188     // When the page has finished loading, maybeDump above will dump the results now that we have
189     // just set shouldWaitUntilDone to false.
190     if (!m_loadFinished)
191         return;
192
193     emit done();
194
195     // FIXME: investigate why always resetting these result in timeouts
196     m_hasDumped = true;
197     m_waitForPolicy = false;
198 }
199
200 int LayoutTestController::windowCount()
201 {
202     return m_drt->windowCount();
203 }
204
205 void LayoutTestController::grantDesktopNotificationPermission(const QString& origin)
206 {
207     QWebFrame* frame = m_drt->webPage()->mainFrame();
208     m_drt->webPage()->setFeaturePermission(frame, QWebPage::Notifications, QWebPage::PermissionGrantedByUser);
209     m_desktopNotificationAllowedOrigins.append(origin);
210 }
211
212 void LayoutTestController::ignoreDesktopNotificationPermissionRequests()
213 {
214     m_ignoreDesktopNotification = true;
215 }
216
217 bool LayoutTestController::checkDesktopNotificationPermission(const QString& origin)
218 {
219     return !m_ignoreDesktopNotification && m_desktopNotificationAllowedOrigins.contains(origin);
220 }
221
222 void LayoutTestController::simulateDesktopNotificationClick(const QString& title)
223 {
224     DumpRenderTreeSupportQt::simulateDesktopNotificationClick(title);
225 }
226
227 void LayoutTestController::display()
228 {
229     emit showPage();
230 }
231
232 void LayoutTestController::displayInvalidatedRegion()
233 {
234     display();
235 }
236
237 void LayoutTestController::clearBackForwardList()
238 {
239     m_drt->webPage()->history()->clear();
240 }
241
242 QString LayoutTestController::pathToLocalResource(const QString& url)
243 {
244     QString localTmpUrl(QLatin1String("file:///tmp/LayoutTests"));
245
246     // Translate a request for /tmp/LayoutTests to the repository LayoutTests directory.
247     // Do not rely on a symlink to be created via the test runner, which will not work on Windows.
248     if (url.startsWith(localTmpUrl)) {
249         // DumpRenderTree lives in WebKit/WebKitBuild/<build_mode>/bin.
250         // Translate from WebKit/WebKitBuild/Release/bin => WebKit/LayoutTests.
251         QFileInfo layoutTestsRoot(QCoreApplication::applicationDirPath() + QLatin1String("/../../../LayoutTests/"));
252         if (layoutTestsRoot.exists())
253             return QLatin1String("file://") + layoutTestsRoot.absolutePath() + url.mid(localTmpUrl.length());
254     }
255
256     return url;
257 }
258
259 void LayoutTestController::dumpConfigurationForViewport(int deviceDPI, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
260 {
261     QString res = DumpRenderTreeSupportQt::viewportAsText(m_drt->webPage(), deviceDPI, QSize(deviceWidth, deviceHeight), QSize(availableWidth, availableHeight));
262     fputs(qPrintable(res), stdout);
263 }
264
265 void LayoutTestController::dumpEditingCallbacks()
266 {
267     qDebug() << ">>>dumpEditingCallbacks";
268     DumpRenderTreeSupportQt::dumpEditingCallbacks(true);
269 }
270
271 void LayoutTestController::dumpFrameLoadCallbacks()
272 {
273     DumpRenderTreeSupportQt::dumpFrameLoader(true);
274 }
275
276 void LayoutTestController::dumpProgressFinishedCallback()
277 {
278     DumpRenderTreeSupportQt::dumpProgressFinishedCallback(true);
279 }
280
281 void LayoutTestController::dumpUserGestureInFrameLoadCallbacks()
282 {
283     DumpRenderTreeSupportQt::dumpUserGestureInFrameLoader(true);
284 }
285
286 void LayoutTestController::dumpResourceLoadCallbacks()
287 {
288     DumpRenderTreeSupportQt::dumpResourceLoadCallbacks(true);
289 }
290
291 void LayoutTestController::dumpResourceResponseMIMETypes()
292 {
293     DumpRenderTreeSupportQt::dumpResourceResponseMIMETypes(true);
294 }
295
296 void LayoutTestController::dumpHistoryCallbacks()
297 {
298     DumpRenderTreeSupportQt::dumpHistoryCallbacks(true);
299 }
300
301 void LayoutTestController::setWillSendRequestReturnsNullOnRedirect(bool enabled)
302 {
303     DumpRenderTreeSupportQt::setWillSendRequestReturnsNullOnRedirect(enabled);
304 }
305
306 void LayoutTestController::setWillSendRequestReturnsNull(bool enabled)
307 {
308     DumpRenderTreeSupportQt::setWillSendRequestReturnsNull(enabled);
309 }
310
311 void LayoutTestController::setWillSendRequestClearHeader(const QStringList& headers)
312 {
313     DumpRenderTreeSupportQt::setWillSendRequestClearHeaders(headers);
314 }
315
316 void LayoutTestController::setDeferMainResourceDataLoad(bool defer)
317 {
318     DumpRenderTreeSupportQt::setDeferMainResourceDataLoad(defer);
319 }
320
321 void LayoutTestController::queueBackNavigation(int howFarBackward)
322 {
323     //qDebug() << ">>>queueBackNavigation" << howFarBackward;
324     for (int i = 0; i != howFarBackward; ++i)
325         WorkQueue::shared()->queue(new BackItem(1, m_drt->webPage()));
326 }
327
328 void LayoutTestController::queueForwardNavigation(int howFarForward)
329 {
330     //qDebug() << ">>>queueForwardNavigation" << howFarForward;
331     for (int i = 0; i != howFarForward; ++i)
332         WorkQueue::shared()->queue(new ForwardItem(1, m_drt->webPage()));
333 }
334
335 void LayoutTestController::queueLoad(const QString& url, const QString& target)
336 {
337     //qDebug() << ">>>queueLoad" << url << target;
338     QUrl mainResourceUrl = m_drt->webPage()->mainFrame()->url();
339     QString absoluteUrl = mainResourceUrl.resolved(QUrl(url)).toEncoded();
340     WorkQueue::shared()->queue(new LoadItem(absoluteUrl, target, m_drt->webPage()));
341 }
342
343 void LayoutTestController::queueLoadHTMLString(const QString& content, const QString& baseURL, const QString& failingURL)
344 {
345     if (failingURL.isEmpty())
346         WorkQueue::shared()->queue(new LoadHTMLStringItem(content, baseURL, m_drt->webPage()));
347     else
348         WorkQueue::shared()->queue(new LoadAlternateHTMLStringItem(content, baseURL, failingURL, m_drt->webPage()));
349 }
350
351 void LayoutTestController::queueReload()
352 {
353     //qDebug() << ">>>queueReload";
354     WorkQueue::shared()->queue(new ReloadItem(m_drt->webPage()));
355 }
356
357 void LayoutTestController::queueLoadingScript(const QString& script)
358 {
359     //qDebug() << ">>>queueLoadingScript" << script;
360     WorkQueue::shared()->queue(new LoadingScriptItem(script, m_drt->webPage()));
361 }
362
363 void LayoutTestController::queueNonLoadingScript(const QString& script)
364 {
365     //qDebug() << ">>>queueNonLoadingScript" << script;
366     WorkQueue::shared()->queue(new NonLoadingScriptItem(script, m_drt->webPage()));
367 }
368
369 void LayoutTestController::provisionalLoad()
370 {
371     QWebFrame* frame = qobject_cast<QWebFrame*>(sender());
372     if (!m_topLoadingFrame && !m_hasDumped)
373         m_topLoadingFrame = frame;
374 }
375
376 void LayoutTestController::timerEvent(QTimerEvent *ev)
377 {
378     if (ev->timerId() == m_timeoutTimer.timerId()) {
379         const char* message = "FAIL: Timed out waiting for notifyDone to be called\n";
380         fprintf(stderr, "%s", message);
381         fprintf(stdout, "%s", message);
382         notifyDone();
383     } else
384         QObject::timerEvent(ev);
385 }
386
387 QString LayoutTestController::encodeHostName(const QString& host)
388 {
389     QString encoded = QString::fromLatin1(QUrl::toAce(host + QLatin1String(".no")));
390     encoded.truncate(encoded.length() - 3); // strip .no
391     return encoded;
392 }
393
394 QString LayoutTestController::decodeHostName(const QString& host)
395 {
396     QString decoded = QUrl::fromAce(host.toLatin1() + QByteArray(".no"));
397     decoded.truncate(decoded.length() - 3);
398     return decoded;
399 }
400
401 void LayoutTestController::setMediaType(const QString& type)
402 {
403     DumpRenderTreeSupportQt::setMediaType(m_drt->webPage()->mainFrame(), type);
404 }
405
406 void LayoutTestController::closeWebInspector()
407 {
408     DumpRenderTreeSupportQt::webInspectorClose(m_drt->webPage());
409     m_drt->webPage()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, false);
410 }
411
412 void LayoutTestController::setDeveloperExtrasEnabled(bool enabled)
413 {
414     m_drt->webPage()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, enabled);
415 }
416
417 void LayoutTestController::setAsynchronousSpellCheckingEnabled(bool)
418 {
419     // FIXME: Implement this.
420 }
421
422 void LayoutTestController::showWebInspector()
423 {
424     m_drt->webPage()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
425     DumpRenderTreeSupportQt::webInspectorShow(m_drt->webPage());
426 }
427
428 void LayoutTestController::evaluateInWebInspector(long callId, const QString& script)
429 {
430     DumpRenderTreeSupportQt::webInspectorExecuteScript(m_drt->webPage(), callId, script);
431 }
432
433 void LayoutTestController::setFrameFlatteningEnabled(bool enabled)
434 {
435     DumpRenderTreeSupportQt::setFrameFlatteningEnabled(m_drt->webPage(), enabled);
436 }
437
438 void LayoutTestController::goBack()
439 {
440     DumpRenderTreeSupportQt::goBack(m_drt->webPage());
441 }
442
443 void LayoutTestController::setDefersLoading(bool flag)
444 {
445     DumpRenderTreeSupportQt::setDefersLoading(m_drt->webPage(), flag);
446 }
447
448 void LayoutTestController::setAllowUniversalAccessFromFileURLs(bool enabled)
449 {
450     m_drt->webPage()->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, enabled);
451 }
452
453 void LayoutTestController::setAllowFileAccessFromFileURLs(bool enabled)
454 {
455     m_drt->webPage()->settings()->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, enabled);
456 }
457
458 void LayoutTestController::setAppCacheMaximumSize(unsigned long long quota)
459 {
460     m_drt->webPage()->settings()->setOfflineWebApplicationCacheQuota(quota);
461 }
462
463 void LayoutTestController::setAutofilled(const QWebElement& element, bool isAutofilled)
464 {
465     return DumpRenderTreeSupportQt::setAutofilled(element, isAutofilled);
466 }
467
468 void LayoutTestController::setJavaScriptProfilingEnabled(bool enable)
469 {
470     setDeveloperExtrasEnabled(enable);
471     DumpRenderTreeSupportQt::setJavaScriptProfilingEnabled(m_topLoadingFrame, enable);
472 }
473
474 void LayoutTestController::setValueForUser(const QWebElement& element, const QString& value)
475 {
476     DumpRenderTreeSupportQt::setValueForUser(element, value);
477 }
478
479 void LayoutTestController::setFixedContentsSize(int width, int height)
480 {
481     m_topLoadingFrame->page()->setPreferredContentsSize(QSize(width, height));
482 }
483
484 void LayoutTestController::setPrivateBrowsingEnabled(bool enable)
485 {
486     m_drt->webPage()->settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, enable);
487 }
488
489 void LayoutTestController::setSpatialNavigationEnabled(bool enable)
490 {
491     m_drt->webPage()->settings()->setAttribute(QWebSettings::SpatialNavigationEnabled, enable);
492 }
493
494 void LayoutTestController::setPopupBlockingEnabled(bool enable)
495 {
496     m_drt->webPage()->settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, !enable);
497 }
498
499 void LayoutTestController::setPluginsEnabled(bool flag)
500 {
501     // FIXME: Implement
502 }
503
504 void LayoutTestController::setPOSIXLocale(const QString& locale)
505 {
506     QLocale qlocale(locale);
507     QLocale::setDefault(qlocale);
508
509
510 void LayoutTestController::setWindowIsKey(bool isKey)
511 {
512     m_drt->switchFocus(isKey);
513 }
514
515 void LayoutTestController::setMainFrameIsFirstResponder(bool isFirst)
516 {
517     //FIXME: only need this for the moment: https://bugs.webkit.org/show_bug.cgi?id=32990
518 }
519
520 void LayoutTestController::setJavaScriptCanAccessClipboard(bool enable)
521 {
522     m_drt->webPage()->settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, enable);
523 }
524
525 void LayoutTestController::setXSSAuditorEnabled(bool enable)
526 {
527     // Set XSSAuditingEnabled globally so that windows created by the test inherit it too.
528     // resetSettings() will call this to reset the page and global setting to false again.
529     // Needed by http/tests/security/xssAuditor/link-opens-new-window.html
530     QWebSettings* globalSettings = QWebSettings::globalSettings();
531     globalSettings->setAttribute(QWebSettings::XSSAuditingEnabled, enable);
532     m_drt->webPage()->settings()->setAttribute(QWebSettings::XSSAuditingEnabled, enable);
533 }
534
535 bool LayoutTestController::pauseAnimationAtTimeOnElementWithId(const QString& animationName,
536                                                                double time,
537                                                                const QString& elementId)
538 {
539     QWebFrame* frame = m_drt->webPage()->mainFrame();
540     Q_ASSERT(frame);
541     return DumpRenderTreeSupportQt::pauseAnimation(frame, animationName, time, elementId);
542 }
543
544 bool LayoutTestController::pauseTransitionAtTimeOnElementWithId(const QString& propertyName,
545                                                                 double time,
546                                                                 const QString& elementId)
547 {
548     QWebFrame* frame = m_drt->webPage()->mainFrame();
549     Q_ASSERT(frame);
550     return DumpRenderTreeSupportQt::pauseTransitionOfProperty(frame, propertyName, time, elementId);
551 }
552
553 bool LayoutTestController::sampleSVGAnimationForElementAtTime(const QString& animationId,
554                                                               double time,
555                                                               const QString& elementId)
556 {
557     QWebFrame* frame = m_drt->webPage()->mainFrame();
558     Q_ASSERT(frame);
559     return DumpRenderTreeSupportQt::pauseSVGAnimation(frame, animationId, time, elementId);
560 }
561
562 unsigned LayoutTestController::numberOfActiveAnimations() const
563 {
564     QWebFrame* frame = m_drt->webPage()->mainFrame();
565     Q_ASSERT(frame);
566     return DumpRenderTreeSupportQt::numberOfActiveAnimations(frame);
567 }
568
569 void LayoutTestController::suspendAnimations() const
570 {
571     QWebFrame* frame = m_drt->webPage()->mainFrame();
572     Q_ASSERT(frame);
573     DumpRenderTreeSupportQt::suspendAnimations(frame);
574 }
575
576 void LayoutTestController::resumeAnimations() const
577 {
578     QWebFrame* frame = m_drt->webPage()->mainFrame();
579     Q_ASSERT(frame);
580     DumpRenderTreeSupportQt::resumeAnimations(frame);
581 }
582
583 void LayoutTestController::disableImageLoading()
584 {
585     m_drt->webPage()->settings()->setAttribute(QWebSettings::AutoLoadImages, false);
586 }
587
588 void LayoutTestController::dispatchPendingLoadRequests()
589 {
590     // FIXME: Implement for testing fix for 6727495
591 }
592
593 void LayoutTestController::clearAllApplicationCaches()
594 {
595     DumpRenderTreeSupportQt::clearAllApplicationCaches();
596 }
597
598 void LayoutTestController::clearApplicationCacheForOrigin(const QString& url)
599 {
600     // FIXME: Implement to support deleting all application caches for an origin.
601 }
602
603 long long LayoutTestController::localStorageDiskUsageForOrigin(const QString& originIdentifier)
604 {
605     // FIXME: Implement to support getting disk usage in bytes for an origin.
606     return 0;
607 }
608
609 void LayoutTestController::setApplicationCacheOriginQuota(unsigned long long quota)
610 {
611     if (!m_topLoadingFrame)
612         return;
613     m_topLoadingFrame->securityOrigin().setApplicationCacheQuota(quota);
614 }
615
616 long long LayoutTestController::applicationCacheDiskUsageForOrigin(const QString& origin)
617 {
618     // FIXME: Implement to support getting disk usage by all application caches for an origin.
619     return 0;
620 }
621
622 QStringList LayoutTestController::originsWithApplicationCache()
623 {
624     // FIXME: Implement to get origins that have application caches.
625     return QStringList();
626 }
627
628 void LayoutTestController::setCacheModel(int model)
629 {
630     // qwebsetting doesn't have matched setting yet :
631     // WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER
632     // WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER
633     // WEBKIT_CACHE_MODEL_WEB_BROWSER
634
635     // FIXME: Implement.
636 }
637
638 void LayoutTestController::setDatabaseQuota(int size)
639 {
640     if (!m_topLoadingFrame)
641         return;
642     m_topLoadingFrame->securityOrigin().setDatabaseQuota(size);
643 }
644
645 void LayoutTestController::clearAllDatabases()
646 {
647     QWebDatabase::removeAllDatabases();
648 }
649
650 void LayoutTestController::addOriginAccessWhitelistEntry(const QString& sourceOrigin, const QString& destinationProtocol, const QString& destinationHost, bool allowDestinationSubdomains)
651 {
652     DumpRenderTreeSupportQt::whiteListAccessFromOrigin(sourceOrigin, destinationProtocol, destinationHost, allowDestinationSubdomains);
653 }
654
655 void LayoutTestController::removeOriginAccessWhitelistEntry(const QString& sourceOrigin, const QString& destinationProtocol, const QString& destinationHost, bool allowDestinationSubdomains)
656 {
657     DumpRenderTreeSupportQt::removeWhiteListAccessFromOrigin(sourceOrigin, destinationProtocol, destinationHost, allowDestinationSubdomains);
658 }
659
660 void LayoutTestController::setCustomPolicyDelegate(bool enabled, bool permissive)
661 {
662     DumpRenderTreeSupportQt::setCustomPolicyDelegate(enabled, permissive);
663 }
664
665 void LayoutTestController::waitForPolicyDelegate()
666 {
667     setCustomPolicyDelegate(true);
668     m_waitForPolicy = true;
669     waitUntilDone();
670 }
671
672 void LayoutTestController::overridePreference(const QString& name, const QVariant& value)
673 {
674     QWebSettings* settings = m_topLoadingFrame->page()->settings();
675
676     if (name == "WebKitJavaScriptEnabled")
677         settings->setAttribute(QWebSettings::JavascriptEnabled, value.toBool());
678     else if (name == "WebKitTabToLinksPreferenceKey")
679         settings->setAttribute(QWebSettings::LinksIncludedInFocusChain, value.toBool());
680     else if (name == "WebKitOfflineWebApplicationCacheEnabled")
681         settings->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, value.toBool());
682     else if (name == "WebKitDefaultFontSize")
683         settings->setFontSize(QWebSettings::DefaultFontSize, value.toInt());
684     else if (name == "WebKitUsesPageCachePreferenceKey")
685         QWebSettings::setMaximumPagesInCache(value.toInt());
686     else if (name == "WebKitEnableCaretBrowsing")
687         setCaretBrowsingEnabled(value.toBool());
688     else if (name == "WebKitPluginsEnabled")
689         settings->setAttribute(QWebSettings::PluginsEnabled, value.toBool());
690     else if (name == "WebKitWebGLEnabled")
691         settings->setAttribute(QWebSettings::WebGLEnabled, value.toBool());
692     else if (name == "WebKitHyperlinkAuditingEnabled")
693         settings->setAttribute(QWebSettings::HyperlinkAuditingEnabled, value.toBool());
694     else if (name == "WebKitHixie76WebSocketProtocolEnabled")
695         DumpRenderTreeSupportQt::setHixie76WebSocketProtocolEnabled(m_topLoadingFrame->page(), value.toBool());
696     else
697         printf("ERROR: LayoutTestController::overridePreference() does not support the '%s' preference\n",
698             name.toLatin1().data());
699 }
700
701 void LayoutTestController::setUserStyleSheetLocation(const QString& url)
702 {
703     QByteArray urlData = pathToLocalResource(url).toLatin1();
704     m_userStyleSheetLocation = QUrl::fromEncoded(urlData, QUrl::StrictMode);
705
706     if (m_userStyleSheetEnabled)
707         setUserStyleSheetEnabled(true);
708 }
709
710 void LayoutTestController::setCaretBrowsingEnabled(bool value)
711 {
712     DumpRenderTreeSupportQt::setCaretBrowsingEnabled(m_drt->webPage(), value);
713 }
714
715 void LayoutTestController::setAuthorAndUserStylesEnabled(bool value)
716 {
717     DumpRenderTreeSupportQt::setAuthorAndUserStylesEnabled(m_drt->webPage(), value);
718 }
719
720 void LayoutTestController::setUserStyleSheetEnabled(bool enabled)
721 {
722     m_userStyleSheetEnabled = enabled;
723
724     if (enabled)
725         m_drt->webPage()->settings()->setUserStyleSheetUrl(m_userStyleSheetLocation);
726     else
727         m_drt->webPage()->settings()->setUserStyleSheetUrl(QUrl());
728 }
729
730 void LayoutTestController::setDomainRelaxationForbiddenForURLScheme(bool forbidden, const QString& scheme)
731 {
732     DumpRenderTreeSupportQt::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
733 }
734
735 int LayoutTestController::workerThreadCount()
736 {
737     return DumpRenderTreeSupportQt::workerThreadCount();
738 }
739
740 int LayoutTestController::pageNumberForElementById(const QString& id, float width, float height)
741 {
742     // If no size specified, webpage viewport size is used
743     if (!width && !height) {
744         width = m_drt->webPage()->viewportSize().width();
745         height = m_drt->webPage()->viewportSize().height();
746     }
747
748     return DumpRenderTreeSupportQt::pageNumberForElementById(m_drt->webPage()->mainFrame(), id, width, height);
749 }
750
751 int LayoutTestController::numberOfPages(float width, float height)
752 {
753     return DumpRenderTreeSupportQt::numberOfPages(m_drt->webPage()->mainFrame(), width, height);
754 }
755
756 bool LayoutTestController::callShouldCloseOnWebView()
757 {
758     return DumpRenderTreeSupportQt::shouldClose(m_drt->webPage()->mainFrame());
759 }
760
761 void LayoutTestController::setScrollbarPolicy(const QString& orientation, const QString& policy)
762 {
763     Qt::Orientation o;
764     Qt::ScrollBarPolicy p;
765
766     if (orientation == "vertical")
767         o = Qt::Vertical;
768     else if (orientation == "horizontal")
769         o = Qt::Horizontal;
770     else
771         return;
772
773     if (policy == "on")
774         p = Qt::ScrollBarAlwaysOn;
775     else if (policy == "auto")
776         p = Qt::ScrollBarAsNeeded;
777     else if (policy == "off")
778         p = Qt::ScrollBarAlwaysOff;
779     else
780         return;
781
782     m_drt->webPage()->mainFrame()->setScrollBarPolicy(o, p);
783 }
784
785 void LayoutTestController::setSmartInsertDeleteEnabled(bool enable)
786 {
787     DumpRenderTreeSupportQt::setSmartInsertDeleteEnabled(m_drt->webPage(), enable);
788 }
789
790 void LayoutTestController::setSelectTrailingWhitespaceEnabled(bool enable)
791 {
792     DumpRenderTreeSupportQt::setSelectTrailingWhitespaceEnabled(m_drt->webPage(), enable);
793 }
794
795 void LayoutTestController::execCommand(const QString& name, const QString& value)
796 {
797     DumpRenderTreeSupportQt::executeCoreCommandByName(m_drt->webPage(), name, value);
798 }
799
800 bool LayoutTestController::isCommandEnabled(const QString& name) const
801 {
802     return DumpRenderTreeSupportQt::isCommandEnabled(m_drt->webPage(), name);
803 }
804
805 bool LayoutTestController::findString(const QString& string, const QStringList& optionArray)
806 {
807     return DumpRenderTreeSupportQt::findString(m_drt->webPage(), string, optionArray);
808 }
809
810 QString LayoutTestController::markerTextForListItem(const QWebElement& listItem)
811 {
812     return DumpRenderTreeSupportQt::markerTextForListItem(listItem);
813 }
814
815 QVariantMap LayoutTestController::computedStyleIncludingVisitedInfo(const QWebElement& element) const
816 {
817     return DumpRenderTreeSupportQt::computedStyleIncludingVisitedInfo(element);
818 }
819
820 bool LayoutTestController::elementDoesAutoCompleteForElementWithId(const QString& elementId)
821 {
822     return DumpRenderTreeSupportQt::elementDoesAutoCompleteForElementWithId(m_drt->webPage()->mainFrame(), elementId);
823 }
824
825 void LayoutTestController::authenticateSession(const QString&, const QString&, const QString&)
826 {
827     // FIXME: If there is a concept per-session (per-process) credential storage, the credentials should be added to it for later use.
828 }
829
830 void LayoutTestController::setIconDatabaseEnabled(bool enable)
831 {
832     if (enable && !m_drt->persistentStoragePath().isEmpty())
833         QWebSettings::setIconDatabasePath(m_drt->persistentStoragePath());
834     else
835         QWebSettings::setIconDatabasePath(QString());
836 }
837
838 void LayoutTestController::setEditingBehavior(const QString& editingBehavior)
839 {
840     DumpRenderTreeSupportQt::setEditingBehavior(m_drt->webPage(), editingBehavior);
841 }
842
843 void LayoutTestController::setMockDeviceOrientation(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma)
844 {
845     DumpRenderTreeSupportQt::setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma);
846 }
847
848 void LayoutTestController::setGeolocationPermission(bool allow)
849 {
850     setGeolocationPermissionCommon(allow);
851     QList<WebCore::WebPage*> pages = m_drt->getAllPages();
852     foreach (WebCore::WebPage* page, pages)
853         DumpRenderTreeSupportQt::setMockGeolocationPermission(page, allow);
854 }
855
856 int LayoutTestController::numberOfPendingGeolocationPermissionRequests()
857 {
858     int pendingPermissionCount = 0;
859     QList<WebCore::WebPage*> pages = m_drt->getAllPages();
860     foreach (WebCore::WebPage* page, pages)
861         pendingPermissionCount += DumpRenderTreeSupportQt::numberOfPendingGeolocationPermissionRequests(page);
862
863     return pendingPermissionCount;
864 }
865
866 void LayoutTestController::setGeolocationPermissionCommon(bool allow)
867 {
868      m_isGeolocationPermissionSet = true;
869      m_geolocationPermission = allow;
870 }
871
872 void LayoutTestController::setMockGeolocationError(int code, const QString& message)
873 {
874     QList<WebCore::WebPage*> pages = m_drt->getAllPages();
875     foreach (WebCore::WebPage* page, pages)
876         DumpRenderTreeSupportQt::setMockGeolocationError(page, code, message);
877 }
878
879 void LayoutTestController::setMockGeolocationPosition(double latitude, double longitude, double accuracy)
880 {
881     QList<WebCore::WebPage*> pages = m_drt->getAllPages();
882     foreach (WebCore::WebPage* page, pages)
883         DumpRenderTreeSupportQt::setMockGeolocationPosition(page, latitude, longitude, accuracy);
884 }
885
886 void LayoutTestController::addMockSpeechInputResult(const QString& result, double confidence, const QString& language)
887 {
888     // FIXME: Implement for speech input layout tests.
889     // See https://bugs.webkit.org/show_bug.cgi?id=39485.
890 }
891
892 void LayoutTestController::startSpeechInput(const QString& inputElement)
893 {
894     // FIXME: Implement for speech input layout tests.
895     // See https://bugs.webkit.org/show_bug.cgi?id=39485.
896 }
897
898 void LayoutTestController::evaluateScriptInIsolatedWorld(int worldID, const QString& script)
899 {
900     DumpRenderTreeSupportQt::evaluateScriptInIsolatedWorld(m_drt->webPage()->mainFrame(), worldID, script);
901 }
902
903 bool LayoutTestController::isPageBoxVisible(int pageIndex)
904 {
905     return DumpRenderTreeSupportQt::isPageBoxVisible(m_drt->webPage()->mainFrame(), pageIndex);
906 }
907
908 QString LayoutTestController::pageSizeAndMarginsInPixels(int pageIndex, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft)
909 {
910     return DumpRenderTreeSupportQt::pageSizeAndMarginsInPixels(m_drt->webPage()->mainFrame(), pageIndex,
911                                                                width, height, marginTop, marginRight, marginBottom, marginLeft);
912 }
913
914 QString LayoutTestController::pageProperty(const QString& propertyName, int pageNumber)
915 {
916     return DumpRenderTreeSupportQt::pageProperty(m_drt->webPage()->mainFrame(), propertyName, pageNumber);
917 }
918
919 void LayoutTestController::addUserStyleSheet(const QString& sourceCode)
920 {
921     DumpRenderTreeSupportQt::addUserStyleSheet(m_drt->webPage(), sourceCode);
922 }
923
924 void LayoutTestController::removeAllVisitedLinks()
925 {
926     QWebHistory* history = m_drt->webPage()->history();
927     history->clear();
928     DumpRenderTreeSupportQt::dumpVisitedLinksCallbacks(true);
929 }
930
931 bool LayoutTestController::hasSpellingMarker(int, int)
932 {
933     // FIXME: Implement.
934     return false;
935 }
936
937 QVariantList LayoutTestController::nodesFromRect(const QWebElement& document, int x, int y, unsigned top, unsigned right, unsigned bottom, unsigned left, bool ignoreClipping)
938 {
939     return DumpRenderTreeSupportQt::nodesFromRect(document, x, y, top, right, bottom, left, ignoreClipping);
940 }
941
942 void LayoutTestController::addURLToRedirect(const QString& origin, const QString& destination)
943 {
944     DumpRenderTreeSupportQt::addURLToRedirect(origin, destination);
945 }
946
947 void LayoutTestController::setMinimumTimerInterval(double minimumTimerInterval)
948 {
949     DumpRenderTreeSupportQt::setMinimumTimerInterval(m_drt->webPage(), minimumTimerInterval);
950 }
951
952 void LayoutTestController::originsWithLocalStorage()
953 {
954     // FIXME: Implement.
955 }
956
957 void LayoutTestController::deleteAllLocalStorage()
958 {
959     // FIXME: Implement.
960 }
961
962 void LayoutTestController::deleteLocalStorageForOrigin(const QString& originIdentifier)
963 {
964     // FIXME: Implement.
965 }
966
967 void LayoutTestController::observeStorageTrackerNotifications(unsigned number)
968 {
969     // FIXME: Implement.
970 }
971
972 void LayoutTestController::syncLocalStorage()
973 {
974     // FIXME: Implement.
975 }
976
977 QString LayoutTestController::layerTreeAsText()
978 {
979     return DumpRenderTreeSupportQt::layerTreeAsText(m_drt->webPage()->mainFrame());
980 }
981
982 void LayoutTestController::setTextDirection(const QString& directionName)
983 {
984     if (directionName == "auto")
985         m_drt->webPage()->triggerAction(QWebPage::SetTextDirectionDefault);
986     else if (directionName == "rtl")
987         m_drt->webPage()->triggerAction(QWebPage::SetTextDirectionRightToLeft);
988     else if (directionName == "ltr")
989         m_drt->webPage()->triggerAction(QWebPage::SetTextDirectionLeftToRight);
990 }
991
992 #if QT_VERSION >= 0x040800
993 void LayoutTestController::setAlwaysAcceptCookies(bool accept)
994 {
995     QWebSettings* globalSettings = QWebSettings::globalSettings();
996     if (accept)
997         globalSettings->setThirdPartyCookiePolicy(QWebSettings::AlwaysAllowThirdPartyCookies);
998     else {
999         // This matches the Safari third-party cookie blocking policy tested in third-party-cookie-relaxing.html
1000         globalSettings->setThirdPartyCookiePolicy(QWebSettings::AllowThirdPartyWithExistingCookies);
1001     }
1002 }
1003
1004 void LayoutTestController::setAlwaysBlockCookies(bool block)
1005 {
1006     QWebSettings* globalSettings = QWebSettings::globalSettings();
1007     if (block)
1008         globalSettings->setThirdPartyCookiePolicy(QWebSettings::AlwaysBlockThirdPartyCookies);
1009     else
1010         globalSettings->setThirdPartyCookiePolicy(QWebSettings::AlwaysAllowThirdPartyCookies);
1011 }
1012 #endif
1013
1014 const unsigned LayoutTestController::maxViewWidth = 800;
1015 const unsigned LayoutTestController::maxViewHeight = 600;