2010-05-06 Anders Carlsson <andersca@apple.com>
[WebKit.git] / WebKitTools / DumpRenderTree / mac / DumpRenderTree.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  *           (C) 2007 Graham Dennis (graham.dennis@gmail.com)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #import "config.h"
31 #import "DumpRenderTree.h"
32
33 #import "AccessibilityController.h"
34 #import "CheckedMalloc.h"
35 #import "DumpRenderTreeDraggingInfo.h"
36 #import "DumpRenderTreePasteboard.h"
37 #import "DumpRenderTreeWindow.h"
38 #import "EditingDelegate.h"
39 #import "EventSendingController.h"
40 #import "FrameLoadDelegate.h"
41 #import "HistoryDelegate.h"
42 #import "JavaScriptThreading.h"
43 #import "LayoutTestController.h"
44 #import "NavigationController.h"
45 #import "ObjCPlugin.h"
46 #import "ObjCPluginFunction.h"
47 #import "PixelDumpSupport.h"
48 #import "PolicyDelegate.h"
49 #import "ResourceLoadDelegate.h"
50 #import "UIDelegate.h"
51 #import "WorkQueue.h"
52 #import "WorkQueueItem.h"
53 #import <Carbon/Carbon.h>
54 #import <CoreFoundation/CoreFoundation.h>
55 #import <WebKit/DOMElement.h>
56 #import <WebKit/DOMExtensions.h>
57 #import <WebKit/DOMRange.h>
58 #import <WebKit/WebBackForwardList.h>
59 #import <WebKit/WebCache.h>
60 #import <WebKit/WebCoreStatistics.h>
61 #import <WebKit/WebDataSourcePrivate.h>
62 #import <WebKit/WebDatabaseManagerPrivate.h>
63 #import <WebKit/WebDocumentPrivate.h>
64 #import <WebKit/WebEditingDelegate.h>
65 #import <WebKit/WebFrameView.h>
66 #import <WebKit/WebHTMLRepresentationInternal.h>
67 #import <WebKit/WebHistory.h>
68 #import <WebKit/WebHistoryItemPrivate.h>
69 #import <WebKit/WebInspector.h>
70 #import <WebKit/WebKitNSStringExtras.h>
71 #import <WebKit/WebPluginDatabase.h>
72 #import <WebKit/WebPreferences.h>
73 #import <WebKit/WebPreferencesPrivate.h>
74 #import <WebKit/WebPreferenceKeysPrivate.h>
75 #import <WebKit/WebResourceLoadDelegate.h>
76 #import <WebKit/WebTypesInternal.h>
77 #import <WebKit/WebViewPrivate.h>
78 #import <getopt.h>
79 #import <objc/objc-runtime.h>
80 #import <wtf/Assertions.h>
81 #import <wtf/RetainPtr.h>
82 #import <wtf/Threading.h>
83 #import <wtf/OwnPtr.h>
84
85 extern "C" {
86 #import <mach-o/getsect.h>
87 }
88
89 using namespace std;
90
91 @interface DumpRenderTreeApplication : NSApplication
92 @end
93
94 @interface DumpRenderTreeEvent : NSEvent
95 @end
96
97 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
98 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
99 @end
100
101 static void runTest(const string& testPathOrURL);
102
103 // Deciding when it's OK to dump out the state is a bit tricky.  All these must be true:
104 // - There is no load in progress
105 // - There is no work queued up (see workQueue var, below)
106 // - waitToDump==NO.  This means either waitUntilDone was never called, or it was called
107 //       and notifyDone was called subsequently.
108 // Note that the call to notifyDone and the end of the load can happen in either order.
109
110 volatile bool done;
111
112 NavigationController* gNavigationController = 0;
113 LayoutTestController* gLayoutTestController = 0;
114
115 WebFrame *mainFrame = 0;
116 // This is the topmost frame that is loading, during a given load, or nil when no load is 
117 // in progress.  Usually this is the same as the main frame, but not always.  In the case
118 // where a frameset is loaded, and then new content is loaded into one of the child frames,
119 // that child frame is the "topmost frame that is loading".
120 WebFrame *topLoadingFrame = nil;     // !nil iff a load is in progress
121
122
123 CFMutableSetRef disallowedURLs = 0;
124 CFRunLoopTimerRef waitToDumpWatchdog = 0;
125
126 // Delegates
127 static FrameLoadDelegate *frameLoadDelegate;
128 static UIDelegate *uiDelegate;
129 static EditingDelegate *editingDelegate;
130 static ResourceLoadDelegate *resourceLoadDelegate;
131 static HistoryDelegate *historyDelegate;
132 PolicyDelegate *policyDelegate;
133
134 static int dumpPixels;
135 static int threaded;
136 static int dumpTree = YES;
137 static int forceComplexText;
138 static BOOL printSeparators;
139 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
140
141 static WebHistoryItem *prevTestBFItem = nil;  // current b/f item at the end of the previous test
142
143 #if __OBJC2__
144 static void swizzleAllMethods(Class imposter, Class original)
145 {
146     unsigned int imposterMethodCount;
147     Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
148
149     unsigned int originalMethodCount;
150     Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
151
152     for (unsigned int i = 0; i < imposterMethodCount; i++) {
153         SEL imposterMethodName = method_getName(imposterMethods[i]);
154
155         // Attempt to add the method to the original class.  If it fails, the method already exists and we should
156         // instead exchange the implementations.
157         if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
158             continue;
159
160         unsigned int j = 0;
161         for (; j < originalMethodCount; j++) {
162             SEL originalMethodName = method_getName(originalMethods[j]);
163             if (sel_isEqual(imposterMethodName, originalMethodName))
164                 break;
165         }
166
167         // If class_addMethod failed above then the method must exist on the original class.
168         ASSERT(j < originalMethodCount);
169         method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
170     }
171
172     free(imposterMethods);
173     free(originalMethods);
174 }
175 #endif
176
177 static void poseAsClass(const char* imposter, const char* original)
178 {
179     Class imposterClass = objc_getClass(imposter);
180     Class originalClass = objc_getClass(original);
181
182 #if !__OBJC2__
183     class_poseAs(imposterClass, originalClass);
184 #else
185
186     // Swizzle instance methods
187     swizzleAllMethods(imposterClass, originalClass);
188     // and then class methods
189     swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
190 #endif
191 }
192
193 void setPersistentUserStyleSheetLocation(CFStringRef url)
194 {
195     persistentUserStyleSheetLocation = url;
196 }
197
198 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
199 {
200     static char* const ignoreSet[] = {
201         // Keeping this infrastructure around in case we ever need it again.
202     };
203     static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
204     
205     for (int i = 0; i < ignoreSetCount; i++) {
206         // FIXME: ignore case
207         string curIgnore(ignoreSet[i]);
208         // Match at the end of the URLString
209         if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
210             return true;
211     }
212     return false;
213 }
214
215 static void activateFonts()
216 {
217 #if defined(BUILDING_ON_LEOPARD) || defined(BUILDING_ON_TIGER)
218     static const char* fontSectionNames[] = {
219         "Ahem",
220         "WeightWatcher100",
221         "WeightWatcher200",
222         "WeightWatcher300",
223         "WeightWatcher400",
224         "WeightWatcher500",
225         "WeightWatcher600",
226         "WeightWatcher700",
227         "WeightWatcher800",
228         "WeightWatcher900",
229         0
230     };
231
232     for (unsigned i = 0; fontSectionNames[i]; ++i) {
233         unsigned long fontDataLength;
234         char* fontData = getsectdata("__DATA", fontSectionNames[i], &fontDataLength);
235         if (!fontData) {
236             fprintf(stderr, "Failed to locate the %s font.\n", fontSectionNames[i]);
237             exit(1);
238         }
239
240         ATSFontContainerRef fontContainer;
241         OSStatus status = ATSFontActivateFromMemory(fontData, fontDataLength, kATSFontContextLocal, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &fontContainer);
242
243         if (status != noErr) {
244             fprintf(stderr, "Failed to activate the %s font.\n", fontSectionNames[i]);
245             exit(1);
246         }
247     }
248 #else
249
250     // Work around <rdar://problem/6698023> by activating fonts from disk
251     // FIXME: This code can be removed once <rdar://problem/6698023> is addressed.
252
253     static const char* fontFileNames[] = {
254         "AHEM____.TTF",
255         "ColorBits.ttf",
256         "WebKitWeightWatcher100.ttf",
257         "WebKitWeightWatcher200.ttf",
258         "WebKitWeightWatcher300.ttf",
259         "WebKitWeightWatcher400.ttf",
260         "WebKitWeightWatcher500.ttf",
261         "WebKitWeightWatcher600.ttf",
262         "WebKitWeightWatcher700.ttf",
263         "WebKitWeightWatcher800.ttf",
264         "WebKitWeightWatcher900.ttf",
265         0
266     };
267
268     NSMutableArray *fontURLs = [NSMutableArray array];
269     NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
270     for (unsigned i = 0; fontFileNames[i]; ++i) {
271         NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]]];
272         [fontURLs addObject:[fontURL absoluteURL]];
273     }
274
275     CFArrayRef errors = 0;
276     if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
277         NSLog(@"Failed to activate fonts: %@", errors);
278         CFRelease(errors);
279         exit(1);
280     }
281 #endif
282 }
283
284 WebView *createWebViewAndOffscreenWindow()
285 {
286     NSRect rect = NSMakeRect(0, 0, LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight);
287     WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
288         
289     [webView setUIDelegate:uiDelegate];
290     [webView setFrameLoadDelegate:frameLoadDelegate];
291     [webView setEditingDelegate:editingDelegate];
292     [webView setResourceLoadDelegate:resourceLoadDelegate];
293
294     // Register the same schemes that Safari does
295     [WebView registerURLSchemeAsLocal:@"feed"];
296     [WebView registerURLSchemeAsLocal:@"feeds"];
297     [WebView registerURLSchemeAsLocal:@"feedsearch"];
298     
299     [webView setContinuousSpellCheckingEnabled:YES];
300     
301     // To make things like certain NSViews, dragging, and plug-ins work, put the WebView a window, but put it off-screen so you don't see it.
302     // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
303     NSRect windowRect = NSOffsetRect(rect, -10000, [[[NSScreen screens] objectAtIndex:0] frame].size.height - rect.size.height + 10000);
304     DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
305
306 #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
307     [window setColorSpace:[[NSScreen mainScreen] colorSpace]];
308 #endif
309
310     [[window contentView] addSubview:webView];
311     [window orderBack:nil];
312     [window setAutodisplay:NO];
313
314     [window startListeningForAcceleratedCompositingChanges];
315     
316     // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
317     // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
318     NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
319     [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
320         
321     return webView;
322 }
323
324 void testStringByEvaluatingJavaScriptFromString()
325 {
326     // maps expected result <= JavaScript expression
327     NSDictionary *expressions = [NSDictionary dictionaryWithObjectsAndKeys:
328         @"0", @"0", 
329         @"0", @"'0'", 
330         @"", @"",
331         @"", @"''", 
332         @"", @"new String()", 
333         @"", @"new String('0')", 
334         @"", @"throw 1", 
335         @"", @"{ }", 
336         @"", @"[ ]", 
337         @"", @"//", 
338         @"", @"a.b.c", 
339         @"", @"(function() { throw 'error'; })()", 
340         @"", @"null",
341         @"", @"undefined",
342         @"true", @"true",
343         @"false", @"false",
344         nil
345     ];
346
347     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
348     WebView *webView = [[WebView alloc] initWithFrame:NSZeroRect frameName:@"" groupName:@""];
349
350     NSEnumerator *enumerator = [expressions keyEnumerator];
351     id expression;
352     while ((expression = [enumerator nextObject])) {
353         NSString *expectedResult = [expressions objectForKey:expression];
354         NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
355         assert([result isEqualToString:expectedResult]);
356     }
357
358     [webView close];
359     [webView release];
360     [pool release];
361 }
362
363 static NSString *libraryPathForDumpRenderTree()
364 {
365     //FIXME: This may not be sufficient to prevent interactions/crashes
366     //when running more than one copy of DumpRenderTree.
367     //See https://bugs.webkit.org/show_bug.cgi?id=10906
368     char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
369     if (dumpRenderTreeTemp)
370         return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
371     else
372         return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
373 }
374
375 // Called before each test.
376 static void resetDefaultsToConsistentValues()
377 {
378     // Give some clear to undocumented defaults values
379     static const int NoFontSmoothing = 0;
380     static const int BlueTintedAppearance = 1;
381
382     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
383     [defaults setInteger:4 forKey:@"AppleAntiAliasingThreshold"]; // smallest font size to CG should perform antialiasing on
384     [defaults setInteger:NoFontSmoothing forKey:@"AppleFontSmoothing"];
385     [defaults setInteger:BlueTintedAppearance forKey:@"AppleAquaColorVariant"];
386     [defaults setObject:@"0.709800 0.835300 1.000000" forKey:@"AppleHighlightColor"];
387     [defaults setObject:@"0.500000 0.500000 0.500000" forKey:@"AppleOtherHighlightColor"];
388     [defaults setObject:[NSArray arrayWithObject:@"en"] forKey:@"AppleLanguages"];
389     [defaults setBool:YES forKey:WebKitEnableFullDocumentTeardownPreferenceKey];
390
391     // Scrollbars are drawn either using AppKit (which uses NSUserDefaults) or using HIToolbox (which uses CFPreferences / kCFPreferencesAnyApplication / kCFPreferencesCurrentUser / kCFPreferencesAnyHost)
392     [defaults setObject:@"DoubleMax" forKey:@"AppleScrollBarVariant"];
393     RetainPtr<CFTypeRef> initialValue = CFPreferencesCopyValue(CFSTR("AppleScrollBarVariant"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
394     CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), CFSTR("DoubleMax"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
395 #ifndef __LP64__
396     // See <rdar://problem/6347388>.
397     ThemeScrollBarArrowStyle style;
398     GetThemeScrollBarArrowStyle(&style); // Force HIToolbox to read from CFPreferences
399 #endif
400     if (initialValue)
401         CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), initialValue.get(), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
402
403     NSString *path = libraryPathForDumpRenderTree();
404     [defaults setObject:[path stringByAppendingPathComponent:@"Databases"] forKey:WebDatabaseDirectoryDefaultsKey];
405     [defaults setObject:[path stringByAppendingPathComponent:@"LocalCache"] forKey:WebKitLocalCacheDefaultsKey];
406
407     WebPreferences *preferences = [WebPreferences standardPreferences];
408
409     [preferences setAllowUniversalAccessFromFileURLs:YES];
410     [preferences setAllowFileAccessFromFileURLs:YES];
411     [preferences setStandardFontFamily:@"Times"];
412     [preferences setFixedFontFamily:@"Courier"];
413     [preferences setSerifFontFamily:@"Times"];
414     [preferences setSansSerifFontFamily:@"Helvetica"];
415     [preferences setCursiveFontFamily:@"Apple Chancery"];
416     [preferences setFantasyFontFamily:@"Papyrus"];
417     [preferences setDefaultFontSize:16];
418     [preferences setDefaultFixedFontSize:13];
419     [preferences setMinimumFontSize:1];
420     [preferences setJavaEnabled:NO];
421     [preferences setJavaScriptEnabled:YES];
422     [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
423     [preferences setTabsToLinks:NO];
424     [preferences setDOMPasteAllowed:YES];
425     [preferences setShouldPrintBackgrounds:YES];
426     [preferences setCacheModel:WebCacheModelDocumentBrowser];
427     [preferences setXSSAuditorEnabled:NO];
428     [preferences setExperimentalNotificationsEnabled:NO];
429     [preferences setPluginAllowedRunTime:1];
430     [preferences setPlugInsEnabled:YES];
431
432     [preferences setPrivateBrowsingEnabled:NO];
433     [preferences setAuthorAndUserStylesEnabled:YES];
434     [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
435     [preferences setJavaScriptCanAccessClipboard:YES];
436     [preferences setOfflineWebApplicationCacheEnabled:YES];
437     [preferences setDeveloperExtrasEnabled:NO];
438     [preferences setLoadsImagesAutomatically:YES];
439     [preferences setFrameFlatteningEnabled:NO];
440     if (persistentUserStyleSheetLocation) {
441         [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
442         [preferences setUserStyleSheetEnabled:YES];
443     } else
444         [preferences setUserStyleSheetEnabled:NO];
445
446     // The back/forward cache is causing problems due to layouts during transition from one page to another.
447     // So, turn it off for now, but we might want to turn it back on some day.
448     [preferences setUsesPageCache:NO];
449     [preferences setAcceleratedCompositingEnabled:YES];
450     [preferences setWebGLEnabled:NO];
451
452     [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
453
454     setlocale(LC_ALL, "");
455 }
456
457 // Called once on DumpRenderTree startup.
458 static void setDefaultsToConsistentValuesForTesting()
459 {
460     resetDefaultsToConsistentValues();
461
462     NSString *path = libraryPathForDumpRenderTree();
463     NSURLCache *sharedCache =
464         [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
465                                       diskCapacity:0
466                                           diskPath:[path stringByAppendingPathComponent:@"URLCache"]];
467     [NSURLCache setSharedURLCache:sharedCache];
468     [sharedCache release];
469
470 }
471
472 static void* runThread(void* arg)
473 {
474     static ThreadIdentifier previousId = 0;
475     ThreadIdentifier currentId = currentThread();
476     // Verify 2 successive threads do not get the same Id.
477     ASSERT(previousId != currentId);
478     previousId = currentId;
479     return 0;
480 }
481
482 static void testThreadIdentifierMap()
483 {
484     // Imitate 'foreign' threads that are not created by WTF.
485     pthread_t pthread;
486     pthread_create(&pthread, 0, &runThread, 0);
487     pthread_join(pthread, 0);
488
489     pthread_create(&pthread, 0, &runThread, 0);
490     pthread_join(pthread, 0);
491
492     // Now create another thread using WTF. On OSX, it will have the same pthread handle
493     // but should get a different ThreadIdentifier.
494     createThread(runThread, 0, "DumpRenderTree: test");
495 }
496
497 static void crashHandler(int sig)
498 {
499     char *signalName = strsignal(sig);
500     write(STDERR_FILENO, signalName, strlen(signalName));
501     write(STDERR_FILENO, "\n", 1);
502     restoreMainDisplayColorProfile(0);
503     exit(128 + sig);
504 }
505
506 static void installSignalHandlers()
507 {
508     signal(SIGILL, crashHandler);    /* 4:   illegal instruction (not reset when caught) */
509     signal(SIGTRAP, crashHandler);   /* 5:   trace trap (not reset when caught) */
510     signal(SIGEMT, crashHandler);    /* 7:   EMT instruction */
511     signal(SIGFPE, crashHandler);    /* 8:   floating point exception */
512     signal(SIGBUS, crashHandler);    /* 10:  bus error */
513     signal(SIGSEGV, crashHandler);   /* 11:  segmentation violation */
514     signal(SIGSYS, crashHandler);    /* 12:  bad argument to system call */
515     signal(SIGPIPE, crashHandler);   /* 13:  write on a pipe with no reader */
516     signal(SIGXCPU, crashHandler);   /* 24:  exceeded CPU time limit */
517     signal(SIGXFSZ, crashHandler);   /* 25:  exceeded file size limit */
518 }
519
520 static void allocateGlobalControllers()
521 {
522     // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
523     gNavigationController = [[NavigationController alloc] init];
524     frameLoadDelegate = [[FrameLoadDelegate alloc] init];
525     uiDelegate = [[UIDelegate alloc] init];
526     editingDelegate = [[EditingDelegate alloc] init];
527     resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
528     policyDelegate = [[PolicyDelegate alloc] init];
529     historyDelegate = [[HistoryDelegate alloc] init];
530 }
531
532 // ObjC++ doens't seem to let me pass NSObject*& sadly.
533 static inline void releaseAndZero(NSObject** object)
534 {
535     [*object release];
536     *object = nil;
537 }
538
539 static void releaseGlobalControllers()
540 {
541     releaseAndZero(&gNavigationController);
542     releaseAndZero(&frameLoadDelegate);
543     releaseAndZero(&editingDelegate);
544     releaseAndZero(&resourceLoadDelegate);
545     releaseAndZero(&uiDelegate);
546     releaseAndZero(&policyDelegate);
547 }
548
549 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
550 {
551     struct option options[] = {
552         {"notree", no_argument, &dumpTree, NO},
553         {"pixel-tests", no_argument, &dumpPixels, YES},
554         {"tree", no_argument, &dumpTree, YES},
555         {"threaded", no_argument, &threaded, YES},
556         {"complex-text", no_argument, &forceComplexText, YES},
557         {NULL, 0, NULL, 0}
558     };
559     
560     int option;
561     while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
562         switch (option) {
563             case '?':   // unknown or ambiguous option
564             case ':':   // missing argument
565                 exit(1);
566                 break;
567         }
568     }
569 }
570
571 static void addTestPluginsToPluginSearchPath(const char* executablePath)
572 {
573     NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
574     [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
575     [[WebPluginDatabase sharedDatabase] refresh];
576 }
577
578 static bool useLongRunningServerMode(int argc, const char *argv[])
579 {
580     // This assumes you've already called getopt_long
581     return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
582 }
583
584 static void runTestingServerLoop()
585 {
586     // When DumpRenderTree run in server mode, we just wait around for file names
587     // to be passed to us and read each in turn, passing the results back to the client
588     char filenameBuffer[2048];
589     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
590         char *newLineCharacter = strchr(filenameBuffer, '\n');
591         if (newLineCharacter)
592             *newLineCharacter = '\0';
593
594         if (strlen(filenameBuffer) == 0)
595             continue;
596
597         runTest(filenameBuffer);
598     }
599 }
600
601 static void prepareConsistentTestingEnvironment()
602 {
603     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
604     poseAsClass("DumpRenderTreeEvent", "NSEvent");
605
606     setDefaultsToConsistentValuesForTesting();
607     activateFonts();
608     
609     if (dumpPixels)
610         setupMainDisplayColorProfile();
611     allocateGlobalControllers();
612     
613     makeLargeMallocFailSilently();
614 }
615
616 void dumpRenderTree(int argc, const char *argv[])
617 {
618     initializeGlobalsFromCommandLineOptions(argc, argv);
619     prepareConsistentTestingEnvironment();
620     addTestPluginsToPluginSearchPath(argv[0]);
621     if (dumpPixels)
622         installSignalHandlers();
623
624     if (forceComplexText)
625         [WebView _setAlwaysUsesComplexTextCodePath:YES];
626
627     WebView *webView = createWebViewAndOffscreenWindow();
628     mainFrame = [webView mainFrame];
629
630     [[NSURLCache sharedURLCache] removeAllCachedResponses];
631     [WebCache empty];
632
633     // <http://webkit.org/b/31200> In order to prevent extra frame load delegate logging being generated if the first test to use SSL
634     // is set to log frame load delegate calls we ignore SSL certificate errors on localhost and 127.0.0.1.
635 #if BUILDING_ON_TIGER
636     // Initialize internal NSURLRequest data for setAllowsAnyHTTPSCertificate:forHost: to work properly.
637     [[[[NSURLRequest alloc] init] autorelease] HTTPMethod];
638 #endif
639     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
640     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
641
642     // <rdar://problem/5222911>
643     testStringByEvaluatingJavaScriptFromString();
644
645     // http://webkit.org/b/32689
646     testThreadIdentifierMap();
647
648     if (threaded)
649         startJavaScriptThreads();
650
651     if (useLongRunningServerMode(argc, argv)) {
652         printSeparators = YES;
653         runTestingServerLoop();
654     } else {
655         printSeparators = (optind < argc-1 || (dumpPixels && dumpTree));
656         for (int i = optind; i != argc; ++i)
657             runTest(argv[i]);
658     }
659
660     if (threaded)
661         stopJavaScriptThreads();
662
663     NSWindow *window = [webView window];
664     [webView close];
665     mainFrame = nil;
666
667     // Work around problem where registering drag types leaves an outstanding
668     // "perform selector" on the window, which retains the window. It's a bit
669     // inelegant and perhaps dangerous to just blow them all away, but in practice
670     // it probably won't cause any trouble (and this is just a test tool, after all).
671     [NSObject cancelPreviousPerformRequestsWithTarget:window];
672     
673     [window close]; // releases when closed
674     [webView release];
675     
676     releaseGlobalControllers();
677     
678     [DumpRenderTreePasteboard releaseLocalPasteboards];
679
680     // FIXME: This should be moved onto LayoutTestController and made into a HashSet
681     if (disallowedURLs) {
682         CFRelease(disallowedURLs);
683         disallowedURLs = 0;
684     }
685
686     if (dumpPixels)
687         restoreMainDisplayColorProfile(0);
688 }
689
690 int main(int argc, const char *argv[])
691 {
692     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
693     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
694     dumpRenderTree(argc, argv);
695     [WebCoreStatistics garbageCollectJavaScriptObjects];
696     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts    
697     [pool release];
698     return 0;
699 }
700
701 static NSInteger compareHistoryItems(id item1, id item2, void *context)
702 {
703     return [[item1 target] caseInsensitiveCompare:[item2 target]];
704 }
705
706 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
707 {
708     int start = 0;
709     if (current) {
710         printf("curr->");
711         start = 6;
712     }
713     for (int i = start; i < indent; i++)
714         putchar(' ');
715     
716     NSString *urlString = [item URLString];
717     if ([[NSURL URLWithString:urlString] isFileURL]) {
718         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
719         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
720     }
721     
722     printf("%s", [urlString UTF8String]);
723     NSString *target = [item target];
724     if (target && [target length] > 0)
725         printf(" (in frame \"%s\")", [target UTF8String]);
726     if ([item isTargetItem])
727         printf("  **nav target**");
728     putchar('\n');
729     NSArray *kids = [item children];
730     if (kids) {
731         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
732         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
733         for (unsigned i = 0; i < [kids count]; i++)
734             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
735     }
736 }
737
738 static void dumpFrameScrollPosition(WebFrame *f)
739 {
740     NSPoint scrollPosition = [[[[f frameView] documentView] superview] bounds].origin;
741     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
742         if ([f parentFrame] != nil)
743             printf("frame '%s' ", [[f name] UTF8String]);
744         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
745     }
746
747     if (gLayoutTestController->dumpChildFrameScrollPositions()) {
748         NSArray *kids = [f childFrames];
749         if (kids)
750             for (unsigned i = 0; i < [kids count]; i++)
751                 dumpFrameScrollPosition([kids objectAtIndex:i]);
752     }
753 }
754
755 static NSString *dumpFramesAsText(WebFrame *frame)
756 {
757     DOMDocument *document = [frame DOMDocument];
758     DOMElement *documentElement = [document documentElement];
759
760     if (!documentElement)
761         return @"";
762
763     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
764
765     // Add header for all but the main frame.
766     if ([frame parentFrame])
767         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
768
769     [result appendFormat:@"%@\n", [documentElement innerText]];
770
771     if (gLayoutTestController->dumpChildFramesAsText()) {
772         NSArray *kids = [frame childFrames];
773         if (kids) {
774             for (unsigned i = 0; i < [kids count]; i++)
775                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
776         }
777     }
778
779     return result;
780 }
781
782 static NSData *dumpFrameAsPDF(WebFrame *frame)
783 {
784     if (!frame)
785         return nil;
786
787     // Sadly we have to dump to a file and then read from that file again
788     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
789     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
790     // The goal of this function is to test "real" printing across multiple pages.
791     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
792     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
793
794     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
795     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
796     [printInfoDict setObject:path forKey:NSPrintSavePath];
797
798     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
799     [printInfo setHorizontalPagination:NSAutoPagination];
800     [printInfo setVerticalPagination:NSAutoPagination];
801     [printInfo setVerticallyCentered:NO];
802
803     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
804     [printOperation setShowPanels:NO];
805     [printOperation runOperation];
806
807     [printInfo release];
808
809     NSData *pdfData = [NSData dataWithContentsOfFile:path];
810     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
811
812     return pdfData;
813 }
814
815 static void convertMIMEType(NSMutableString *mimeType)
816 {
817 #ifdef BUILDING_ON_LEOPARD
818     // Workaround for <rdar://problem/5539824> on Leopard
819     if ([mimeType isEqualToString:@"text/xml"])
820         [mimeType setString:@"application/xml"];
821 #endif
822     // Workaround for <rdar://problem/6234318> with Dashcode 2.0
823     if ([mimeType isEqualToString:@"application/x-javascript"])
824         [mimeType setString:@"text/javascript"];
825 }
826
827 static void convertWebResourceDataToString(NSMutableDictionary *resource)
828 {
829     NSMutableString *mimeType = [resource objectForKey:@"WebResourceMIMEType"];
830     convertMIMEType(mimeType);
831
832     if ([mimeType hasPrefix:@"text/"] || [[WebHTMLRepresentation supportedNonImageMIMETypes] containsObject:mimeType]) {
833         NSString *textEncodingName = [resource objectForKey:@"WebResourceTextEncodingName"];
834         NSStringEncoding stringEncoding;
835         if ([textEncodingName length] > 0)
836             stringEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)textEncodingName));
837         else
838             stringEncoding = NSUTF8StringEncoding;
839
840         NSData *data = [resource objectForKey:@"WebResourceData"];
841         NSString *dataAsString = [[NSString alloc] initWithData:data encoding:stringEncoding];
842         if (dataAsString)
843             [resource setObject:dataAsString forKey:@"WebResourceData"];
844         [dataAsString release];
845     }
846 }
847
848 static void normalizeHTTPResponseHeaderFields(NSMutableDictionary *fields)
849 {
850     // Normalize headers
851     if ([fields objectForKey:@"Date"])
852         [fields setObject:@"Sun, 16 Nov 2008 17:00:00 GMT" forKey:@"Date"];
853     if ([fields objectForKey:@"Last-Modified"])
854         [fields setObject:@"Sun, 16 Nov 2008 16:55:00 GMT" forKey:@"Last-Modified"];
855     if ([fields objectForKey:@"Etag"])
856         [fields setObject:@"\"301925-21-45c7d72d3e780\"" forKey:@"Etag"];
857     if ([fields objectForKey:@"Server"])
858         [fields setObject:@"Apache/2.2.9 (Unix) mod_ssl/2.2.9 OpenSSL/0.9.7l PHP/5.2.6" forKey:@"Server"];
859
860     // Remove headers
861     if ([fields objectForKey:@"Connection"])
862         [fields removeObjectForKey:@"Connection"];
863     if ([fields objectForKey:@"Keep-Alive"])
864         [fields removeObjectForKey:@"Keep-Alive"];
865 }
866
867 static void normalizeWebResourceURL(NSMutableString *webResourceURL)
868 {
869     static int fileUrlLength = [(NSString *)@"file://" length];
870     NSRange layoutTestsWebArchivePathRange = [webResourceURL rangeOfString:@"/LayoutTests/" options:NSBackwardsSearch];
871     if (layoutTestsWebArchivePathRange.location == NSNotFound)
872         return;
873     NSRange currentWorkingDirectoryRange = NSMakeRange(fileUrlLength, layoutTestsWebArchivePathRange.location - fileUrlLength);
874     [webResourceURL replaceCharactersInRange:currentWorkingDirectoryRange withString:@""];
875 }
876
877 static void convertWebResourceResponseToDictionary(NSMutableDictionary *propertyList)
878 {
879     NSURLResponse *response = nil;
880     NSData *responseData = [propertyList objectForKey:@"WebResourceResponse"]; // WebResourceResponseKey in WebResource.m
881     if ([responseData isKindOfClass:[NSData class]]) {
882         // Decode NSURLResponse
883         NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:responseData];
884         response = [unarchiver decodeObjectForKey:@"WebResourceResponse"]; // WebResourceResponseKey in WebResource.m
885         [unarchiver finishDecoding];
886         [unarchiver release];
887     }        
888
889     NSMutableDictionary *responseDictionary = [[NSMutableDictionary alloc] init];
890
891     NSMutableString *urlString = [[[response URL] description] mutableCopy];
892     normalizeWebResourceURL(urlString);
893     [responseDictionary setObject:urlString forKey:@"URL"];
894     [urlString release];
895
896     NSMutableString *mimeTypeString = [[response MIMEType] mutableCopy];
897     convertMIMEType(mimeTypeString);
898     [responseDictionary setObject:mimeTypeString forKey:@"MIMEType"];
899     [mimeTypeString release];
900
901     NSString *textEncodingName = [response textEncodingName];
902     if (textEncodingName)
903         [responseDictionary setObject:textEncodingName forKey:@"textEncodingName"];
904     [responseDictionary setObject:[NSNumber numberWithLongLong:[response expectedContentLength]] forKey:@"expectedContentLength"];
905
906     if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
907         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
908
909         NSMutableDictionary *allHeaderFields = [[httpResponse allHeaderFields] mutableCopy];
910         normalizeHTTPResponseHeaderFields(allHeaderFields);
911         [responseDictionary setObject:allHeaderFields forKey:@"allHeaderFields"];
912         [allHeaderFields release];
913
914         [responseDictionary setObject:[NSNumber numberWithInt:[httpResponse statusCode]] forKey:@"statusCode"];
915     }
916
917     [propertyList setObject:responseDictionary forKey:@"WebResourceResponse"];
918     [responseDictionary release];
919 }
920
921 static NSInteger compareResourceURLs(id resource1, id resource2, void *context)
922 {
923     NSString *url1 = [resource1 objectForKey:@"WebResourceURL"];
924     NSString *url2 = [resource2 objectForKey:@"WebResourceURL"];
925  
926     return [url1 compare:url2];
927 }
928
929 static NSString *serializeWebArchiveToXML(WebArchive *webArchive)
930 {
931     NSString *errorString;
932     NSMutableDictionary *propertyList = [NSPropertyListSerialization propertyListFromData:[webArchive data]
933                                                                          mutabilityOption:NSPropertyListMutableContainersAndLeaves
934                                                                                    format:NULL
935                                                                          errorDescription:&errorString];
936     if (!propertyList)
937         return errorString;
938
939     NSMutableArray *resources = [NSMutableArray arrayWithCapacity:1];
940     [resources addObject:propertyList];
941
942     while ([resources count]) {
943         NSMutableDictionary *resourcePropertyList = [resources objectAtIndex:0];
944         [resources removeObjectAtIndex:0];
945
946         NSMutableDictionary *mainResource = [resourcePropertyList objectForKey:@"WebMainResource"];
947         normalizeWebResourceURL([mainResource objectForKey:@"WebResourceURL"]);
948         convertWebResourceDataToString(mainResource);
949
950         // Add subframeArchives to list for processing
951         NSMutableArray *subframeArchives = [resourcePropertyList objectForKey:@"WebSubframeArchives"]; // WebSubframeArchivesKey in WebArchive.m
952         if (subframeArchives)
953             [resources addObjectsFromArray:subframeArchives];
954
955         NSMutableArray *subresources = [resourcePropertyList objectForKey:@"WebSubresources"]; // WebSubresourcesKey in WebArchive.m
956         NSEnumerator *enumerator = [subresources objectEnumerator];
957         NSMutableDictionary *subresourcePropertyList;
958         while ((subresourcePropertyList = [enumerator nextObject])) {
959             normalizeWebResourceURL([subresourcePropertyList objectForKey:@"WebResourceURL"]);
960             convertWebResourceResponseToDictionary(subresourcePropertyList);
961             convertWebResourceDataToString(subresourcePropertyList);
962         }
963         
964         // Sort the subresources so they're always in a predictable order for the dump
965         if (NSArray *sortedSubresources = [subresources sortedArrayUsingFunction:compareResourceURLs context:nil])
966             [resourcePropertyList setObject:sortedSubresources forKey:@"WebSubresources"];
967     }
968
969     NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:propertyList
970                                                                  format:NSPropertyListXMLFormat_v1_0
971                                                        errorDescription:&errorString];
972     if (!xmlData)
973         return errorString;
974
975     NSMutableString *string = [[[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease];
976
977     // Replace "Apple Computer" with "Apple" in the DTD declaration.
978     NSRange range = [string rangeOfString:@"-//Apple Computer//"];
979     if (range.location != NSNotFound)
980         [string replaceCharactersInRange:range withString:@"-//Apple//"];
981     
982     return string;
983 }
984
985 static void dumpBackForwardListForWebView(WebView *view)
986 {
987     printf("\n============== Back Forward List ==============\n");
988     WebBackForwardList *bfList = [view backForwardList];
989
990     // Print out all items in the list after prevTestBFItem, which was from the previous test
991     // Gather items from the end of the list, the print them out from oldest to newest
992     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
993     for (int i = [bfList forwardListCount]; i > 0; i--) {
994         WebHistoryItem *item = [bfList itemAtIndex:i];
995         // something is wrong if the item from the last test is in the forward part of the b/f list
996         assert(item != prevTestBFItem);
997         [itemsToPrint addObject:item];
998     }
999             
1000     assert([bfList currentItem] != prevTestBFItem);
1001     [itemsToPrint addObject:[bfList currentItem]];
1002     int currentItemIndex = [itemsToPrint count] - 1;
1003
1004     for (int i = -1; i >= -[bfList backListCount]; i--) {
1005         WebHistoryItem *item = [bfList itemAtIndex:i];
1006         if (item == prevTestBFItem)
1007             break;
1008         [itemsToPrint addObject:item];
1009     }
1010
1011     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1012         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1013
1014     [itemsToPrint release];
1015     printf("===============================================\n");
1016 }
1017
1018 static void sizeWebViewForCurrentTest()
1019 {
1020     // W3C SVG tests expect to be 480x360
1021     bool isSVGW3CTest = (gLayoutTestController->testPathOrURL().find("svg/W3C-SVG-1.1") != string::npos);
1022     if (isSVGW3CTest)
1023         [[mainFrame webView] setFrameSize:NSMakeSize(480, 360)];
1024     else
1025         [[mainFrame webView] setFrameSize:NSMakeSize(LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight)];
1026 }
1027
1028 static const char *methodNameStringForFailedTest()
1029 {
1030     const char *errorMessage;
1031     if (gLayoutTestController->dumpAsText())
1032         errorMessage = "[documentElement innerText]";
1033     else if (gLayoutTestController->dumpDOMAsWebArchive())
1034         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1035     else if (gLayoutTestController->dumpSourceAsWebArchive())
1036         errorMessage = "[[mainFrame dataSource] webArchive]";
1037     else
1038         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1039
1040     return errorMessage;
1041 }
1042
1043 static void dumpBackForwardListForAllWindows()
1044 {
1045     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1046     unsigned count = CFArrayGetCount(openWindows);
1047     for (unsigned i = 0; i < count; i++) {
1048         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1049         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1050         dumpBackForwardListForWebView(webView);
1051     }
1052 }
1053
1054 static void invalidateAnyPreviousWaitToDumpWatchdog()
1055 {
1056     if (waitToDumpWatchdog) {
1057         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1058         CFRelease(waitToDumpWatchdog);
1059         waitToDumpWatchdog = 0;
1060     }
1061 }
1062
1063 void dump()
1064 {
1065     invalidateAnyPreviousWaitToDumpWatchdog();
1066
1067     bool dumpAsText = gLayoutTestController->dumpAsText();
1068     if (dumpTree) {
1069         NSString *resultString = nil;
1070         NSData *resultData = nil;
1071         NSString *resultMimeType = @"text/plain";
1072
1073         dumpAsText |= [[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"];
1074         gLayoutTestController->setDumpAsText(dumpAsText);
1075         if (gLayoutTestController->dumpAsText()) {
1076             resultString = dumpFramesAsText(mainFrame);
1077         } else if (gLayoutTestController->dumpAsPDF()) {
1078             resultData = dumpFrameAsPDF(mainFrame);
1079             resultMimeType = @"application/pdf";
1080         } else if (gLayoutTestController->dumpDOMAsWebArchive()) {
1081             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1082             resultString = serializeWebArchiveToXML(webArchive);
1083             resultMimeType = @"application/x-webarchive";
1084         } else if (gLayoutTestController->dumpSourceAsWebArchive()) {
1085             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1086             resultString = serializeWebArchiveToXML(webArchive);
1087             resultMimeType = @"application/x-webarchive";
1088         } else {
1089             sizeWebViewForCurrentTest();
1090             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gLayoutTestController->isPrinting()];
1091         }
1092
1093         if (resultString && !resultData)
1094             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1095
1096         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1097
1098         if (resultData) {
1099             fwrite([resultData bytes], 1, [resultData length], stdout);
1100
1101             if (!gLayoutTestController->dumpAsText() && !gLayoutTestController->dumpDOMAsWebArchive() && !gLayoutTestController->dumpSourceAsWebArchive())
1102                 dumpFrameScrollPosition(mainFrame);
1103
1104             if (gLayoutTestController->dumpBackForwardList())
1105                 dumpBackForwardListForAllWindows();
1106         } else
1107             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1108
1109         // Stop the watchdog thread before we leave this test to make sure it doesn't
1110         // fire in between tests causing the next test to fail.
1111         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1112         invalidateAnyPreviousWaitToDumpWatchdog();
1113
1114         if (printSeparators) {
1115             puts("#EOF");       // terminate the content block
1116             fputs("#EOF\n", stderr);
1117         }            
1118     }
1119
1120     if (dumpPixels && !dumpAsText)
1121         // FIXME: when isPrinting is set, dump the image with page separators.
1122         dumpWebViewAsPixelsAndCompareWithExpected(gLayoutTestController->expectedPixelHash());
1123
1124     puts("#EOF");   // terminate the (possibly empty) pixels block
1125
1126     fflush(stdout);
1127     fflush(stderr);
1128
1129     done = YES;
1130 }
1131
1132 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1133 {
1134     return strstr(pathOrURL, "loading/");
1135 }
1136
1137 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1138 {
1139     return strstr(pathOrURL, "globalhistory/");
1140 }
1141
1142 static bool shouldOpenWebInspector(const char* pathOrURL)
1143 {
1144     return strstr(pathOrURL, "inspector/");
1145 }
1146
1147 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1148 {
1149     return shouldOpenWebInspector(pathOrURL) || strstr(pathOrURL, "inspector-enabled/");
1150 }
1151
1152 static void resetWebViewToConsistentStateBeforeTesting()
1153 {
1154     WebView *webView = [mainFrame webView];
1155     [webView setEditable:NO];
1156     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1157     [webView makeTextStandardSize:nil];
1158     [webView resetPageZoom:nil];
1159     [webView setTabKeyCyclesThroughElements:YES];
1160     [webView setPolicyDelegate:nil];
1161     [policyDelegate setPermissive:NO];
1162     [policyDelegate setControllerToNotifyDone:0];
1163     [frameLoadDelegate resetToConsistentState];
1164     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1165     [webView _clearMainFrameName];
1166     [[webView undoManager] removeAllActions];
1167     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1168     [[webView window] setAutodisplay:NO];
1169
1170     resetDefaultsToConsistentValues();
1171
1172     [[mainFrame webView] setSmartInsertDeleteEnabled:YES];
1173     [[[mainFrame webView] inspector] setJavaScriptProfilingEnabled:NO];
1174
1175     [WebView _setUsesTestModeFocusRingColor:YES];
1176     [WebView _resetOriginAccessWhitelists];
1177 }
1178
1179 static void runTest(const string& testPathOrURL)
1180 {
1181     ASSERT(!testPathOrURL.empty());
1182     
1183     // Look for "'" as a separator between the path or URL, and the pixel dump hash that follows.
1184     string pathOrURL(testPathOrURL);
1185     string expectedPixelHash;
1186     
1187     size_t separatorPos = pathOrURL.find("'");
1188     if (separatorPos != string::npos) {
1189         pathOrURL = string(testPathOrURL, 0, separatorPos);
1190         expectedPixelHash = string(testPathOrURL, separatorPos + 1);
1191     }
1192
1193     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1194     if (!pathOrURLString) {
1195         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1196         return;
1197     }
1198
1199     NSURL *url;
1200     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"])
1201         url = [NSURL URLWithString:pathOrURLString];
1202     else
1203         url = [NSURL fileURLWithPath:pathOrURLString];
1204     if (!url) {
1205         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1206         return;
1207     }
1208
1209     const string testURL([[url absoluteString] UTF8String]);
1210     
1211     resetWebViewToConsistentStateBeforeTesting();
1212
1213     gLayoutTestController = new LayoutTestController(testURL, expectedPixelHash);
1214     topLoadingFrame = nil;
1215     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1216     releaseAndZero(&draggingInfo);
1217     done = NO;
1218
1219     gLayoutTestController->setIconDatabaseEnabled(false);
1220
1221     if (disallowedURLs)
1222         CFSetRemoveAllValues(disallowedURLs);
1223     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1224         gLayoutTestController->setDumpFrameLoadCallbacks(true);
1225
1226     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1227         [[mainFrame webView] setHistoryDelegate:historyDelegate];
1228     else
1229         [[mainFrame webView] setHistoryDelegate:nil];
1230
1231     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1232         gLayoutTestController->setDeveloperExtrasEnabled(true);
1233         if (shouldOpenWebInspector(pathOrURL.c_str()))
1234             gLayoutTestController->showWebInspector();
1235     }
1236
1237     if ([WebHistory optionalSharedHistory])
1238         [WebHistory setOptionalSharedHistory:nil];
1239     lastMousePosition = NSZeroPoint;
1240     lastClickPosition = NSZeroPoint;
1241
1242     [prevTestBFItem release];
1243     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
1244
1245     WorkQueue::shared()->clear();
1246     WorkQueue::shared()->setFrozen(false);
1247
1248     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
1249     if (ignoreWebCoreNodeLeaks)
1250         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
1251
1252     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1253     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
1254     [pool release];
1255
1256     while (!done) {
1257         pool = [[NSAutoreleasePool alloc] init];
1258         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]]; 
1259         [pool release];
1260     }
1261
1262     pool = [[NSAutoreleasePool alloc] init];
1263     [EventSendingController clearSavedEvents];
1264     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
1265
1266     WorkQueue::shared()->clear();
1267
1268     if (gLayoutTestController->closeRemainingWindowsWhenComplete()) {
1269         NSArray* array = [DumpRenderTreeWindow openWindows];
1270
1271         unsigned count = [array count];
1272         for (unsigned i = 0; i < count; i++) {
1273             NSWindow *window = [array objectAtIndex:i];
1274
1275             // Don't try to close the main window
1276             if (window == [[mainFrame webView] window])
1277                 continue;
1278             
1279             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1280
1281             [webView close];
1282             [window close];
1283         }
1284     }
1285
1286     // If developer extras enabled Web Inspector may have been open by the test.
1287     if (shouldEnableDeveloperExtras(pathOrURL.c_str()))
1288         gLayoutTestController->closeWebInspector();
1289
1290     resetWebViewToConsistentStateBeforeTesting();
1291
1292     [mainFrame loadHTMLString:@"<html></html>" baseURL:[NSURL URLWithString:@"about:blank"]];
1293     [mainFrame stopLoading];
1294
1295     [pool release];
1296
1297     // We should only have our main window left open when we're done
1298     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
1299     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
1300
1301     gLayoutTestController->deref();
1302     gLayoutTestController = 0;
1303
1304     if (ignoreWebCoreNodeLeaks)
1305         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
1306 }
1307
1308 void displayWebView()
1309 {
1310     NSView *webView = [mainFrame webView];
1311     [webView display];
1312     [webView lockFocus];
1313     [[[NSColor blackColor] colorWithAlphaComponent:0.66] set];
1314     NSRectFillUsingOperation([webView frame], NSCompositeSourceOver);
1315     [webView unlockFocus];
1316 }
1317
1318 @implementation DumpRenderTreeEvent
1319
1320 + (NSPoint)mouseLocation
1321 {
1322     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
1323 }
1324
1325 @end
1326
1327 @implementation DumpRenderTreeApplication
1328
1329 - (BOOL)isRunning
1330 {
1331     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
1332     return YES;
1333 }
1334
1335 @end