OSDN Git Service

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