2011-03-28 Andreas Kling <kling@webkit.org>
[WebKit-https.git] / Source / WebKit / qt / tests / qwebpage / tst_qwebpage.cpp
1 /*
2     Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
3     Copyright (C) 2009 Girish Ramakrishnan <girish@forwardbias.in>
4     Copyright (C) 2010 Holger Hans Peter Freyther
5
6     This library is free software; you can redistribute it and/or
7     modify it under the terms of the GNU Library General Public
8     License as published by the Free Software Foundation; either
9     version 2 of the License, or (at your option) any later version.
10
11     This library is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14     Library General Public License for more details.
15
16     You should have received a copy of the GNU Library General Public License
17     along with this library; see the file COPYING.LIB.  If not, write to
18     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19     Boston, MA 02110-1301, USA.
20 */
21
22 #include "../util.h"
23 #include "../WebCoreSupport/DumpRenderTreeSupportQt.h"
24 #include <QClipboard>
25 #include <QDir>
26 #include <QGraphicsWidget>
27 #include <QLineEdit>
28 #include <QMainWindow>
29 #include <QMenu>
30 #include <QPushButton>
31 #include <QStyle>
32 #include <QtTest/QtTest>
33 #include <QTextCharFormat>
34 #include <qgraphicsscene.h>
35 #include <qgraphicsview.h>
36 #include <qgraphicswebview.h>
37 #include <qnetworkcookiejar.h>
38 #include <qnetworkrequest.h>
39 #include <qwebdatabase.h>
40 #include <qwebelement.h>
41 #include <qwebframe.h>
42 #include <qwebhistory.h>
43 #include <qwebpage.h>
44 #include <qwebsecurityorigin.h>
45 #include <qwebview.h>
46 #include <qimagewriter.h>
47
48 class EventSpy : public QObject, public QList<QEvent::Type>
49 {
50     Q_OBJECT
51 public:
52     EventSpy(QObject* objectToSpy)
53     {
54         objectToSpy->installEventFilter(this);
55     }
56
57     virtual bool eventFilter(QObject* receiver, QEvent* event)
58     {
59         append(event->type());
60         return false;
61     }
62 };
63
64 class tst_QWebPage : public QObject
65 {
66     Q_OBJECT
67
68 public:
69     tst_QWebPage();
70     virtual ~tst_QWebPage();
71
72 public slots:
73     void init();
74     void cleanup();
75     void cleanupFiles();
76
77 private slots:
78     void initTestCase();
79     void cleanupTestCase();
80
81     void contextMenuCopy();
82     void acceptNavigationRequest();
83     void geolocationRequestJS();
84     void loadFinished();
85     void acceptNavigationRequestWithNewWindow();
86     void userStyleSheet();
87     void loadHtml5Video();
88     void modified();
89     void contextMenuCrash();
90     void updatePositionDependentActionsCrash();
91     void database();
92     void createPluginWithPluginsEnabled();
93     void createPluginWithPluginsDisabled();
94     void destroyPlugin_data();
95     void destroyPlugin();
96     void createViewlessPlugin_data();
97     void createViewlessPlugin();
98     void graphicsWidgetPlugin();
99     void multiplePageGroupsAndLocalStorage();
100     void cursorMovements();
101     void textSelection();
102     void textEditing();
103     void backActionUpdate();
104     void frameAt();
105     void requestCache();
106     void loadCachedPage();
107     void protectBindingsRuntimeObjectsFromCollector();
108     void localURLSchemes();
109     void testOptionalJSObjects();
110     void testEnablePersistentStorage();
111     void consoleOutput();
112     void inputMethods_data();
113     void inputMethods();
114     void inputMethodsTextFormat_data();
115     void inputMethodsTextFormat();
116     void defaultTextEncoding();
117     void errorPageExtension();
118     void errorPageExtensionInIFrames();
119     void errorPageExtensionInFrameset();
120     void userAgentApplicationName();
121
122     void viewModes();
123
124     void crashTests_LazyInitializationOfMainFrame();
125
126     void screenshot_data();
127     void screenshot();
128
129 #if defined(ENABLE_WEBGL) && ENABLE_WEBGL
130     void acceleratedWebGLScreenshotWithoutView();
131     void unacceleratedWebGLScreenshotWithoutView();
132 #endif
133
134     void originatingObjectInNetworkRequests();
135     void testJSPrompt();
136     void showModalDialog();
137     void testStopScheduledPageRefresh();
138     void findText();
139     void supportedContentType();
140     void infiniteLoopJS();
141     void navigatorCookieEnabled();
142     void deleteQWebViewTwice();
143     void renderOnRepaintRequestedShouldNotRecurse();
144
145 #ifdef Q_OS_MAC
146     void macCopyUnicodeToClipboard();
147 #endif
148     
149 private:
150     QWebView* m_view;
151     QWebPage* m_page;
152 };
153
154 tst_QWebPage::tst_QWebPage()
155 {
156 }
157
158 tst_QWebPage::~tst_QWebPage()
159 {
160 }
161
162 void tst_QWebPage::init()
163 {
164     m_view = new QWebView();
165     m_page = m_view->page();
166 }
167
168 void tst_QWebPage::cleanup()
169 {
170     delete m_view;
171 }
172
173 void tst_QWebPage::cleanupFiles()
174 {
175     QFile::remove("Databases.db");
176     QDir::current().rmdir("http_www.myexample.com_0");
177     QFile::remove("http_www.myexample.com_0.localstorage");
178 }
179
180 void tst_QWebPage::initTestCase()
181 {
182     cleanupFiles(); // In case there are old files from previous runs
183 }
184
185 void tst_QWebPage::cleanupTestCase()
186 {
187     cleanupFiles(); // Be nice
188 }
189
190 class NavigationRequestOverride : public QWebPage
191 {
192 public:
193     NavigationRequestOverride(QWebView* parent, bool initialValue) : QWebPage(parent), m_acceptNavigationRequest(initialValue) {}
194
195     bool m_acceptNavigationRequest;
196 protected:
197     virtual bool acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest &request, QWebPage::NavigationType type) {
198         Q_UNUSED(frame);
199         Q_UNUSED(request);
200         Q_UNUSED(type);
201
202         return m_acceptNavigationRequest;
203     }
204 };
205
206 void tst_QWebPage::acceptNavigationRequest()
207 {
208     QSignalSpy loadSpy(m_view, SIGNAL(loadFinished(bool)));
209
210     NavigationRequestOverride* newPage = new NavigationRequestOverride(m_view, false);
211     m_view->setPage(newPage);
212
213     m_view->setHtml(QString("<html><body><form name='tstform' action='data:text/html,foo'method='get'>"
214                             "<input type='text'><input type='submit'></form></body></html>"), QUrl());
215     QTRY_COMPARE(loadSpy.count(), 1);
216
217     m_view->page()->mainFrame()->evaluateJavaScript("tstform.submit();");
218
219     newPage->m_acceptNavigationRequest = true;
220     m_view->page()->mainFrame()->evaluateJavaScript("tstform.submit();");
221     QTRY_COMPARE(loadSpy.count(), 2);
222
223     QCOMPARE(m_view->page()->mainFrame()->toPlainText(), QString("foo?"));
224
225     // Restore default page
226     m_view->setPage(0);
227 }
228
229 class JSTestPage : public QWebPage
230 {
231 Q_OBJECT
232 public:
233     JSTestPage(QObject* parent = 0)
234     : QWebPage(parent) {}
235
236 public slots:
237     bool shouldInterruptJavaScript() {
238         return true;
239     }
240     void requestPermission(QWebFrame* frame, QWebPage::Feature feature)
241     {
242         if (m_allowGeolocation)
243             setFeaturePermission(frame, feature, PermissionGrantedByUser);
244         else 
245             setFeaturePermission(frame, feature, PermissionDeniedByUser);
246     }
247
248 public:
249     void setGeolocationPermission(bool allow) 
250     {
251         m_allowGeolocation = allow;
252     }
253
254 private: 
255     bool m_allowGeolocation;
256 };
257
258 void tst_QWebPage::infiniteLoopJS()
259 {
260     JSTestPage* newPage = new JSTestPage(m_view);
261     m_view->setPage(newPage);
262     m_view->setHtml(QString("<html><body>test</body></html>"), QUrl());
263     m_view->page()->mainFrame()->evaluateJavaScript("var run = true;var a = 1;while(run){a++;}");
264     delete newPage;
265 }
266
267 void tst_QWebPage::geolocationRequestJS()
268 {
269     JSTestPage* newPage = new JSTestPage(m_view);
270
271     if (newPage->mainFrame()->evaluateJavaScript(QLatin1String("!navigator.geolocation")).toBool()) {
272         delete newPage;
273         QSKIP("Geolocation is not supported.", SkipSingle);
274     }
275
276     connect(newPage, SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)),
277             newPage, SLOT(requestPermission(QWebFrame*, QWebPage::Feature)));
278
279     newPage->setGeolocationPermission(false);
280     m_view->setPage(newPage);
281     m_view->setHtml(QString("<html><body>test</body></html>"), QUrl());
282     m_view->page()->mainFrame()->evaluateJavaScript("var errorCode = 0; function error(err) { errorCode = err.code; } function success(pos) { } navigator.geolocation.getCurrentPosition(success, error)");
283     QTest::qWait(2000);
284     QVariant empty = m_view->page()->mainFrame()->evaluateJavaScript("errorCode");
285
286     QVERIFY(empty.type() == QVariant::Double && empty.toInt() != 0);
287
288     newPage->setGeolocationPermission(true);
289     m_view->page()->mainFrame()->evaluateJavaScript("errorCode = 0; navigator.geolocation.getCurrentPosition(success, error);");
290     empty = m_view->page()->mainFrame()->evaluateJavaScript("errorCode");
291
292     //http://dev.w3.org/geo/api/spec-source.html#position
293     //PositionError: const unsigned short PERMISSION_DENIED = 1;
294     QVERIFY(empty.type() == QVariant::Double && empty.toInt() != 1);
295     delete newPage;
296 }
297
298 void tst_QWebPage::loadFinished()
299 {
300     qRegisterMetaType<QWebFrame*>("QWebFrame*");
301     qRegisterMetaType<QNetworkRequest*>("QNetworkRequest*");
302     QSignalSpy spyLoadStarted(m_view, SIGNAL(loadStarted()));
303     QSignalSpy spyLoadFinished(m_view, SIGNAL(loadFinished(bool)));
304
305     m_view->page()->mainFrame()->load(QUrl("data:text/html,<frameset cols=\"25%,75%\"><frame src=\"data:text/html,"
306                                            "<head><meta http-equiv='refresh' content='1'></head>foo \">"
307                                            "<frame src=\"data:text/html,bar\"></frameset>"));
308     QTRY_COMPARE(spyLoadFinished.count(), 1);
309
310     QTRY_VERIFY(spyLoadStarted.count() > 1);
311     QTRY_VERIFY(spyLoadFinished.count() > 1);
312
313     spyLoadFinished.clear();
314
315     m_view->page()->mainFrame()->load(QUrl("data:text/html,<frameset cols=\"25%,75%\"><frame src=\"data:text/html,"
316                                            "foo \"><frame src=\"data:text/html,bar\"></frameset>"));
317     QTRY_COMPARE(spyLoadFinished.count(), 1);
318     QCOMPARE(spyLoadFinished.count(), 1);
319 }
320
321 class ConsolePage : public QWebPage
322 {
323 public:
324     ConsolePage(QObject* parent = 0) : QWebPage(parent) {}
325
326     virtual void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID)
327     {
328         messages.append(message);
329         lineNumbers.append(lineNumber);
330         sourceIDs.append(sourceID);
331     }
332
333     QStringList messages;
334     QList<int> lineNumbers;
335     QStringList sourceIDs;
336 };
337
338 void tst_QWebPage::consoleOutput()
339 {
340     ConsolePage page;
341     page.mainFrame()->evaluateJavaScript("this is not valid JavaScript");
342     QCOMPARE(page.messages.count(), 1);
343     QCOMPARE(page.lineNumbers.at(0), 1);
344 }
345
346 class TestPage : public QWebPage
347 {
348 public:
349     TestPage(QObject* parent = 0) : QWebPage(parent) {}
350
351     struct Navigation {
352         QPointer<QWebFrame> frame;
353         QNetworkRequest request;
354         NavigationType type;
355     };
356
357     QList<Navigation> navigations;
358     QList<QWebPage*> createdWindows;
359
360     virtual bool acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest &request, NavigationType type) {
361         Navigation n;
362         n.frame = frame;
363         n.request = request;
364         n.type = type;
365         navigations.append(n);
366         return true;
367     }
368
369     virtual QWebPage* createWindow(WebWindowType) {
370         QWebPage* page = new TestPage(this);
371         createdWindows.append(page);
372         return page;
373     }
374 };
375
376 void tst_QWebPage::acceptNavigationRequestWithNewWindow()
377 {
378     TestPage* page = new TestPage(m_view);
379     page->settings()->setAttribute(QWebSettings::LinksIncludedInFocusChain, true);
380     m_page = page;
381     m_view->setPage(m_page);
382
383     m_view->setUrl(QString("data:text/html,<a href=\"data:text/html,Reached\" target=\"_blank\">Click me</a>"));
384     QVERIFY(::waitForSignal(m_view, SIGNAL(loadFinished(bool))));
385
386     QFocusEvent fe(QEvent::FocusIn);
387     m_page->event(&fe);
388
389     QVERIFY(m_page->focusNextPrevChild(/*next*/ true));
390
391     QKeyEvent keyEnter(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
392     m_page->event(&keyEnter);
393
394     QCOMPARE(page->navigations.count(), 2);
395
396     TestPage::Navigation n = page->navigations.at(1);
397     QVERIFY(n.frame.isNull());
398     QCOMPARE(n.request.url().toString(), QString("data:text/html,Reached"));
399     QVERIFY(n.type == QWebPage::NavigationTypeLinkClicked);
400
401     QCOMPARE(page->createdWindows.count(), 1);
402 }
403
404 class TestNetworkManager : public QNetworkAccessManager
405 {
406 public:
407     TestNetworkManager(QObject* parent) : QNetworkAccessManager(parent) {}
408
409     QList<QUrl> requestedUrls;
410     QList<QNetworkRequest> requests;
411
412 protected:
413     virtual QNetworkReply* createRequest(Operation op, const QNetworkRequest &request, QIODevice* outgoingData) {
414         requests.append(request);
415         requestedUrls.append(request.url());
416         return QNetworkAccessManager::createRequest(op, request, outgoingData);
417     }
418 };
419
420 void tst_QWebPage::userStyleSheet()
421 {
422     TestNetworkManager* networkManager = new TestNetworkManager(m_page);
423     m_page->setNetworkAccessManager(networkManager);
424     networkManager->requestedUrls.clear();
425
426     m_page->settings()->setUserStyleSheetUrl(QUrl("data:text/css;charset=utf-8;base64,"
427             + QByteArray("p { background-image: url('http://does.not/exist.png');}").toBase64()));
428     m_view->setHtml("<p>hello world</p>");
429     QVERIFY(::waitForSignal(m_view, SIGNAL(loadFinished(bool))));
430
431     QVERIFY(networkManager->requestedUrls.count() >= 1);
432     QCOMPARE(networkManager->requestedUrls.at(0), QUrl("http://does.not/exist.png"));
433 }
434
435 void tst_QWebPage::loadHtml5Video()
436 {
437 #if defined(ENABLE_QT_MULTIMEDIA) && ENABLE_QT_MULTIMEDIA
438     QByteArray url("http://does.not/exist?a=1%2Cb=2");
439     m_view->setHtml("<p><video id ='video' src='" + url + "' autoplay/></p>");
440     QTest::qWait(2000);
441     QUrl mUrl = DumpRenderTreeSupportQt::mediaContentUrlByElementId(m_page->mainFrame(), "video");
442     QCOMPARE(mUrl.toEncoded(), url);
443 #else
444     QSKIP("This test requires Qt Multimedia", SkipAll);
445 #endif
446 }
447
448 void tst_QWebPage::viewModes()
449 {
450     m_view->setHtml("<body></body>");
451     m_page->setProperty("_q_viewMode", "minimized");
452
453     QVariant empty = m_page->mainFrame()->evaluateJavaScript("window.styleMedia.matchMedium(\"(-webkit-view-mode)\")");
454     QVERIFY(empty.type() == QVariant::Bool && empty.toBool());
455
456     QVariant minimized = m_page->mainFrame()->evaluateJavaScript("window.styleMedia.matchMedium(\"(-webkit-view-mode: minimized)\")");
457     QVERIFY(minimized.type() == QVariant::Bool && minimized.toBool());
458
459     QVariant maximized = m_page->mainFrame()->evaluateJavaScript("window.styleMedia.matchMedium(\"(-webkit-view-mode: maximized)\")");
460     QVERIFY(maximized.type() == QVariant::Bool && !maximized.toBool());
461 }
462
463 void tst_QWebPage::modified()
464 {
465     m_page->mainFrame()->setUrl(QUrl("data:text/html,<body>blub"));
466     QVERIFY(::waitForSignal(m_view, SIGNAL(loadFinished(bool))));
467
468     m_page->mainFrame()->setUrl(QUrl("data:text/html,<body id=foo contenteditable>blah"));
469     QVERIFY(::waitForSignal(m_view, SIGNAL(loadFinished(bool))));
470
471     QVERIFY(!m_page->isModified());
472
473 //    m_page->mainFrame()->evaluateJavaScript("alert(document.getElementById('foo'))");
474     m_page->mainFrame()->evaluateJavaScript("document.getElementById('foo').focus()");
475     m_page->mainFrame()->evaluateJavaScript("document.execCommand('InsertText', true, 'Test');");
476
477     QVERIFY(m_page->isModified());
478
479     m_page->mainFrame()->evaluateJavaScript("document.execCommand('Undo', true);");
480
481     QVERIFY(!m_page->isModified());
482
483     m_page->mainFrame()->evaluateJavaScript("document.execCommand('Redo', true);");
484
485     QVERIFY(m_page->isModified());
486
487     QVERIFY(m_page->history()->canGoBack());
488     QVERIFY(!m_page->history()->canGoForward());
489     QCOMPARE(m_page->history()->count(), 2);
490     QVERIFY(m_page->history()->backItem().isValid());
491     QVERIFY(!m_page->history()->forwardItem().isValid());
492
493     m_page->history()->back();
494     QVERIFY(::waitForSignal(m_view, SIGNAL(loadFinished(bool))));
495
496     QVERIFY(!m_page->history()->canGoBack());
497     QVERIFY(m_page->history()->canGoForward());
498
499     QVERIFY(!m_page->isModified());
500
501     QVERIFY(m_page->history()->currentItemIndex() == 0);
502
503     m_page->history()->setMaximumItemCount(3);
504     QVERIFY(m_page->history()->maximumItemCount() == 3);
505
506     QVariant variant("string test");
507     m_page->history()->currentItem().setUserData(variant);
508     QVERIFY(m_page->history()->currentItem().userData().toString() == "string test");
509
510     m_page->mainFrame()->setUrl(QUrl("data:text/html,<body>This is second page"));
511     m_page->mainFrame()->setUrl(QUrl("data:text/html,<body>This is third page"));
512     QVERIFY(m_page->history()->count() == 2);
513     m_page->mainFrame()->setUrl(QUrl("data:text/html,<body>This is fourth page"));
514     QVERIFY(m_page->history()->count() == 2);
515     m_page->mainFrame()->setUrl(QUrl("data:text/html,<body>This is fifth page"));
516     QVERIFY(::waitForSignal(m_page, SIGNAL(saveFrameStateRequested(QWebFrame*,QWebHistoryItem*))));
517 }
518
519 // https://bugs.webkit.org/show_bug.cgi?id=51331
520 void tst_QWebPage::updatePositionDependentActionsCrash()
521 {
522     QWebView view;
523     view.setHtml("<p>test");
524     QPoint pos(0, 0);
525     view.page()->updatePositionDependentActions(pos);
526     QMenu* contextMenu = 0;
527     foreach (QObject* child, view.children()) {
528         contextMenu = qobject_cast<QMenu*>(child);
529         if (contextMenu)
530             break;
531     }
532     QVERIFY(!contextMenu);
533 }
534
535 // https://bugs.webkit.org/show_bug.cgi?id=20357
536 void tst_QWebPage::contextMenuCrash()
537 {
538     QWebView view;
539     view.setHtml("<p>test");
540     QPoint pos(0, 0);
541     QContextMenuEvent event(QContextMenuEvent::Mouse, pos);
542     view.page()->swallowContextMenuEvent(&event);
543     view.page()->updatePositionDependentActions(pos);
544     QMenu* contextMenu = 0;
545     foreach (QObject* child, view.children()) {
546         contextMenu = qobject_cast<QMenu*>(child);
547         if (contextMenu)
548             break;
549     }
550     QVERIFY(contextMenu);
551     delete contextMenu;
552 }
553
554 void tst_QWebPage::database()
555 {
556     QString path = QDir::currentPath();
557     m_page->settings()->setOfflineStoragePath(path);
558     QVERIFY(m_page->settings()->offlineStoragePath() == path);
559
560     QWebSettings::setOfflineStorageDefaultQuota(1024 * 1024);
561     QVERIFY(QWebSettings::offlineStorageDefaultQuota() == 1024 * 1024);
562
563     m_page->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
564     m_page->settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);
565
566     QString dbFileName = path + "Databases.db";
567
568     if (QFile::exists(dbFileName))
569         QFile::remove(dbFileName);
570
571     qRegisterMetaType<QWebFrame*>("QWebFrame*");
572     QSignalSpy spy(m_page, SIGNAL(databaseQuotaExceeded(QWebFrame*,QString)));
573     m_view->setHtml(QString("<html><head><script>var db; db=openDatabase('testdb', '1.0', 'test database API', 50000); </script></head><body><div></div></body></html>"), QUrl("http://www.myexample.com"));
574     QTRY_COMPARE(spy.count(), 1);
575     m_page->mainFrame()->evaluateJavaScript("var db2; db2=openDatabase('testdb', '1.0', 'test database API', 50000);");
576     QTRY_COMPARE(spy.count(),1);
577
578     m_page->mainFrame()->evaluateJavaScript("localStorage.test='This is a test for local storage';");
579     m_view->setHtml(QString("<html><body id='b'>text</body></html>"), QUrl("http://www.myexample.com"));
580
581     QVariant s1 = m_page->mainFrame()->evaluateJavaScript("localStorage.test");
582     QCOMPARE(s1.toString(), QString("This is a test for local storage"));
583
584     m_page->mainFrame()->evaluateJavaScript("sessionStorage.test='This is a test for session storage';");
585     m_view->setHtml(QString("<html><body id='b'>text</body></html>"), QUrl("http://www.myexample.com"));
586     QVariant s2 = m_page->mainFrame()->evaluateJavaScript("sessionStorage.test");
587     QCOMPARE(s2.toString(), QString("This is a test for session storage"));
588
589     m_view->setHtml(QString("<html><head></head><body><div></div></body></html>"), QUrl("http://www.myexample.com"));
590     m_page->mainFrame()->evaluateJavaScript("var db3; db3=openDatabase('testdb', '1.0', 'test database API', 50000);db3.transaction(function(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS Test (text TEXT)', []); }, function(tx, result) { }, function(tx, error) { });");
591     QTest::qWait(200);
592
593     // Remove all databases.
594     QWebSecurityOrigin origin = m_page->mainFrame()->securityOrigin();
595     QList<QWebDatabase> dbs = origin.databases();
596     for (int i = 0; i < dbs.count(); i++) {
597         QString fileName = dbs[i].fileName();
598         QVERIFY(QFile::exists(fileName));
599         QWebDatabase::removeDatabase(dbs[i]);
600         QVERIFY(!QFile::exists(fileName));
601     }
602     QVERIFY(!origin.databases().size());
603     // Remove removed test :-)
604     QWebDatabase::removeAllDatabases();
605     QVERIFY(!origin.databases().size());
606 }
607
608 class PluginPage : public QWebPage
609 {
610 public:
611     PluginPage(QObject *parent = 0)
612         : QWebPage(parent) {}
613
614     struct CallInfo
615     {
616         CallInfo(const QString &c, const QUrl &u,
617                  const QStringList &pn, const QStringList &pv,
618                  QObject *r)
619             : classid(c), url(u), paramNames(pn),
620               paramValues(pv), returnValue(r)
621             {}
622         QString classid;
623         QUrl url;
624         QStringList paramNames;
625         QStringList paramValues;
626         QObject *returnValue;
627     };
628
629     QList<CallInfo> calls;
630
631 protected:
632     virtual QObject *createPlugin(const QString &classid, const QUrl &url,
633                                   const QStringList &paramNames,
634                                   const QStringList &paramValues)
635     {
636         QObject *result = 0;
637         if (classid == "pushbutton")
638             result = new QPushButton();
639 #ifndef QT_NO_INPUTDIALOG
640         else if (classid == "lineedit")
641             result = new QLineEdit();
642 #endif
643         else if (classid == "graphicswidget")
644             result = new QGraphicsWidget();
645         if (result)
646             result->setObjectName(classid);
647         calls.append(CallInfo(classid, url, paramNames, paramValues, result));
648         return result;
649     }
650 };
651
652 static void createPlugin(QWebView *view)
653 {
654     QSignalSpy loadSpy(view, SIGNAL(loadFinished(bool)));
655
656     PluginPage* newPage = new PluginPage(view);
657     view->setPage(newPage);
658
659     // type has to be application/x-qt-plugin
660     view->setHtml(QString("<html><body><object type='application/x-foobarbaz' classid='pushbutton' id='mybutton'/></body></html>"));
661     QTRY_COMPARE(loadSpy.count(), 1);
662     QCOMPARE(newPage->calls.count(), 0);
663
664     view->setHtml(QString("<html><body><object type='application/x-qt-plugin' classid='pushbutton' id='mybutton'/></body></html>"));
665     QTRY_COMPARE(loadSpy.count(), 2);
666     QCOMPARE(newPage->calls.count(), 1);
667     {
668         PluginPage::CallInfo ci = newPage->calls.takeFirst();
669         QCOMPARE(ci.classid, QString::fromLatin1("pushbutton"));
670         QCOMPARE(ci.url, QUrl());
671         QCOMPARE(ci.paramNames.count(), 3);
672         QCOMPARE(ci.paramValues.count(), 3);
673         QCOMPARE(ci.paramNames.at(0), QString::fromLatin1("type"));
674         QCOMPARE(ci.paramValues.at(0), QString::fromLatin1("application/x-qt-plugin"));
675         QCOMPARE(ci.paramNames.at(1), QString::fromLatin1("classid"));
676         QCOMPARE(ci.paramValues.at(1), QString::fromLatin1("pushbutton"));
677         QCOMPARE(ci.paramNames.at(2), QString::fromLatin1("id"));
678         QCOMPARE(ci.paramValues.at(2), QString::fromLatin1("mybutton"));
679         QVERIFY(ci.returnValue != 0);
680         QVERIFY(ci.returnValue->inherits("QPushButton"));
681     }
682     // test JS bindings
683     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("document.getElementById('mybutton').toString()").toString(),
684              QString::fromLatin1("[object HTMLObjectElement]"));
685     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("mybutton.toString()").toString(),
686              QString::fromLatin1("[object HTMLObjectElement]"));
687     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("typeof mybutton.objectName").toString(),
688              QString::fromLatin1("string"));
689     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("mybutton.objectName").toString(),
690              QString::fromLatin1("pushbutton"));
691     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("typeof mybutton.clicked").toString(),
692              QString::fromLatin1("function"));
693     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("mybutton.clicked.toString()").toString(),
694              QString::fromLatin1("function clicked() {\n    [native code]\n}"));
695
696     view->setHtml(QString("<html><body><table>"
697                             "<tr><object type='application/x-qt-plugin' classid='lineedit' id='myedit'/></tr>"
698                             "<tr><object type='application/x-qt-plugin' classid='pushbutton' id='mybutton'/></tr>"
699                             "</table></body></html>"), QUrl("http://foo.bar.baz"));
700     QTRY_COMPARE(loadSpy.count(), 3);
701     QCOMPARE(newPage->calls.count(), 2);
702     {
703         PluginPage::CallInfo ci = newPage->calls.takeFirst();
704         QCOMPARE(ci.classid, QString::fromLatin1("lineedit"));
705         QCOMPARE(ci.url, QUrl());
706         QCOMPARE(ci.paramNames.count(), 3);
707         QCOMPARE(ci.paramValues.count(), 3);
708         QCOMPARE(ci.paramNames.at(0), QString::fromLatin1("type"));
709         QCOMPARE(ci.paramValues.at(0), QString::fromLatin1("application/x-qt-plugin"));
710         QCOMPARE(ci.paramNames.at(1), QString::fromLatin1("classid"));
711         QCOMPARE(ci.paramValues.at(1), QString::fromLatin1("lineedit"));
712         QCOMPARE(ci.paramNames.at(2), QString::fromLatin1("id"));
713         QCOMPARE(ci.paramValues.at(2), QString::fromLatin1("myedit"));
714         QVERIFY(ci.returnValue != 0);
715         QVERIFY(ci.returnValue->inherits("QLineEdit"));
716     }
717     {
718         PluginPage::CallInfo ci = newPage->calls.takeFirst();
719         QCOMPARE(ci.classid, QString::fromLatin1("pushbutton"));
720         QCOMPARE(ci.url, QUrl());
721         QCOMPARE(ci.paramNames.count(), 3);
722         QCOMPARE(ci.paramValues.count(), 3);
723         QCOMPARE(ci.paramNames.at(0), QString::fromLatin1("type"));
724         QCOMPARE(ci.paramValues.at(0), QString::fromLatin1("application/x-qt-plugin"));
725         QCOMPARE(ci.paramNames.at(1), QString::fromLatin1("classid"));
726         QCOMPARE(ci.paramValues.at(1), QString::fromLatin1("pushbutton"));
727         QCOMPARE(ci.paramNames.at(2), QString::fromLatin1("id"));
728         QCOMPARE(ci.paramValues.at(2), QString::fromLatin1("mybutton"));
729         QVERIFY(ci.returnValue != 0);
730         QVERIFY(ci.returnValue->inherits("QPushButton"));
731     }
732 }
733
734 void tst_QWebPage::graphicsWidgetPlugin()
735 {
736     m_view->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
737     QGraphicsWebView webView;
738
739     QSignalSpy loadSpy(&webView, SIGNAL(loadFinished(bool)));
740
741     PluginPage* newPage = new PluginPage(&webView);
742     webView.setPage(newPage);
743
744     // type has to be application/x-qt-plugin
745     webView.setHtml(QString("<html><body><object type='application/x-foobarbaz' classid='graphicswidget' id='mygraphicswidget'/></body></html>"));
746     QTRY_COMPARE(loadSpy.count(), 1);
747     QCOMPARE(newPage->calls.count(), 0);
748
749     webView.setHtml(QString("<html><body><object type='application/x-qt-plugin' classid='graphicswidget' id='mygraphicswidget'/></body></html>"));
750     QTRY_COMPARE(loadSpy.count(), 2);
751     QCOMPARE(newPage->calls.count(), 1);
752     {
753         PluginPage::CallInfo ci = newPage->calls.takeFirst();
754         QCOMPARE(ci.classid, QString::fromLatin1("graphicswidget"));
755         QCOMPARE(ci.url, QUrl());
756         QCOMPARE(ci.paramNames.count(), 3);
757         QCOMPARE(ci.paramValues.count(), 3);
758         QCOMPARE(ci.paramNames.at(0), QString::fromLatin1("type"));
759         QCOMPARE(ci.paramValues.at(0), QString::fromLatin1("application/x-qt-plugin"));
760         QCOMPARE(ci.paramNames.at(1), QString::fromLatin1("classid"));
761         QCOMPARE(ci.paramValues.at(1), QString::fromLatin1("graphicswidget"));
762         QCOMPARE(ci.paramNames.at(2), QString::fromLatin1("id"));
763         QCOMPARE(ci.paramValues.at(2), QString::fromLatin1("mygraphicswidget"));
764         QVERIFY(ci.returnValue);
765         QVERIFY(ci.returnValue->inherits("QGraphicsWidget"));
766     }
767     // test JS bindings
768     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("document.getElementById('mygraphicswidget').toString()").toString(),
769              QString::fromLatin1("[object HTMLObjectElement]"));
770     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("mygraphicswidget.toString()").toString(),
771              QString::fromLatin1("[object HTMLObjectElement]"));
772     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("typeof mygraphicswidget.objectName").toString(),
773              QString::fromLatin1("string"));
774     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("mygraphicswidget.objectName").toString(),
775              QString::fromLatin1("graphicswidget"));
776     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("typeof mygraphicswidget.geometryChanged").toString(),
777              QString::fromLatin1("function"));
778     QCOMPARE(newPage->mainFrame()->evaluateJavaScript("mygraphicswidget.geometryChanged.toString()").toString(),
779              QString::fromLatin1("function geometryChanged() {\n    [native code]\n}"));
780 }
781
782 void tst_QWebPage::createPluginWithPluginsEnabled()
783 {
784     m_view->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
785     createPlugin(m_view);
786 }
787
788 void tst_QWebPage::createPluginWithPluginsDisabled()
789 {
790     // Qt Plugins should be loaded by QtWebKit even when PluginsEnabled is
791     // false. The client decides whether a Qt plugin is enabled or not when
792     // it decides whether or not to instantiate it.
793     m_view->settings()->setAttribute(QWebSettings::PluginsEnabled, false);
794     createPlugin(m_view);
795 }
796
797 // Standard base class for template PluginTracerPage. In tests it is used as interface.
798 class PluginCounterPage : public QWebPage {
799 public:
800     int m_count;
801     QPointer<QObject> m_widget;
802     QObject* m_pluginParent;
803     PluginCounterPage(QObject* parent = 0)
804         : QWebPage(parent)
805         , m_count(0)
806         , m_widget(0)
807         , m_pluginParent(0)
808     {
809        settings()->setAttribute(QWebSettings::PluginsEnabled, true);
810     }
811     ~PluginCounterPage()
812     {
813         if (m_pluginParent)
814             m_pluginParent->deleteLater();
815     }
816 };
817
818 template<class T>
819 class PluginTracerPage : public PluginCounterPage {
820 public:
821     PluginTracerPage(QObject* parent = 0)
822         : PluginCounterPage(parent)
823     {
824         // this is a dummy parent object for the created plugin
825         m_pluginParent = new T;
826     }
827     virtual QObject* createPlugin(const QString&, const QUrl&, const QStringList&, const QStringList&)
828     {
829         m_count++;
830         m_widget = new T;
831         // need a cast to the specific type, as QObject::setParent cannot be called,
832         // because it is not virtual. Instead it is necesary to call QWidget::setParent,
833         // which also takes a QWidget* instead of a QObject*. Therefore we need to
834         // upcast to T*, which is a QWidget.
835         static_cast<T*>(m_widget.data())->setParent(static_cast<T*>(m_pluginParent));
836         return m_widget;
837     }
838 };
839
840 class PluginFactory {
841 public:
842     enum FactoredType {QWidgetType, QGraphicsWidgetType};
843     static PluginCounterPage* create(FactoredType type, QObject* parent = 0)
844     {
845         PluginCounterPage* result = 0;
846         switch (type) {
847         case QWidgetType:
848             result = new PluginTracerPage<QWidget>(parent);
849             break;
850         case QGraphicsWidgetType:
851             result = new PluginTracerPage<QGraphicsWidget>(parent);
852             break;
853         default: {/*Oops*/};
854         }
855         return result;
856     }
857
858     static void prepareTestData()
859     {
860         QTest::addColumn<int>("type");
861         QTest::newRow("QWidget") << (int)PluginFactory::QWidgetType;
862         QTest::newRow("QGraphicsWidget") << (int)PluginFactory::QGraphicsWidgetType;
863     }
864 };
865
866 void tst_QWebPage::destroyPlugin_data()
867 {
868     PluginFactory::prepareTestData();
869 }
870
871 void tst_QWebPage::destroyPlugin()
872 {
873     QFETCH(int, type);
874     PluginCounterPage* page = PluginFactory::create((PluginFactory::FactoredType)type, m_view);
875     m_view->setPage(page);
876
877     // we create the plugin, so the widget should be constructed
878     QString content("<html><body><object type=\"application/x-qt-plugin\" classid=\"QProgressBar\"></object></body></html>");
879     m_view->setHtml(content);
880     QVERIFY(page->m_widget);
881     QCOMPARE(page->m_count, 1);
882
883     // navigate away, the plugin widget should be destructed
884     m_view->setHtml("<html><body>Hi</body></html>");
885     QTestEventLoop::instance().enterLoop(1);
886     QVERIFY(!page->m_widget);
887 }
888
889 void tst_QWebPage::createViewlessPlugin_data()
890 {
891     PluginFactory::prepareTestData();
892 }
893
894 void tst_QWebPage::createViewlessPlugin()
895 {
896     QFETCH(int, type);
897     PluginCounterPage* page = PluginFactory::create((PluginFactory::FactoredType)type);
898     QString content("<html><body><object type=\"application/x-qt-plugin\" classid=\"QProgressBar\"></object></body></html>");
899     page->mainFrame()->setHtml(content);
900     QCOMPARE(page->m_count, 1);
901     QVERIFY(page->m_widget);
902     QVERIFY(page->m_pluginParent);
903     QVERIFY(page->m_widget->parent() == page->m_pluginParent);
904     delete page;
905
906 }
907
908 void tst_QWebPage::multiplePageGroupsAndLocalStorage()
909 {
910     QDir dir(QDir::currentPath());
911     dir.mkdir("path1");
912     dir.mkdir("path2");
913
914     QWebView view1;
915     QWebView view2;
916
917     view1.page()->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
918     view1.page()->settings()->setLocalStoragePath(QDir::toNativeSeparators(QDir::currentPath() + "/path1"));
919     DumpRenderTreeSupportQt::webPageSetGroupName(view1.page(), "group1");
920     view2.page()->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);    
921     view2.page()->settings()->setLocalStoragePath(QDir::toNativeSeparators(QDir::currentPath() + "/path2"));
922     DumpRenderTreeSupportQt::webPageSetGroupName(view2.page(), "group2");
923     QCOMPARE(DumpRenderTreeSupportQt::webPageGroupName(view1.page()), QString("group1"));
924     QCOMPARE(DumpRenderTreeSupportQt::webPageGroupName(view2.page()), QString("group2"));
925
926
927     view1.setHtml(QString("<html><body> </body></html>"), QUrl("http://www.myexample.com"));
928     view2.setHtml(QString("<html><body> </body></html>"), QUrl("http://www.myexample.com"));
929
930     view1.page()->mainFrame()->evaluateJavaScript("localStorage.test='value1';");
931     view2.page()->mainFrame()->evaluateJavaScript("localStorage.test='value2';");
932
933     view1.setHtml(QString("<html><body> </body></html>"), QUrl("http://www.myexample.com"));
934     view2.setHtml(QString("<html><body> </body></html>"), QUrl("http://www.myexample.com"));
935
936     QVariant s1 = view1.page()->mainFrame()->evaluateJavaScript("localStorage.test");
937     QCOMPARE(s1.toString(), QString("value1"));
938
939     QVariant s2 = view2.page()->mainFrame()->evaluateJavaScript("localStorage.test");
940     QCOMPARE(s2.toString(), QString("value2"));
941
942     QTest::qWait(1000);
943
944     QFile::remove(QDir::toNativeSeparators(QDir::currentPath() + "/path1/http_www.myexample.com_0.localstorage"));
945     QFile::remove(QDir::toNativeSeparators(QDir::currentPath() + "/path2/http_www.myexample.com_0.localstorage"));
946     dir.rmdir(QDir::toNativeSeparators("./path1"));
947     dir.rmdir(QDir::toNativeSeparators("./path2"));
948 }
949
950 class CursorTrackedPage : public QWebPage
951 {
952 public:
953
954     CursorTrackedPage(QWidget *parent = 0): QWebPage(parent) {
955         setViewportSize(QSize(1024, 768)); // big space
956     }
957
958     QString selectedText() {
959         return mainFrame()->evaluateJavaScript("window.getSelection().toString()").toString();
960     }
961
962     int selectionStartOffset() {
963         return mainFrame()->evaluateJavaScript("window.getSelection().getRangeAt(0).startOffset").toInt();
964     }
965
966     int selectionEndOffset() {
967         return mainFrame()->evaluateJavaScript("window.getSelection().getRangeAt(0).endOffset").toInt();
968     }
969
970     // true if start offset == end offset, i.e. no selected text
971     int isSelectionCollapsed() {
972         return mainFrame()->evaluateJavaScript("window.getSelection().getRangeAt(0).collapsed").toBool();
973     }
974 };
975
976 void tst_QWebPage::cursorMovements()
977 {
978     CursorTrackedPage* page = new CursorTrackedPage;
979     QString content("<html><body><p id=one>The quick brown fox</p><p id=two>jumps over the lazy dog</p><p>May the source<br/>be with you!</p></body></html>");
980     page->mainFrame()->setHtml(content);
981
982     // this will select the first paragraph
983     QString script = "var range = document.createRange(); " \
984         "var node = document.getElementById(\"one\"); " \
985         "range.selectNode(node); " \
986         "getSelection().addRange(range);";
987     page->mainFrame()->evaluateJavaScript(script);
988     QCOMPARE(page->selectedText().trimmed(), QString::fromLatin1("The quick brown fox"));
989     QCOMPARE(page->selectedHtml().trimmed(), QString::fromLatin1("<span class=\"Apple-style-span\" style=\"border-collapse: separate; color: rgb(0, 0, 0); font-family: Times; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-align: -webkit-auto; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; font-size: medium; \"><p id=\"one\">The quick brown fox</p></span>"));
990
991     // these actions must exist
992     QVERIFY(page->action(QWebPage::MoveToNextChar) != 0);
993     QVERIFY(page->action(QWebPage::MoveToPreviousChar) != 0);
994     QVERIFY(page->action(QWebPage::MoveToNextWord) != 0);
995     QVERIFY(page->action(QWebPage::MoveToPreviousWord) != 0);
996     QVERIFY(page->action(QWebPage::MoveToNextLine) != 0);
997     QVERIFY(page->action(QWebPage::MoveToPreviousLine) != 0);
998     QVERIFY(page->action(QWebPage::MoveToStartOfLine) != 0);
999     QVERIFY(page->action(QWebPage::MoveToEndOfLine) != 0);
1000     QVERIFY(page->action(QWebPage::MoveToStartOfBlock) != 0);
1001     QVERIFY(page->action(QWebPage::MoveToEndOfBlock) != 0);
1002     QVERIFY(page->action(QWebPage::MoveToStartOfDocument) != 0);
1003     QVERIFY(page->action(QWebPage::MoveToEndOfDocument) != 0);
1004
1005     // right now they are disabled because contentEditable is false
1006     QCOMPARE(page->action(QWebPage::MoveToNextChar)->isEnabled(), false);
1007     QCOMPARE(page->action(QWebPage::MoveToPreviousChar)->isEnabled(), false);
1008     QCOMPARE(page->action(QWebPage::MoveToNextWord)->isEnabled(), false);
1009     QCOMPARE(page->action(QWebPage::MoveToPreviousWord)->isEnabled(), false);
1010     QCOMPARE(page->action(QWebPage::MoveToNextLine)->isEnabled(), false);
1011     QCOMPARE(page->action(QWebPage::MoveToPreviousLine)->isEnabled(), false);
1012     QCOMPARE(page->action(QWebPage::MoveToStartOfLine)->isEnabled(), false);
1013     QCOMPARE(page->action(QWebPage::MoveToEndOfLine)->isEnabled(), false);
1014     QCOMPARE(page->action(QWebPage::MoveToStartOfBlock)->isEnabled(), false);
1015     QCOMPARE(page->action(QWebPage::MoveToEndOfBlock)->isEnabled(), false);
1016     QCOMPARE(page->action(QWebPage::MoveToStartOfDocument)->isEnabled(), false);
1017     QCOMPARE(page->action(QWebPage::MoveToEndOfDocument)->isEnabled(), false);
1018
1019     // make it editable before navigating the cursor
1020     page->setContentEditable(true);
1021
1022     // here the actions are enabled after contentEditable is true
1023     QCOMPARE(page->action(QWebPage::MoveToNextChar)->isEnabled(), true);
1024     QCOMPARE(page->action(QWebPage::MoveToPreviousChar)->isEnabled(), true);
1025     QCOMPARE(page->action(QWebPage::MoveToNextWord)->isEnabled(), true);
1026     QCOMPARE(page->action(QWebPage::MoveToPreviousWord)->isEnabled(), true);
1027     QCOMPARE(page->action(QWebPage::MoveToNextLine)->isEnabled(), true);
1028     QCOMPARE(page->action(QWebPage::MoveToPreviousLine)->isEnabled(), true);
1029     QCOMPARE(page->action(QWebPage::MoveToStartOfLine)->isEnabled(), true);
1030     QCOMPARE(page->action(QWebPage::MoveToEndOfLine)->isEnabled(), true);
1031     QCOMPARE(page->action(QWebPage::MoveToStartOfBlock)->isEnabled(), true);
1032     QCOMPARE(page->action(QWebPage::MoveToEndOfBlock)->isEnabled(), true);
1033     QCOMPARE(page->action(QWebPage::MoveToStartOfDocument)->isEnabled(), true);
1034     QCOMPARE(page->action(QWebPage::MoveToEndOfDocument)->isEnabled(), true);
1035
1036     // cursor will be before the word "jump"
1037     page->triggerAction(QWebPage::MoveToNextChar);
1038     QVERIFY(page->isSelectionCollapsed());
1039     QCOMPARE(page->selectionStartOffset(), 0);
1040
1041     // cursor will be between 'j' and 'u' in the word "jump"
1042     page->triggerAction(QWebPage::MoveToNextChar);
1043     QVERIFY(page->isSelectionCollapsed());
1044     QCOMPARE(page->selectionStartOffset(), 1);
1045
1046     // cursor will be between 'u' and 'm' in the word "jump"
1047     page->triggerAction(QWebPage::MoveToNextChar);
1048     QVERIFY(page->isSelectionCollapsed());
1049     QCOMPARE(page->selectionStartOffset(), 2);
1050
1051     // cursor will be after the word "jump"
1052     page->triggerAction(QWebPage::MoveToNextWord);
1053     QVERIFY(page->isSelectionCollapsed());
1054     QCOMPARE(page->selectionStartOffset(), 5);
1055
1056     // cursor will be after the word "lazy"
1057     page->triggerAction(QWebPage::MoveToNextWord);
1058     page->triggerAction(QWebPage::MoveToNextWord);
1059     page->triggerAction(QWebPage::MoveToNextWord);
1060     QVERIFY(page->isSelectionCollapsed());
1061     QCOMPARE(page->selectionStartOffset(), 19);
1062
1063     // cursor will be between 'z' and 'y' in "lazy"
1064     page->triggerAction(QWebPage::MoveToPreviousChar);
1065     QVERIFY(page->isSelectionCollapsed());
1066     QCOMPARE(page->selectionStartOffset(), 18);
1067
1068     // cursor will be between 'a' and 'z' in "lazy"
1069     page->triggerAction(QWebPage::MoveToPreviousChar);
1070     QVERIFY(page->isSelectionCollapsed());
1071     QCOMPARE(page->selectionStartOffset(), 17);
1072
1073     // cursor will be before the word "lazy"
1074     page->triggerAction(QWebPage::MoveToPreviousWord);
1075     QVERIFY(page->isSelectionCollapsed());
1076     QCOMPARE(page->selectionStartOffset(), 15);
1077
1078     // cursor will be before the word "quick"
1079     page->triggerAction(QWebPage::MoveToPreviousWord);
1080     page->triggerAction(QWebPage::MoveToPreviousWord);
1081     page->triggerAction(QWebPage::MoveToPreviousWord);
1082     page->triggerAction(QWebPage::MoveToPreviousWord);
1083     page->triggerAction(QWebPage::MoveToPreviousWord);
1084     page->triggerAction(QWebPage::MoveToPreviousWord);
1085     QVERIFY(page->isSelectionCollapsed());
1086     QCOMPARE(page->selectionStartOffset(), 4);
1087
1088     // cursor will be between 'p' and 's' in the word "jumps"
1089     page->triggerAction(QWebPage::MoveToNextWord);
1090     page->triggerAction(QWebPage::MoveToNextWord);
1091     page->triggerAction(QWebPage::MoveToNextWord);
1092     page->triggerAction(QWebPage::MoveToNextChar);
1093     page->triggerAction(QWebPage::MoveToNextChar);
1094     page->triggerAction(QWebPage::MoveToNextChar);
1095     page->triggerAction(QWebPage::MoveToNextChar);
1096     page->triggerAction(QWebPage::MoveToNextChar);
1097     QVERIFY(page->isSelectionCollapsed());
1098     QCOMPARE(page->selectionStartOffset(), 4);
1099
1100     // cursor will be before the word "jumps"
1101     page->triggerAction(QWebPage::MoveToStartOfLine);
1102     QVERIFY(page->isSelectionCollapsed());
1103     QCOMPARE(page->selectionStartOffset(), 0);
1104
1105     // cursor will be after the word "dog"
1106     page->triggerAction(QWebPage::MoveToEndOfLine);
1107     QVERIFY(page->isSelectionCollapsed());
1108     QCOMPARE(page->selectionStartOffset(), 23);
1109
1110     // cursor will be between 'w' and 'n' in "brown"
1111     page->triggerAction(QWebPage::MoveToStartOfLine);
1112     page->triggerAction(QWebPage::MoveToPreviousWord);
1113     page->triggerAction(QWebPage::MoveToPreviousWord);
1114     page->triggerAction(QWebPage::MoveToNextChar);
1115     page->triggerAction(QWebPage::MoveToNextChar);
1116     page->triggerAction(QWebPage::MoveToNextChar);
1117     page->triggerAction(QWebPage::MoveToNextChar);
1118     QVERIFY(page->isSelectionCollapsed());
1119     QCOMPARE(page->selectionStartOffset(), 14);
1120
1121     // cursor will be after the word "fox"
1122     page->triggerAction(QWebPage::MoveToEndOfLine);
1123     QVERIFY(page->isSelectionCollapsed());
1124     QCOMPARE(page->selectionStartOffset(), 19);
1125
1126     // cursor will be before the word "The"
1127     page->triggerAction(QWebPage::MoveToStartOfDocument);
1128     QVERIFY(page->isSelectionCollapsed());
1129     QCOMPARE(page->selectionStartOffset(), 0);
1130
1131     // cursor will be after the word "you!"
1132     page->triggerAction(QWebPage::MoveToEndOfDocument);
1133     QVERIFY(page->isSelectionCollapsed());
1134     QCOMPARE(page->selectionStartOffset(), 12);
1135
1136     // cursor will be before the word "be"
1137     page->triggerAction(QWebPage::MoveToStartOfBlock);
1138     QVERIFY(page->isSelectionCollapsed());
1139     QCOMPARE(page->selectionStartOffset(), 0);
1140
1141     // cursor will be after the word "you!"
1142     page->triggerAction(QWebPage::MoveToEndOfBlock);
1143     QVERIFY(page->isSelectionCollapsed());
1144     QCOMPARE(page->selectionStartOffset(), 12);
1145
1146     // try to move before the document start
1147     page->triggerAction(QWebPage::MoveToStartOfDocument);
1148     page->triggerAction(QWebPage::MoveToPreviousChar);
1149     QVERIFY(page->isSelectionCollapsed());
1150     QCOMPARE(page->selectionStartOffset(), 0);
1151     page->triggerAction(QWebPage::MoveToStartOfDocument);
1152     page->triggerAction(QWebPage::MoveToPreviousWord);
1153     QVERIFY(page->isSelectionCollapsed());
1154     QCOMPARE(page->selectionStartOffset(), 0);
1155
1156     // try to move past the document end
1157     page->triggerAction(QWebPage::MoveToEndOfDocument);
1158     page->triggerAction(QWebPage::MoveToNextChar);
1159     QVERIFY(page->isSelectionCollapsed());
1160     QCOMPARE(page->selectionStartOffset(), 12);
1161     page->triggerAction(QWebPage::MoveToEndOfDocument);
1162     page->triggerAction(QWebPage::MoveToNextWord);
1163     QVERIFY(page->isSelectionCollapsed());
1164     QCOMPARE(page->selectionStartOffset(), 12);
1165
1166     delete page;
1167 }
1168
1169 void tst_QWebPage::textSelection()
1170 {
1171     CursorTrackedPage* page = new CursorTrackedPage;
1172     QString content("<html><body><p id=one>The quick brown fox</p>" \
1173         "<p id=two>jumps over the lazy dog</p>" \
1174         "<p>May the source<br/>be with you!</p></body></html>");
1175     page->mainFrame()->setHtml(content);
1176
1177     // these actions must exist
1178     QVERIFY(page->action(QWebPage::SelectAll) != 0);
1179     QVERIFY(page->action(QWebPage::SelectNextChar) != 0);
1180     QVERIFY(page->action(QWebPage::SelectPreviousChar) != 0);
1181     QVERIFY(page->action(QWebPage::SelectNextWord) != 0);
1182     QVERIFY(page->action(QWebPage::SelectPreviousWord) != 0);
1183     QVERIFY(page->action(QWebPage::SelectNextLine) != 0);
1184     QVERIFY(page->action(QWebPage::SelectPreviousLine) != 0);
1185     QVERIFY(page->action(QWebPage::SelectStartOfLine) != 0);
1186     QVERIFY(page->action(QWebPage::SelectEndOfLine) != 0);
1187     QVERIFY(page->action(QWebPage::SelectStartOfBlock) != 0);
1188     QVERIFY(page->action(QWebPage::SelectEndOfBlock) != 0);
1189     QVERIFY(page->action(QWebPage::SelectStartOfDocument) != 0);
1190     QVERIFY(page->action(QWebPage::SelectEndOfDocument) != 0);
1191
1192     // right now they are disabled because contentEditable is false and 
1193     // there isn't an existing selection to modify
1194     QCOMPARE(page->action(QWebPage::SelectNextChar)->isEnabled(), false);
1195     QCOMPARE(page->action(QWebPage::SelectPreviousChar)->isEnabled(), false);
1196     QCOMPARE(page->action(QWebPage::SelectNextWord)->isEnabled(), false);
1197     QCOMPARE(page->action(QWebPage::SelectPreviousWord)->isEnabled(), false);
1198     QCOMPARE(page->action(QWebPage::SelectNextLine)->isEnabled(), false);
1199     QCOMPARE(page->action(QWebPage::SelectPreviousLine)->isEnabled(), false);
1200     QCOMPARE(page->action(QWebPage::SelectStartOfLine)->isEnabled(), false);
1201     QCOMPARE(page->action(QWebPage::SelectEndOfLine)->isEnabled(), false);
1202     QCOMPARE(page->action(QWebPage::SelectStartOfBlock)->isEnabled(), false);
1203     QCOMPARE(page->action(QWebPage::SelectEndOfBlock)->isEnabled(), false);
1204     QCOMPARE(page->action(QWebPage::SelectStartOfDocument)->isEnabled(), false);
1205     QCOMPARE(page->action(QWebPage::SelectEndOfDocument)->isEnabled(), false);
1206
1207     // ..but SelectAll is awalys enabled
1208     QCOMPARE(page->action(QWebPage::SelectAll)->isEnabled(), true);
1209
1210     // Verify hasSelection returns false since there is no selection yet...
1211     QCOMPARE(page->hasSelection(), false);
1212
1213     // this will select the first paragraph
1214     QString selectScript = "var range = document.createRange(); " \
1215         "var node = document.getElementById(\"one\"); " \
1216         "range.selectNode(node); " \
1217         "getSelection().addRange(range);";
1218     page->mainFrame()->evaluateJavaScript(selectScript);
1219     QCOMPARE(page->selectedText().trimmed(), QString::fromLatin1("The quick brown fox"));
1220     QCOMPARE(page->selectedHtml().trimmed(), QString::fromLatin1("<span class=\"Apple-style-span\" style=\"border-collapse: separate; color: rgb(0, 0, 0); font-family: Times; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-align: -webkit-auto; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; font-size: medium; \"><p id=\"one\">The quick brown fox</p></span>"));
1221
1222     // Make sure hasSelection returns true, since there is selected text now...
1223     QCOMPARE(page->hasSelection(), true);
1224
1225     // here the actions are enabled after a selection has been created
1226     QCOMPARE(page->action(QWebPage::SelectNextChar)->isEnabled(), true);
1227     QCOMPARE(page->action(QWebPage::SelectPreviousChar)->isEnabled(), true);
1228     QCOMPARE(page->action(QWebPage::SelectNextWord)->isEnabled(), true);
1229     QCOMPARE(page->action(QWebPage::SelectPreviousWord)->isEnabled(), true);
1230     QCOMPARE(page->action(QWebPage::SelectNextLine)->isEnabled(), true);
1231     QCOMPARE(page->action(QWebPage::SelectPreviousLine)->isEnabled(), true);
1232     QCOMPARE(page->action(QWebPage::SelectStartOfLine)->isEnabled(), true);
1233     QCOMPARE(page->action(QWebPage::SelectEndOfLine)->isEnabled(), true);
1234     QCOMPARE(page->action(QWebPage::SelectStartOfBlock)->isEnabled(), true);
1235     QCOMPARE(page->action(QWebPage::SelectEndOfBlock)->isEnabled(), true);
1236     QCOMPARE(page->action(QWebPage::SelectStartOfDocument)->isEnabled(), true);
1237     QCOMPARE(page->action(QWebPage::SelectEndOfDocument)->isEnabled(), true);
1238
1239     // make it editable before navigating the cursor
1240     page->setContentEditable(true);
1241
1242     // cursor will be before the word "The", this makes sure there is a charet
1243     page->triggerAction(QWebPage::MoveToStartOfDocument);
1244     QVERIFY(page->isSelectionCollapsed());
1245     QCOMPARE(page->selectionStartOffset(), 0);
1246
1247     // here the actions are enabled after contentEditable is true
1248     QCOMPARE(page->action(QWebPage::SelectNextChar)->isEnabled(), true);
1249     QCOMPARE(page->action(QWebPage::SelectPreviousChar)->isEnabled(), true);
1250     QCOMPARE(page->action(QWebPage::SelectNextWord)->isEnabled(), true);
1251     QCOMPARE(page->action(QWebPage::SelectPreviousWord)->isEnabled(), true);
1252     QCOMPARE(page->action(QWebPage::SelectNextLine)->isEnabled(), true);
1253     QCOMPARE(page->action(QWebPage::SelectPreviousLine)->isEnabled(), true);
1254     QCOMPARE(page->action(QWebPage::SelectStartOfLine)->isEnabled(), true);
1255     QCOMPARE(page->action(QWebPage::SelectEndOfLine)->isEnabled(), true);
1256     QCOMPARE(page->action(QWebPage::SelectStartOfBlock)->isEnabled(), true);
1257     QCOMPARE(page->action(QWebPage::SelectEndOfBlock)->isEnabled(), true);
1258     QCOMPARE(page->action(QWebPage::SelectStartOfDocument)->isEnabled(), true);
1259     QCOMPARE(page->action(QWebPage::SelectEndOfDocument)->isEnabled(), true);
1260
1261     delete page;
1262 }
1263
1264 void tst_QWebPage::textEditing()
1265 {
1266     CursorTrackedPage* page = new CursorTrackedPage;
1267     QString content("<html><body><p id=one>The quick brown fox</p>" \
1268         "<p id=two>jumps over the lazy dog</p>" \
1269         "<p>May the source<br/>be with you!</p></body></html>");
1270     page->mainFrame()->setHtml(content);
1271
1272     // these actions must exist
1273     QVERIFY(page->action(QWebPage::Cut) != 0);
1274     QVERIFY(page->action(QWebPage::Copy) != 0);
1275     QVERIFY(page->action(QWebPage::Paste) != 0);
1276     QVERIFY(page->action(QWebPage::DeleteStartOfWord) != 0);
1277     QVERIFY(page->action(QWebPage::DeleteEndOfWord) != 0);
1278     QVERIFY(page->action(QWebPage::SetTextDirectionDefault) != 0);
1279     QVERIFY(page->action(QWebPage::SetTextDirectionLeftToRight) != 0);
1280     QVERIFY(page->action(QWebPage::SetTextDirectionRightToLeft) != 0);
1281     QVERIFY(page->action(QWebPage::ToggleBold) != 0);
1282     QVERIFY(page->action(QWebPage::ToggleItalic) != 0);
1283     QVERIFY(page->action(QWebPage::ToggleUnderline) != 0);
1284     QVERIFY(page->action(QWebPage::InsertParagraphSeparator) != 0);
1285     QVERIFY(page->action(QWebPage::InsertLineSeparator) != 0);
1286     QVERIFY(page->action(QWebPage::PasteAndMatchStyle) != 0);
1287     QVERIFY(page->action(QWebPage::RemoveFormat) != 0);
1288     QVERIFY(page->action(QWebPage::ToggleStrikethrough) != 0);
1289     QVERIFY(page->action(QWebPage::ToggleSubscript) != 0);
1290     QVERIFY(page->action(QWebPage::ToggleSuperscript) != 0);
1291     QVERIFY(page->action(QWebPage::InsertUnorderedList) != 0);
1292     QVERIFY(page->action(QWebPage::InsertOrderedList) != 0);
1293     QVERIFY(page->action(QWebPage::Indent) != 0);
1294     QVERIFY(page->action(QWebPage::Outdent) != 0);
1295     QVERIFY(page->action(QWebPage::AlignCenter) != 0);
1296     QVERIFY(page->action(QWebPage::AlignJustified) != 0);
1297     QVERIFY(page->action(QWebPage::AlignLeft) != 0);
1298     QVERIFY(page->action(QWebPage::AlignRight) != 0);
1299
1300     // right now they are disabled because contentEditable is false
1301     QCOMPARE(page->action(QWebPage::Cut)->isEnabled(), false);
1302     QCOMPARE(page->action(QWebPage::Paste)->isEnabled(), false);
1303     QCOMPARE(page->action(QWebPage::DeleteStartOfWord)->isEnabled(), false);
1304     QCOMPARE(page->action(QWebPage::DeleteEndOfWord)->isEnabled(), false);
1305     QCOMPARE(page->action(QWebPage::SetTextDirectionDefault)->isEnabled(), false);
1306     QCOMPARE(page->action(QWebPage::SetTextDirectionLeftToRight)->isEnabled(), false);
1307     QCOMPARE(page->action(QWebPage::SetTextDirectionRightToLeft)->isEnabled(), false);
1308     QCOMPARE(page->action(QWebPage::ToggleBold)->isEnabled(), false);
1309     QCOMPARE(page->action(QWebPage::ToggleItalic)->isEnabled(), false);
1310     QCOMPARE(page->action(QWebPage::ToggleUnderline)->isEnabled(), false);
1311     QCOMPARE(page->action(QWebPage::InsertParagraphSeparator)->isEnabled(), false);
1312     QCOMPARE(page->action(QWebPage::InsertLineSeparator)->isEnabled(), false);
1313     QCOMPARE(page->action(QWebPage::PasteAndMatchStyle)->isEnabled(), false);
1314     QCOMPARE(page->action(QWebPage::RemoveFormat)->isEnabled(), false);
1315     QCOMPARE(page->action(QWebPage::ToggleStrikethrough)->isEnabled(), false);
1316     QCOMPARE(page->action(QWebPage::ToggleSubscript)->isEnabled(), false);
1317     QCOMPARE(page->action(QWebPage::ToggleSuperscript)->isEnabled(), false);
1318     QCOMPARE(page->action(QWebPage::InsertUnorderedList)->isEnabled(), false);
1319     QCOMPARE(page->action(QWebPage::InsertOrderedList)->isEnabled(), false);
1320     QCOMPARE(page->action(QWebPage::Indent)->isEnabled(), false);
1321     QCOMPARE(page->action(QWebPage::Outdent)->isEnabled(), false);
1322     QCOMPARE(page->action(QWebPage::AlignCenter)->isEnabled(), false);
1323     QCOMPARE(page->action(QWebPage::AlignJustified)->isEnabled(), false);
1324     QCOMPARE(page->action(QWebPage::AlignLeft)->isEnabled(), false);
1325     QCOMPARE(page->action(QWebPage::AlignRight)->isEnabled(), false);
1326
1327     // Select everything
1328     page->triggerAction(QWebPage::SelectAll);
1329
1330     // make sure it is enabled since there is a selection
1331     QCOMPARE(page->action(QWebPage::Copy)->isEnabled(), true);
1332
1333     // make it editable before navigating the cursor
1334     page->setContentEditable(true);
1335
1336     // clear the selection
1337     page->triggerAction(QWebPage::MoveToStartOfDocument);
1338     QVERIFY(page->isSelectionCollapsed());
1339     QCOMPARE(page->selectionStartOffset(), 0);
1340
1341     // make sure it is disabled since there isn't a selection
1342     QCOMPARE(page->action(QWebPage::Copy)->isEnabled(), false);
1343
1344     // here the actions are enabled after contentEditable is true
1345     QCOMPARE(page->action(QWebPage::Paste)->isEnabled(), true);
1346     QCOMPARE(page->action(QWebPage::DeleteStartOfWord)->isEnabled(), true);
1347     QCOMPARE(page->action(QWebPage::DeleteEndOfWord)->isEnabled(), true);
1348     QCOMPARE(page->action(QWebPage::SetTextDirectionDefault)->isEnabled(), true);
1349     QCOMPARE(page->action(QWebPage::SetTextDirectionLeftToRight)->isEnabled(), true);
1350     QCOMPARE(page->action(QWebPage::SetTextDirectionRightToLeft)->isEnabled(), true);
1351     QCOMPARE(page->action(QWebPage::ToggleBold)->isEnabled(), true);
1352     QCOMPARE(page->action(QWebPage::ToggleItalic)->isEnabled(), true);
1353     QCOMPARE(page->action(QWebPage::ToggleUnderline)->isEnabled(), true);
1354     QCOMPARE(page->action(QWebPage::InsertParagraphSeparator)->isEnabled(), true);
1355     QCOMPARE(page->action(QWebPage::InsertLineSeparator)->isEnabled(), true);
1356     QCOMPARE(page->action(QWebPage::PasteAndMatchStyle)->isEnabled(), true);
1357     QCOMPARE(page->action(QWebPage::ToggleStrikethrough)->isEnabled(), true);
1358     QCOMPARE(page->action(QWebPage::ToggleSubscript)->isEnabled(), true);
1359     QCOMPARE(page->action(QWebPage::ToggleSuperscript)->isEnabled(), true);
1360     QCOMPARE(page->action(QWebPage::InsertUnorderedList)->isEnabled(), true);
1361     QCOMPARE(page->action(QWebPage::InsertOrderedList)->isEnabled(), true);
1362     QCOMPARE(page->action(QWebPage::Indent)->isEnabled(), true);
1363     QCOMPARE(page->action(QWebPage::Outdent)->isEnabled(), true);
1364     QCOMPARE(page->action(QWebPage::AlignCenter)->isEnabled(), true);
1365     QCOMPARE(page->action(QWebPage::AlignJustified)->isEnabled(), true);
1366     QCOMPARE(page->action(QWebPage::AlignLeft)->isEnabled(), true);
1367     QCOMPARE(page->action(QWebPage::AlignRight)->isEnabled(), true);
1368     
1369     // make sure these are disabled since there isn't a selection
1370     QCOMPARE(page->action(QWebPage::Cut)->isEnabled(), false);
1371     QCOMPARE(page->action(QWebPage::RemoveFormat)->isEnabled(), false);
1372     
1373     // make sure everything is selected
1374     page->triggerAction(QWebPage::SelectAll);
1375     
1376     // this is only true if there is an editable selection
1377     QCOMPARE(page->action(QWebPage::Cut)->isEnabled(), true);
1378     QCOMPARE(page->action(QWebPage::RemoveFormat)->isEnabled(), true);
1379
1380     delete page;
1381 }
1382
1383 void tst_QWebPage::requestCache()
1384 {
1385     TestPage page;
1386     QSignalSpy loadSpy(&page, SIGNAL(loadFinished(bool)));
1387
1388     page.mainFrame()->setUrl(QString("data:text/html,<a href=\"data:text/html,Reached\" target=\"_blank\">Click me</a>"));
1389     QTRY_COMPARE(loadSpy.count(), 1);
1390     QTRY_COMPARE(page.navigations.count(), 1);
1391
1392     page.mainFrame()->setUrl(QString("data:text/html,<a href=\"data:text/html,Reached\" target=\"_blank\">Click me2</a>"));
1393     QTRY_COMPARE(loadSpy.count(), 2);
1394     QTRY_COMPARE(page.navigations.count(), 2);
1395
1396     page.triggerAction(QWebPage::Stop);
1397     QVERIFY(page.history()->canGoBack());
1398     page.triggerAction(QWebPage::Back);
1399
1400     QTRY_COMPARE(loadSpy.count(), 3);
1401     QTRY_COMPARE(page.navigations.count(), 3);
1402     QCOMPARE(page.navigations.at(0).request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt(),
1403              (int)QNetworkRequest::PreferNetwork);
1404     QCOMPARE(page.navigations.at(1).request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt(),
1405              (int)QNetworkRequest::PreferNetwork);
1406     QCOMPARE(page.navigations.at(2).request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt(),
1407              (int)QNetworkRequest::PreferCache);
1408 }
1409
1410 void tst_QWebPage::loadCachedPage()
1411 {
1412     TestPage page;
1413     QSignalSpy loadSpy(&page, SIGNAL(loadFinished(bool)));
1414     page.settings()->setMaximumPagesInCache(3);
1415
1416     page.mainFrame()->load(QUrl("data:text/html,This is first page"));
1417
1418     QTRY_COMPARE(loadSpy.count(), 1);
1419     QTRY_COMPARE(page.navigations.count(), 1);
1420
1421     QUrl firstPageUrl = page.mainFrame()->url();
1422     page.mainFrame()->load(QUrl("data:text/html,This is second page"));
1423
1424     QTRY_COMPARE(loadSpy.count(), 2);
1425     QTRY_COMPARE(page.navigations.count(), 2);
1426
1427     page.triggerAction(QWebPage::Stop);
1428     QVERIFY(page.history()->canGoBack());
1429
1430     QSignalSpy urlSpy(page.mainFrame(), SIGNAL(urlChanged(QUrl)));
1431     QVERIFY(urlSpy.isValid());
1432
1433     page.triggerAction(QWebPage::Back);
1434     ::waitForSignal(page.mainFrame(), SIGNAL(urlChanged(QUrl)));
1435     QCOMPARE(urlSpy.size(), 1);
1436
1437     QList<QVariant> arguments1 = urlSpy.takeFirst();
1438     QCOMPARE(arguments1.at(0).toUrl(), firstPageUrl);
1439
1440 }
1441 void tst_QWebPage::backActionUpdate()
1442 {
1443     QWebView view;
1444     QWebPage *page = view.page();
1445     QAction *action = page->action(QWebPage::Back);
1446     QVERIFY(!action->isEnabled());
1447     QSignalSpy loadSpy(page, SIGNAL(loadFinished(bool)));
1448     QUrl url = QUrl("qrc:///resources/framedindex.html");
1449     page->mainFrame()->load(url);
1450     QTRY_COMPARE(loadSpy.count(), 1);
1451     QVERIFY(!action->isEnabled());
1452     QTest::mouseClick(&view, Qt::LeftButton, 0, QPoint(10, 10));
1453     QTRY_COMPARE(loadSpy.count(), 2);
1454
1455     QVERIFY(action->isEnabled());
1456 }
1457
1458 void frameAtHelper(QWebPage* webPage, QWebFrame* webFrame, QPoint framePosition)
1459 {
1460     if (!webFrame)
1461         return;
1462
1463     framePosition += QPoint(webFrame->pos());
1464     QList<QWebFrame*> children = webFrame->childFrames();
1465     for (int i = 0; i < children.size(); ++i) {
1466         if (children.at(i)->childFrames().size() > 0)
1467             frameAtHelper(webPage, children.at(i), framePosition);
1468
1469         QRect frameRect(children.at(i)->pos() + framePosition, children.at(i)->geometry().size());
1470         QVERIFY(children.at(i) == webPage->frameAt(frameRect.topLeft()));
1471     }
1472 }
1473
1474 void tst_QWebPage::frameAt()
1475 {
1476     QWebView webView;
1477     QWebPage* webPage = webView.page();
1478     QSignalSpy loadSpy(webPage, SIGNAL(loadFinished(bool)));
1479     QUrl url = QUrl("qrc:///resources/iframe.html");
1480     webPage->mainFrame()->load(url);
1481     QTRY_COMPARE(loadSpy.count(), 1);
1482     frameAtHelper(webPage, webPage->mainFrame(), webPage->mainFrame()->pos());
1483 }
1484
1485 void tst_QWebPage::inputMethods_data()
1486 {
1487     QTest::addColumn<QString>("viewType");
1488     QTest::newRow("QWebView") << "QWebView";
1489     QTest::newRow("QGraphicsWebView") << "QGraphicsWebView";
1490 }
1491
1492 static Qt::InputMethodHints inputMethodHints(QObject* object)
1493 {
1494     if (QGraphicsObject* o = qobject_cast<QGraphicsObject*>(object))
1495         return o->inputMethodHints();
1496     if (QWidget* w = qobject_cast<QWidget*>(object))
1497         return w->inputMethodHints();
1498     return Qt::InputMethodHints();
1499 }
1500
1501 static bool inputMethodEnabled(QObject* object)
1502 {
1503     if (QGraphicsObject* o = qobject_cast<QGraphicsObject*>(object))
1504         return o->flags() & QGraphicsItem::ItemAcceptsInputMethod;
1505     if (QWidget* w = qobject_cast<QWidget*>(object))
1506         return w->testAttribute(Qt::WA_InputMethodEnabled);
1507     return false;
1508 }
1509
1510 static void clickOnPage(QWebPage* page, const QPoint& position)
1511 {
1512     QMouseEvent evpres(QEvent::MouseButtonPress, position, Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
1513     page->event(&evpres);
1514     QMouseEvent evrel(QEvent::MouseButtonRelease, position, Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
1515     page->event(&evrel);
1516 }
1517
1518 void tst_QWebPage::inputMethods()
1519 {
1520     QFETCH(QString, viewType);
1521     QWebPage* page = new QWebPage;
1522     QObject* view = 0;
1523     QObject* container = 0;
1524     if (viewType == "QWebView") {
1525         QWebView* wv = new QWebView;
1526         wv->setPage(page);
1527         view = wv;
1528         container = view;
1529     } else if (viewType == "QGraphicsWebView") {
1530         QGraphicsWebView* wv = new QGraphicsWebView;
1531         wv->setPage(page);
1532         view = wv;
1533
1534         QGraphicsView* gv = new QGraphicsView;
1535         QGraphicsScene* scene = new QGraphicsScene(gv);
1536         gv->setScene(scene);
1537         scene->addItem(wv);
1538         wv->setGeometry(QRect(0, 0, 500, 500));
1539
1540         container = gv;
1541     } else
1542         QVERIFY2(false, "Unknown view type");
1543
1544     page->settings()->setFontFamily(QWebSettings::SerifFont, "FooSerifFont");
1545     page->mainFrame()->setHtml("<html><body>" \
1546                                             "<input type='text' id='input1' style='font-family: serif' value='' maxlength='20'/><br>" \
1547                                             "<input type='password'/>" \
1548                                             "</body></html>");
1549     page->mainFrame()->setFocus();
1550
1551     EventSpy viewEventSpy(container);
1552
1553     QWebElementCollection inputs = page->mainFrame()->documentElement().findAll("input");
1554     QPoint textInputCenter = inputs.at(0).geometry().center();
1555
1556     clickOnPage(page, textInputCenter);
1557
1558     // This part of the test checks if the SIP (Software Input Panel) is triggered,
1559     // which normally happens on mobile platforms, when a user input form receives
1560     // a mouse click.
1561     int  inputPanel = 0;
1562     if (viewType == "QWebView") {
1563         if (QWebView* wv = qobject_cast<QWebView*>(view))
1564             inputPanel = wv->style()->styleHint(QStyle::SH_RequestSoftwareInputPanel);
1565     } else if (viewType == "QGraphicsWebView") {
1566         if (QGraphicsWebView* wv = qobject_cast<QGraphicsWebView*>(view))
1567             inputPanel = wv->style()->styleHint(QStyle::SH_RequestSoftwareInputPanel);
1568     }
1569
1570     // For non-mobile platforms RequestSoftwareInputPanel event is not called
1571     // because there is no SIP (Software Input Panel) triggered. In the case of a
1572     // mobile platform, an input panel, e.g. virtual keyboard, is usually invoked
1573     // and the RequestSoftwareInputPanel event is called. For these two situations
1574     // this part of the test can verified as the checks below.
1575     if (inputPanel)
1576         QVERIFY(viewEventSpy.contains(QEvent::RequestSoftwareInputPanel));
1577     else
1578         QVERIFY(!viewEventSpy.contains(QEvent::RequestSoftwareInputPanel));
1579     viewEventSpy.clear();
1580
1581     clickOnPage(page, textInputCenter);
1582     QVERIFY(viewEventSpy.contains(QEvent::RequestSoftwareInputPanel));
1583
1584     //ImMicroFocus
1585     QVariant variant = page->inputMethodQuery(Qt::ImMicroFocus);
1586     QRect focusRect = variant.toRect();
1587     QVERIFY(inputs.at(0).geometry().contains(variant.toRect().topLeft()));
1588
1589     //ImFont
1590     variant = page->inputMethodQuery(Qt::ImFont);
1591     QFont font = variant.value<QFont>();
1592     QCOMPARE(page->settings()->fontFamily(QWebSettings::SerifFont), font.family());
1593
1594     QList<QInputMethodEvent::Attribute> inputAttributes;
1595
1596     //Insert text.
1597     {
1598         QInputMethodEvent eventText("QtWebKit", inputAttributes);
1599         QSignalSpy signalSpy(page, SIGNAL(microFocusChanged()));
1600         page->event(&eventText);
1601         QCOMPARE(signalSpy.count(), 0);
1602     }
1603
1604     {
1605         QInputMethodEvent eventText("", inputAttributes);
1606         eventText.setCommitString(QString("QtWebKit"), 0, 0);
1607         page->event(&eventText);
1608     }
1609
1610     //ImMaximumTextLength
1611     variant = page->inputMethodQuery(Qt::ImMaximumTextLength);
1612     QCOMPARE(20, variant.toInt());
1613
1614     //Set selection
1615     inputAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, 3, 2, QVariant());
1616     QInputMethodEvent eventSelection("",inputAttributes);
1617     page->event(&eventSelection);
1618
1619     //ImAnchorPosition
1620     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1621     int anchorPosition =  variant.toInt();
1622     QCOMPARE(anchorPosition, 3);
1623
1624     //ImCursorPosition
1625     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1626     int cursorPosition =  variant.toInt();
1627     QCOMPARE(cursorPosition, 5);
1628
1629     //ImCurrentSelection
1630     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1631     QString selectionValue = variant.value<QString>();
1632     QCOMPARE(selectionValue, QString("eb"));
1633
1634     //Set selection with negative length
1635     inputAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, 6, -5, QVariant());
1636     QInputMethodEvent eventSelection3("",inputAttributes);
1637     page->event(&eventSelection3);
1638
1639     //ImAnchorPosition
1640     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1641     anchorPosition =  variant.toInt();
1642     QCOMPARE(anchorPosition, 1);
1643
1644     //ImCursorPosition
1645     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1646     cursorPosition =  variant.toInt();
1647     QCOMPARE(cursorPosition, 6);
1648
1649     //ImCurrentSelection
1650     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1651     selectionValue = variant.value<QString>();
1652     QCOMPARE(selectionValue, QString("tWebK"));
1653
1654     //ImSurroundingText
1655     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1656     QString value = variant.value<QString>();
1657     QCOMPARE(value, QString("QtWebKit"));
1658
1659     {
1660         QList<QInputMethodEvent::Attribute> attributes;
1661         // Clear the selection, so the next test does not clear any contents.
1662         QInputMethodEvent::Attribute newSelection(QInputMethodEvent::Selection, 0, 0, QVariant());
1663         attributes.append(newSelection);
1664         QInputMethodEvent event("composition", attributes);
1665         page->event(&event);
1666     }
1667
1668     // A ongoing composition should not change the surrounding text before it is committed.
1669     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1670     value = variant.value<QString>();
1671     QCOMPARE(value, QString("QtWebKit"));
1672
1673     // Cancel current composition first
1674     inputAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, 0, 0, QVariant());
1675     QInputMethodEvent eventSelection4("", inputAttributes);
1676     page->event(&eventSelection4);
1677
1678     // START - Tests for Selection when the Editor is NOT in Composition mode
1679
1680     // LEFT to RIGHT selection
1681     // Deselect the selection by sending MouseButtonPress events
1682     // This moves the current cursor to the end of the text
1683     clickOnPage(page, textInputCenter);
1684
1685     {
1686         QList<QInputMethodEvent::Attribute> attributes;
1687         QInputMethodEvent event(QString(), attributes);
1688         event.setCommitString("XXX", 0, 0);
1689         page->event(&event);
1690         event.setCommitString(QString(), -2, 2); // Erase two characters.
1691         page->event(&event);
1692         event.setCommitString(QString(), -1, 1); // Erase one character.
1693         page->event(&event);
1694         variant = page->inputMethodQuery(Qt::ImSurroundingText);
1695         value = variant.value<QString>();
1696         QCOMPARE(value, QString("QtWebKit"));
1697     }
1698
1699     //Move to the start of the line
1700     page->triggerAction(QWebPage::MoveToStartOfLine);
1701
1702     QKeyEvent keyRightEventPress(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier);
1703     QKeyEvent keyRightEventRelease(QEvent::KeyRelease, Qt::Key_Right, Qt::NoModifier);
1704
1705     //Move 2 characters RIGHT
1706     for (int j = 0; j < 2; ++j) {
1707         page->event(&keyRightEventPress);
1708         page->event(&keyRightEventRelease);
1709     }
1710
1711     //Select to the end of the line
1712     page->triggerAction(QWebPage::SelectEndOfLine);
1713
1714     //ImAnchorPosition QtWebKit
1715     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1716     anchorPosition =  variant.toInt();
1717     QCOMPARE(anchorPosition, 2);
1718
1719     //ImCursorPosition
1720     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1721     cursorPosition =  variant.toInt();
1722     QCOMPARE(cursorPosition, 8);
1723
1724     //ImCurrentSelection
1725     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1726     selectionValue = variant.value<QString>();
1727     QCOMPARE(selectionValue, QString("WebKit"));
1728
1729     //RIGHT to LEFT selection
1730     //Deselect the selection (this moves the current cursor to the end of the text)
1731     clickOnPage(page, textInputCenter);
1732
1733     //ImAnchorPosition
1734     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1735     anchorPosition =  variant.toInt();
1736     QCOMPARE(anchorPosition, 8);
1737
1738     //ImCursorPosition
1739     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1740     cursorPosition =  variant.toInt();
1741     QCOMPARE(cursorPosition, 8);
1742
1743     //ImCurrentSelection
1744     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1745     selectionValue = variant.value<QString>();
1746     QCOMPARE(selectionValue, QString(""));
1747
1748     QKeyEvent keyLeftEventPress(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier);
1749     QKeyEvent keyLeftEventRelease(QEvent::KeyRelease, Qt::Key_Left, Qt::NoModifier);
1750
1751     //Move 2 characters LEFT
1752     for (int i = 0; i < 2; ++i) {
1753         page->event(&keyLeftEventPress);
1754         page->event(&keyLeftEventRelease);
1755     }
1756
1757     //Select to the start of the line
1758     page->triggerAction(QWebPage::SelectStartOfLine);
1759
1760     //ImAnchorPosition
1761     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1762     anchorPosition =  variant.toInt();
1763     QCOMPARE(anchorPosition, 6);
1764
1765     //ImCursorPosition
1766     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1767     cursorPosition =  variant.toInt();
1768     QCOMPARE(cursorPosition, 0);
1769
1770     //ImCurrentSelection
1771     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1772     selectionValue = variant.value<QString>();
1773     QCOMPARE(selectionValue, QString("QtWebK"));
1774
1775     //END - Tests for Selection when the Editor is not in Composition mode
1776
1777     //ImhHiddenText
1778     QPoint passwordInputCenter = inputs.at(1).geometry().center();
1779     clickOnPage(page, passwordInputCenter);
1780
1781     QVERIFY(inputMethodEnabled(view));
1782     QVERIFY(inputMethodHints(view) & Qt::ImhHiddenText);
1783
1784     clickOnPage(page, textInputCenter);
1785     QVERIFY(!(inputMethodHints(view) & Qt::ImhHiddenText));
1786
1787     page->mainFrame()->setHtml("<html><body><p>nothing to input here");
1788     viewEventSpy.clear();
1789
1790     QWebElement para = page->mainFrame()->findFirstElement("p");
1791     clickOnPage(page, para.geometry().center());
1792
1793     QVERIFY(!viewEventSpy.contains(QEvent::RequestSoftwareInputPanel));
1794
1795     //START - Test for sending empty QInputMethodEvent
1796     page->mainFrame()->setHtml("<html><body>" \
1797                                             "<input type='text' id='input3' value='QtWebKit2'/>" \
1798                                             "</body></html>");
1799     page->mainFrame()->evaluateJavaScript("var inputEle = document.getElementById('input3'); inputEle.focus(); inputEle.select();");
1800
1801     //Send empty QInputMethodEvent
1802     QInputMethodEvent emptyEvent;
1803     page->event(&emptyEvent);
1804
1805     QString inputValue = page->mainFrame()->evaluateJavaScript("document.getElementById('input3').value").toString();
1806     QCOMPARE(inputValue, QString("QtWebKit2"));
1807     //END - Test for sending empty QInputMethodEvent
1808
1809     page->mainFrame()->setHtml("<html><body>" \
1810                                             "<input type='text' id='input4' value='QtWebKit inputMethod'/>" \
1811                                             "</body></html>");
1812     page->mainFrame()->evaluateJavaScript("var inputEle = document.getElementById('input4'); inputEle.focus(); inputEle.select();");
1813
1814     // Clear the selection, also cancel the ongoing composition if there is one.
1815     {
1816         QList<QInputMethodEvent::Attribute> attributes;
1817         QInputMethodEvent::Attribute newSelection(QInputMethodEvent::Selection, 0, 0, QVariant());
1818         attributes.append(newSelection);
1819         QInputMethodEvent event("", attributes);
1820         page->event(&event);
1821     }
1822
1823     // ImCurrentSelection
1824     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1825     selectionValue = variant.value<QString>();
1826     QCOMPARE(selectionValue, QString(""));
1827
1828     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1829     QString surroundingValue = variant.value<QString>();
1830     QCOMPARE(surroundingValue, QString("QtWebKit inputMethod"));
1831
1832     // ImAnchorPosition
1833     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1834     anchorPosition =  variant.toInt();
1835     QCOMPARE(anchorPosition, 0);
1836
1837     // ImCursorPosition
1838     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1839     cursorPosition =  variant.toInt();
1840     QCOMPARE(cursorPosition, 0);
1841
1842     // 1. Insert a character to the begining of the line.
1843     // Send temporary text, which makes the editor has composition 'm'.
1844     {
1845         QList<QInputMethodEvent::Attribute> attributes;
1846         QInputMethodEvent event("m", attributes);
1847         page->event(&event);
1848     }
1849
1850     // ImCurrentSelection
1851     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1852     selectionValue = variant.value<QString>();
1853     QCOMPARE(selectionValue, QString(""));
1854
1855     // ImSurroundingText
1856     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1857     surroundingValue = variant.value<QString>();
1858     QCOMPARE(surroundingValue, QString("QtWebKit inputMethod"));
1859
1860     // ImCursorPosition
1861     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1862     cursorPosition =  variant.toInt();
1863     QCOMPARE(cursorPosition, 0);
1864
1865     // ImAnchorPosition
1866     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1867     anchorPosition =  variant.toInt();
1868     QCOMPARE(anchorPosition, 0);
1869
1870     // Send temporary text, which makes the editor has composition 'n'.
1871     {
1872         QList<QInputMethodEvent::Attribute> attributes;
1873         QInputMethodEvent event("n", attributes);
1874         page->event(&event);
1875     }
1876
1877     // ImCurrentSelection
1878     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1879     selectionValue = variant.value<QString>();
1880     QCOMPARE(selectionValue, QString(""));
1881
1882     // ImSurroundingText
1883     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1884     surroundingValue = variant.value<QString>();
1885     QCOMPARE(surroundingValue, QString("QtWebKit inputMethod"));
1886
1887     // ImCursorPosition
1888     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1889     cursorPosition =  variant.toInt();
1890     QCOMPARE(cursorPosition, 0);
1891
1892     // ImAnchorPosition
1893     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1894     anchorPosition =  variant.toInt();
1895     QCOMPARE(anchorPosition, 0);
1896
1897     // Send commit text, which makes the editor conforms composition.
1898     {
1899         QList<QInputMethodEvent::Attribute> attributes;
1900         QInputMethodEvent event("", attributes);
1901         event.setCommitString("o");
1902         page->event(&event);
1903     }
1904
1905     // ImCurrentSelection
1906     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1907     selectionValue = variant.value<QString>();
1908     QCOMPARE(selectionValue, QString(""));
1909
1910     // ImSurroundingText
1911     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1912     surroundingValue = variant.value<QString>();
1913     QCOMPARE(surroundingValue, QString("oQtWebKit inputMethod"));
1914
1915     // ImCursorPosition
1916     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1917     cursorPosition =  variant.toInt();
1918     QCOMPARE(cursorPosition, 1);
1919
1920     // ImAnchorPosition
1921     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1922     anchorPosition =  variant.toInt();
1923     QCOMPARE(anchorPosition, 1);
1924
1925     // 2. insert a character to the middle of the line.
1926     // Send temporary text, which makes the editor has composition 'd'.
1927     {
1928         QList<QInputMethodEvent::Attribute> attributes;
1929         QInputMethodEvent event("d", attributes);
1930         page->event(&event);
1931     }
1932
1933     // ImCurrentSelection
1934     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1935     selectionValue = variant.value<QString>();
1936     QCOMPARE(selectionValue, QString(""));
1937
1938     // ImSurroundingText
1939     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1940     surroundingValue = variant.value<QString>();
1941     QCOMPARE(surroundingValue, QString("oQtWebKit inputMethod"));
1942
1943     // ImCursorPosition
1944     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1945     cursorPosition =  variant.toInt();
1946     QCOMPARE(cursorPosition, 1);
1947
1948     // ImAnchorPosition
1949     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1950     anchorPosition =  variant.toInt();
1951     QCOMPARE(anchorPosition, 1);
1952
1953     // Send commit text, which makes the editor conforms composition.
1954     {
1955         QList<QInputMethodEvent::Attribute> attributes;
1956         QInputMethodEvent event("", attributes);
1957         event.setCommitString("e");
1958         page->event(&event);
1959     }
1960
1961     // ImCurrentSelection
1962     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1963     selectionValue = variant.value<QString>();
1964     QCOMPARE(selectionValue, QString(""));
1965
1966     // ImSurroundingText
1967     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1968     surroundingValue = variant.value<QString>();
1969     QCOMPARE(surroundingValue, QString("oeQtWebKit inputMethod"));
1970
1971     // ImCursorPosition
1972     variant = page->inputMethodQuery(Qt::ImCursorPosition);
1973     cursorPosition =  variant.toInt();
1974     QCOMPARE(cursorPosition, 2);
1975
1976     // ImAnchorPosition
1977     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
1978     anchorPosition =  variant.toInt();
1979     QCOMPARE(anchorPosition, 2);
1980
1981     // 3. Insert a character to the end of the line.
1982     page->triggerAction(QWebPage::MoveToEndOfLine);
1983     
1984     // Send temporary text, which makes the editor has composition 't'.
1985     {
1986         QList<QInputMethodEvent::Attribute> attributes;
1987         QInputMethodEvent event("t", attributes);
1988         page->event(&event);
1989     }
1990
1991     // ImCurrentSelection
1992     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
1993     selectionValue = variant.value<QString>();
1994     QCOMPARE(selectionValue, QString(""));
1995
1996     // ImSurroundingText
1997     variant = page->inputMethodQuery(Qt::ImSurroundingText);
1998     surroundingValue = variant.value<QString>();
1999     QCOMPARE(surroundingValue, QString("oeQtWebKit inputMethod"));
2000
2001     // ImCursorPosition
2002     variant = page->inputMethodQuery(Qt::ImCursorPosition);
2003     cursorPosition =  variant.toInt();
2004     QCOMPARE(cursorPosition, 22);
2005
2006     // ImAnchorPosition
2007     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
2008     anchorPosition =  variant.toInt();
2009     QCOMPARE(anchorPosition, 22);
2010
2011     // Send commit text, which makes the editor conforms composition.
2012     {
2013         QList<QInputMethodEvent::Attribute> attributes;
2014         QInputMethodEvent event("", attributes);
2015         event.setCommitString("t");
2016         page->event(&event);
2017     }
2018
2019     // ImCurrentSelection
2020     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
2021     selectionValue = variant.value<QString>();
2022     QCOMPARE(selectionValue, QString(""));
2023
2024     // ImSurroundingText
2025     variant = page->inputMethodQuery(Qt::ImSurroundingText);
2026     surroundingValue = variant.value<QString>();
2027     QCOMPARE(surroundingValue, QString("oeQtWebKit inputMethodt"));
2028
2029     // ImCursorPosition
2030     variant = page->inputMethodQuery(Qt::ImCursorPosition);
2031     cursorPosition =  variant.toInt();
2032     QCOMPARE(cursorPosition, 23);
2033
2034     // ImAnchorPosition
2035     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
2036     anchorPosition =  variant.toInt();
2037     QCOMPARE(anchorPosition, 23);
2038
2039     // 4. Replace the selection.
2040     page->triggerAction(QWebPage::SelectPreviousWord);
2041
2042     // ImCurrentSelection
2043     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
2044     selectionValue = variant.value<QString>();
2045     QCOMPARE(selectionValue, QString("inputMethodt"));
2046
2047     // ImSurroundingText
2048     variant = page->inputMethodQuery(Qt::ImSurroundingText);
2049     surroundingValue = variant.value<QString>();
2050     QCOMPARE(surroundingValue, QString("oeQtWebKit inputMethodt"));
2051
2052     // ImCursorPosition
2053     variant = page->inputMethodQuery(Qt::ImCursorPosition);
2054     cursorPosition =  variant.toInt();
2055     QCOMPARE(cursorPosition, 11);
2056
2057     // ImAnchorPosition
2058     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
2059     anchorPosition =  variant.toInt();
2060     QCOMPARE(anchorPosition, 23);
2061
2062     // Send temporary text, which makes the editor has composition 'w'.
2063     {
2064         QList<QInputMethodEvent::Attribute> attributes;
2065         QInputMethodEvent event("w", attributes);
2066         page->event(&event);
2067     }
2068
2069     // ImCurrentSelection
2070     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
2071     selectionValue = variant.value<QString>();
2072     QCOMPARE(selectionValue, QString(""));
2073
2074     // ImSurroundingText
2075     variant = page->inputMethodQuery(Qt::ImSurroundingText);
2076     surroundingValue = variant.value<QString>();
2077     QCOMPARE(surroundingValue, QString("oeQtWebKit "));
2078
2079     // ImCursorPosition
2080     variant = page->inputMethodQuery(Qt::ImCursorPosition);
2081     cursorPosition =  variant.toInt();
2082     QCOMPARE(cursorPosition, 11);
2083
2084     // ImAnchorPosition
2085     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
2086     anchorPosition =  variant.toInt();
2087     QCOMPARE(anchorPosition, 11);
2088
2089     // Send commit text, which makes the editor conforms composition.
2090     {
2091         QList<QInputMethodEvent::Attribute> attributes;
2092         QInputMethodEvent event("", attributes);
2093         event.setCommitString("2");
2094         page->event(&event);
2095     }
2096
2097     // ImCurrentSelection
2098     variant = page->inputMethodQuery(Qt::ImCurrentSelection);
2099     selectionValue = variant.value<QString>();
2100     QCOMPARE(selectionValue, QString(""));
2101
2102     // ImSurroundingText
2103     variant = page->inputMethodQuery(Qt::ImSurroundingText);
2104     surroundingValue = variant.value<QString>();
2105     QCOMPARE(surroundingValue, QString("oeQtWebKit 2"));
2106
2107     // ImCursorPosition
2108     variant = page->inputMethodQuery(Qt::ImCursorPosition);
2109     cursorPosition =  variant.toInt();
2110     QCOMPARE(cursorPosition, 12);
2111
2112     // ImAnchorPosition
2113     variant = page->inputMethodQuery(Qt::ImAnchorPosition);
2114     anchorPosition =  variant.toInt();
2115     QCOMPARE(anchorPosition, 12);
2116
2117     // Check sending RequestSoftwareInputPanel event
2118     page->mainFrame()->setHtml("<html><body>" \
2119                                             "<input type='text' id='input5' value='QtWebKit inputMethod'/>" \
2120                                             "<div id='btnDiv' onclick='i=document.getElementById(&quot;input5&quot;); i.focus();'>abc</div>"\
2121                                             "</body></html>");
2122     QWebElement inputElement = page->mainFrame()->findFirstElement("div");
2123     clickOnPage(page, inputElement.geometry().center());
2124
2125     QVERIFY(!viewEventSpy.contains(QEvent::RequestSoftwareInputPanel));
2126     delete container;
2127 }
2128
2129 void tst_QWebPage::inputMethodsTextFormat_data()
2130 {
2131     QTest::addColumn<QString>("string");
2132     QTest::addColumn<int>("start");
2133     QTest::addColumn<int>("length");
2134
2135     QTest::newRow("") << QString("") << 0 << 0;
2136     QTest::newRow("Q") << QString("Q") << 0 << 1;
2137     QTest::newRow("Qt") << QString("Qt") << 0 << 1;
2138     QTest::newRow("Qt") << QString("Qt") << 0 << 2;
2139     QTest::newRow("Qt") << QString("Qt") << 1 << 1;
2140     QTest::newRow("Qt ") << QString("Qt ") << 0 << 1;
2141     QTest::newRow("Qt ") << QString("Qt ") << 1 << 1;
2142     QTest::newRow("Qt ") << QString("Qt ") << 2 << 1;
2143     QTest::newRow("Qt ") << QString("Qt ") << 2 << -1;
2144     QTest::newRow("Qt ") << QString("Qt ") << -2 << 3;
2145     QTest::newRow("Qt ") << QString("Qt ") << 0 << 3;
2146     QTest::newRow("Qt by") << QString("Qt by") << 0 << 1;
2147     QTest::newRow("Qt by Nokia") << QString("Qt by Nokia") << 0 << 1;
2148 }
2149
2150
2151 void tst_QWebPage::inputMethodsTextFormat()
2152 {
2153     QWebPage* page = new QWebPage;
2154     QWebView* view = new QWebView;
2155     view->setPage(page);
2156     page->settings()->setFontFamily(QWebSettings::SerifFont, "FooSerifFont");
2157     page->mainFrame()->setHtml("<html><body>" \
2158                                             "<input type='text' id='input1' style='font-family: serif' value='' maxlength='20'/>");
2159     page->mainFrame()->evaluateJavaScript("document.getElementById('input1').focus()");
2160     page->mainFrame()->setFocus();
2161     view->show();
2162
2163     QFETCH(QString, string);
2164     QFETCH(int, start);
2165     QFETCH(int, length);
2166
2167     QList<QInputMethodEvent::Attribute> attrs;
2168     QTextCharFormat format;
2169     format.setUnderlineStyle(QTextCharFormat::SingleUnderline);
2170     format.setUnderlineColor(Qt::red);
2171     attrs.append(QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, start, length, format));
2172     QInputMethodEvent im(string, attrs);
2173     page->event(&im);
2174
2175     QTest::qWait(1000);
2176
2177     delete view;
2178 }
2179
2180 void tst_QWebPage::protectBindingsRuntimeObjectsFromCollector()
2181 {
2182     QSignalSpy loadSpy(m_view, SIGNAL(loadFinished(bool)));
2183
2184     PluginPage* newPage = new PluginPage(m_view);
2185     m_view->setPage(newPage);
2186
2187     m_view->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
2188
2189     m_view->setHtml(QString("<html><body><object type='application/x-qt-plugin' classid='lineedit' id='mylineedit'/></body></html>"));
2190     QTRY_COMPARE(loadSpy.count(), 1);
2191
2192     newPage->mainFrame()->evaluateJavaScript("function testme(text) { var lineedit = document.getElementById('mylineedit'); lineedit.setText(text); lineedit.selectAll(); }");
2193
2194     newPage->mainFrame()->evaluateJavaScript("testme('foo')");
2195
2196     DumpRenderTreeSupportQt::garbageCollectorCollect();
2197
2198     // don't crash!
2199     newPage->mainFrame()->evaluateJavaScript("testme('bar')");
2200 }
2201
2202 void tst_QWebPage::localURLSchemes()
2203 {
2204     int i = QWebSecurityOrigin::localSchemes().size();
2205
2206     QWebSecurityOrigin::removeLocalScheme("file");
2207     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i);
2208     QWebSecurityOrigin::addLocalScheme("file");
2209     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i);
2210
2211     QWebSecurityOrigin::removeLocalScheme("qrc");
2212     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i - 1);
2213     QWebSecurityOrigin::addLocalScheme("qrc");
2214     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i);
2215
2216     QString myscheme = "myscheme";
2217     QWebSecurityOrigin::addLocalScheme(myscheme);
2218     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i + 1);
2219     QVERIFY(QWebSecurityOrigin::localSchemes().contains(myscheme));
2220     QWebSecurityOrigin::removeLocalScheme(myscheme);
2221     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i);
2222     QWebSecurityOrigin::removeLocalScheme(myscheme);
2223     QTRY_COMPARE(QWebSecurityOrigin::localSchemes().size(), i);
2224 }
2225
2226 static inline bool testFlag(QWebPage& webPage, QWebSettings::WebAttribute settingAttribute, const QString& jsObjectName, bool settingValue)
2227 {
2228     webPage.settings()->setAttribute(settingAttribute, settingValue);
2229     return webPage.mainFrame()->evaluateJavaScript(QString("(window.%1 != undefined)").arg(jsObjectName)).toBool();
2230 }
2231
2232 void tst_QWebPage::testOptionalJSObjects()
2233 {
2234     // Once a feature is enabled and the JS object is accessed turning off the setting will not turn off
2235     // the visibility of the JS object any more. For this reason this test uses two QWebPage instances.
2236     // Part of the test is to make sure that the QWebPage instances do not interfere with each other so turning on
2237     // a feature for one instance will not turn it on for another.
2238
2239     QWebPage webPage1;
2240     QWebPage webPage2;
2241
2242     webPage1.currentFrame()->setHtml(QString("<html><body>test</body></html>"), QUrl());
2243     webPage2.currentFrame()->setHtml(QString("<html><body>test</body></html>"), QUrl());
2244
2245     QEXPECT_FAIL("","Feature enabled/disabled checking problem. Look at bugs.webkit.org/show_bug.cgi?id=29867", Continue);
2246     QCOMPARE(testFlag(webPage1, QWebSettings::OfflineWebApplicationCacheEnabled, "applicationCache", false), false);
2247     QCOMPARE(testFlag(webPage2, QWebSettings::OfflineWebApplicationCacheEnabled, "applicationCache", true),  true);
2248     QEXPECT_FAIL("","Feature enabled/disabled checking problem. Look at bugs.webkit.org/show_bug.cgi?id=29867", Continue);
2249     QCOMPARE(testFlag(webPage1, QWebSettings::OfflineWebApplicationCacheEnabled, "applicationCache", false), false);
2250     QCOMPARE(testFlag(webPage2, QWebSettings::OfflineWebApplicationCacheEnabled, "applicationCache", false), true);
2251
2252     QCOMPARE(testFlag(webPage1, QWebSettings::LocalStorageEnabled, "localStorage", false), false);
2253     QCOMPARE(testFlag(webPage2, QWebSettings::LocalStorageEnabled, "localStorage", true),  true);
2254     QCOMPARE(testFlag(webPage1, QWebSettings::LocalStorageEnabled, "localStorage", false), false);
2255     QCOMPARE(testFlag(webPage2, QWebSettings::LocalStorageEnabled, "localStorage", false), true);
2256 }
2257
2258 void tst_QWebPage::testEnablePersistentStorage()
2259 {
2260     QWebPage webPage;
2261
2262     // By default all persistent options should be disabled
2263     QCOMPARE(webPage.settings()->testAttribute(QWebSettings::LocalStorageEnabled), false);
2264     QCOMPARE(webPage.settings()->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled), false);
2265     QCOMPARE(webPage.settings()->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled), false);
2266     QVERIFY(webPage.settings()->iconDatabasePath().isEmpty());
2267
2268     QWebSettings::enablePersistentStorage();
2269
2270
2271     QTRY_COMPARE(webPage.settings()->testAttribute(QWebSettings::LocalStorageEnabled), true);
2272     QTRY_COMPARE(webPage.settings()->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled), true);
2273     QTRY_COMPARE(webPage.settings()->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled), true);
2274
2275     QTRY_VERIFY(!webPage.settings()->offlineStoragePath().isEmpty());
2276     QTRY_VERIFY(!webPage.settings()->offlineWebApplicationCachePath().isEmpty());
2277     QTRY_VERIFY(!webPage.settings()->iconDatabasePath().isEmpty());
2278 }
2279
2280 void tst_QWebPage::defaultTextEncoding()
2281 {
2282     QWebFrame* mainFrame = m_page->mainFrame();
2283
2284     QString defaultCharset = mainFrame->evaluateJavaScript("document.defaultCharset").toString();
2285     QVERIFY(!defaultCharset.isEmpty());
2286     QCOMPARE(QWebSettings::globalSettings()->defaultTextEncoding(), defaultCharset);
2287
2288     m_page->settings()->setDefaultTextEncoding(QString("utf-8"));
2289     QString charset = mainFrame->evaluateJavaScript("document.defaultCharset").toString();
2290     QCOMPARE(charset, QString("utf-8"));
2291     QCOMPARE(m_page->settings()->defaultTextEncoding(), charset);
2292
2293     m_page->settings()->setDefaultTextEncoding(QString());
2294     charset = mainFrame->evaluateJavaScript("document.defaultCharset").toString();
2295     QVERIFY(!charset.isEmpty());
2296     QCOMPARE(charset, defaultCharset);
2297
2298     QWebSettings::globalSettings()->setDefaultTextEncoding(QString("utf-8"));
2299     charset = mainFrame->evaluateJavaScript("document.defaultCharset").toString();
2300     QCOMPARE(charset, QString("utf-8"));
2301     QCOMPARE(QWebSettings::globalSettings()->defaultTextEncoding(), charset);
2302 }
2303
2304 class ErrorPage : public QWebPage
2305 {
2306 public:
2307
2308     ErrorPage(QWidget* parent = 0): QWebPage(parent)
2309     {
2310     }
2311
2312     virtual bool supportsExtension(Extension extension) const
2313     {
2314         return extension == ErrorPageExtension;
2315     }
2316
2317     virtual bool extension(Extension, const ExtensionOption* option, ExtensionReturn* output)
2318     {
2319         ErrorPageExtensionReturn* errorPage = static_cast<ErrorPageExtensionReturn*>(output);
2320
2321         errorPage->contentType = "text/html";
2322         errorPage->content = "error";
2323         return true;
2324     }
2325 };
2326
2327 void tst_QWebPage::errorPageExtension()
2328 {
2329     ErrorPage* page = new ErrorPage;
2330     m_view->setPage(page);
2331
2332     QSignalSpy spyLoadFinished(m_view, SIGNAL(loadFinished(bool)));
2333
2334     m_view->setUrl(QUrl("data:text/html,foo"));
2335     QTRY_COMPARE(spyLoadFinished.count(), 1);
2336
2337     page->mainFrame()->setUrl(QUrl("http://non.existent/url"));
2338     QTRY_COMPARE(spyLoadFinished.count(), 2);
2339     QCOMPARE(page->mainFrame()->toPlainText(), QString("error"));
2340     QCOMPARE(page->history()->count(), 2);
2341     QCOMPARE(page->history()->currentItem().url(), QUrl("http://non.existent/url"));
2342     QCOMPARE(page->history()->canGoBack(), true);
2343     QCOMPARE(page->history()->canGoForward(), false);
2344
2345     page->triggerAction(QWebPage::Back);
2346     QTRY_COMPARE(page->history()->canGoBack(), false);
2347     QTRY_COMPARE(page->history()->canGoForward(), true);
2348
2349     page->triggerAction(QWebPage::Forward);
2350     QTRY_COMPARE(page->history()->canGoBack(), true);
2351     QTRY_COMPARE(page->history()->canGoForward(), false);
2352
2353     page->triggerAction(QWebPage::Back);
2354     QTRY_COMPARE(page->history()->canGoBack(), false);
2355     QTRY_COMPARE(page->history()->canGoForward(), true);
2356     QTRY_COMPARE(page->history()->currentItem().url(), QUrl("data:text/html,foo"));
2357
2358     m_view->setPage(0);
2359 }
2360
2361 void tst_QWebPage::errorPageExtensionInIFrames()
2362 {
2363     ErrorPage* page = new ErrorPage;
2364     m_view->setPage(page);
2365
2366     m_view->page()->mainFrame()->load(QUrl(
2367         "data:text/html,"
2368         "<h1>h1</h1>"
2369         "<iframe src='data:text/html,<p/>p'></iframe>"
2370         "<iframe src='http://non.existent/url'></iframe>"));
2371     QSignalSpy spyLoadFinished(m_view, SIGNAL(loadFinished(bool)));
2372     QTRY_COMPARE(spyLoadFinished.count(), 1);
2373
2374     QCOMPARE(page->mainFrame()->childFrames()[1]->toPlainText(), QString("error"));
2375
2376     m_view->setPage(0);
2377 }
2378
2379 void tst_QWebPage::errorPageExtensionInFrameset()
2380 {
2381     ErrorPage* page = new ErrorPage;
2382     m_view->setPage(page);
2383
2384     m_view->load(QUrl("qrc:///resources/index.html"));
2385
2386     QSignalSpy spyLoadFinished(m_view, SIGNAL(loadFinished(bool)));
2387     QTRY_COMPARE(spyLoadFinished.count(), 1);
2388     QCOMPARE(page->mainFrame()->childFrames()[1]->toPlainText(), QString("error"));
2389
2390     m_view->setPage(0);
2391 }
2392
2393 class FriendlyWebPage : public QWebPage
2394 {
2395 public:
2396     friend class tst_QWebPage;
2397 };
2398
2399 void tst_QWebPage::userAgentApplicationName()
2400 {
2401     const QString oldApplicationName = QCoreApplication::applicationName();
2402     FriendlyWebPage page;
2403
2404     const QString applicationNameMarker = QString::fromUtf8("StrangeName\342\210\236");
2405     QCoreApplication::setApplicationName(applicationNameMarker);
2406     QVERIFY(page.userAgentForUrl(QUrl()).contains(applicationNameMarker));
2407
2408     QCoreApplication::setApplicationName(oldApplicationName);
2409 }
2410
2411 void tst_QWebPage::crashTests_LazyInitializationOfMainFrame()
2412 {
2413     {
2414         QWebPage webPage;
2415     }
2416     {
2417         QWebPage webPage;
2418         webPage.selectedText();
2419     }
2420     {
2421         QWebPage webPage;
2422         webPage.selectedHtml();
2423     }
2424     {
2425         QWebPage webPage;
2426         webPage.triggerAction(QWebPage::Back, true);
2427     }
2428     {
2429         QWebPage webPage;
2430         QPoint pos(10,10);
2431         webPage.updatePositionDependentActions(pos);
2432     }
2433 }
2434
2435 static void takeScreenshot(QWebPage* page)
2436 {
2437     QWebFrame* mainFrame = page->mainFrame();
2438     page->setViewportSize(mainFrame->contentsSize());
2439     QImage image(page->viewportSize(), QImage::Format_ARGB32);
2440     QPainter painter(&image);
2441     mainFrame->render(&painter);
2442     painter.end();
2443 }
2444
2445 void tst_QWebPage::screenshot_data()
2446 {
2447     QTest::addColumn<QString>("html");
2448     QTest::newRow("WithoutPlugin") << "<html><body id='b'>text</body></html>";
2449     QTest::newRow("WindowedPlugin") << QString("<html><body id='b'>text<embed src='resources/test.swf'></embed></body></html>");
2450     QTest::newRow("WindowlessPlugin") << QString("<html><body id='b'>text<embed src='resources/test.swf' wmode='transparent'></embed></body></html>");
2451 }
2452
2453 void tst_QWebPage::screenshot()
2454 {
2455     if (!QDir(TESTS_SOURCE_DIR).exists())
2456         QSKIP(QString("This test requires access to resources found in '%1'").arg(TESTS_SOURCE_DIR).toLatin1().constData(), SkipAll);
2457
2458     QDir::setCurrent(TESTS_SOURCE_DIR);
2459
2460     QFETCH(QString, html);
2461     QWebPage* page = new QWebPage;
2462     page->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
2463     QWebFrame* mainFrame = page->mainFrame();
2464     mainFrame->setHtml(html, QUrl::fromLocalFile(TESTS_SOURCE_DIR));
2465     ::waitForSignal(mainFrame, SIGNAL(loadFinished(bool)), 2000);
2466
2467     // take screenshot without a view
2468     takeScreenshot(page);
2469
2470     QWebView* view = new QWebView;
2471     view->setPage(page);
2472
2473     // take screenshot when attached to a view
2474     takeScreenshot(page);
2475
2476     delete page;
2477     delete view;
2478
2479     QDir::setCurrent(QApplication::applicationDirPath());
2480 }
2481
2482 #if defined(ENABLE_WEBGL) && ENABLE_WEBGL
2483 // https://bugs.webkit.org/show_bug.cgi?id=54138
2484 static void webGLScreenshotWithoutView(bool accelerated)
2485 {
2486     QWebPage page;
2487     page.settings()->setAttribute(QWebSettings::WebGLEnabled, true);
2488     page.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled, accelerated);
2489     QWebFrame* mainFrame = page.mainFrame();
2490     mainFrame->setHtml("<html><body>"
2491                        "<canvas id='webgl' width='300' height='300'></canvas>"
2492                        "<script>document.getElementById('webgl').getContext('experimental-webgl')</script>"
2493                        "</body></html>");
2494
2495     takeScreenshot(&page);
2496 }
2497
2498 void tst_QWebPage::acceleratedWebGLScreenshotWithoutView()
2499 {
2500     webGLScreenshotWithoutView(true);
2501 }
2502
2503 void tst_QWebPage::unacceleratedWebGLScreenshotWithoutView()
2504 {
2505     webGLScreenshotWithoutView(false);
2506 }
2507 #endif
2508
2509 void tst_QWebPage::originatingObjectInNetworkRequests()
2510 {
2511     TestNetworkManager* networkManager = new TestNetworkManager(m_page);
2512     m_page->setNetworkAccessManager(networkManager);
2513     networkManager->requests.clear();
2514
2515     m_view->setHtml(QString("<frameset cols=\"25%,75%\"><frame src=\"data:text/html,"
2516                             "<head><meta http-equiv='refresh' content='1'></head>foo \">"
2517                             "<frame src=\"data:text/html,bar\"></frameset>"), QUrl());
2518     QVERIFY(::waitForSignal(m_view, SIGNAL(loadFinished(bool))));
2519
2520     QCOMPARE(networkManager->requests.count(), 2);
2521
2522     QList<QWebFrame*> childFrames = m_page->mainFrame()->childFrames();
2523     QCOMPARE(childFrames.count(), 2);
2524
2525     for (int i = 0; i < 2; ++i)
2526         QVERIFY(qobject_cast<QWebFrame*>(networkManager->requests.at(i).originatingObject()) == childFrames.at(i));
2527 }
2528
2529 /**
2530  * Test fixups for https://bugs.webkit.org/show_bug.cgi?id=30914
2531  *
2532  * From JS we test the following conditions.
2533  *
2534  *   OK     + QString() => SUCCESS, empty string (but not null)
2535  *   OK     + "text"    => SUCCESS, "text"
2536  *   CANCEL + QString() => CANCEL, null string
2537  *   CANCEL + "text"    => CANCEL, null string
2538  */
2539 class JSPromptPage : public QWebPage {
2540     Q_OBJECT
2541 public:
2542     JSPromptPage()
2543     {}
2544
2545     bool javaScriptPrompt(QWebFrame* frame, const QString& msg, const QString& defaultValue, QString* result)
2546     {
2547         if (msg == QLatin1String("test1")) {
2548             *result = QString();
2549             return true;
2550         } else if (msg == QLatin1String("test2")) {
2551             *result = QLatin1String("text");
2552             return true;
2553         } else if (msg == QLatin1String("test3")) {
2554             *result = QString();
2555             return false;
2556         } else if (msg == QLatin1String("test4")) {
2557             *result = QLatin1String("text");
2558             return false;
2559         }
2560
2561         qFatal("Unknown msg.");
2562         return QWebPage::javaScriptPrompt(frame, msg, defaultValue, result);
2563     }
2564 };
2565
2566 void tst_QWebPage::testJSPrompt()
2567 {
2568     JSPromptPage page;
2569     bool res;
2570
2571     // OK + QString()
2572     res = page.mainFrame()->evaluateJavaScript(
2573             "var retval = prompt('test1');"
2574             "retval=='' && retval.length == 0;").toBool();
2575     QVERIFY(res);
2576
2577     // OK + "text"
2578     res = page.mainFrame()->evaluateJavaScript(
2579             "var retval = prompt('test2');"
2580             "retval=='text' && retval.length == 4;").toBool();
2581     QVERIFY(res);
2582
2583     // Cancel + QString()
2584     res = page.mainFrame()->evaluateJavaScript(
2585             "var retval = prompt('test3');"
2586             "retval===null;").toBool();
2587     QVERIFY(res);
2588
2589     // Cancel + "text"
2590     res = page.mainFrame()->evaluateJavaScript(
2591             "var retval = prompt('test4');"
2592             "retval===null;").toBool();
2593     QVERIFY(res);
2594 }
2595
2596 class TestModalPage : public QWebPage
2597 {
2598     Q_OBJECT
2599 public:
2600     TestModalPage(QObject* parent = 0) : QWebPage(parent) {
2601     }
2602     virtual QWebPage* createWindow(WebWindowType) {
2603         QWebPage* page = new TestModalPage();
2604         connect(page, SIGNAL(windowCloseRequested()), page, SLOT(deleteLater()));
2605         return page;
2606     }
2607 };
2608
2609 void tst_QWebPage::showModalDialog()
2610 {
2611     TestModalPage page;
2612     page.mainFrame()->setHtml(QString("<html></html>"));
2613     QString res = page.mainFrame()->evaluateJavaScript("window.showModalDialog('javascript:window.returnValue=dialogArguments; window.close();', 'This is a test');").toString();
2614     QCOMPARE(res, QString("This is a test"));
2615 }
2616
2617 void tst_QWebPage::testStopScheduledPageRefresh()
2618 {    
2619     // Without QWebPage::StopScheduledPageRefresh
2620     QWebPage page1;
2621     page1.setNetworkAccessManager(new TestNetworkManager(&page1));
2622     page1.mainFrame()->setHtml("<html><head>"
2623                                 "<meta http-equiv=\"refresh\"content=\"0;URL=qrc:///resources/index.html\">"
2624                                 "</head><body><h1>Page redirects immediately...</h1>"
2625                                 "</body></html>");
2626     QVERIFY(::waitForSignal(&page1, SIGNAL(loadFinished(bool))));
2627     QTest::qWait(500);
2628     QCOMPARE(page1.mainFrame()->url(), QUrl(QLatin1String("qrc:///resources/index.html")));
2629     
2630     // With QWebPage::StopScheduledPageRefresh
2631     QWebPage page2;
2632     page2.setNetworkAccessManager(new TestNetworkManager(&page2));
2633     page2.mainFrame()->setHtml("<html><head>"
2634                                "<meta http-equiv=\"refresh\"content=\"1;URL=qrc:///resources/index.html\">"
2635                                "</head><body><h1>Page redirect test with 1 sec timeout...</h1>"
2636                                "</body></html>");
2637     page2.triggerAction(QWebPage::StopScheduledPageRefresh);
2638     QTest::qWait(1500);
2639     QCOMPARE(page2.mainFrame()->url().toString(), QLatin1String("about:blank"));
2640 }
2641
2642 void tst_QWebPage::findText()
2643 {
2644     m_view->setHtml(QString("<html><head></head><body><div>foo bar</div></body></html>"));
2645     m_page->triggerAction(QWebPage::SelectAll);
2646     QVERIFY(!m_page->selectedText().isEmpty());
2647     QVERIFY(!m_page->selectedHtml().isEmpty());
2648     m_page->findText("");
2649     QVERIFY(m_page->selectedText().isEmpty());
2650     QVERIFY(m_page->selectedHtml().isEmpty());
2651     QStringList words = (QStringList() << "foo" << "bar");
2652     foreach (QString subString, words) {
2653         m_page->findText(subString, QWebPage::FindWrapsAroundDocument);
2654         QCOMPARE(m_page->selectedText(), subString);
2655         QCOMPARE(m_page->selectedHtml(), QString("<span class=\"Apple-style-span\" style=\"border-collapse: separate; color: rgb(0, 0, 0); font-family: Times; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-align: -webkit-auto; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; font-size: medium; \">%1</span>").arg(subString));
2656         m_page->findText("");
2657         QVERIFY(m_page->selectedText().isEmpty());
2658         QVERIFY(m_page->selectedHtml().isEmpty());
2659     }
2660 }
2661
2662 struct ImageExtensionMap {
2663     const char* extension;
2664     const char* mimeType;
2665 };
2666
2667 static const ImageExtensionMap extensionMap[] = {
2668     { "bmp", "image/bmp" },
2669     { "css", "text/css" },
2670     { "gif", "image/gif" },
2671     { "html", "text/html" },
2672     { "htm", "text/html" },
2673     { "ico", "image/x-icon" },
2674     { "jpeg", "image/jpeg" },
2675     { "jpg", "image/jpeg" },
2676     { "js", "application/x-javascript" },
2677     { "mng", "video/x-mng" },
2678     { "pbm", "image/x-portable-bitmap" },
2679     { "pgm", "image/x-portable-graymap" },
2680     { "pdf", "application/pdf" },
2681     { "png", "image/png" },
2682     { "ppm", "image/x-portable-pixmap" },
2683     { "rss", "application/rss+xml" },
2684     { "svg", "image/svg+xml" },
2685     { "text", "text/plain" },
2686     { "tif", "image/tiff" },
2687     { "tiff", "image/tiff" },
2688     { "txt", "text/plain" },
2689     { "xbm", "image/x-xbitmap" },
2690     { "xml", "text/xml" },
2691     { "xpm", "image/x-xpm" },
2692     { "xsl", "text/xsl" },
2693     { "xhtml", "application/xhtml+xml" },
2694     { "wml", "text/vnd.wap.wml" },
2695     { "wmlc", "application/vnd.wap.wmlc" },
2696     { 0, 0 }
2697 };
2698
2699 static QString getMimeTypeForExtension(const QString &ext)
2700 {
2701     const ImageExtensionMap *e = extensionMap;
2702     while (e->extension) {
2703         if (ext.compare(QLatin1String(e->extension), Qt::CaseInsensitive) == 0)
2704             return QLatin1String(e->mimeType);
2705         ++e;
2706     }
2707
2708     return QString();
2709 }
2710
2711 void tst_QWebPage::supportedContentType()
2712 {
2713    QStringList contentTypes;
2714
2715    // Add supported non image types...
2716    contentTypes << "text/html" << "text/xml" << "text/xsl" << "text/plain" << "text/"
2717                 << "application/xml" << "application/xhtml+xml" << "application/vnd.wap.xhtml+xml"
2718                 << "application/rss+xml" << "application/atom+xml" << "application/json";
2719
2720    // Add supported image types...
2721    Q_FOREACH(const QByteArray& imageType, QImageWriter::supportedImageFormats()) {
2722       const QString mimeType = getMimeTypeForExtension(imageType);
2723       if (!mimeType.isEmpty())
2724           contentTypes << mimeType;
2725    }
2726
2727    // Get the mime types supported by webkit...
2728    const QStringList supportedContentTypes = m_page->supportedContentTypes();
2729
2730    Q_FOREACH(const QString& mimeType, contentTypes)
2731       QVERIFY2(supportedContentTypes.contains(mimeType), QString("'%1' is not a supported content type!").arg(mimeType).toLatin1());
2732       
2733    Q_FOREACH(const QString& mimeType, contentTypes)
2734       QVERIFY2(m_page->supportsContentType(mimeType), QString("Cannot handle content types '%1'!").arg(mimeType).toLatin1());
2735 }
2736
2737
2738 void tst_QWebPage::navigatorCookieEnabled()
2739 {
2740     m_page->networkAccessManager()->setCookieJar(0);
2741     QVERIFY(!m_page->networkAccessManager()->cookieJar());
2742     QVERIFY(!m_page->mainFrame()->evaluateJavaScript("navigator.cookieEnabled").toBool());
2743
2744     m_page->networkAccessManager()->setCookieJar(new QNetworkCookieJar());
2745     QVERIFY(m_page->networkAccessManager()->cookieJar());
2746     QVERIFY(m_page->mainFrame()->evaluateJavaScript("navigator.cookieEnabled").toBool());
2747 }
2748
2749 #ifdef Q_OS_MAC
2750 void tst_QWebPage::macCopyUnicodeToClipboard()
2751 {
2752     QString unicodeText = QString::fromUtf8("αβγδεζηθικλμπ");
2753     m_page->mainFrame()->setHtml(QString("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>%1</body></html>").arg(unicodeText));
2754     m_page->triggerAction(QWebPage::SelectAll);
2755     m_page->triggerAction(QWebPage::Copy);
2756
2757     QString clipboardData = QString::fromUtf8(QApplication::clipboard()->mimeData()->data(QLatin1String("text/html")));
2758
2759     QVERIFY(clipboardData.contains(QLatin1String("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />")));
2760     QVERIFY(clipboardData.contains(unicodeText));
2761 }
2762 #endif
2763
2764 void tst_QWebPage::contextMenuCopy()
2765 {
2766     QWebView view;
2767
2768     view.setHtml("<a href=\"http://www.google.com\">You cant miss this</a>");
2769
2770     view.page()->triggerAction(QWebPage::SelectAll);
2771     QVERIFY(!view.page()->selectedText().isEmpty());
2772
2773     QWebElement link = view.page()->mainFrame()->findFirstElement("a");
2774     QPoint pos(link.geometry().center());
2775     QContextMenuEvent event(QContextMenuEvent::Mouse, pos);
2776     view.page()->swallowContextMenuEvent(&event);
2777     view.page()->updatePositionDependentActions(pos);
2778
2779     QList<QMenu*> contextMenus = view.findChildren<QMenu*>();
2780     QVERIFY(!contextMenus.isEmpty());
2781     QMenu* contextMenu = contextMenus.first();
2782     QVERIFY(contextMenu);
2783     
2784     QList<QAction *> list = contextMenu->actions();
2785     int index = list.indexOf(view.page()->action(QWebPage::Copy));
2786     QVERIFY(index != -1);
2787 }
2788
2789 void tst_QWebPage::deleteQWebViewTwice()
2790 {
2791     for (int i = 0; i < 2; ++i) {
2792         QMainWindow mainWindow;
2793         QWebView* webView = new QWebView(&mainWindow);
2794         mainWindow.setCentralWidget(webView);
2795         webView->load(QUrl("qrc:///resources/frame_a.html"));
2796         mainWindow.show();
2797         connect(webView, SIGNAL(loadFinished(bool)), &mainWindow, SLOT(close()));
2798         QApplication::instance()->exec();
2799     }
2800 }
2801
2802 class RepaintRequestedRenderer : public QObject {
2803     Q_OBJECT
2804 public:
2805     RepaintRequestedRenderer(QWebPage* page, QPainter* painter)
2806         : m_page(page)
2807         , m_painter(painter)
2808         , m_recursionCount(0)
2809     {
2810         connect(m_page, SIGNAL(repaintRequested(QRect)), this, SLOT(onRepaintRequested(QRect)));
2811     }
2812
2813 signals:
2814     void finished();
2815
2816 private slots:
2817     void onRepaintRequested(const QRect& rect)
2818     {
2819         QCOMPARE(m_recursionCount, 0);
2820
2821         m_recursionCount++;
2822         m_page->mainFrame()->render(m_painter, rect);
2823         m_recursionCount--;
2824
2825         QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
2826     }
2827
2828 private:
2829     QWebPage* m_page;
2830     QPainter* m_painter;
2831     int m_recursionCount;
2832 };
2833
2834 void tst_QWebPage::renderOnRepaintRequestedShouldNotRecurse()
2835 {
2836     QSize viewportSize(720, 576);
2837     QWebPage page;
2838
2839     QImage image(viewportSize, QImage::Format_ARGB32);
2840     QPainter painter(&image);
2841
2842     page.setPreferredContentsSize(viewportSize);
2843     page.setViewportSize(viewportSize);
2844     RepaintRequestedRenderer r(&page, &painter);
2845
2846     page.mainFrame()->setHtml("zalan loves trunk", QUrl());
2847
2848     QVERIFY(::waitForSignal(&r, SIGNAL(finished())));
2849 }
2850
2851 QTEST_MAIN(tst_QWebPage)
2852 #include "tst_qwebpage.moc"