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