[GTK] Implement DumpRenderTreeSupportGtk (similarly to DumpRenderTreeSupportQt idea)
[WebKit-https.git] / WebKitTools / DumpRenderTree / gtk / DumpRenderTree.cpp
1 /*
2  * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
3  * Copyright (C) 2008 Alp Toker <alp@nuanti.com>
4  * Copyright (C) 2009 Jan Alonzo <jmalonzo@gmail.com>
5  * Copyright (C) 2010 Igalia S.L.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1.  Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  * 2.  Redistributions in binary form must reproduce the above copyright
14  *     notice, this list of conditions and the following disclaimer in the
15  *     documentation and/or other materials provided with the distribution.
16  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
17  *     its contributors may be used to endorse or promote products derived
18  *     from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
21  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
24  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include "config.h"
33 #include "DumpRenderTree.h"
34
35 #include "AccessibilityController.h"
36 #include "EventSender.h"
37 #include "GCController.h"
38 #include "GOwnPtr.h"
39 #include "LayoutTestController.h"
40 #include "PixelDumpSupport.h"
41 #include "WebCoreSupport/DumpRenderTreeSupportGtk.h"
42 #include "WorkQueue.h"
43 #include "WorkQueueItem.h"
44 #include <JavaScriptCore/JavaScript.h>
45 #include <cassert>
46 #include <cstdlib>
47 #include <cstring>
48 #include <getopt.h>
49 #include <gtk/gtk.h>
50 #include <webkit/webkit.h>
51 #include <wtf/Assertions.h>
52
53 #if PLATFORM(X11)
54 #include <fontconfig/fontconfig.h>
55 #endif
56
57
58 using namespace std;
59
60 extern "C" {
61 // This API is not yet public.
62 extern G_CONST_RETURN gchar* webkit_web_history_item_get_target(WebKitWebHistoryItem*);
63 extern gboolean webkit_web_history_item_is_target_item(WebKitWebHistoryItem*);
64 extern GList* webkit_web_history_item_get_children(WebKitWebHistoryItem*);
65 extern GSList* webkit_web_frame_get_children(WebKitWebFrame* frame);
66 extern gchar* webkit_web_frame_get_inner_text(WebKitWebFrame* frame);
67 extern gchar* webkit_web_frame_dump_render_tree(WebKitWebFrame* frame);
68 extern guint webkit_web_frame_get_pending_unload_event_count(WebKitWebFrame* frame);
69 extern void webkit_web_settings_add_extra_plugin_directory(WebKitWebView* view, const gchar* directory);
70 extern gchar* webkit_web_frame_get_response_mime_type(WebKitWebFrame* frame);
71 extern void webkit_web_frame_clear_main_frame_name(WebKitWebFrame* frame);
72 extern void webkit_web_view_set_group_name(WebKitWebView* view, const gchar* groupName);
73 extern void webkit_reset_origin_access_white_lists();
74 }
75
76 volatile bool done;
77 static bool printSeparators;
78 static int dumpPixels;
79 static int dumpTree = 1;
80
81 AccessibilityController* axController = 0;
82 RefPtr<LayoutTestController> gLayoutTestController;
83 static GCController* gcController = 0;
84 static WebKitWebView* webView;
85 static GtkWidget* window;
86 static GtkWidget* container;
87 static GtkWidget* webInspectorWindow;
88 WebKitWebFrame* mainFrame = 0;
89 WebKitWebFrame* topLoadingFrame = 0;
90 guint waitToDumpWatchdog = 0;
91 bool waitForPolicy = false;
92
93 // This is a list of opened webviews
94 GSList* webViewList = 0;
95
96 // current b/f item at the end of the previous test
97 static WebKitWebHistoryItem* prevTestBFItem = NULL;
98
99 const unsigned historyItemIndent = 8;
100
101 static void runTest(const string& testPathOrURL);
102
103 static bool shouldLogFrameLoadDelegates(const string& pathOrURL)
104 {
105     return pathOrURL.find("loading/") != string::npos;
106 }
107
108 static bool shouldOpenWebInspector(const string& pathOrURL)
109 {
110     return pathOrURL.find("inspector/") != string::npos;
111 }
112
113 static bool shouldEnableDeveloperExtras(const string& pathOrURL)
114 {
115     return shouldOpenWebInspector(pathOrURL) || pathOrURL.find("inspector-enabled/") != string::npos;
116 }
117
118 void dumpFrameScrollPosition(WebKitWebFrame* frame)
119 {
120
121 }
122
123 void displayWebView()
124 {
125     gtk_widget_queue_draw(GTK_WIDGET(webView));
126 }
127
128 static void appendString(gchar*& target, gchar* string)
129 {
130     gchar* oldString = target;
131     target = g_strconcat(target, string, NULL);
132     g_free(oldString);
133 }
134
135 static void initializeGtkFontSettings(const char* testURL)
136 {
137     GtkSettings* settings = gtk_settings_get_default();
138     if (!settings)
139         return;
140     g_object_set(settings, "gtk-xft-antialias", 1, NULL);
141     g_object_set(settings, "gtk-xft-hinting", 1, NULL);
142     g_object_set(settings, "gtk-xft-hintstyle", "hintfull", NULL);
143     g_object_set(settings, "gtk-font-name", "Liberation Sans 16", NULL);
144
145     // One test needs subpixel anti-aliasing turned on, but generally we
146     // want all text in other tests to use to grayscale anti-aliasing.
147     if (testURL && strstr(testURL, "xsettings_antialias_settings.html"))
148         g_object_set(settings, "gtk-xft-rgba", "rgb", NULL);
149     else
150         g_object_set(settings, "gtk-xft-rgba", "none", NULL);
151 }
152
153 static void initializeFonts(const char* testURL = 0)
154 {
155 #if PLATFORM(X11)
156     initializeGtkFontSettings(testURL);
157
158     FcInit();
159
160     // If a test resulted a font being added or removed via the @font-face rule, then
161     // we want to reset the FontConfig configuration to prevent it from affecting other tests.
162     static int numFonts = 0;
163     FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication);
164     if (appFontSet && numFonts && appFontSet->nfont == numFonts)
165         return;
166
167     // Load our configuration file, which sets up proper aliases for family
168     // names like sans, serif and monospace.
169     FcConfig* config = FcConfigCreate();
170     GOwnPtr<gchar> fontConfigFilename(g_build_filename(FONTS_CONF_DIR, "fonts.conf", NULL));
171     if (!FcConfigParseAndLoad(config, reinterpret_cast<FcChar8*>(fontConfigFilename.get()), true))
172         g_error("Couldn't load font configuration file from: %s", fontConfigFilename.get());
173
174     static const char *const fontPaths[][2] = {
175         { "/usr/share/fonts/truetype/ttf-liberation/LiberationMono-BoldItalic.ttf",
176           "/usr/share/fonts/liberation/LiberationMono-BoldItalic.ttf", },
177         { "/usr/share/fonts/truetype/ttf-liberation/LiberationMono-Bold.ttf",
178           "/usr/share/fonts/liberation/LiberationMono-Bold.ttf", },
179         { "/usr/share/fonts/truetype/ttf-liberation/LiberationMono-Italic.ttf",
180           "/usr/share/fonts/liberation/LiberationMono-Italic.ttf", },
181         { "/usr/share/fonts/truetype/ttf-liberation/LiberationMono-Regular.ttf",
182           "/usr/share/fonts/liberation/LiberationMono-Regular.ttf", },
183         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSans-BoldItalic.ttf",
184           "/usr/share/fonts/liberation/LiberationSans-BoldItalic.ttf", },
185         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSans-Bold.ttf",
186           "/usr/share/fonts/liberation/LiberationSans-Bold.ttf", },
187         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSans-Italic.ttf",
188           "/usr/share/fonts/liberation/LiberationSans-Italic.ttf", },
189         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSans-Regular.ttf",
190           "/usr/share/fonts/liberation/LiberationSans-Regular.ttf", },
191         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-BoldItalic.ttf",
192           "/usr/share/fonts/liberation/LiberationSerif-BoldItalic.ttf", },
193         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-Bold.ttf",
194           "/usr/share/fonts/liberation/LiberationSerif-Bold.ttf", },
195         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-Italic.ttf",
196           "/usr/share/fonts/liberation/LiberationSerif-Italic.ttf", },
197         { "/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-Regular.ttf",
198           "/usr/share/fonts/liberation/LiberationSerif-Regular.ttf", },
199         { "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf",
200           "/usr/share/fonts/dejavu/DejaVuSans.ttf", },
201         { "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf",
202           "/usr/share/fonts/dejavu/DejaVuSerif.ttf", },
203
204         // MathML tests require the STIX fonts.
205         { "/usr/share/fonts/opentype/stix/STIXGeneral.otf",
206           "/usr/share/fonts/stix/STIXGeneral.otf" },
207         { "/usr/share/fonts/opentype/stix/STIXGeneralBolIta.otf",
208           "/usr/share/fonts/stix/STIXGeneralBolIta.otf" },
209         { "/usr/share/fonts/opentype/stix/STIXGeneralBol.otf",
210           "/usr/share/fonts/stix/STIXGeneralBol.otf" },
211         { "/usr/share/fonts/opentype/stix/STIXGeneralItalic.otf",
212           "/usr/share/fonts/stix/STIXGeneralItalic.otf" }
213     };
214
215     // TODO: Some tests use Lucida. We should load these as well, once it becomes
216     // clear how to install these fonts easily on Fedora.
217     for (size_t font = 0; font < G_N_ELEMENTS(fontPaths); font++) {
218         bool found = false;
219         for (size_t path = 0; path < 2; path++) {
220
221             if (g_file_test(fontPaths[font][path], G_FILE_TEST_EXISTS)) {
222                 found = true;
223                 if (!FcConfigAppFontAddFile(config, reinterpret_cast<const FcChar8*>(fontPaths[font][path])))
224                     g_error("Could not load font at %s!", fontPaths[font][path]);
225                 else
226                     break;
227             }
228         }
229
230         if (!found)
231             g_error("Could not find font at %s. Either install this font or file a bug "
232                     "at http://bugs.webkit.org if it is installed in another location.",
233                     fontPaths[font][0]);
234     }
235
236     // Ahem is used by many layout tests.
237     GOwnPtr<gchar> ahemFontFilename(g_build_filename(FONTS_CONF_DIR, "AHEM____.TTF", NULL));
238     if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(ahemFontFilename.get())))
239         g_error("Could not load font at %s!", ahemFontFilename.get()); 
240
241     if (!FcConfigSetCurrent(config))
242         g_error("Could not set the current font configuration!");
243
244     numFonts = FcConfigGetFonts(config, FcSetApplication)->nfont;
245 #endif
246 }
247
248 static gchar* dumpFramesAsText(WebKitWebFrame* frame)
249 {
250     gchar* result = 0;
251
252     // Add header for all but the main frame.
253     bool isMainFrame = (webkit_web_view_get_main_frame(webView) == frame);
254
255     gchar* innerText = webkit_web_frame_get_inner_text(frame);
256     if (isMainFrame)
257         result = g_strdup_printf("%s\n", innerText);
258     else {
259         const gchar* frameName = webkit_web_frame_get_name(frame);
260         result = g_strdup_printf("\n--------\nFrame: '%s'\n--------\n%s\n", frameName, innerText);
261     }
262     g_free(innerText);
263
264     if (gLayoutTestController->dumpChildFramesAsText()) {
265         GSList* children = webkit_web_frame_get_children(frame);
266         for (GSList* child = children; child; child = g_slist_next(child))
267             appendString(result, dumpFramesAsText(static_cast<WebKitWebFrame* >(child->data)));
268         g_slist_free(children);
269     }
270
271     return result;
272 }
273
274 static gint compareHistoryItems(gpointer* item1, gpointer* item2)
275 {
276     return g_ascii_strcasecmp(webkit_web_history_item_get_target(WEBKIT_WEB_HISTORY_ITEM(item1)),
277                               webkit_web_history_item_get_target(WEBKIT_WEB_HISTORY_ITEM(item2)));
278 }
279
280 static void dumpHistoryItem(WebKitWebHistoryItem* item, int indent, bool current)
281 {
282     ASSERT(item != NULL);
283     int start = 0;
284     g_object_ref(item);
285     if (current) {
286         printf("curr->");
287         start = 6;
288     }
289     for (int i = start; i < indent; i++)
290         putchar(' ');
291
292     // normalize file URLs.
293     const gchar* uri = webkit_web_history_item_get_uri(item);
294     gchar* uriScheme = g_uri_parse_scheme(uri);
295     if (g_strcmp0(uriScheme, "file") == 0) {
296         gchar* pos = g_strstr_len(uri, -1, "/LayoutTests/");
297         if (!pos)
298             return;
299
300         GString* result = g_string_sized_new(strlen(uri));
301         result = g_string_append(result, "(file test):");
302         result = g_string_append(result, pos + strlen("/LayoutTests/"));
303         printf("%s", result->str);
304         g_string_free(result, TRUE);
305     } else
306         printf("%s", uri);
307
308     g_free(uriScheme);
309
310     const gchar* target = webkit_web_history_item_get_target(item);
311     if (target && strlen(target) > 0)
312         printf(" (in frame \"%s\")", target);
313     if (webkit_web_history_item_is_target_item(item))
314         printf("  **nav target**");
315     putchar('\n');
316     GList* kids = webkit_web_history_item_get_children(item);
317     if (kids) {
318         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
319         kids = g_list_sort(kids, (GCompareFunc) compareHistoryItems);
320         for (unsigned i = 0; i < g_list_length(kids); i++)
321             dumpHistoryItem(WEBKIT_WEB_HISTORY_ITEM(g_list_nth_data(kids, i)), indent+4, FALSE);
322     }
323     g_object_unref(item);
324 }
325
326 static void dumpBackForwardListForWebView(WebKitWebView* view)
327 {
328     printf("\n============== Back Forward List ==============\n");
329     WebKitWebBackForwardList* bfList = webkit_web_view_get_back_forward_list(view);
330
331     // Print out all items in the list after prevTestBFItem, which was from the previous test
332     // Gather items from the end of the list, the print them out from oldest to newest
333     GList* itemsToPrint = NULL;
334     gint forwardListCount = webkit_web_back_forward_list_get_forward_length(bfList);
335     for (int i = forwardListCount; i > 0; i--) {
336         WebKitWebHistoryItem* item = webkit_web_back_forward_list_get_nth_item(bfList, i);
337         // something is wrong if the item from the last test is in the forward part of the b/f list
338         ASSERT(item != prevTestBFItem);
339         g_object_ref(item);
340         itemsToPrint = g_list_append(itemsToPrint, item);
341     }
342
343     WebKitWebHistoryItem* currentItem = webkit_web_back_forward_list_get_current_item(bfList);
344
345     g_object_ref(currentItem);
346     itemsToPrint = g_list_append(itemsToPrint, currentItem);
347
348     gint currentItemIndex = g_list_length(itemsToPrint) - 1;
349     gint backListCount = webkit_web_back_forward_list_get_back_length(bfList);
350     for (int i = -1; i >= -(backListCount); i--) {
351         WebKitWebHistoryItem* item = webkit_web_back_forward_list_get_nth_item(bfList, i);
352         if (item == prevTestBFItem)
353             break;
354         g_object_ref(item);
355         itemsToPrint = g_list_append(itemsToPrint, item);
356     }
357
358     for (int i = g_list_length(itemsToPrint) - 1; i >= 0; i--) {
359         WebKitWebHistoryItem* item = WEBKIT_WEB_HISTORY_ITEM(g_list_nth_data(itemsToPrint, i));
360         dumpHistoryItem(item, historyItemIndent, i == currentItemIndex);
361         g_object_unref(item);
362     }
363     g_list_free(itemsToPrint);
364     printf("===============================================\n");
365 }
366
367 static void dumpBackForwardListForAllWebViews()
368 {
369     // Dump the back forward list of the main WebView first
370     dumpBackForwardListForWebView(webView);
371
372     // The view list is prepended. Reverse the list so we get the order right.
373     GSList* viewList = g_slist_reverse(webViewList);
374     for (unsigned i = 0; i < g_slist_length(viewList); ++i)
375         dumpBackForwardListForWebView(WEBKIT_WEB_VIEW(g_slist_nth_data(viewList, i)));
376 }
377
378 static void invalidateAnyPreviousWaitToDumpWatchdog()
379 {
380     if (waitToDumpWatchdog) {
381         g_source_remove(waitToDumpWatchdog);
382         waitToDumpWatchdog = 0;
383     }
384
385     waitForPolicy = false;
386 }
387
388 static void resetDefaultsToConsistentValues()
389 {
390     WebKitWebSettings* settings = webkit_web_view_get_settings(webView);
391     g_object_set(G_OBJECT(settings),
392                  "enable-private-browsing", FALSE,
393                  "enable-developer-extras", FALSE,
394                  "enable-spell-checking", TRUE,
395                  "enable-html5-database", TRUE,
396                  "enable-html5-local-storage", TRUE,
397                  "enable-xss-auditor", FALSE,
398                  "enable-spatial-navigation", FALSE,
399                  "enable-frame-flattening", FALSE,
400                  "javascript-can-access-clipboard", TRUE,
401                  "javascript-can-open-windows-automatically", TRUE,
402                  "enable-offline-web-application-cache", TRUE,
403                  "enable-universal-access-from-file-uris", TRUE,
404                  "enable-scripts", TRUE,
405                  "enable-dom-paste", TRUE,
406                  "default-font-family", "Times",
407                  "monospace-font-family", "Courier",
408                  "serif-font-family", "Times",
409                  "sans-serif-font-family", "Helvetica",
410                  "cursive-font-family", "cursive",
411                  "fantasy-font-family", "fantasy",
412                  "default-font-size", 16,
413                  "default-monospace-font-size", 13,
414                  "minimum-font-size", 1,
415                  "enable-caret-browsing", FALSE,
416                  "enable-page-cache", FALSE,
417                  "auto-resize-window", TRUE,
418                  "enable-java-applet", FALSE,
419                  "enable-plugins", TRUE,
420                  "enable-hyperlink-auditing", FALSE,
421                  "editing-behavior", WEBKIT_EDITING_BEHAVIOR_MAC,
422                  NULL);
423
424     webkit_web_frame_clear_main_frame_name(mainFrame);
425
426     WebKitWebInspector* inspector = webkit_web_view_get_inspector(webView);
427     g_object_set(G_OBJECT(inspector), "javascript-profiling-enabled", FALSE, NULL);
428
429     webkit_web_view_set_zoom_level(webView, 1.0);
430
431     webkit_reset_origin_access_white_lists();
432
433     WebKitWebBackForwardList* list = webkit_web_view_get_back_forward_list(webView);
434     webkit_web_back_forward_list_clear(list);
435
436 #ifdef HAVE_LIBSOUP_2_29_90
437     SoupSession* session = webkit_get_default_session();
438     SoupCookieJar* jar = reinterpret_cast<SoupCookieJar*>(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
439
440     // We only create the jar when the soup backend needs to do
441     // HTTP. Should we initialize it earlier, perhaps?
442     if (jar)
443         g_object_set(G_OBJECT(jar), SOUP_COOKIE_JAR_ACCEPT_POLICY, SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY, NULL);
444 #endif
445
446     setlocale(LC_ALL, "");
447
448     DumpRenderTreeSupportGtk::setLinksIncludedInFocusChain(true);
449 }
450
451 static bool useLongRunningServerMode(int argc, char *argv[])
452 {
453     // This assumes you've already called getopt_long
454     return (argc == optind+1 && !strcmp(argv[optind], "-"));
455 }
456
457 static void runTestingServerLoop()
458 {
459     // When DumpRenderTree runs in server mode, we just wait around for file names
460     // to be passed to us and read each in turn, passing the results back to the client
461     char filenameBuffer[2048];
462     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
463         char* newLineCharacter = strchr(filenameBuffer, '\n');
464         if (newLineCharacter)
465             *newLineCharacter = '\0';
466
467         if (!strlen(filenameBuffer))
468             continue;
469
470         runTest(filenameBuffer);
471     }
472 }
473
474 static void initializeGlobalsFromCommandLineOptions(int argc, char *argv[])
475 {
476     struct option options[] = {
477         {"notree", no_argument, &dumpTree, false},
478         {"pixel-tests", no_argument, &dumpPixels, true},
479         {"tree", no_argument, &dumpTree, true},
480         {NULL, 0, NULL, 0}
481     };
482     
483     int option;
484     while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
485         switch (option) {
486         case '?': // unknown or ambiguous option
487         case ':': // missing argument
488             exit(1);
489             break;
490         }
491     }
492 }
493
494
495 void dump()
496 {
497     invalidateAnyPreviousWaitToDumpWatchdog();
498
499     bool dumpAsText = gLayoutTestController->dumpAsText();
500     if (dumpTree) {
501         char* result = 0;
502         gchar* responseMimeType = webkit_web_frame_get_response_mime_type(mainFrame);
503
504         dumpAsText = g_str_equal(responseMimeType, "text/plain");
505         g_free(responseMimeType);
506
507         // Test can request controller to be dumped as text even
508         // while test's response mime type is not text/plain.
509         // Overriding this behavior with dumpAsText being false is a bad idea.
510         if (dumpAsText)
511             gLayoutTestController->setDumpAsText(dumpAsText);
512
513         if (gLayoutTestController->dumpAsText())
514             result = dumpFramesAsText(mainFrame);
515         else {
516             // Widget resizing is done asynchronously in GTK+. We pump the main
517             // loop here, to flush any pending resize requests. This prevents
518             // timing issues which affect the size of elements in the output.
519             // We only enable this workaround for tests that print the render tree
520             // because this seems to break some dumpAsText tests: see bug 39988
521             // After fixing that test, we should apply this approach to all dumps.
522             while (gtk_events_pending())
523                 gtk_main_iteration();
524
525             result = webkit_web_frame_dump_render_tree(mainFrame);
526         }
527
528         if (!result) {
529             const char* errorMessage;
530             if (gLayoutTestController->dumpAsText())
531                 errorMessage = "[documentElement innerText]";
532             else if (gLayoutTestController->dumpDOMAsWebArchive())
533                 errorMessage = "[[mainFrame DOMDocument] webArchive]";
534             else if (gLayoutTestController->dumpSourceAsWebArchive())
535                 errorMessage = "[[mainFrame dataSource] webArchive]";
536             else
537                 errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
538             printf("ERROR: nil result from %s", errorMessage);
539         } else {
540             printf("%s", result);
541             g_free(result);
542             if (!gLayoutTestController->dumpAsText() && !gLayoutTestController->dumpDOMAsWebArchive() && !gLayoutTestController->dumpSourceAsWebArchive())
543                 dumpFrameScrollPosition(mainFrame);
544
545             if (gLayoutTestController->dumpBackForwardList())
546                 dumpBackForwardListForAllWebViews();
547         }
548
549         if (printSeparators) {
550             puts("#EOF"); // terminate the content block
551             fputs("#EOF\n", stderr);
552             fflush(stdout);
553             fflush(stderr);
554         }
555     }
556
557     if (dumpPixels
558      && gLayoutTestController->generatePixelResults()
559      && !gLayoutTestController->dumpDOMAsWebArchive()
560      && !gLayoutTestController->dumpSourceAsWebArchive())
561         dumpWebViewAsPixelsAndCompareWithExpected(gLayoutTestController->expectedPixelHash());
562
563     // FIXME: call displayWebView here when we support --paint
564
565     done = true;
566     gtk_main_quit();
567 }
568
569 static void setDefaultsToConsistentStateValuesForTesting()
570 {
571     gdk_screen_set_resolution(gdk_screen_get_default(), 72.0);
572
573     resetDefaultsToConsistentValues();
574
575     /* Disable the default auth dialog for testing */
576     SoupSession* session = webkit_get_default_session();
577     soup_session_remove_feature_by_type(session, WEBKIT_TYPE_SOUP_AUTH_DIALOG);
578
579 #if PLATFORM(X11)
580     webkit_web_settings_add_extra_plugin_directory(webView, TEST_PLUGIN_DIR);
581 #endif
582
583     gchar* databaseDirectory = g_build_filename(g_get_user_data_dir(), "gtkwebkitdrt", "databases", NULL);
584     webkit_set_web_database_directory_path(databaseDirectory);
585     g_free(databaseDirectory);
586 }
587
588 static void sendPixelResultsEOF()
589 {
590     puts("#EOF");
591
592     fflush(stdout);
593     fflush(stderr);
594 }
595
596 static void runTest(const string& testPathOrURL)
597 {
598     ASSERT(!testPathOrURL.empty());
599
600     // Look for "'" as a separator between the path or URL, and the pixel dump hash that follows.
601     string testURL(testPathOrURL);
602     string expectedPixelHash;
603     size_t separatorPos = testURL.find("'");
604     if (separatorPos != string::npos) {
605         testURL = string(testPathOrURL, 0, separatorPos);
606         expectedPixelHash = string(testPathOrURL, separatorPos + 1);
607     }
608
609     // Convert the path into a full file URL if it does not look
610     // like an HTTP/S URL (doesn't start with http:// or https://).
611     if (testURL.find("http://") && testURL.find("https://")) {
612         GFile* testFile = g_file_new_for_path(testURL.c_str());
613         gchar* testURLCString = g_file_get_uri(testFile);
614         testURL = testURLCString;
615         g_free(testURLCString);
616         g_object_unref(testFile);
617     }
618
619     resetDefaultsToConsistentValues();
620
621     gLayoutTestController = LayoutTestController::create(testURL, expectedPixelHash);
622     topLoadingFrame = 0;
623     done = false;
624
625     gLayoutTestController->setIconDatabaseEnabled(false);
626
627     if (shouldLogFrameLoadDelegates(testURL))
628         gLayoutTestController->setDumpFrameLoadCallbacks(true);
629
630     if (shouldEnableDeveloperExtras(testURL)) {
631         gLayoutTestController->setDeveloperExtrasEnabled(true);
632         if (shouldOpenWebInspector(testURL))
633             gLayoutTestController->showWebInspector();
634     }
635
636     WorkQueue::shared()->clear();
637     WorkQueue::shared()->setFrozen(false);
638
639     bool isSVGW3CTest = (testURL.find("svg/W3C-SVG-1.1") != string::npos);
640     GtkAllocation size;
641     size.x = size.y = 0;
642     size.width = isSVGW3CTest ? 480 : LayoutTestController::maxViewWidth;
643     size.height = isSVGW3CTest ? 360 : LayoutTestController::maxViewHeight;
644     gtk_window_resize(GTK_WINDOW(window), size.width, size.height);
645     gtk_widget_size_allocate(container, &size);
646
647     if (prevTestBFItem)
648         g_object_unref(prevTestBFItem);
649     WebKitWebBackForwardList* bfList = webkit_web_view_get_back_forward_list(webView);
650     prevTestBFItem = webkit_web_back_forward_list_get_current_item(bfList);
651     if (prevTestBFItem)
652         g_object_ref(prevTestBFItem);
653
654     initializeFonts(testURL.c_str());
655
656     // Focus the web view before loading the test to avoid focusing problems
657     gtk_widget_grab_focus(GTK_WIDGET(webView));
658     webkit_web_view_open(webView, testURL.c_str());
659
660     gtk_main();
661
662     // If developer extras enabled Web Inspector may have been open by the test.
663     if (shouldEnableDeveloperExtras(testURL)) {
664         gLayoutTestController->closeWebInspector();
665         gLayoutTestController->setDeveloperExtrasEnabled(false);
666     }
667
668     // Also check if we still have opened webViews and free them.
669     if (gLayoutTestController->closeRemainingWindowsWhenComplete() || webViewList) {
670         while (webViewList) {
671             g_object_unref(WEBKIT_WEB_VIEW(webViewList->data));
672             webViewList = g_slist_next(webViewList);
673         }
674         g_slist_free(webViewList);
675         webViewList = 0;
676     }
677
678     // A blank load seems to be necessary to reset state after certain tests.
679     webkit_web_view_open(webView, "about:blank");
680
681     gLayoutTestController.clear();
682
683     // terminate the (possibly empty) pixels block after all the state reset
684     sendPixelResultsEOF();
685 }
686
687 void webViewLoadStarted(WebKitWebView* view, WebKitWebFrame* frame, void*)
688 {
689     // Make sure we only set this once per test.  If it gets cleared, and then set again, we might
690     // end up doing two dumps for one test.
691     if (!topLoadingFrame && !done)
692         topLoadingFrame = frame;
693 }
694
695 static gboolean processWork(void* data)
696 {
697     // if we finish all the commands, we're ready to dump state
698     if (WorkQueue::shared()->processWork() && !gLayoutTestController->waitToDump())
699         dump();
700
701     return FALSE;
702 }
703
704 static char* getFrameNameSuitableForTestResult(WebKitWebView* view, WebKitWebFrame* frame)
705 {
706     char* frameName = g_strdup(webkit_web_frame_get_name(frame));
707
708     if (frame == webkit_web_view_get_main_frame(view)) {
709         // This is a bit strange. Shouldn't web_frame_get_name return NULL?
710         if (frameName && (frameName[0] != '\0')) {
711             char* tmp = g_strdup_printf("main frame \"%s\"", frameName);
712             g_free(frameName);
713             frameName = tmp;
714         } else {
715             g_free(frameName);
716             frameName = g_strdup("main frame");
717         }
718     } else if (!frameName || (frameName[0] == '\0')) {
719         g_free(frameName);
720         frameName = g_strdup("frame (anonymous)");
721     } else {
722         char* tmp = g_strdup_printf("frame \"%s\"", frameName);
723         g_free(frameName);
724         frameName = tmp;
725     }
726
727     return frameName;
728 }
729
730 static void webViewLoadCommitted(WebKitWebView* view, WebKitWebFrame* frame, void*)
731 {
732     if (!done && gLayoutTestController->dumpFrameLoadCallbacks()) {
733         char* frameName = getFrameNameSuitableForTestResult(view, frame);
734         printf("%s - didCommitLoadForFrame\n", frameName);
735         g_free(frameName);
736     }
737 }
738
739
740 static void webViewLoadFinished(WebKitWebView* view, WebKitWebFrame* frame, void*)
741 {
742     if (!done && gLayoutTestController->dumpFrameLoadCallbacks()) {
743         char* frameName = getFrameNameSuitableForTestResult(view, frame);
744         printf("%s - didFinishLoadForFrame\n", frameName);
745         g_free(frameName);
746     }
747
748     if (frame != topLoadingFrame)
749         return;
750
751     topLoadingFrame = 0;
752     WorkQueue::shared()->setFrozen(true); // first complete load freezes the queue for the rest of this test
753     if (gLayoutTestController->waitToDump())
754         return;
755
756     if (WorkQueue::shared()->count())
757         g_timeout_add(0, processWork, 0);
758     else
759         dump();
760 }
761
762 static void webViewDocumentLoadFinished(WebKitWebView* view, WebKitWebFrame* frame, void*)
763 {
764     if (!done && gLayoutTestController->dumpFrameLoadCallbacks()) {
765         char* frameName = getFrameNameSuitableForTestResult(view, frame);
766         printf("%s - didFinishDocumentLoadForFrame\n", frameName);
767         g_free(frameName);
768     } else if (!done) {
769         guint pendingFrameUnloadEvents = webkit_web_frame_get_pending_unload_event_count(frame);
770         if (pendingFrameUnloadEvents) {
771             char* frameName = getFrameNameSuitableForTestResult(view, frame);
772             printf("%s - has %u onunload handler(s)\n", frameName, pendingFrameUnloadEvents);
773             g_free(frameName);
774         }
775     }
776 }
777
778 static void webViewOnloadEvent(WebKitWebView* view, WebKitWebFrame* frame, void*)
779 {
780     if (!done && gLayoutTestController->dumpFrameLoadCallbacks()) {
781         char* frameName = getFrameNameSuitableForTestResult(view, frame);
782         printf("%s - didHandleOnloadEventsForFrame\n", frameName);
783         g_free(frameName);
784     }
785 }
786
787 static void webViewWindowObjectCleared(WebKitWebView* view, WebKitWebFrame* frame, JSGlobalContextRef context, JSObjectRef windowObject, gpointer data)
788 {
789     JSValueRef exception = 0;
790     ASSERT(gLayoutTestController);
791
792     gLayoutTestController->makeWindowObject(context, windowObject, &exception);
793     ASSERT(!exception);
794
795     gcController->makeWindowObject(context, windowObject, &exception);
796     ASSERT(!exception);
797
798     axController->makeWindowObject(context, windowObject, &exception);
799     ASSERT(!exception);
800
801     JSStringRef eventSenderStr = JSStringCreateWithUTF8CString("eventSender");
802     JSValueRef eventSender = makeEventSender(context, !webkit_web_frame_get_parent(frame));
803     JSObjectSetProperty(context, windowObject, eventSenderStr, eventSender, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, 0);
804     JSStringRelease(eventSenderStr);
805 }
806
807 static gboolean webViewConsoleMessage(WebKitWebView* view, const gchar* message, unsigned int line, const gchar* sourceId, gpointer data)
808 {
809     gchar* testMessage = 0;
810     const gchar* uriScheme;
811
812     // Tests expect only the filename part of local URIs
813     uriScheme = g_strstr_len(message, -1, "file://");
814     if (uriScheme) {
815         GString* tempString = g_string_sized_new(strlen(message));
816         gchar* filename = g_strrstr(uriScheme, G_DIR_SEPARATOR_S);
817
818         if (filename) {
819             filename += strlen(G_DIR_SEPARATOR_S);
820             tempString = g_string_append_len(tempString, message, (uriScheme - message));
821             tempString = g_string_append_len(tempString, filename, strlen(filename));
822             testMessage = g_string_free(tempString, FALSE);
823         }
824     }
825
826     fprintf(stdout, "CONSOLE MESSAGE: line %d: %s\n", line, testMessage ? testMessage : message);
827     g_free(testMessage);
828
829     return TRUE;
830 }
831
832
833 static gboolean webViewScriptAlert(WebKitWebView* view, WebKitWebFrame* frame, const gchar* message, gpointer data)
834 {
835     fprintf(stdout, "ALERT: %s\n", message);
836     return TRUE;
837 }
838
839 static gboolean webViewScriptPrompt(WebKitWebView* webView, WebKitWebFrame* frame, const gchar* message, const gchar* defaultValue, gchar** value, gpointer data)
840 {
841     fprintf(stdout, "PROMPT: %s, default text: %s\n", message, defaultValue);
842     *value = g_strdup(defaultValue);
843     return TRUE;
844 }
845
846 static gboolean webViewScriptConfirm(WebKitWebView* view, WebKitWebFrame* frame, const gchar* message, gboolean* didConfirm, gpointer data)
847 {
848     fprintf(stdout, "CONFIRM: %s\n", message);
849     *didConfirm = TRUE;
850     return TRUE;
851 }
852
853 static void webViewTitleChanged(WebKitWebView* view, WebKitWebFrame* frame, const gchar* title, gpointer data)
854 {
855     if (gLayoutTestController->dumpTitleChanges() && !done)
856         printf("TITLE CHANGED: %s\n", title ? title : "");
857 }
858
859 static bool webViewNavigationPolicyDecisionRequested(WebKitWebView* view, WebKitWebFrame* frame,
860                                                      WebKitNetworkRequest* request,
861                                                      WebKitWebNavigationAction* navAction,
862                                                      WebKitWebPolicyDecision* policyDecision)
863 {
864     // Use the default handler if we're not waiting for policy,
865     // i.e., LayoutTestController::waitForPolicyDelegate
866     if (!waitForPolicy)
867         return FALSE;
868
869     gchar* typeDescription;
870     WebKitWebNavigationReason reason;
871     g_object_get(G_OBJECT(navAction), "reason", &reason, NULL);
872
873     switch(reason) {
874         case WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED:
875             typeDescription = g_strdup("link clicked");
876             break;
877         case WEBKIT_WEB_NAVIGATION_REASON_FORM_SUBMITTED:
878             typeDescription = g_strdup("form submitted");
879             break;
880         case WEBKIT_WEB_NAVIGATION_REASON_BACK_FORWARD:
881             typeDescription = g_strdup("back/forward");
882             break;
883         case WEBKIT_WEB_NAVIGATION_REASON_RELOAD:
884             typeDescription = g_strdup("reload");
885             break;
886         case WEBKIT_WEB_NAVIGATION_REASON_FORM_RESUBMITTED:
887             typeDescription = g_strdup("form resubmitted");
888             break;
889         case WEBKIT_WEB_NAVIGATION_REASON_OTHER:
890             typeDescription = g_strdup("other");
891             break;
892         default:
893             typeDescription = g_strdup("illegal value");
894     }
895
896     printf("Policy delegate: attempt to load %s with navigation type '%s'\n", webkit_network_request_get_uri(request), typeDescription);
897     g_free(typeDescription);
898
899     webkit_web_policy_decision_ignore(policyDecision);
900     gLayoutTestController->notifyDone();
901
902     return TRUE;
903 }
904
905 static void webViewStatusBarTextChanged(WebKitWebView* view, const gchar* message, gpointer data)
906 {
907     // Are we doing anything wrong? One test that does not call
908     // dumpStatusCallbacks gets true here
909     if (gLayoutTestController->dumpStatusCallbacks()) {
910         if (message && strcmp(message, ""))
911             printf("UI DELEGATE STATUS CALLBACK: setStatusText:%s\n", message);
912     }
913 }
914
915 static gboolean webViewClose(WebKitWebView* view)
916 {
917     ASSERT(view);
918
919     webViewList = g_slist_remove(webViewList, view);
920     g_object_unref(view);
921
922     return TRUE;
923 }
924
925 static void databaseQuotaExceeded(WebKitWebView* view, WebKitWebFrame* frame, WebKitWebDatabase *database)
926 {
927     ASSERT(view);
928     ASSERT(frame);
929     ASSERT(database);
930
931     WebKitSecurityOrigin* origin = webkit_web_database_get_security_origin(database);
932     if (gLayoutTestController->dumpDatabaseCallbacks()) {
933         printf("UI DELEGATE DATABASE CALLBACK: exceededDatabaseQuotaForSecurityOrigin:{%s, %s, %i} database:%s\n",
934             webkit_security_origin_get_protocol(origin),
935             webkit_security_origin_get_host(origin),
936             webkit_security_origin_get_port(origin),
937             webkit_web_database_get_name(database));
938     }
939     webkit_security_origin_set_web_database_quota(origin, 5 * 1024 * 1024);
940 }
941
942 static bool
943 geolocationPolicyDecisionRequested(WebKitWebView*, WebKitWebFrame*, WebKitGeolocationPolicyDecision* decision)
944 {
945     if (!gLayoutTestController->isGeolocationPermissionSet())
946         return FALSE;
947     if (gLayoutTestController->geolocationPermission())
948         webkit_geolocation_policy_allow(decision);
949     else
950         webkit_geolocation_policy_deny(decision);
951
952     return TRUE;
953 }
954
955
956 static WebKitWebView* webViewCreate(WebKitWebView*, WebKitWebFrame*);
957
958 static gboolean webInspectorShowWindow(WebKitWebInspector*, gpointer data)
959 {
960     gtk_window_set_default_size(GTK_WINDOW(webInspectorWindow), 800, 600);
961     gtk_widget_show_all(webInspectorWindow);
962     return TRUE;
963 }
964
965 static gboolean webInspectorCloseWindow(WebKitWebInspector*, gpointer data)
966 {
967     gtk_widget_destroy(webInspectorWindow);
968     webInspectorWindow = 0;
969     return TRUE;
970 }
971
972 static WebKitWebView* webInspectorInspectWebView(WebKitWebInspector*, gpointer data)
973 {
974     webInspectorWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
975
976     GtkWidget* webView = webkit_web_view_new();
977     gtk_container_add(GTK_CONTAINER(webInspectorWindow),
978                       webView);
979
980     return WEBKIT_WEB_VIEW(webView);
981 }
982
983 static void webViewLoadStatusNotified(WebKitWebView* view, gpointer user_data)
984 {
985     WebKitLoadStatus loadStatus = webkit_web_view_get_load_status(view);
986
987     if (gLayoutTestController->dumpFrameLoadCallbacks()) {
988         if (loadStatus == WEBKIT_LOAD_PROVISIONAL) {
989             char* frameName = getFrameNameSuitableForTestResult(view, mainFrame);
990             printf("%s - didStartProvisionalLoadForFrame\n", frameName);
991             g_free(frameName);
992         }
993     }
994 }
995
996 static WebKitWebView* createWebView()
997 {
998     WebKitWebView* view = WEBKIT_WEB_VIEW(webkit_web_view_new());
999
1000     DumpRenderTreeSupportGtk::setDumpRenderTreeModeEnabled(true);
1001
1002     // From bug 11756: Use a frame group name for all WebViews created by
1003     // DumpRenderTree to allow testing of cross-page frame lookup.
1004     webkit_web_view_set_group_name(view, "org.webkit.gtk.DumpRenderTree");
1005
1006     g_object_connect(G_OBJECT(view),
1007                      "signal::load-started", webViewLoadStarted, 0,
1008                      "signal::load-finished", webViewLoadFinished, 0,
1009                      "signal::load-committed", webViewLoadCommitted, 0,
1010                      "signal::window-object-cleared", webViewWindowObjectCleared, 0,
1011                      "signal::console-message", webViewConsoleMessage, 0,
1012                      "signal::script-alert", webViewScriptAlert, 0,
1013                      "signal::script-prompt", webViewScriptPrompt, 0,
1014                      "signal::script-confirm", webViewScriptConfirm, 0,
1015                      "signal::title-changed", webViewTitleChanged, 0,
1016                      "signal::navigation-policy-decision-requested", webViewNavigationPolicyDecisionRequested, 0,
1017                      "signal::status-bar-text-changed", webViewStatusBarTextChanged, 0,
1018                      "signal::create-web-view", webViewCreate, 0,
1019                      "signal::close-web-view", webViewClose, 0,
1020                      "signal::database-quota-exceeded", databaseQuotaExceeded, 0,
1021                      "signal::document-load-finished", webViewDocumentLoadFinished, 0,
1022                      "signal::geolocation-policy-decision-requested", geolocationPolicyDecisionRequested, 0,
1023                      "signal::onload-event", webViewOnloadEvent, 0,
1024                      "signal::drag-begin", dragBeginCallback, 0,
1025                      "signal::drag-end", dragEndCallback, 0,
1026                      "signal::drag-failed", dragFailedCallback, 0,
1027
1028                      NULL);
1029
1030     g_signal_connect(view,
1031                      "notify::load-status", G_CALLBACK(webViewLoadStatusNotified),
1032                      NULL);
1033
1034     WebKitWebInspector* inspector = webkit_web_view_get_inspector(view);
1035     g_object_connect(G_OBJECT(inspector),
1036                      "signal::inspect-web-view", webInspectorInspectWebView, 0,
1037                      "signal::show-window", webInspectorShowWindow, 0,
1038                      "signal::close-window", webInspectorCloseWindow, 0,
1039                      NULL);
1040
1041     if (webView) {
1042         WebKitWebSettings* settings = webkit_web_view_get_settings(webView);
1043         webkit_web_view_set_settings(view, settings);
1044     }
1045
1046     return view;
1047 }
1048
1049 static WebKitWebView* webViewCreate(WebKitWebView* view, WebKitWebFrame* frame)
1050 {
1051     if (!gLayoutTestController->canOpenWindows())
1052         return 0;
1053
1054     // Make sure that waitUntilDone has been called.
1055     ASSERT(gLayoutTestController->waitToDump());
1056
1057     WebKitWebView* newWebView = createWebView();
1058     g_object_ref_sink(G_OBJECT(newWebView));
1059     webViewList = g_slist_prepend(webViewList, newWebView);
1060     return newWebView;
1061 }
1062
1063 static void logHandler(const gchar* domain, GLogLevelFlags level, const gchar* message, gpointer data)
1064 {
1065     if (level < G_LOG_LEVEL_DEBUG)
1066         fprintf(stderr, "%s\n", message);
1067 }
1068
1069 int main(int argc, char* argv[])
1070 {
1071     g_thread_init(NULL);
1072     gtk_init(&argc, &argv);
1073
1074     // Some plugins might try to use the GLib logger for printing debug
1075     // messages. This will cause tests to fail because of unexpected output.
1076     // We squelch all debug messages sent to the logger.
1077     g_log_set_default_handler(logHandler, 0);
1078
1079     initializeGlobalsFromCommandLineOptions(argc, argv);
1080     initializeFonts();
1081
1082     window = gtk_window_new(GTK_WINDOW_POPUP);
1083     container = GTK_WIDGET(gtk_scrolled_window_new(NULL, NULL));
1084     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(container), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1085     gtk_container_add(GTK_CONTAINER(window), container);
1086     gtk_widget_show_all(window);
1087
1088     webView = createWebView();
1089     gtk_container_add(GTK_CONTAINER(container), GTK_WIDGET(webView));
1090     gtk_widget_realize(GTK_WIDGET(webView));
1091     gtk_widget_show_all(container);
1092     gtk_widget_grab_focus(GTK_WIDGET(webView));
1093     mainFrame = webkit_web_view_get_main_frame(webView);
1094
1095     setDefaultsToConsistentStateValuesForTesting();
1096
1097     gcController = new GCController();
1098     axController = new AccessibilityController();
1099
1100     if (useLongRunningServerMode(argc, argv)) {
1101         printSeparators = true;
1102         runTestingServerLoop();
1103     } else {
1104         printSeparators = (optind < argc-1 || (dumpPixels && dumpTree));
1105         for (int i = optind; i != argc; ++i)
1106             runTest(argv[i]);
1107     }
1108
1109     delete gcController;
1110     gcController = 0;
1111
1112     delete axController;
1113     axController = 0;
1114
1115     gtk_widget_destroy(window);
1116
1117     return 0;
1118 }