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