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