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