Source/WebCore: Don't flush compositing layers within FrameView::willPaintContents()
[WebKit-https.git] / Tools / DumpRenderTree / mac / DumpRenderTree.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  *           (C) 2007 Graham Dennis (graham.dennis@gmail.com)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple 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 "DefaultPolicyDelegate.h"
36 #import "DumpRenderTreeDraggingInfo.h"
37 #import "DumpRenderTreePasteboard.h"
38 #import "DumpRenderTreeWindow.h"
39 #import "EditingDelegate.h"
40 #import "EventSendingController.h"
41 #import "FrameLoadDelegate.h"
42 #import "HistoryDelegate.h"
43 #import "JavaScriptThreading.h"
44 #import "TestRunner.h"
45 #import "MockGeolocationProvider.h"
46 #import "MockWebNotificationProvider.h"
47 #import "NavigationController.h"
48 #import "ObjCPlugin.h"
49 #import "ObjCPluginFunction.h"
50 #import "PixelDumpSupport.h"
51 #import "PolicyDelegate.h"
52 #import "ResourceLoadDelegate.h"
53 #import "StorageTrackerDelegate.h"
54 #import "UIDelegate.h"
55 #import "WebArchiveDumpSupport.h"
56 #import "WebCoreTestSupport.h"
57 #import "WorkQueue.h"
58 #import "WorkQueueItem.h"
59 #import <CoreFoundation/CoreFoundation.h>
60 #import <JavaScriptCore/HeapStatistics.h>
61 #import <JavaScriptCore/Options.h>
62 #import <WebKit/DOMElement.h>
63 #import <WebKit/DOMExtensions.h>
64 #import <WebKit/DOMRange.h>
65 #import <WebKit/WebArchive.h>
66 #import <WebKit/WebBackForwardList.h>
67 #import <WebKit/WebCache.h>
68 #import <WebKit/WebCoreStatistics.h>
69 #import <WebKit/WebDataSourcePrivate.h>
70 #import <WebKit/WebDatabaseManagerPrivate.h>
71 #import <WebKit/WebDocumentPrivate.h>
72 #import <WebKit/WebDeviceOrientationProviderMock.h>
73 #import <WebKit/WebEditingDelegate.h>
74 #import <WebKit/WebFrameView.h>
75 #import <WebKit/WebHistory.h>
76 #import <WebKit/WebHistoryItemPrivate.h>
77 #import <WebKit/WebInspector.h>
78 #import <WebKit/WebKitNSStringExtras.h>
79 #import <WebKit/WebPluginDatabase.h>
80 #import <WebKit/WebPreferences.h>
81 #import <WebKit/WebPreferencesPrivate.h>
82 #import <WebKit/WebPreferenceKeysPrivate.h>
83 #import <WebKit/WebResourceLoadDelegate.h>
84 #import <WebKit/WebStorageManagerPrivate.h>
85 #import <WebKit/WebViewPrivate.h>
86 #import <getopt.h>
87 #import <wtf/Assertions.h>
88 #import <wtf/FastMalloc.h>
89 #import <wtf/RetainPtr.h>
90 #import <wtf/Threading.h>
91 #import <wtf/ObjcRuntimeExtras.h>
92 #import <wtf/OwnPtr.h>
93 #import <wtf/text/WTFString.h>
94
95 #if !PLATFORM(IOS)
96 #import <Carbon/Carbon.h>
97 #import <WebKit/WebDynamicScrollBarsView.h>
98 #endif
99
100 #if PLATFORM(IOS)
101 #import <CoreGraphics/CGFontDB.h>
102 #import <GraphicsServices/GSFont.h>
103 #import <QuartzCore/QuartzCore.h>
104 #import <UIKit/UIApplication_Private.h>
105 #import <UIKit/UIMath.h>
106 #import <UIKit/UIWebBrowserView.h>
107 #import <UIKit/UIWebScrollView.h>
108 #import <WebKit/WAKViewPrivate.h>
109 #import <WebKit/WAKWindow.h>
110 #import <WebKit/WebCoreThread.h>
111 #import <WebKit/WebCoreThreadRun.h>
112 #import <WebKit/WebDOMOperations.h>
113 #import <fcntl.h>
114 #import "DumpRenderTreeBrowserView.h"
115 #endif
116
117 extern "C" {
118 #import <mach-o/getsect.h>
119 }
120
121 using namespace std;
122
123 #if !PLATFORM(IOS)
124 @interface DumpRenderTreeApplication : NSApplication
125 @end
126
127 @interface DumpRenderTreeEvent : NSEvent
128 @end
129 #else
130 @interface ScrollViewResizerDelegate : NSObject
131 @end
132
133 @implementation ScrollViewResizerDelegate
134 - (void)view:(UIWebDocumentView *)view didSetFrame:(CGRect)newFrame oldFrame:(CGRect)oldFrame asResultOfZoom:(BOOL)wasResultOfZoom
135 {
136     UIView *scrollView = [view superview];
137     while (![scrollView isKindOfClass:[UIWebScrollView class]])
138         scrollView = [scrollView superview];
139
140     ASSERT(scrollView && [scrollView isKindOfClass:[UIWebScrollView class]]);
141     const CGSize scrollViewSize = [scrollView bounds].size;
142     CGSize contentSize = newFrame.size;
143     contentSize.height = _ROUNDF_(MAX(CGRectGetMaxY(newFrame), scrollViewSize.height));
144     [(UIWebScrollView *)scrollView setContentSize:contentSize];
145 }
146 @end
147 #endif
148
149 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
150 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
151 @end
152
153 #if USE(APPKIT)
154 @interface NSSound (Details)
155 + (void)_setAlertType:(NSUInteger)alertType;
156 @end
157 #endif
158
159 static void runTest(const string& testPathOrURL);
160
161 // Deciding when it's OK to dump out the state is a bit tricky.  All these must be true:
162 // - There is no load in progress
163 // - There is no work queued up (see workQueue var, below)
164 // - waitToDump==NO.  This means either waitUntilDone was never called, or it was called
165 //       and notifyDone was called subsequently.
166 // Note that the call to notifyDone and the end of the load can happen in either order.
167
168 volatile bool done;
169
170 NavigationController* gNavigationController = 0;
171 RefPtr<TestRunner> gTestRunner;
172
173 WebFrame *mainFrame = 0;
174 // This is the topmost frame that is loading, during a given load, or nil when no load is 
175 // in progress.  Usually this is the same as the main frame, but not always.  In the case
176 // where a frameset is loaded, and then new content is loaded into one of the child frames,
177 // that child frame is the "topmost frame that is loading".
178 WebFrame *topLoadingFrame = nil;     // !nil iff a load is in progress
179
180
181 CFMutableSetRef disallowedURLs = 0;
182 static CFRunLoopTimerRef waitToDumpWatchdog = 0;
183
184 // Delegates
185 static FrameLoadDelegate *frameLoadDelegate;
186 static UIDelegate *uiDelegate;
187 static EditingDelegate *editingDelegate;
188 static ResourceLoadDelegate *resourceLoadDelegate;
189 static HistoryDelegate *historyDelegate;
190 PolicyDelegate *policyDelegate;
191 DefaultPolicyDelegate *defaultPolicyDelegate;
192 StorageTrackerDelegate *storageDelegate;
193 #if PLATFORM(IOS)
194 static ScrollViewResizerDelegate *scrollViewResizerDelegate;
195 #endif
196
197 static int dumpPixelsForAllTests = NO;
198 static bool dumpPixelsForCurrentTest = false;
199 static int threaded;
200 static int dumpTree = YES;
201 static int useTimeoutWatchdog = YES;
202 static int forceComplexText;
203 static int useAcceleratedDrawing;
204 static int gcBetweenTests;
205 static BOOL printSeparators;
206 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
207
208 static WebHistoryItem *prevTestBFItem = nil;  // current b/f item at the end of the previous test
209
210 #if PLATFORM(IOS)
211 const unsigned phoneViewHeight = 480;
212 const unsigned phoneViewWidth = 320;
213 const unsigned phoneBrowserScrollViewHeight = 416;
214 const unsigned phoneBrowserAddressBarOffset = 60;
215 const CGRect layoutTestViewportRect = { {0, 0}, {static_cast<CGFloat>(TestRunner::viewWidth), static_cast<CGFloat>(TestRunner::viewHeight)} };
216 UIWebBrowserView *gWebBrowserView = nil;
217 UIWebScrollView *gWebScrollView = nil;
218 DumpRenderTreeWindow *gDrtWindow = nil;
219 #endif
220
221 #ifdef __OBJC2__
222 static void swizzleAllMethods(Class imposter, Class original)
223 {
224     unsigned int imposterMethodCount;
225     Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
226
227     unsigned int originalMethodCount;
228     Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
229
230     for (unsigned int i = 0; i < imposterMethodCount; i++) {
231         SEL imposterMethodName = method_getName(imposterMethods[i]);
232
233         // Attempt to add the method to the original class.  If it fails, the method already exists and we should
234         // instead exchange the implementations.
235         if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
236             continue;
237
238         unsigned int j = 0;
239         for (; j < originalMethodCount; j++) {
240             SEL originalMethodName = method_getName(originalMethods[j]);
241             if (sel_isEqual(imposterMethodName, originalMethodName))
242                 break;
243         }
244
245         // If class_addMethod failed above then the method must exist on the original class.
246         ASSERT(j < originalMethodCount);
247         method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
248     }
249
250     free(imposterMethods);
251     free(originalMethods);
252 }
253 #endif
254
255 static void poseAsClass(const char* imposter, const char* original)
256 {
257     Class imposterClass = objc_getClass(imposter);
258     Class originalClass = objc_getClass(original);
259
260 #ifndef __OBJC2__
261     class_poseAs(imposterClass, originalClass);
262 #else
263
264     // Swizzle instance methods
265     swizzleAllMethods(imposterClass, originalClass);
266     // and then class methods
267     swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
268 #endif
269 }
270
271 void setPersistentUserStyleSheetLocation(CFStringRef url)
272 {
273     persistentUserStyleSheetLocation = url;
274 }
275
276 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
277 {
278     static char* const ignoreSet[] = {
279         // Keeping this infrastructure around in case we ever need it again.
280     };
281     static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
282     
283     for (int i = 0; i < ignoreSetCount; i++) {
284         // FIXME: ignore case
285         string curIgnore(ignoreSet[i]);
286         // Match at the end of the URLString
287         if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
288             return true;
289     }
290     return false;
291 }
292
293 #if !PLATFORM(IOS)
294 static NSSet *allowedFontFamilySet()
295 {
296     static NSSet *fontFamilySet = [[NSSet setWithObjects:
297         @"Ahem",
298         @"Al Bayan",
299         @"American Typewriter",
300         @"Andale Mono",
301         @"Apple Braille",
302         @"Apple Color Emoji",
303         @"Apple Chancery",
304         @"Apple Garamond BT",
305         @"Apple LiGothic",
306         @"Apple LiSung",
307         @"Apple Symbols",
308         @"AppleGothic",
309         @"AppleMyungjo",
310         @"Arial Black",
311         @"Arial Hebrew",
312         @"Arial Narrow",
313         @"Arial Rounded MT Bold",
314         @"Arial Unicode MS",
315         @"Arial",
316         @"Ayuthaya",
317         @"Baghdad",
318         @"Baskerville",
319         @"BiauKai",
320         @"Big Caslon",
321         @"Brush Script MT",
322         @"Chalkboard",
323         @"Chalkduster",
324         @"Charcoal CY",
325         @"Cochin",
326         @"Comic Sans MS",
327         @"Copperplate",
328         @"Corsiva Hebrew",
329         @"Courier New",
330         @"Courier",
331         @"DecoType Naskh",
332         @"Devanagari MT",
333         @"Didot",
334         @"Euphemia UCAS",
335         @"Futura",
336         @"GB18030 Bitmap",
337         @"Geeza Pro",
338         @"Geneva CY",
339         @"Geneva",
340         @"Georgia",
341         @"Gill Sans",
342         @"Gujarati MT",
343         @"GungSeo",
344         @"Gurmukhi MT",
345         @"HeadLineA",
346         @"Hei",
347         @"Heiti SC",
348         @"Heiti TC",
349         @"Helvetica CY",
350         @"Helvetica Neue",
351         @"Helvetica",
352         @"Herculanum",
353         @"Hiragino Kaku Gothic Pro",
354         @"Hiragino Kaku Gothic ProN",
355         @"Hiragino Kaku Gothic Std",
356         @"Hiragino Kaku Gothic StdN",
357         @"Hiragino Maru Gothic Monospaced",
358         @"Hiragino Maru Gothic Pro",
359         @"Hiragino Maru Gothic ProN",
360         @"Hiragino Mincho Pro",
361         @"Hiragino Mincho ProN",
362         @"Hiragino Sans GB",
363         @"Hoefler Text",
364         @"Impact",
365         @"InaiMathi",
366         @"Kai",
367         @"Kailasa",
368         @"Kokonor",
369         @"Krungthep",
370         @"KufiStandardGK",
371         @"LiHei Pro",
372         @"LiSong Pro",
373         @"Lucida Grande",
374         @"Marker Felt",
375         @"Menlo",
376         @"Microsoft Sans Serif",
377         @"Monaco",
378         @"Mshtakan",
379         @"Nadeem",
380         @"New Peninim MT",
381         @"Optima",
382         @"Osaka",
383         @"Papyrus",
384         @"PCMyungjo",
385         @"PilGi",
386         @"Plantagenet Cherokee",
387         @"Raanana",
388         @"Sathu",
389         @"Silom",
390         @"Skia",
391         @"Songti SC",
392         @"Songti TC",
393         @"STFangsong",
394         @"STHeiti",
395         @"STIXGeneral",
396         @"STIXSizeOneSym",
397         @"STKaiti",
398         @"STSong",
399         @"Symbol",
400         @"System Font",
401         @"Tahoma",
402         @"Thonburi",
403         @"Times New Roman",
404         @"Times",
405         @"Trebuchet MS",
406         @"Verdana",
407         @"Webdings",
408         @"WebKit WeightWatcher",
409         @"Wingdings 2",
410         @"Wingdings 3",
411         @"Wingdings",
412         @"Zapf Dingbats",
413         @"Zapfino",
414         nil] retain];
415     
416     return fontFamilySet;
417 }
418
419 static NSSet *systemHiddenFontFamilySet()
420 {
421     static NSSet *fontFamilySet = [[NSSet setWithObjects:
422         @".LucidaGrandeUI",
423         nil] retain];
424
425     return fontFamilySet;
426 }
427
428 static IMP appKitAvailableFontFamiliesIMP;
429 static IMP appKitAvailableFontsIMP;
430
431 static NSArray *drt_NSFontManager_availableFontFamilies(id self, SEL _cmd)
432 {
433     static NSArray *availableFontFamilies;
434     if (availableFontFamilies)
435         return availableFontFamilies;
436     
437     NSArray *availableFamilies = wtfCallIMP<id>(appKitAvailableFontFamiliesIMP, self, _cmd);
438
439     NSMutableSet *prunedFamiliesSet = [NSMutableSet setWithArray:availableFamilies];
440     [prunedFamiliesSet intersectSet:allowedFontFamilySet()];
441
442     availableFontFamilies = [[prunedFamiliesSet allObjects] retain];
443     return availableFontFamilies;
444 }
445
446 static NSArray *drt_NSFontManager_availableFonts(id self, SEL _cmd)
447 {
448     static NSArray *availableFonts;
449     if (availableFonts)
450         return availableFonts;
451     
452     NSSet *allowedFamilies = allowedFontFamilySet();
453     NSMutableArray *availableFontList = [[NSMutableArray alloc] initWithCapacity:[allowedFamilies count] * 2];
454     for (NSString *fontFamily in allowedFontFamilySet()) {
455         NSArray* fontsForFamily = [[NSFontManager sharedFontManager] availableMembersOfFontFamily:fontFamily];
456         for (NSArray* fontInfo in fontsForFamily) {
457             // Font name is the first entry in the array.
458             [availableFontList addObject:[fontInfo objectAtIndex:0]];
459         }
460     }
461
462     for (NSString *hiddenFontFamily in systemHiddenFontFamilySet()) {
463         [availableFontList addObject:hiddenFontFamily];
464     }
465
466     availableFonts = availableFontList;
467     return availableFonts;
468 }
469
470 static void swizzleNSFontManagerMethods()
471 {
472     Method availableFontFamiliesMethod = class_getInstanceMethod(objc_getClass("NSFontManager"), @selector(availableFontFamilies));
473     ASSERT(availableFontFamiliesMethod);
474     if (!availableFontFamiliesMethod) {
475         NSLog(@"Failed to swizzle the \"availableFontFamilies\" method on NSFontManager");
476         return;
477     }
478     
479     appKitAvailableFontFamiliesIMP = method_setImplementation(availableFontFamiliesMethod, (IMP)drt_NSFontManager_availableFontFamilies);
480
481     Method availableFontsMethod = class_getInstanceMethod(objc_getClass("NSFontManager"), @selector(availableFonts));
482     ASSERT(availableFontsMethod);
483     if (!availableFontsMethod) {
484         NSLog(@"Failed to swizzle the \"availableFonts\" method on NSFontManager");
485         return;
486     }
487     
488     appKitAvailableFontsIMP = method_setImplementation(availableFontsMethod, (IMP)drt_NSFontManager_availableFonts);
489 }
490
491 static void activateTestingFonts()
492 {
493     static const char* fontFileNames[] = {
494         "AHEM____.TTF",
495         "WebKitWeightWatcher100.ttf",
496         "WebKitWeightWatcher200.ttf",
497         "WebKitWeightWatcher300.ttf",
498         "WebKitWeightWatcher400.ttf",
499         "WebKitWeightWatcher500.ttf",
500         "WebKitWeightWatcher600.ttf",
501         "WebKitWeightWatcher700.ttf",
502         "WebKitWeightWatcher800.ttf",
503         "WebKitWeightWatcher900.ttf",
504 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
505         "SampleFont.sfont",
506 #endif
507         0
508     };
509
510     NSMutableArray *fontURLs = [NSMutableArray array];
511     NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
512     for (unsigned i = 0; fontFileNames[i]; ++i) {
513         NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]]];
514         [fontURLs addObject:[fontURL absoluteURL]];
515     }
516
517     CFArrayRef errors = 0;
518     if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
519         NSLog(@"Failed to activate fonts: %@", errors);
520         CFRelease(errors);
521         exit(1);
522     }
523 }
524
525 static void adjustFonts()
526 {
527     swizzleNSFontManagerMethods();
528     activateTestingFonts();
529 }
530 #else
531 static void activateFontsIOS()
532 {
533     static const char* fontSectionNames[] = {
534         "Ahem",
535         "WeightWatcher100",
536         "WeightWatcher200",
537         "WeightWatcher300",
538         "WeightWatcher400",
539         "WeightWatcher500",
540         "WeightWatcher600",
541         "WeightWatcher700",
542         "WeightWatcher800",
543         "WeightWatcher900",
544         0
545     };
546
547     for (unsigned i = 0; fontSectionNames[i]; ++i) {
548         unsigned long fontDataLength;
549         char* fontData = getsectdata("__DATA", fontSectionNames[i], &fontDataLength);
550         if (!fontData) {
551             fprintf(stderr, "Failed to locate the %s font.\n", fontSectionNames[i]);
552             exit(1);
553         }
554
555         CGDataProviderRef data = CGDataProviderCreateWithData(NULL, fontData, fontDataLength, NULL);
556         if (!data) {
557             fprintf(stderr, "Failed to create CGDataProviderRef for the %s font.\n", fontSectionNames[i]);
558             exit(1);
559         }
560
561         CGFontRef cgFont = CGFontCreateWithDataProvider(data);
562         CGDataProviderRelease(data);
563         if (!cgFont) {
564             fprintf(stderr, "Failed to create CGFontRef for the %s font.\n", fontSectionNames[i]);
565             exit(1);
566         }
567
568         if (!GSFontAddCGFont(cgFont)) {
569             fprintf(stderr, "Failed to add CGFont to GraphicsServices for the %s font.\n", fontSectionNames[i]);
570             exit(1);
571         }
572         CGFontRelease(cgFont);
573     }
574 }
575 #endif // !PLATFORM(IOS)
576
577
578 #if PLATFORM(IOS)
579 void adjustWebDocumentForFlexibleViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
580 {
581     // These values match MobileSafari's, see -[TabDocument _createDocumentView].
582     [webBrowserView setMinimumScale:0.25f forDocumentTypes:UIEveryDocumentMask];
583     [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
584     [webBrowserView setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:UIEveryDocumentMask];
585     [webBrowserView setViewportSize:CGSizeMake(UIWebViewStandardViewportWidth, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:UIEveryDocumentMask];
586
587     // Adjust the viewport view and viewport to have similar behavior
588     // as the browser.
589     [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:YES];
590     [webBrowserView setDelegate:scrollViewResizerDelegate];
591
592     CGRect viewportRect = CGRectMake(0, 0, phoneViewWidth, phoneBrowserScrollViewHeight);
593     [scrollView setBounds:viewportRect];
594     [scrollView setFrame:viewportRect];
595
596     [webBrowserView setMinimumSize:viewportRect.size];
597     [webBrowserView setAutoresizes:YES];
598     CGRect browserViewFrame = [webBrowserView frame];
599     browserViewFrame.origin = CGPointMake(0, phoneBrowserAddressBarOffset);
600     [webBrowserView setFrame:browserViewFrame];
601 }
602
603 void adjustWebDocumentForStandardViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
604 {
605     [webBrowserView setMinimumScale:1.0f forDocumentTypes:UIEveryDocumentMask];
606     [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
607     [webBrowserView setInitialScale:1.0f forDocumentTypes:UIEveryDocumentMask];
608
609     [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:NO];
610     [webBrowserView setDelegate: nil];
611
612     [scrollView setBounds:layoutTestViewportRect];
613     [scrollView setFrame:layoutTestViewportRect];
614
615     [webBrowserView setMinimumSize:layoutTestViewportRect.size];
616     [webBrowserView setAutoresizes:NO];
617     CGRect browserViewFrame = [webBrowserView frame];
618     browserViewFrame.origin = CGPointZero;
619     [webBrowserView setFrame:browserViewFrame];
620 }
621 #endif
622
623 #if !PLATFORM(IOS)
624 @interface DRTMockScroller : NSScroller
625 @end
626
627 @implementation DRTMockScroller
628
629 - (NSRect)rectForPart:(NSScrollerPart)partCode
630 {
631     if (partCode != NSScrollerKnob)
632         return [super rectForPart:partCode];
633
634     NSRect frameRect = [self frame];
635     NSRect bounds = [self bounds];
636     BOOL isHorizontal = frameRect.size.width > frameRect.size.height;
637     CGFloat trackLength = isHorizontal ? bounds.size.width : bounds.size.height;
638     CGFloat minKnobSize = isHorizontal ? bounds.size.height : bounds.size.width;
639     CGFloat knobLength = max(minKnobSize, static_cast<CGFloat>(round(trackLength * [self knobProportion])));
640     CGFloat knobPosition = static_cast<CGFloat>((round([self doubleValue] * (trackLength - knobLength))));
641     
642     if (isHorizontal)
643         return NSMakeRect(bounds.origin.x + knobPosition, bounds.origin.y, knobLength, bounds.size.height);
644
645     return NSMakeRect(bounds.origin.x, bounds.origin.y +  + knobPosition, bounds.size.width, knobLength);
646 }
647
648 - (void)drawKnob
649 {
650     if (![self isEnabled])
651         return;
652
653     NSRect knobRect = [self rectForPart:NSScrollerKnob];
654     
655     static NSColor *knobColor = [[NSColor colorWithDeviceRed:0x80 / 255.0 green:0x80 / 255.0 blue:0x80 / 255.0 alpha:1] retain];
656     [knobColor set];
657
658     NSRectFill(knobRect);
659 }
660
661 - (void)drawRect:(NSRect)dirtyRect
662 {
663     static NSColor *trackColor = [[NSColor colorWithDeviceRed:0xC0 / 255.0 green:0xC0 / 255.0 blue:0xC0 / 255.0 alpha:1] retain];
664     static NSColor *disabledTrackColor = [[NSColor colorWithDeviceRed:0xE0 / 255.0 green:0xE0 / 255.0 blue:0xE0 / 255.0 alpha:1] retain];
665
666     if ([self isEnabled])
667         [trackColor set];
668     else
669         [disabledTrackColor set];
670
671     NSRectFill(dirtyRect);
672     
673     [self drawKnob];
674 }
675
676 @end
677
678 static void registerMockScrollbars()
679 {
680     [WebDynamicScrollBarsView setCustomScrollerClass:[DRTMockScroller class]];
681 }
682 #endif
683
684 WebView *createWebViewAndOffscreenWindow()
685 {
686 #if !PLATFORM(IOS)
687     NSRect rect = NSMakeRect(0, 0, TestRunner::viewWidth, TestRunner::viewHeight);
688     WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
689 #else
690     UIWebBrowserView *webBrowserView = [[[DumpRenderTreeBrowserView alloc] initWithFrame:layoutTestViewportRect] autorelease];
691
692     WebView *webView = [[webBrowserView webView] retain];
693     [webView setGroupName:@"org.webkit.DumpRenderTree"];
694 #endif
695
696     [webView setUIDelegate:uiDelegate];
697     [webView setFrameLoadDelegate:frameLoadDelegate];
698     [webView setEditingDelegate:editingDelegate];
699     [webView setResourceLoadDelegate:resourceLoadDelegate];
700     [webView _setGeolocationProvider:[MockGeolocationProvider shared]];
701     [webView _setDeviceOrientationProvider:[WebDeviceOrientationProviderMock shared]];
702     [webView _setNotificationProvider:[MockWebNotificationProvider shared]];
703
704     // Register the same schemes that Safari does
705     [WebView registerURLSchemeAsLocal:@"feed"];
706     [WebView registerURLSchemeAsLocal:@"feeds"];
707     [WebView registerURLSchemeAsLocal:@"feedsearch"];
708     
709 #if !PLATFORM(IOS)
710     [webView setContinuousSpellCheckingEnabled:YES];
711     [webView setAutomaticQuoteSubstitutionEnabled:NO];
712     [webView setAutomaticLinkDetectionEnabled:NO];
713     [webView setAutomaticDashSubstitutionEnabled:NO];
714     [webView setAutomaticTextReplacementEnabled:NO];
715     [webView setAutomaticSpellingCorrectionEnabled:YES];
716     [webView setGrammarCheckingEnabled:YES];
717
718     [webView setDefersCallbacks:NO];
719     [webView setInteractiveFormValidationEnabled:YES];
720     [webView setValidationMessageTimerMagnification:-1];
721     
722     // 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.
723     // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
724     NSRect windowRect = NSOffsetRect(rect, -10000, [(NSScreen *)[[NSScreen screens] objectAtIndex:0] frame].size.height - rect.size.height + 10000);
725     DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
726
727     [window setColorSpace:[[NSScreen mainScreen] colorSpace]];
728     [window setCollectionBehavior:NSWindowCollectionBehaviorStationary];
729     [[window contentView] addSubview:webView];
730     [window orderBack:nil];
731     [window setAutodisplay:NO];
732
733     [window startListeningForAcceleratedCompositingChanges];
734 #else
735     DumpRenderTreeWindow *drtWindow = [[DumpRenderTreeWindow alloc] initWithLayer:[webBrowserView layer]];
736     [drtWindow setContentView:webView];
737     [webBrowserView setWAKWindow:drtWindow];
738
739     [[webView window] makeFirstResponder:[[[webView mainFrame] frameView] documentView]];
740
741     CGRect uiWindowRect = layoutTestViewportRect;
742     uiWindowRect.origin.y += [UIApp statusBarHeight];
743     UIWindow *uiWindow = [[[UIWindow alloc] initWithFrame:uiWindowRect] autorelease];
744
745     // The UIWindow and UIWebBrowserView are released when the DumpRenderTreeWindow is closed.
746     drtWindow.uiWindow = uiWindow;
747     drtWindow.browserView = webBrowserView;
748
749     UIWebScrollView *scrollView = [[UIWebScrollView alloc] initWithFrame:layoutTestViewportRect];
750     [scrollView addSubview:webBrowserView];
751
752     [uiWindow addSubview:scrollView];
753     [scrollView release];
754
755     adjustWebDocumentForStandardViewport(webBrowserView, scrollView);
756 #endif
757     
758 #if !PLATFORM(IOS)
759     // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
760     // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
761     NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
762     [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
763 #else
764     [[webView mainFrame] _setVisibleSize:CGSizeMake(phoneViewWidth, phoneViewHeight)];
765     [[webView preferences] _setTelephoneNumberParsingEnabled:NO];
766
767     // Initialize the global UIViews, and set the key UIWindow to be painted.
768     if (!gWebBrowserView) {
769         gWebBrowserView = [webBrowserView retain];
770         gWebScrollView = [scrollView retain];
771         gDrtWindow = [drtWindow retain];
772         [uiWindow makeKeyAndVisible];
773         [uiWindow retain];
774     }
775 #endif
776
777     return webView;
778 }
779
780 static void destroyWebViewAndOffscreenWindow()
781 {
782     WebView *webView = [mainFrame webView];
783 #if !PLATFORM(IOS)
784     NSWindow *window = [webView window];
785 #endif
786     [webView close];
787     mainFrame = nil;
788
789 #if !PLATFORM(IOS)
790     // Work around problem where registering drag types leaves an outstanding
791     // "perform selector" on the window, which retains the window. It's a bit
792     // inelegant and perhaps dangerous to just blow them all away, but in practice
793     // it probably won't cause any trouble (and this is just a test tool, after all).
794     [NSObject cancelPreviousPerformRequestsWithTarget:window];
795
796     [window close]; // releases when closed
797 #else
798     UIWindow *uiWindow = [gWebBrowserView window];
799     [uiWindow removeFromSuperview];
800     [uiWindow release];
801 #endif
802
803     [webView release];
804 }
805
806 static NSString *libraryPathForDumpRenderTree()
807 {
808     //FIXME: This may not be sufficient to prevent interactions/crashes
809     //when running more than one copy of DumpRenderTree.
810     //See https://bugs.webkit.org/show_bug.cgi?id=10906
811     char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
812     if (dumpRenderTreeTemp)
813         return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
814     else
815         return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
816 }
817
818 // Called before each test.
819 static void resetWebPreferencesToConsistentValues()
820 {
821     WebPreferences *preferences = [WebPreferences standardPreferences];
822
823     [preferences setAllowUniversalAccessFromFileURLs:YES];
824     [preferences setAllowFileAccessFromFileURLs:YES];
825     [preferences setStandardFontFamily:@"Times"];
826     [preferences setFixedFontFamily:@"Courier"];
827     [preferences setSerifFontFamily:@"Times"];
828     [preferences setSansSerifFontFamily:@"Helvetica"];
829     [preferences setCursiveFontFamily:@"Apple Chancery"];
830     [preferences setFantasyFontFamily:@"Papyrus"];
831     [preferences setPictographFontFamily:@"Apple Color Emoji"];
832     [preferences setDefaultFontSize:16];
833     [preferences setDefaultFixedFontSize:13];
834     [preferences setMinimumFontSize:0];
835     [preferences setDefaultTextEncodingName:@"ISO-8859-1"];
836     [preferences setJavaEnabled:NO];
837     [preferences setJavaScriptEnabled:YES];
838     [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
839 #if !PLATFORM(IOS)
840     [preferences setTabsToLinks:NO];
841 #endif
842     [preferences setDOMPasteAllowed:YES];
843 #if !PLATFORM(IOS)
844     [preferences setShouldPrintBackgrounds:YES];
845 #endif
846     [preferences setCacheModel:WebCacheModelDocumentBrowser];
847     [preferences setXSSAuditorEnabled:NO];
848     [preferences setExperimentalNotificationsEnabled:NO];
849     [preferences setPlugInsEnabled:YES];
850 #if !PLATFORM(IOS)
851     [preferences setTextAreasAreResizable:YES];
852 #endif
853
854     [preferences setPrivateBrowsingEnabled:NO];
855     [preferences setAuthorAndUserStylesEnabled:YES];
856     [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
857     [preferences setJavaScriptCanAccessClipboard:YES];
858     [preferences setOfflineWebApplicationCacheEnabled:YES];
859     [preferences setDeveloperExtrasEnabled:NO];
860     [preferences setJavaScriptExperimentsEnabled:YES];
861     [preferences setLoadsImagesAutomatically:YES];
862     [preferences setLoadsSiteIconsIgnoringImageLoadingPreference:NO];
863     [preferences setFrameFlatteningEnabled:NO];
864     [preferences setSpatialNavigationEnabled:NO];
865     if (persistentUserStyleSheetLocation) {
866         [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
867         [preferences setUserStyleSheetEnabled:YES];
868     } else
869         [preferences setUserStyleSheetEnabled:NO];
870 #if PLATFORM(IOS)
871     [preferences setMediaPlaybackAllowsInline:YES];
872     [preferences setMediaPlaybackRequiresUserGesture:NO];
873
874     // Enable the tracker before creating the first WebView will
875     // cause initialization to use the correct database paths.
876     [preferences setStorageTrackerEnabled:YES];
877 #endif
878
879 #if ENABLE(IOS_TEXT_AUTOSIZING)
880     // Disable text autosizing by default.
881     [preferences _setMinimumZoomFontSize:0];
882 #endif
883
884     // The back/forward cache is causing problems due to layouts during transition from one page to another.
885     // So, turn it off for now, but we might want to turn it back on some day.
886     [preferences setUsesPageCache:NO];
887     [preferences setAcceleratedCompositingEnabled:YES];
888 #if USE(CA)
889     [preferences setCanvasUsesAcceleratedDrawing:YES];
890     [preferences setAcceleratedDrawingEnabled:useAcceleratedDrawing];
891 #endif
892     [preferences setWebGLEnabled:NO];
893     [preferences setCSSRegionsEnabled:YES];
894     [preferences setCSSGridLayoutEnabled:NO];
895     [preferences setUsePreHTML5ParserQuirks:NO];
896     [preferences setAsynchronousSpellCheckingEnabled:NO];
897     [preferences setMockScrollbarsEnabled:YES];
898
899 #if ENABLE(WEB_AUDIO)
900     [preferences setWebAudioEnabled:YES];
901 #endif
902
903 #if ENABLE(IOS_TEXT_AUTOSIZING)
904     // Disable text autosizing by default.
905     [preferences _setMinimumZoomFontSize:0];
906 #endif
907
908     [preferences setScreenFontSubstitutionEnabled:YES];
909
910 #if ENABLE(MEDIA_SOURCE)
911     [preferences setMediaSourceEnabled:YES];
912 #endif
913
914     [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
915 }
916
917 // Called once on DumpRenderTree startup.
918 static void setDefaultsToConsistentValuesForTesting()
919 {
920 #if PLATFORM(IOS)
921     WebThreadLock();
922 #endif
923
924     static const int NoFontSmoothing = 0;
925     static const int BlueTintedAppearance = 1;
926
927     NSString *libraryPath = libraryPathForDumpRenderTree();
928
929     NSDictionary *dict = @{
930         @"AppleKeyboardUIMode": @1,
931         @"AppleAntiAliasingThreshold": @4,
932         @"AppleFontSmoothing": @(NoFontSmoothing),
933         @"AppleAquaColorVariant": @(BlueTintedAppearance),
934         @"AppleHighlightColor": @"0.709800 0.835300 1.000000",
935         @"AppleOtherHighlightColor":@"0.500000 0.500000 0.500000",
936         @"AppleLanguages": @[ @"en" ],
937         WebKitEnableFullDocumentTeardownPreferenceKey: @YES,
938         WebKitFullScreenEnabledPreferenceKey: @YES,
939         @"UseWebKitWebInspector": @YES,
940 #if !PLATFORM(IOS)
941         @"NSTestCorrectionDictionary": @{
942             @"notationl": @"notational",
943             @"mesage": @"message",
944             @"wouldn": @"would",
945             @"wellcome": @"welcome",
946             @"hellolfworld": @"hello\nworld"
947         },
948 #endif
949         @"WebKitKerningAndLigaturesEnabledByDefault": @NO,
950         @"AppleScrollBarVariant": @"DoubleMax",
951 #if !PLATFORM(IOS)
952         @"NSScrollAnimationEnabled": @NO,
953 #endif
954         @"NSOverlayScrollersEnabled": @NO,
955         @"AppleShowScrollBars": @"Always",
956         WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
957         WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
958         WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"]
959     };
960
961     [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:dict];
962 }
963
964 static void runThread(void* arg)
965 {
966     static ThreadIdentifier previousId = 0;
967     ThreadIdentifier currentId = currentThread();
968     // Verify 2 successive threads do not get the same Id.
969     ASSERT(previousId != currentId);
970     previousId = currentId;
971 }
972
973 static void* runPthread(void* arg)
974 {
975     runThread(arg);
976     return 0;
977 }
978
979 static void testThreadIdentifierMap()
980 {
981     // Imitate 'foreign' threads that are not created by WTF.
982     pthread_t pthread;
983     pthread_create(&pthread, 0, &runPthread, 0);
984     pthread_join(pthread, 0);
985
986     pthread_create(&pthread, 0, &runPthread, 0);
987     pthread_join(pthread, 0);
988
989     // Now create another thread using WTF. On OSX, it will have the same pthread handle
990     // but should get a different ThreadIdentifier.
991     createThread(runThread, 0, "DumpRenderTree: test");
992 }
993
994 static void allocateGlobalControllers()
995 {
996     // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
997     gNavigationController = [[NavigationController alloc] init];
998     frameLoadDelegate = [[FrameLoadDelegate alloc] init];
999     uiDelegate = [[UIDelegate alloc] init];
1000     editingDelegate = [[EditingDelegate alloc] init];
1001     resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
1002     policyDelegate = [[PolicyDelegate alloc] init];
1003     historyDelegate = [[HistoryDelegate alloc] init];
1004     storageDelegate = [[StorageTrackerDelegate alloc] init];
1005     defaultPolicyDelegate = [[DefaultPolicyDelegate alloc] init];
1006 #if PLATFORM(IOS)
1007     scrollViewResizerDelegate = [[ScrollViewResizerDelegate alloc] init];
1008 #endif
1009 }
1010
1011 // ObjC++ doens't seem to let me pass NSObject*& sadly.
1012 static inline void releaseAndZero(NSObject** object)
1013 {
1014     [*object release];
1015     *object = nil;
1016 }
1017
1018 static void releaseGlobalControllers()
1019 {
1020     releaseAndZero(&gNavigationController);
1021     releaseAndZero(&frameLoadDelegate);
1022     releaseAndZero(&editingDelegate);
1023     releaseAndZero(&resourceLoadDelegate);
1024     releaseAndZero(&uiDelegate);
1025     releaseAndZero(&policyDelegate);
1026     releaseAndZero(&storageDelegate);
1027 #if PLATFORM(IOS)
1028     releaseAndZero(&scrollViewResizerDelegate);
1029 #endif
1030 }
1031
1032 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
1033 {
1034     struct option options[] = {
1035         {"notree", no_argument, &dumpTree, NO},
1036         {"pixel-tests", no_argument, &dumpPixelsForAllTests, YES},
1037         {"tree", no_argument, &dumpTree, YES},
1038         {"threaded", no_argument, &threaded, YES},
1039         {"complex-text", no_argument, &forceComplexText, YES},
1040         {"accelerated-drawing", no_argument, &useAcceleratedDrawing, YES},
1041         {"gc-between-tests", no_argument, &gcBetweenTests, YES},
1042         {"no-timeout", no_argument, &useTimeoutWatchdog, NO},
1043         {NULL, 0, NULL, 0}
1044     };
1045     
1046     int option;
1047     while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
1048         switch (option) {
1049             case '?':   // unknown or ambiguous option
1050             case ':':   // missing argument
1051                 exit(1);
1052                 break;
1053         }
1054     }
1055 }
1056
1057 static void addTestPluginsToPluginSearchPath(const char* executablePath)
1058 {
1059 #if !PLATFORM(IOS)
1060     NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
1061     [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
1062     [[WebPluginDatabase sharedDatabase] refresh];
1063 #endif
1064 }
1065
1066 static bool useLongRunningServerMode(int argc, const char *argv[])
1067 {
1068     // This assumes you've already called getopt_long
1069     return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
1070 }
1071
1072 static void runTestingServerLoop()
1073 {
1074     // When DumpRenderTree run in server mode, we just wait around for file names
1075     // to be passed to us and read each in turn, passing the results back to the client
1076     char filenameBuffer[2048];
1077     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1078         char *newLineCharacter = strchr(filenameBuffer, '\n');
1079         if (newLineCharacter)
1080             *newLineCharacter = '\0';
1081
1082         if (strlen(filenameBuffer) == 0)
1083             continue;
1084
1085         runTest(filenameBuffer);
1086     }
1087 }
1088
1089 static void prepareConsistentTestingEnvironment()
1090 {
1091 #if !PLATFORM(IOS)
1092     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1093     poseAsClass("DumpRenderTreeEvent", "NSEvent");
1094 #else
1095     poseAsClass("DumpRenderTreeEvent", "GSEvent");
1096 #endif
1097
1098     [[WebPreferences standardPreferences] setAutosaves:NO];
1099
1100 #if !PLATFORM(IOS)
1101
1102     // FIXME: We'd like to start with a clean state for every test, but this function can't be used more than once yet.
1103     [WebPreferences _switchNetworkLoaderToNewTestingSession];
1104
1105     NSURLCache *sharedCache =
1106         [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1107                                       diskCapacity:0
1108                                           diskPath:[libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"URLCache"]];
1109     [NSURLCache setSharedURLCache:sharedCache];
1110     [sharedCache release];
1111
1112     adjustFonts();
1113     registerMockScrollbars();
1114 #else
1115     activateFontsIOS();
1116 #endif
1117     
1118     allocateGlobalControllers();
1119     
1120     makeLargeMallocFailSilently();
1121
1122 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1123     NSActivityOptions options = (NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical) & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled);
1124     static id assertion = [[[NSProcessInfo processInfo] beginActivityWithOptions:options reason:@"DumpRenderTree should not be subject to process suppression"] retain];
1125     ASSERT_UNUSED(assertion, assertion);
1126 #endif
1127 }
1128
1129 void dumpRenderTree(int argc, const char *argv[])
1130 {
1131 #if PLATFORM(IOS)
1132     int infd = open("/tmp/DumpRenderTree_IN", O_RDWR);
1133     dup2(infd, STDIN_FILENO);
1134     int outfd = open("/tmp/DumpRenderTree_OUT", O_RDWR);
1135     dup2(outfd, STDOUT_FILENO);
1136     int errfd = open("/tmp/DumpRenderTree_ERROR", O_RDWR | O_NONBLOCK);
1137     dup2(errfd, STDERR_FILENO);
1138 #endif
1139
1140     initializeGlobalsFromCommandLineOptions(argc, argv);
1141     prepareConsistentTestingEnvironment();
1142     addTestPluginsToPluginSearchPath(argv[0]);
1143
1144     if (forceComplexText)
1145         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1146
1147 #if USE(APPKIT)
1148     [NSSound _setAlertType:0];
1149 #endif
1150
1151     WebView *webView = createWebViewAndOffscreenWindow();
1152     mainFrame = [webView mainFrame];
1153
1154     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1155     [WebCache empty];
1156
1157     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1158     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1159
1160     // http://webkit.org/b/32689
1161     testThreadIdentifierMap();
1162
1163     if (threaded)
1164         startJavaScriptThreads();
1165
1166     if (useLongRunningServerMode(argc, argv)) {
1167         printSeparators = YES;
1168         runTestingServerLoop();
1169     } else {
1170         printSeparators = optind < argc - 1;
1171         for (int i = optind; i != argc; ++i)
1172             runTest(argv[i]);
1173     }
1174
1175     if (threaded)
1176         stopJavaScriptThreads();
1177
1178     destroyWebViewAndOffscreenWindow();
1179     
1180     releaseGlobalControllers();
1181     
1182 #if !PLATFORM(IOS)
1183     [DumpRenderTreePasteboard releaseLocalPasteboards];
1184 #endif
1185
1186     // FIXME: This should be moved onto TestRunner and made into a HashSet
1187     if (disallowedURLs) {
1188         CFRelease(disallowedURLs);
1189         disallowedURLs = 0;
1190     }
1191
1192 #if PLATFORM(IOS)
1193     close(infd);
1194     close(outfd);
1195     close(errfd);
1196 #endif
1197 }
1198
1199 #if PLATFORM(IOS)
1200 static int _argc;
1201 static const char **_argv;
1202
1203 @implementation DumpRenderTree
1204
1205 - (void)_runDumpRenderTree
1206 {
1207     dumpRenderTree(_argc, _argv);
1208 }
1209
1210 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1211 {
1212     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1213 }
1214
1215 - (void)_deferDumpToMainThread
1216 {
1217     ASSERT(WebThreadIsCurrent());
1218     
1219     dispatch_async(dispatch_get_main_queue(), ^{
1220         dump();
1221     });
1222 }
1223
1224 - (void)_webThreadEventLoopHasRun
1225 {
1226     ASSERT(!WebThreadIsCurrent());
1227     _hasFlushedWebThreadRunQueue = YES;
1228 }
1229
1230 - (void)_webThreadInvoked
1231 {
1232     ASSERT(WebThreadIsCurrent());
1233     dispatch_async(dispatch_get_main_queue(), ^{
1234         [self _webThreadEventLoopHasRun];
1235     });
1236 }
1237
1238 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1239 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1240 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1241 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1242 - (void)_waitForWebThread
1243 {
1244     ASSERT(!WebThreadIsCurrent());
1245     _hasFlushedWebThreadRunQueue = NO;
1246     WebThreadRun(^{
1247         [self _webThreadInvoked];
1248     });
1249     while (!_hasFlushedWebThreadRunQueue) {
1250         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1251         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1252         [pool release];
1253     }
1254 }
1255
1256 @end
1257 #endif
1258
1259 int DumpRenderTreeMain(int argc, const char *argv[])
1260 {
1261 #if PLATFORM(IOS)
1262     _UIApplicationLoadWebKit();
1263 #endif
1264     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1265
1266     setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1267
1268 #if !PLATFORM(IOS)
1269     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1270
1271     dumpRenderTree(argc, argv);
1272 #else
1273     _argc = argc;
1274     _argv = argv;
1275     UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", nil);
1276 #endif
1277     [WebCoreStatistics garbageCollectJavaScriptObjects];
1278     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1279     if (JSC::Options::logHeapStatisticsAtExit())
1280         JSC::HeapStatistics::reportSuccess();
1281     [pool release];
1282     return 0;
1283 }
1284
1285 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1286 {
1287     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1288 }
1289
1290 static NSData *dumpAudio()
1291 {
1292     const vector<char>& dataVector = gTestRunner->audioResult();
1293     
1294     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1295     return data;
1296 }
1297
1298 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1299 {
1300     int start = 0;
1301     if (current) {
1302         printf("curr->");
1303         start = 6;
1304     }
1305     for (int i = start; i < indent; i++)
1306         putchar(' ');
1307     
1308     NSString *urlString = [item URLString];
1309     if ([[NSURL URLWithString:urlString] isFileURL]) {
1310         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1311         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1312     }
1313     
1314     printf("%s", [urlString UTF8String]);
1315     NSString *target = [item target];
1316     if (target && [target length] > 0)
1317         printf(" (in frame \"%s\")", [target UTF8String]);
1318     if ([item isTargetItem])
1319         printf("  **nav target**");
1320     putchar('\n');
1321     NSArray *kids = [item children];
1322     if (kids) {
1323         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1324         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1325         for (unsigned i = 0; i < [kids count]; i++)
1326             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1327     }
1328 }
1329
1330 static void dumpFrameScrollPosition(WebFrame *f)
1331 {
1332     WebScriptObject* scriptObject = [f windowObject];
1333     NSPoint scrollPosition = NSMakePoint(
1334         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1335         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1336     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1337         if ([f parentFrame] != nil)
1338             printf("frame '%s' ", [[f name] UTF8String]);
1339         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1340     }
1341
1342     if (gTestRunner->dumpChildFrameScrollPositions()) {
1343         NSArray *kids = [f childFrames];
1344         if (kids)
1345             for (unsigned i = 0; i < [kids count]; i++)
1346                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1347     }
1348 }
1349
1350 static NSString *dumpFramesAsText(WebFrame *frame)
1351 {
1352     DOMDocument *document = [frame DOMDocument];
1353     DOMElement *documentElement = [document documentElement];
1354
1355     if (!documentElement)
1356         return @"";
1357
1358     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1359
1360     // Add header for all but the main frame.
1361     if ([frame parentFrame])
1362         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1363
1364     [result appendFormat:@"%@\n", [documentElement innerText]];
1365
1366     if (gTestRunner->dumpChildFramesAsText()) {
1367         NSArray *kids = [frame childFrames];
1368         if (kids) {
1369             for (unsigned i = 0; i < [kids count]; i++)
1370                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1371         }
1372     }
1373
1374     return result;
1375 }
1376
1377 static NSData *dumpFrameAsPDF(WebFrame *frame)
1378 {
1379 #if !PLATFORM(IOS)
1380     if (!frame)
1381         return nil;
1382
1383     // Sadly we have to dump to a file and then read from that file again
1384     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1385     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1386     // The goal of this function is to test "real" printing across multiple pages.
1387     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1388     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1389
1390     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1391     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1392     [printInfoDict setObject:path forKey:NSPrintSavePath];
1393
1394     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1395     [printInfo setHorizontalPagination:NSAutoPagination];
1396     [printInfo setVerticalPagination:NSAutoPagination];
1397     [printInfo setVerticallyCentered:NO];
1398
1399     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1400     [printOperation setShowPanels:NO];
1401     [printOperation runOperation];
1402
1403     [printInfo release];
1404
1405     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1406     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1407
1408     return pdfData;
1409 #else
1410     return nil;
1411 #endif
1412 }
1413
1414 static void dumpBackForwardListForWebView(WebView *view)
1415 {
1416     printf("\n============== Back Forward List ==============\n");
1417     WebBackForwardList *bfList = [view backForwardList];
1418
1419     // Print out all items in the list after prevTestBFItem, which was from the previous test
1420     // Gather items from the end of the list, the print them out from oldest to newest
1421     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1422     for (int i = [bfList forwardListCount]; i > 0; i--) {
1423         WebHistoryItem *item = [bfList itemAtIndex:i];
1424         // something is wrong if the item from the last test is in the forward part of the b/f list
1425         assert(item != prevTestBFItem);
1426         [itemsToPrint addObject:item];
1427     }
1428             
1429     assert([bfList currentItem] != prevTestBFItem);
1430     [itemsToPrint addObject:[bfList currentItem]];
1431     int currentItemIndex = [itemsToPrint count] - 1;
1432
1433     for (int i = -1; i >= -[bfList backListCount]; i--) {
1434         WebHistoryItem *item = [bfList itemAtIndex:i];
1435         if (item == prevTestBFItem)
1436             break;
1437         [itemsToPrint addObject:item];
1438     }
1439
1440     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1441         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1442
1443     [itemsToPrint release];
1444     printf("===============================================\n");
1445 }
1446
1447 #if !PLATFORM(IOS)
1448 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1449 {
1450     bool hasHighDPIWindow = [[[mainFrame webView] window] backingScaleFactor] != 1;
1451     WTF::String localPathOrUrl = String(testPathOrUR);
1452     bool needsHighDPIWindow = localPathOrUrl.findIgnoringCase("hidpi-") != notFound;
1453     if (hasHighDPIWindow == needsHighDPIWindow)
1454         return;
1455
1456     CGFloat newScaleFactor = needsHighDPIWindow ? 2 : 1;
1457     // When the new scale factor is set on the window first, WebView doesn't see it as a new scale and stops propagating the behavior change to WebCore::Page.
1458     gTestRunner->setBackingScaleFactor(newScaleFactor);
1459     [[[mainFrame webView] window] _setWindowResolution:newScaleFactor displayIfChanged:YES];
1460 }
1461 #endif
1462
1463 static void sizeWebViewForCurrentTest()
1464 {
1465     // W3C SVG tests expect to be 480x360
1466     bool isSVGW3CTest = (gTestRunner->testPathOrURL().find("svg/W3C-SVG-1.1") != string::npos);
1467     if (isSVGW3CTest)
1468         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1469     else
1470         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1471 }
1472
1473 static const char *methodNameStringForFailedTest()
1474 {
1475     const char *errorMessage;
1476     if (gTestRunner->dumpAsText())
1477         errorMessage = "[documentElement innerText]";
1478     else if (gTestRunner->dumpDOMAsWebArchive())
1479         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1480     else if (gTestRunner->dumpSourceAsWebArchive())
1481         errorMessage = "[[mainFrame dataSource] webArchive]";
1482     else
1483         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1484
1485     return errorMessage;
1486 }
1487
1488 static void dumpBackForwardListForAllWindows()
1489 {
1490     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1491     unsigned count = CFArrayGetCount(openWindows);
1492     for (unsigned i = 0; i < count; i++) {
1493         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1494 #if !PLATFORM(IOS)
1495         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1496 #else
1497         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1498         WebView *webView = (WebView *)[window contentView];
1499 #endif
1500         dumpBackForwardListForWebView(webView);
1501     }
1502 }
1503
1504 static void invalidateAnyPreviousWaitToDumpWatchdog()
1505 {
1506     if (waitToDumpWatchdog) {
1507         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1508         CFRelease(waitToDumpWatchdog);
1509         waitToDumpWatchdog = 0;
1510     }
1511 }
1512
1513 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1514 {
1515     ASSERT(timer);
1516     ASSERT(shouldSetWaitToDumpWatchdog());
1517     waitToDumpWatchdog = timer;
1518     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1519 }
1520
1521 bool shouldSetWaitToDumpWatchdog()
1522 {
1523     return !waitToDumpWatchdog && useTimeoutWatchdog;
1524 }
1525
1526 static void updateDisplay()
1527 {
1528     WebView *webView = [mainFrame webView];
1529
1530     if ([webView _isUsingAcceleratedCompositing])
1531         [webView display];
1532     else
1533         [webView displayIfNeeded];
1534
1535     [webView _flushCompositingChanges];
1536 }
1537
1538 void dump()
1539 {
1540 #if PLATFORM(IOS)
1541     // This can get called on the web thread if from a JavaScript notifyDone().
1542     if (WebThreadIsCurrent()) {
1543         [(DumpRenderTree *)UIApp _deferDumpToMainThread];
1544         return;
1545     }
1546     WebThreadLock();
1547 #endif
1548
1549     updateDisplay();
1550
1551     invalidateAnyPreviousWaitToDumpWatchdog();
1552     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1553
1554     if (dumpTree) {
1555         NSString *resultString = nil;
1556         NSData *resultData = nil;
1557         NSString *resultMimeType = @"text/plain";
1558
1559         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1560             gTestRunner->setDumpAsText(true);
1561             gTestRunner->setGeneratePixelResults(false);
1562         }
1563         if (gTestRunner->dumpAsAudio()) {
1564             resultData = dumpAudio();
1565             resultMimeType = @"audio/wav";
1566         } else if (gTestRunner->dumpAsText()) {
1567             resultString = dumpFramesAsText(mainFrame);
1568         } else if (gTestRunner->dumpAsPDF()) {
1569             resultData = dumpFrameAsPDF(mainFrame);
1570             resultMimeType = @"application/pdf";
1571         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1572             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1573             resultString = CFBridgingRelease(createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1574             resultMimeType = @"application/x-webarchive";
1575         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1576             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1577             resultString = CFBridgingRelease(createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1578             resultMimeType = @"application/x-webarchive";
1579         } else
1580             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1581
1582         if (resultString && !resultData)
1583             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1584
1585         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1586
1587         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1588         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1589
1590         if (gTestRunner->dumpAsAudio())
1591             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1592
1593         if (resultData) {
1594             fwrite([resultData bytes], 1, [resultData length], stdout);
1595
1596             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1597                 dumpFrameScrollPosition(mainFrame);
1598
1599             if (gTestRunner->dumpBackForwardList())
1600                 dumpBackForwardListForAllWindows();
1601         } else
1602             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1603
1604         // Stop the watchdog thread before we leave this test to make sure it doesn't
1605         // fire in between tests causing the next test to fail.
1606         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1607         invalidateAnyPreviousWaitToDumpWatchdog();
1608
1609         if (printSeparators) {
1610             puts("#EOF");       // terminate the content block
1611             fputs("#EOF\n", stderr);
1612         }            
1613     }
1614
1615     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1616         // FIXME: when isPrinting is set, dump the image with page separators.
1617         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1618
1619     puts("#EOF");   // terminate the (possibly empty) pixels block
1620
1621     fflush(stdout);
1622     fflush(stderr);
1623
1624     done = YES;
1625     CFRunLoopStop(CFRunLoopGetMain());
1626 }
1627
1628 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1629 {
1630     return strstr(pathOrURL, "loading/");
1631 }
1632
1633 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1634 {
1635     return strstr(pathOrURL, "globalhistory/");
1636 }
1637
1638 static bool shouldDumpAsText(const char* pathOrURL)
1639 {
1640     return strstr(pathOrURL, "dumpAsText/");
1641 }
1642
1643 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1644 {
1645     return true;
1646 }
1647
1648 #if PLATFORM(IOS)
1649 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1650 {
1651     return strstr(pathOrURL, "viewport/");
1652 }
1653 #endif
1654
1655 static void resetWebViewToConsistentStateBeforeTesting()
1656 {
1657     WebView *webView = [mainFrame webView];
1658 #if PLATFORM(IOS)
1659     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1660     [webView _setAllowsMessaging:YES];
1661     [mainFrame setMediaDataLoadsAutomatically:YES];
1662 #endif
1663     [webView setEditable:NO];
1664     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1665     [webView makeTextStandardSize:nil];
1666     [webView resetPageZoom:nil];
1667     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1668 #if !PLATFORM(IOS)
1669     [webView _setCustomBackingScaleFactor:0];
1670 #endif
1671     [webView setTabKeyCyclesThroughElements:YES];
1672     [webView setPolicyDelegate:defaultPolicyDelegate];
1673     [policyDelegate setPermissive:NO];
1674     [policyDelegate setControllerToNotifyDone:0];
1675     [frameLoadDelegate resetToConsistentState];
1676 #if !PLATFORM(IOS)
1677     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1678 #endif
1679     [webView _clearMainFrameName];
1680     [[webView undoManager] removeAllActions];
1681     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1682 #if !PLATFORM(IOS)
1683     [[webView window] setAutodisplay:NO];
1684 #endif
1685     [webView setTracksRepaints:NO];
1686     
1687     resetWebPreferencesToConsistentValues();
1688
1689     TestRunner::setSerializeHTTPLoads(false);
1690
1691     setlocale(LC_ALL, "");
1692
1693     if (gTestRunner) {
1694         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1695         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1696         gTestRunner->removeChromeInputField();
1697     }
1698
1699 #if !PLATFORM(IOS)
1700     [webView setContinuousSpellCheckingEnabled:YES];
1701     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1702     [webView setAutomaticLinkDetectionEnabled:NO];
1703     [webView setAutomaticDashSubstitutionEnabled:NO];
1704     [webView setAutomaticTextReplacementEnabled:NO];
1705     [webView setAutomaticSpellingCorrectionEnabled:YES];
1706     [webView setGrammarCheckingEnabled:YES];
1707
1708     [WebView _setUsesTestModeFocusRingColor:YES];
1709 #endif
1710     [WebView _resetOriginAccessWhitelists];
1711     [WebView _setAllowsRoundingHacks:NO];
1712
1713     [[MockGeolocationProvider shared] stopTimer];
1714     [[MockWebNotificationProvider shared] reset];
1715     
1716 #if !PLATFORM(IOS)
1717     // Clear the contents of the general pasteboard
1718     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1719 #endif
1720
1721     [mainFrame _clearOpener];
1722 }
1723
1724 #if PLATFORM(IOS)
1725 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1726 // the main thread is not thread safe. If the web thread is attempting to call
1727 // out to a delegate method on the main thread, we want to spin the main thread
1728 // run loop until the delegate method completes before taking the web thread
1729 // lock to prevent potentially re-entering WebCore.
1730 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1731 {
1732     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1733     WebThreadRun(^{
1734         dispatch_semaphore_signal(delegateSemaphore);
1735     });
1736
1737     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1738         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1739         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1740         [pool release];
1741     }
1742
1743     WebThreadLock();
1744     
1745     dispatch_release(delegateSemaphore);
1746 }
1747 #endif
1748
1749 static void runTest(const string& inputLine)
1750 {
1751     ASSERT(!inputLine.empty());
1752
1753     TestCommand command = parseInputLine(inputLine);
1754     const string& pathOrURL = command.pathOrURL;
1755     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1756
1757     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1758     if (!pathOrURLString) {
1759         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1760         return;
1761     }
1762
1763     NSURL *url;
1764     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1765         url = [NSURL URLWithString:pathOrURLString];
1766     else
1767         url = [NSURL fileURLWithPath:pathOrURLString];
1768     if (!url) {
1769         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1770         return;
1771     }
1772
1773     const char* testURL([[url absoluteString] UTF8String]);
1774     
1775     resetWebViewToConsistentStateBeforeTesting();
1776 #if !PLATFORM(IOS)
1777     changeWindowScaleIfNeeded(testURL);
1778 #endif
1779
1780     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
1781     topLoadingFrame = nil;
1782 #if !PLATFORM(IOS)
1783     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1784     releaseAndZero(&draggingInfo);
1785 #endif
1786     done = NO;
1787
1788     sizeWebViewForCurrentTest();
1789     gTestRunner->setIconDatabaseEnabled(false);
1790
1791     if (disallowedURLs)
1792         CFSetRemoveAllValues(disallowedURLs);
1793     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1794         gTestRunner->setDumpFrameLoadCallbacks(true);
1795
1796     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1797         [[mainFrame webView] setHistoryDelegate:historyDelegate];
1798     else
1799         [[mainFrame webView] setHistoryDelegate:nil];
1800
1801     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1802         gTestRunner->setDeveloperExtrasEnabled(true);
1803         if (shouldDumpAsText(pathOrURL.c_str())) {
1804             gTestRunner->setDumpAsText(true);
1805             gTestRunner->setGeneratePixelResults(false);
1806         }
1807     }
1808
1809 #if PLATFORM(IOS)
1810     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
1811         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
1812 #endif
1813
1814     if ([WebHistory optionalSharedHistory])
1815         [WebHistory setOptionalSharedHistory:nil];
1816     lastMousePosition = NSZeroPoint;
1817     lastClickPosition = NSZeroPoint;
1818
1819     [prevTestBFItem release];
1820     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
1821
1822     WorkQueue::shared()->clear();
1823     WorkQueue::shared()->setFrozen(false);
1824
1825     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
1826     if (ignoreWebCoreNodeLeaks)
1827         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
1828
1829     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1830     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
1831     [pool release];
1832
1833     while (!done) {
1834         pool = [[NSAutoreleasePool alloc] init];
1835         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
1836         [pool release];
1837     }
1838
1839 #if PLATFORM(IOS)
1840     [(DumpRenderTree *)UIApp _waitForWebThread];
1841     WebThreadLockAfterDelegateCallbacksHaveCompleted();
1842 #endif
1843     pool = [[NSAutoreleasePool alloc] init];
1844     [EventSendingController clearSavedEvents];
1845     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
1846
1847     WorkQueue::shared()->clear();
1848
1849     if (gTestRunner->closeRemainingWindowsWhenComplete()) {
1850         NSArray* array = [DumpRenderTreeWindow openWindows];
1851
1852         unsigned count = [array count];
1853         for (unsigned i = 0; i < count; i++) {
1854             NSWindow *window = [array objectAtIndex:i];
1855
1856             // Don't try to close the main window
1857             if (window == [[mainFrame webView] window])
1858                 continue;
1859             
1860 #if !PLATFORM(IOS)
1861             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1862 #else
1863             ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1864             WebView *webView = (WebView *)[window contentView];
1865 #endif
1866
1867             [webView close];
1868             [window close];
1869         }
1870     }
1871
1872     // If developer extras enabled Web Inspector may have been open by the test.
1873     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1874         gTestRunner->closeWebInspector();
1875         gTestRunner->setDeveloperExtrasEnabled(false);
1876     }
1877
1878     resetWebViewToConsistentStateBeforeTesting();
1879
1880     // Loading an empty request synchronously replaces the document with a blank one, which is necessary
1881     // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
1882     [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
1883
1884     [pool release];
1885
1886     // We should only have our main window left open when we're done
1887     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
1888     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
1889
1890     gTestRunner.clear();
1891
1892     if (ignoreWebCoreNodeLeaks)
1893         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
1894
1895     if (gcBetweenTests)
1896         [WebCoreStatistics garbageCollectJavaScriptObjects];
1897 }
1898
1899 void displayWebView()
1900 {
1901 #if !PLATFORM(IOS)
1902     WebView *webView = [mainFrame webView];
1903     [webView display];
1904     
1905     [webView setTracksRepaints:YES];
1906     [webView resetTrackedRepaints];
1907 #else
1908     // FIXME: <rdar://problem/5106253> DumpRenderTree: fix DRT and ImageDiff to re-enable pixel tests
1909     [gDrtWindow layoutTilesNow];
1910     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
1911     [CATransaction flush];
1912 #endif
1913 }
1914
1915 #if !PLATFORM(IOS)
1916 @implementation DumpRenderTreeEvent
1917
1918 + (NSPoint)mouseLocation
1919 {
1920     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
1921 }
1922
1923 @end
1924
1925 @implementation DumpRenderTreeApplication
1926
1927 - (BOOL)isRunning
1928 {
1929     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
1930     return YES;
1931 }
1932
1933 @end
1934 #endif