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