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