Wrap legacy WebRTC API in runtime flag
[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 setWebRTCLegacyAPIEnabled:YES];
853     [preferences setCredentialManagementEnabled:YES];
854 }
855
856 // Called before each test.
857 static void resetWebPreferencesToConsistentValues()
858 {
859     WebPreferences *preferences = [WebPreferences standardPreferences];
860     enableExperimentalFeatures(preferences);
861
862     [preferences setNeedsStorageAccessFromFileURLsQuirk: NO];
863     [preferences setAllowUniversalAccessFromFileURLs:YES];
864     [preferences setAllowFileAccessFromFileURLs:YES];
865     [preferences setStandardFontFamily:@"Times"];
866     [preferences setFixedFontFamily:@"Courier"];
867     [preferences setSerifFontFamily:@"Times"];
868     [preferences setSansSerifFontFamily:@"Helvetica"];
869     [preferences setCursiveFontFamily:@"Apple Chancery"];
870     [preferences setFantasyFontFamily:@"Papyrus"];
871     [preferences setPictographFontFamily:@"Apple Color Emoji"];
872     [preferences setDefaultFontSize:16];
873     [preferences setDefaultFixedFontSize:13];
874     [preferences setMinimumFontSize:0];
875     [preferences setDefaultTextEncodingName:@"ISO-8859-1"];
876     [preferences setJavaEnabled:NO];
877     [preferences setJavaScriptEnabled:YES];
878     [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
879 #if !PLATFORM(IOS)
880     [preferences setTabsToLinks:NO];
881 #endif
882     [preferences setDOMPasteAllowed:YES];
883 #if !PLATFORM(IOS)
884     [preferences setShouldPrintBackgrounds:YES];
885 #endif
886     [preferences setCacheModel:WebCacheModelDocumentBrowser];
887     [preferences setXSSAuditorEnabled:NO];
888     [preferences setExperimentalNotificationsEnabled:NO];
889     [preferences setPlugInsEnabled:YES];
890 #if !PLATFORM(IOS)
891     [preferences setTextAreasAreResizable:YES];
892 #endif
893
894     [preferences setPrivateBrowsingEnabled:NO];
895     [preferences setAuthorAndUserStylesEnabled:YES];
896     [preferences setShrinksStandaloneImagesToFit:YES];
897     [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
898     [preferences setJavaScriptCanAccessClipboard:YES];
899     [preferences setOfflineWebApplicationCacheEnabled:YES];
900     [preferences setDeveloperExtrasEnabled:NO];
901     [preferences setJavaScriptRuntimeFlags:WebKitJavaScriptRuntimeFlagsAllEnabled];
902     [preferences setLoadsImagesAutomatically:YES];
903     [preferences setLoadsSiteIconsIgnoringImageLoadingPreference:NO];
904     [preferences setFrameFlatteningEnabled:NO];
905     [preferences setSpatialNavigationEnabled:NO];
906     [preferences setMetaRefreshEnabled:YES];
907
908     if (persistentUserStyleSheetLocation) {
909         [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
910         [preferences setUserStyleSheetEnabled:YES];
911     } else
912         [preferences setUserStyleSheetEnabled:NO];
913
914     [preferences setMediaPlaybackAllowsInline:YES];
915     [preferences setVideoPlaybackRequiresUserGesture:NO];
916     [preferences setAudioPlaybackRequiresUserGesture:NO];
917     [preferences setMediaDataLoadsAutomatically:YES];
918     [preferences setInvisibleAutoplayNotPermitted:NO];
919     [preferences setSubpixelAntialiasedLayerTextEnabled:NO];
920
921 #if PLATFORM(IOS)
922     // Enable the tracker before creating the first WebView will
923     // cause initialization to use the correct database paths.
924     [preferences setStorageTrackerEnabled:YES];
925 #endif
926
927     [preferences _setTextAutosizingEnabled:NO];
928
929     // The back/forward cache is causing problems due to layouts during transition from one page to another.
930     // So, turn it off for now, but we might want to turn it back on some day.
931     [preferences setUsesPageCache:NO];
932     [preferences setAcceleratedCompositingEnabled:YES];
933 #if USE(CA)
934     [preferences setCanvasUsesAcceleratedDrawing:YES];
935     [preferences setAcceleratedDrawingEnabled:useAcceleratedDrawing];
936 #endif
937     [preferences setUsePreHTML5ParserQuirks:NO];
938     [preferences setAsynchronousSpellCheckingEnabled:NO];
939 #if !PLATFORM(IOS)
940     ASSERT([preferences mockScrollbarsEnabled]);
941 #endif
942
943     [preferences setWebAudioEnabled:YES];
944     [preferences setMediaSourceEnabled:YES];
945
946     [preferences setShadowDOMEnabled:YES];
947     [preferences setCustomElementsEnabled:YES];
948
949     [preferences setWebGL2Enabled:YES];
950     [preferences setWebGPUEnabled:YES];
951
952     [preferences setFetchAPIEnabled:YES];
953
954     [preferences setDownloadAttributeEnabled:YES];
955
956     [preferences setHiddenPageDOMTimerThrottlingEnabled:NO];
957     [preferences setHiddenPageCSSAnimationSuspensionEnabled:NO];
958     
959     [preferences setMediaStreamEnabled:YES];
960     
961     [preferences setLargeImageAsyncDecodingEnabled:NO];
962
963     [WebPreferences _clearNetworkLoaderSession];
964     [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
965 }
966
967 static void setWebPreferencesForTestOptions(const TestOptions& options)
968 {
969     WebPreferences *preferences = [WebPreferences standardPreferences];
970
971     preferences.intersectionObserverEnabled = options.enableIntersectionObserver;
972     preferences.modernMediaControlsEnabled = options.enableModernMediaControls;
973     preferences.credentialManagementEnabled = options.enableCredentialManagement;
974 }
975
976 // Called once on DumpRenderTree startup.
977 static void setDefaultsToConsistentValuesForTesting()
978 {
979 #if PLATFORM(IOS)
980     WebThreadLock();
981 #endif
982
983     static const int NoFontSmoothing = 0;
984     static const int BlueTintedAppearance = 1;
985
986     NSString *libraryPath = libraryPathForDumpRenderTree();
987
988     NSDictionary *dict = @{
989         @"AppleKeyboardUIMode": @1,
990         @"AppleAntiAliasingThreshold": @4,
991         @"AppleFontSmoothing": @(NoFontSmoothing),
992         @"AppleAquaColorVariant": @(BlueTintedAppearance),
993         @"AppleHighlightColor": @"0.709800 0.835300 1.000000",
994         @"AppleOtherHighlightColor":@"0.500000 0.500000 0.500000",
995         @"AppleLanguages": @[ @"en" ],
996         WebKitEnableFullDocumentTeardownPreferenceKey: @YES,
997         WebKitFullScreenEnabledPreferenceKey: @YES,
998         WebKitAllowsInlineMediaPlaybackPreferenceKey: @YES,
999         WebKitInlineMediaPlaybackRequiresPlaysInlineAttributeKey: @NO,
1000         @"UseWebKitWebInspector": @YES,
1001 #if !PLATFORM(IOS)
1002         @"NSPreferredSpellServerLanguage": @"en_US",
1003         @"NSUserDictionaryReplacementItems": @[],
1004         @"NSTestCorrectionDictionary": @{
1005             @"notationl": @"notational",
1006             @"mesage": @"message",
1007             @"wouldn": @"would",
1008             @"wellcome": @"welcome",
1009             @"hellolfworld": @"hello\nworld"
1010         },
1011 #endif
1012         @"AppleScrollBarVariant": @"DoubleMax",
1013 #if !PLATFORM(IOS)
1014         @"NSScrollAnimationEnabled": @NO,
1015 #endif
1016         @"NSOverlayScrollersEnabled": @NO,
1017         @"AppleShowScrollBars": @"Always",
1018         @"NSButtonAnimationsEnabled": @NO, // Ideally, we should find a way to test animations, but for now, make sure that the dumped snapshot matches actual state.
1019 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1020         @"AppleSystemFontOSSubversion": @(10),
1021 #endif
1022         @"NSWindowDisplayWithRunLoopObserver": @YES, // Temporary workaround, see <rdar://problem/20351297>.
1023         @"AppleEnableSwipeNavigateWithScrolls": @YES,
1024         @"com.apple.swipescrolldirection": @1,
1025     };
1026
1027     [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:dict];
1028
1029 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1030     // Make NSFont use the new defaults.
1031     [NSFont initialize];
1032 #endif
1033
1034     NSDictionary *processInstanceDefaults = @{
1035         WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
1036         WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1037         WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"],
1038         WebKitResourceLoadStatisticsDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1039 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1040         // This needs to also be added to argument domain because of <rdar://problem/20210002>.
1041         @"AppleSystemFontOSSubversion": @(10),
1042 #endif
1043     };
1044
1045     [[NSUserDefaults standardUserDefaults] setVolatileDomain:processInstanceDefaults forName:NSArgumentDomain];
1046 }
1047
1048 static void runThread(void* arg)
1049 {
1050     static ThreadIdentifier previousId = 0;
1051     ThreadIdentifier currentId = currentThread();
1052     // Verify 2 successive threads do not get the same Id.
1053     ASSERT(previousId != currentId);
1054     previousId = currentId;
1055 }
1056
1057 static void* runPthread(void* arg)
1058 {
1059     runThread(arg);
1060     return 0;
1061 }
1062
1063 static void testThreadIdentifierMap()
1064 {
1065     // Imitate 'foreign' threads that are not created by WTF.
1066     pthread_t pthread;
1067     pthread_create(&pthread, 0, &runPthread, 0);
1068     pthread_join(pthread, 0);
1069
1070     pthread_create(&pthread, 0, &runPthread, 0);
1071     pthread_join(pthread, 0);
1072
1073     // Now create another thread using WTF. On OSX, it will have the same pthread handle
1074     // but should get a different ThreadIdentifier.
1075     createThread(runThread, 0, "DumpRenderTree: test");
1076 }
1077
1078 static void allocateGlobalControllers()
1079 {
1080     // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
1081     gNavigationController = [[NavigationController alloc] init];
1082     frameLoadDelegate = [[FrameLoadDelegate alloc] init];
1083     uiDelegate = [[UIDelegate alloc] init];
1084     editingDelegate = [[EditingDelegate alloc] init];
1085     resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
1086     policyDelegate = [[PolicyDelegate alloc] init];
1087     historyDelegate = [[HistoryDelegate alloc] init];
1088     defaultPolicyDelegate = [[DefaultPolicyDelegate alloc] init];
1089 #if PLATFORM(IOS)
1090     scrollViewResizerDelegate = [[ScrollViewResizerDelegate alloc] init];
1091 #endif
1092 }
1093
1094 // ObjC++ doens't seem to let me pass NSObject*& sadly.
1095 static inline void releaseAndZero(NSObject** object)
1096 {
1097     [*object release];
1098     *object = nil;
1099 }
1100
1101 static void releaseGlobalControllers()
1102 {
1103     releaseAndZero(&gNavigationController);
1104     releaseAndZero(&frameLoadDelegate);
1105     releaseAndZero(&editingDelegate);
1106     releaseAndZero(&resourceLoadDelegate);
1107     releaseAndZero(&uiDelegate);
1108     releaseAndZero(&policyDelegate);
1109 #if PLATFORM(IOS)
1110     releaseAndZero(&scrollViewResizerDelegate);
1111 #endif
1112 }
1113
1114 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
1115 {
1116     struct option options[] = {
1117         {"notree", no_argument, &dumpTree, NO},
1118         {"pixel-tests", no_argument, &dumpPixelsForAllTests, YES},
1119         {"tree", no_argument, &dumpTree, YES},
1120         {"threaded", no_argument, &threaded, YES},
1121         {"complex-text", no_argument, &forceComplexText, YES},
1122         {"accelerated-drawing", no_argument, &useAcceleratedDrawing, YES},
1123         {"gc-between-tests", no_argument, &gcBetweenTests, YES},
1124         {"no-timeout", no_argument, &useTimeoutWatchdog, NO},
1125         {"allowed-host", required_argument, nullptr, 'a'},
1126         {"show-webview", no_argument, &showWebView, YES},
1127         {"print-test-count", no_argument, &printTestCount, YES},
1128         {nullptr, 0, nullptr, 0}
1129     };
1130     
1131     int option;
1132     while ((option = getopt_long(argc, (char * const *)argv, "", options, nullptr)) != -1) {
1133         switch (option) {
1134             case '?':   // unknown or ambiguous option
1135             case ':':   // missing argument
1136                 exit(1);
1137                 break;
1138             case 'a': // "allowed-host"
1139                 allowedHosts.insert(optarg);
1140                 break;
1141         }
1142     }
1143 }
1144
1145 static void addTestPluginsToPluginSearchPath(const char* executablePath)
1146 {
1147 #if !PLATFORM(IOS)
1148     NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
1149     [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
1150     [[WebPluginDatabase sharedDatabase] refresh];
1151 #endif
1152 }
1153
1154 static bool useLongRunningServerMode(int argc, const char *argv[])
1155 {
1156     // This assumes you've already called getopt_long
1157     return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
1158 }
1159
1160 static void runTestingServerLoop()
1161 {
1162     // When DumpRenderTree run in server mode, we just wait around for file names
1163     // to be passed to us and read each in turn, passing the results back to the client
1164     char filenameBuffer[2048];
1165     unsigned testCount = 0;
1166     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1167         char *newLineCharacter = strchr(filenameBuffer, '\n');
1168         if (newLineCharacter)
1169             *newLineCharacter = '\0';
1170
1171         if (strlen(filenameBuffer) == 0)
1172             continue;
1173
1174         runTest(filenameBuffer);
1175
1176         if (printTestCount) {
1177             ++testCount;
1178             printf("\nServer mode has completed %u tests.\n\n", testCount);
1179         }
1180     }
1181 }
1182
1183 static void prepareConsistentTestingEnvironment()
1184 {
1185 #if !PLATFORM(IOS)
1186     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1187     poseAsClass("DumpRenderTreeEvent", "NSEvent");
1188 #else
1189     poseAsClass("DumpRenderTreeEvent", "GSEvent");
1190 #endif
1191
1192     [[WebPreferences standardPreferences] setAutosaves:NO];
1193
1194     // +[WebPreferences _switchNetworkLoaderToNewTestingSession] calls +[NSURLCache sharedURLCache], which initializes a default cache on disk.
1195     // Making the shared cache memory-only avoids touching the file system.
1196     RetainPtr<NSURLCache> sharedCache =
1197         adoptNS([[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1198                                       diskCapacity:0
1199                                           diskPath:nil]);
1200     [NSURLCache setSharedURLCache:sharedCache.get()];
1201
1202     [WebPreferences _switchNetworkLoaderToNewTestingSession];
1203
1204 #if !PLATFORM(IOS)
1205     adjustFonts();
1206     registerMockScrollbars();
1207
1208     // The mock scrollbars setting cannot be modified after creating a view, so we have to do it now.
1209     [[WebPreferences standardPreferences] setMockScrollbarsEnabled:YES];
1210 #else
1211     activateFontsIOS();
1212 #endif
1213     
1214     allocateGlobalControllers();
1215     
1216 #if PLATFORM(MAC)
1217     NSActivityOptions options = (NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical) & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled);
1218     static id assertion = [[[NSProcessInfo processInfo] beginActivityWithOptions:options reason:@"DumpRenderTree should not be subject to process suppression"] retain];
1219     ASSERT_UNUSED(assertion, assertion);
1220 #endif
1221 }
1222
1223 const char crashedMessage[] = "#CRASHED\n";
1224
1225 void writeCrashedMessageOnFatalError(int signalCode)
1226 {
1227     // Reset the default action for the signal so that we run ReportCrash(8) on pending and
1228     // subsequent instances of the signal.
1229     signal(signalCode, SIG_DFL);
1230
1231     // WRITE(2) and FSYNC(2) are considered safe to call from a signal handler by SIGACTION(2).
1232     write(STDERR_FILENO, &crashedMessage[0], sizeof(crashedMessage) - 1);
1233     fsync(STDERR_FILENO);
1234 }
1235
1236 void dumpRenderTree(int argc, const char *argv[])
1237 {
1238 #if PLATFORM(IOS)
1239     const char* identifier = getenv("IPC_IDENTIFIER");
1240     const char *stdinPath = [[NSString stringWithFormat:@"/tmp/%s_IN", identifier] UTF8String];
1241     const char *stdoutPath = [[NSString stringWithFormat:@"/tmp/%s_OUT", identifier] UTF8String];
1242     const char *stderrPath = [[NSString stringWithFormat:@"/tmp/%s_ERROR", identifier] UTF8String];
1243
1244     int infd = open(stdinPath, O_RDWR);
1245     dup2(infd, STDIN_FILENO);
1246     int outfd = open(stdoutPath, O_RDWR);
1247     dup2(outfd, STDOUT_FILENO);
1248     int errfd = open(stderrPath, O_RDWR | O_NONBLOCK);
1249     dup2(errfd, STDERR_FILENO);
1250 #endif
1251
1252     signal(SIGILL, &writeCrashedMessageOnFatalError);
1253     signal(SIGFPE, &writeCrashedMessageOnFatalError);
1254     signal(SIGBUS, &writeCrashedMessageOnFatalError);
1255     signal(SIGSEGV, &writeCrashedMessageOnFatalError);
1256
1257     initializeGlobalsFromCommandLineOptions(argc, argv);
1258     prepareConsistentTestingEnvironment();
1259     addTestPluginsToPluginSearchPath(argv[0]);
1260
1261     if (forceComplexText)
1262         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1263
1264 #if USE(APPKIT)
1265     [NSSound _setAlertType:0];
1266 #endif
1267
1268     WebView *webView = createWebViewAndOffscreenWindow();
1269     mainFrame = [webView mainFrame];
1270
1271     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1272     [WebCache empty];
1273
1274     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1275     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1276
1277     // http://webkit.org/b/32689
1278     testThreadIdentifierMap();
1279
1280     if (threaded)
1281         startJavaScriptThreads();
1282
1283     if (useLongRunningServerMode(argc, argv)) {
1284         printSeparators = YES;
1285         runTestingServerLoop();
1286     } else {
1287         printSeparators = optind < argc - 1;
1288         for (int i = optind; i != argc; ++i)
1289             runTest(argv[i]);
1290     }
1291
1292     if (threaded)
1293         stopJavaScriptThreads();
1294
1295     destroyWebViewAndOffscreenWindow(webView);
1296     
1297     releaseGlobalControllers();
1298     
1299 #if !PLATFORM(IOS)
1300     [DumpRenderTreePasteboard releaseLocalPasteboards];
1301 #endif
1302
1303     // FIXME: This should be moved onto TestRunner and made into a HashSet
1304     if (disallowedURLs) {
1305         CFRelease(disallowedURLs);
1306         disallowedURLs = 0;
1307     }
1308
1309 #if PLATFORM(IOS)
1310     close(infd);
1311     close(outfd);
1312     close(errfd);
1313 #endif
1314 }
1315
1316 #if PLATFORM(IOS)
1317 static int _argc;
1318 static const char **_argv;
1319
1320 @implementation DumpRenderTree
1321
1322 - (void)_runDumpRenderTree
1323 {
1324     dumpRenderTree(_argc, _argv);
1325 }
1326
1327 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1328 {
1329     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1330 }
1331
1332 - (void)applicationDidEnterBackground:(UIApplication *)application
1333 {
1334     RELEASE_ASSERT_NOT_REACHED();
1335 }
1336
1337 - (void)_webThreadEventLoopHasRun
1338 {
1339     ASSERT(!WebThreadIsCurrent());
1340     _hasFlushedWebThreadRunQueue = YES;
1341 }
1342
1343 - (void)_webThreadInvoked
1344 {
1345     ASSERT(WebThreadIsCurrent());
1346     dispatch_async(dispatch_get_main_queue(), ^{
1347         [self _webThreadEventLoopHasRun];
1348     });
1349 }
1350
1351 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1352 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1353 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1354 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1355 - (void)_waitForWebThread
1356 {
1357     ASSERT(!WebThreadIsCurrent());
1358     _hasFlushedWebThreadRunQueue = NO;
1359     WebThreadRun(^{
1360         [self _webThreadInvoked];
1361     });
1362     while (!_hasFlushedWebThreadRunQueue) {
1363         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1364         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1365         [pool release];
1366     }
1367 }
1368
1369 @end
1370 #endif
1371
1372 static bool returningFromMain = false;
1373
1374 void atexitFunction()
1375 {
1376     if (returningFromMain)
1377         return;
1378
1379     NSLog(@"DumpRenderTree is exiting unexpectedly. Generating a crash log.");
1380     __builtin_trap();
1381 }
1382
1383 int DumpRenderTreeMain(int argc, const char *argv[])
1384 {
1385     atexit(atexitFunction);
1386
1387 #if PLATFORM(IOS)
1388     _UIApplicationLoadWebKit();
1389 #endif
1390     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1391
1392     setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1393
1394 #if !PLATFORM(IOS)
1395     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1396
1397     dumpRenderTree(argc, argv);
1398 #else
1399     _argc = argc;
1400     _argv = argv;
1401     UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", @"DumpRenderTree");
1402 #endif
1403     [WebCoreStatistics garbageCollectJavaScriptObjects];
1404     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1405     JSC::finalizeStatsAtEndOfTesting();
1406     [pool release];
1407     returningFromMain = true;
1408     return 0;
1409 }
1410
1411 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1412 {
1413     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1414 }
1415
1416 static NSData *dumpAudio()
1417 {
1418     const vector<char>& dataVector = gTestRunner->audioResult();
1419     
1420     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1421     return data;
1422 }
1423
1424 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1425 {
1426     int start = 0;
1427     if (current) {
1428         printf("curr->");
1429         start = 6;
1430     }
1431     for (int i = start; i < indent; i++)
1432         putchar(' ');
1433     
1434     NSString *urlString = [item URLString];
1435     if ([[NSURL URLWithString:urlString] isFileURL]) {
1436         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1437         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1438     }
1439     
1440     printf("%s", [urlString UTF8String]);
1441     NSString *target = [item target];
1442     if (target && [target length] > 0)
1443         printf(" (in frame \"%s\")", [target UTF8String]);
1444     if ([item isTargetItem])
1445         printf("  **nav target**");
1446     putchar('\n');
1447     NSArray *kids = [item children];
1448     if (kids) {
1449         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1450         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1451         for (unsigned i = 0; i < [kids count]; i++)
1452             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1453     }
1454 }
1455
1456 static void dumpFrameScrollPosition(WebFrame *f)
1457 {
1458     WebScriptObject* scriptObject = [f windowObject];
1459     NSPoint scrollPosition = NSMakePoint(
1460         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1461         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1462     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1463         if ([f parentFrame] != nil)
1464             printf("frame '%s' ", [[f name] UTF8String]);
1465         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1466     }
1467
1468     if (gTestRunner->dumpChildFrameScrollPositions()) {
1469         NSArray *kids = [f childFrames];
1470         if (kids)
1471             for (unsigned i = 0; i < [kids count]; i++)
1472                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1473     }
1474 }
1475
1476 static NSString *dumpFramesAsText(WebFrame *frame)
1477 {
1478     DOMDocument *document = [frame DOMDocument];
1479     DOMElement *documentElement = [document documentElement];
1480
1481     if (!documentElement)
1482         return @"";
1483
1484     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1485
1486     // Add header for all but the main frame.
1487     if ([frame parentFrame])
1488         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1489
1490     NSString *innerText = [documentElement innerText];
1491     // We use WKStringGetUTF8CStringNonStrict() to convert innerText to a WK String since
1492     // WKStringGetUTF8CStringNonStrict() can handle dangling surrogates and the NSString
1493     // conversion methods cannot. After the conversion to a buffer, we turn that buffer into
1494     // a CFString via fromUTF8WithLatin1Fallback().createCFString() which can be appended to
1495     // the result without any conversion.
1496     WKRetainPtr<WKStringRef> stringRef(AdoptWK, WKStringCreateWithCFString((CFStringRef)innerText));
1497     size_t bufferSize = WKStringGetMaximumUTF8CStringSize(stringRef.get());
1498     auto buffer = std::make_unique<char[]>(bufferSize);
1499     size_t stringLength = WKStringGetUTF8CStringNonStrict(stringRef.get(), buffer.get(), bufferSize);
1500     [result appendFormat:@"%@\n", String::fromUTF8WithLatin1Fallback(buffer.get(), stringLength - 1).createCFString().get()];
1501
1502     if (gTestRunner->dumpChildFramesAsText()) {
1503         NSArray *kids = [frame childFrames];
1504         if (kids) {
1505             for (unsigned i = 0; i < [kids count]; i++)
1506                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1507         }
1508     }
1509
1510     return result;
1511 }
1512
1513 static NSData *dumpFrameAsPDF(WebFrame *frame)
1514 {
1515 #if !PLATFORM(IOS)
1516     if (!frame)
1517         return nil;
1518
1519     // Sadly we have to dump to a file and then read from that file again
1520     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1521     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1522     // The goal of this function is to test "real" printing across multiple pages.
1523     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1524     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1525
1526     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1527     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1528     [printInfoDict setObject:path forKey:NSPrintSavePath];
1529
1530     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1531     [printInfo setHorizontalPagination:NSAutoPagination];
1532     [printInfo setVerticalPagination:NSAutoPagination];
1533     [printInfo setVerticallyCentered:NO];
1534
1535     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1536     [printOperation setShowPanels:NO];
1537     [printOperation runOperation];
1538
1539     [printInfo release];
1540
1541     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1542     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1543
1544     return pdfData;
1545 #else
1546     return nil;
1547 #endif
1548 }
1549
1550 static void dumpBackForwardListForWebView(WebView *view)
1551 {
1552     printf("\n============== Back Forward List ==============\n");
1553     WebBackForwardList *bfList = [view backForwardList];
1554
1555     // Print out all items in the list after prevTestBFItem, which was from the previous test
1556     // Gather items from the end of the list, the print them out from oldest to newest
1557     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1558     for (int i = [bfList forwardListCount]; i > 0; i--) {
1559         WebHistoryItem *item = [bfList itemAtIndex:i];
1560         // something is wrong if the item from the last test is in the forward part of the b/f list
1561         assert(item != prevTestBFItem);
1562         [itemsToPrint addObject:item];
1563     }
1564             
1565     assert([bfList currentItem] != prevTestBFItem);
1566     [itemsToPrint addObject:[bfList currentItem]];
1567     int currentItemIndex = [itemsToPrint count] - 1;
1568
1569     for (int i = -1; i >= -[bfList backListCount]; i--) {
1570         WebHistoryItem *item = [bfList itemAtIndex:i];
1571         if (item == prevTestBFItem)
1572             break;
1573         [itemsToPrint addObject:item];
1574     }
1575
1576     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1577         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1578
1579     [itemsToPrint release];
1580     printf("===============================================\n");
1581 }
1582
1583 #if !PLATFORM(IOS)
1584 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1585 {
1586     WTF::String localPathOrUrl = String(testPathOrUR);
1587     float currentScaleFactor = [[[mainFrame webView] window] backingScaleFactor];
1588     float requiredScaleFactor = 1;
1589     if (localPathOrUrl.findIgnoringCase("/hidpi-3x-") != notFound)
1590         requiredScaleFactor = 3;
1591     else if (localPathOrUrl.findIgnoringCase("/hidpi-") != notFound)
1592         requiredScaleFactor = 2;
1593     if (currentScaleFactor == requiredScaleFactor)
1594         return;
1595     // 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.
1596     gTestRunner->setBackingScaleFactor(requiredScaleFactor);
1597     [[[mainFrame webView] window] _setWindowResolution:requiredScaleFactor displayIfChanged:YES];
1598 }
1599 #endif
1600
1601 static void sizeWebViewForCurrentTest()
1602 {
1603     [uiDelegate resetWindowOrigin];
1604
1605     // W3C SVG tests expect to be 480x360
1606     bool isSVGW3CTest = (gTestRunner->testURL().find("svg/W3C-SVG-1.1") != string::npos);
1607     if (isSVGW3CTest)
1608         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1609     else
1610         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1611 }
1612
1613 static const char *methodNameStringForFailedTest()
1614 {
1615     const char *errorMessage;
1616     if (gTestRunner->dumpAsText())
1617         errorMessage = "[documentElement innerText]";
1618     else if (gTestRunner->dumpDOMAsWebArchive())
1619         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1620     else if (gTestRunner->dumpSourceAsWebArchive())
1621         errorMessage = "[[mainFrame dataSource] webArchive]";
1622     else
1623         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1624
1625     return errorMessage;
1626 }
1627
1628 static void dumpBackForwardListForAllWindows()
1629 {
1630     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1631     unsigned count = CFArrayGetCount(openWindows);
1632     for (unsigned i = 0; i < count; i++) {
1633         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1634 #if !PLATFORM(IOS)
1635         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1636 #else
1637         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1638         WebView *webView = (WebView *)[window contentView];
1639 #endif
1640         dumpBackForwardListForWebView(webView);
1641     }
1642 }
1643
1644 static void invalidateAnyPreviousWaitToDumpWatchdog()
1645 {
1646     if (waitToDumpWatchdog) {
1647         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1648         CFRelease(waitToDumpWatchdog);
1649         waitToDumpWatchdog = 0;
1650     }
1651 }
1652
1653 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1654 {
1655     ASSERT(timer);
1656     ASSERT(shouldSetWaitToDumpWatchdog());
1657     waitToDumpWatchdog = timer;
1658     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1659 }
1660
1661 bool shouldSetWaitToDumpWatchdog()
1662 {
1663     return !waitToDumpWatchdog && useTimeoutWatchdog;
1664 }
1665
1666 static void updateDisplay()
1667 {
1668     WebView *webView = [mainFrame webView];
1669 #if PLATFORM(IOS)
1670     [gWebBrowserView layoutIfNeeded]; // Re-enables tile painting, which was disabled when committing the frame load.
1671     [gDrtWindow layoutTilesNow];
1672     [webView _flushCompositingChanges];
1673 #else
1674     if ([webView _isUsingAcceleratedCompositing])
1675         [webView display];
1676     else
1677         [webView displayIfNeeded];
1678 #endif
1679 }
1680
1681 void dump()
1682 {
1683 #if PLATFORM(IOS)
1684     WebThreadLock();
1685 #endif
1686
1687     updateDisplay();
1688
1689     invalidateAnyPreviousWaitToDumpWatchdog();
1690     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1691
1692     if (dumpTree) {
1693         NSString *resultString = nil;
1694         NSData *resultData = nil;
1695         NSString *resultMimeType = @"text/plain";
1696
1697         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1698             gTestRunner->setDumpAsText(true);
1699             gTestRunner->setGeneratePixelResults(false);
1700         }
1701         if (gTestRunner->dumpAsAudio()) {
1702             resultData = dumpAudio();
1703             resultMimeType = @"audio/wav";
1704         } else if (gTestRunner->dumpAsText()) {
1705             resultString = dumpFramesAsText(mainFrame);
1706         } else if (gTestRunner->dumpAsPDF()) {
1707             resultData = dumpFrameAsPDF(mainFrame);
1708             resultMimeType = @"application/pdf";
1709         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1710             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1711             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1712             resultMimeType = @"application/x-webarchive";
1713         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1714             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1715             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1716             resultMimeType = @"application/x-webarchive";
1717         } else
1718             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1719
1720         if (resultString && !resultData)
1721             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1722
1723         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1724
1725         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1726         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1727
1728         if (gTestRunner->dumpAsAudio())
1729             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1730
1731         if (resultData) {
1732             fwrite([resultData bytes], 1, [resultData length], stdout);
1733
1734             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1735                 dumpFrameScrollPosition(mainFrame);
1736
1737             if (gTestRunner->dumpBackForwardList())
1738                 dumpBackForwardListForAllWindows();
1739         } else
1740             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1741
1742         // Stop the watchdog thread before we leave this test to make sure it doesn't
1743         // fire in between tests causing the next test to fail.
1744         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1745         invalidateAnyPreviousWaitToDumpWatchdog();
1746
1747         if (printSeparators)
1748             puts("#EOF");       // terminate the content block
1749     }
1750
1751     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1752         // FIXME: when isPrinting is set, dump the image with page separators.
1753         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1754
1755     puts("#EOF");   // terminate the (possibly empty) pixels block
1756     fflush(stdout);
1757
1758     done = YES;
1759     CFRunLoopStop(CFRunLoopGetMain());
1760 }
1761
1762 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1763 {
1764     return strstr(pathOrURL, "loading/");
1765 }
1766
1767 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1768 {
1769     return strstr(pathOrURL, "globalhistory/");
1770 }
1771
1772 static bool shouldDumpAsText(const char* pathOrURL)
1773 {
1774     return strstr(pathOrURL, "dumpAsText/");
1775 }
1776
1777 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1778 {
1779     return true;
1780 }
1781
1782 #if PLATFORM(IOS)
1783 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1784 {
1785     return strstr(pathOrURL, "viewport/") && !strstr(pathOrURL, "visual-viewport/");
1786 }
1787 #endif
1788
1789 static void resetWebViewToConsistentStateBeforeTesting(const TestOptions& options)
1790 {
1791     WebView *webView = [mainFrame webView];
1792
1793 #if PLATFORM(IOS)
1794     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1795     [webView _setAllowsMessaging:YES];
1796 #endif
1797     [webView setEditable:NO];
1798     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1799     [webView makeTextStandardSize:nil];
1800     [webView resetPageZoom:nil];
1801     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1802 #if !PLATFORM(IOS)
1803     [webView _setCustomBackingScaleFactor:0];
1804 #endif
1805     [webView setTabKeyCyclesThroughElements:YES];
1806     [webView setPolicyDelegate:defaultPolicyDelegate];
1807     [policyDelegate setPermissive:NO];
1808     [policyDelegate setControllerToNotifyDone:0];
1809     [frameLoadDelegate resetToConsistentState];
1810 #if !PLATFORM(IOS)
1811     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1812 #endif
1813     [webView _clearMainFrameName];
1814     [[webView undoManager] removeAllActions];
1815     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1816 #if !PLATFORM(IOS)
1817     [[webView window] setAutodisplay:NO];
1818 #endif
1819     [webView setTracksRepaints:NO];
1820
1821     [WebCache clearCachedCredentials];
1822     
1823     resetWebPreferencesToConsistentValues();
1824     setWebPreferencesForTestOptions(options);
1825
1826     TestRunner::setSerializeHTTPLoads(false);
1827     TestRunner::setAllowsAnySSLCertificate(false);
1828
1829     setlocale(LC_ALL, "");
1830
1831     if (gTestRunner) {
1832         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1833         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1834         gTestRunner->removeChromeInputField();
1835     }
1836
1837 #if !PLATFORM(IOS)
1838     if (WebCore::Frame* frame = [webView _mainCoreFrame])
1839         WebCoreTestSupport::clearWheelEventTestTrigger(*frame);
1840 #endif
1841
1842 #if !PLATFORM(IOS)
1843     [webView setContinuousSpellCheckingEnabled:YES];
1844     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1845     [webView setAutomaticLinkDetectionEnabled:NO];
1846     [webView setAutomaticDashSubstitutionEnabled:NO];
1847     [webView setAutomaticTextReplacementEnabled:NO];
1848     [webView setAutomaticSpellingCorrectionEnabled:YES];
1849     [webView setGrammarCheckingEnabled:YES];
1850
1851     [WebView _setUsesTestModeFocusRingColor:YES];
1852 #endif
1853     [WebView _resetOriginAccessWhitelists];
1854
1855     [[MockGeolocationProvider shared] stopTimer];
1856     [[MockWebNotificationProvider shared] reset];
1857     
1858 #if !PLATFORM(IOS)
1859     // Clear the contents of the general pasteboard
1860     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1861 #endif
1862
1863     [mainFrame _clearOpener];
1864
1865     setSpellCheckerLoggingEnabled(false);
1866
1867     resetAccumulatedLogs();
1868     WebCoreTestSupport::initializeLogChannelsIfNecessary();
1869 }
1870
1871 #if PLATFORM(IOS)
1872 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1873 // the main thread is not thread safe. If the web thread is attempting to call
1874 // out to a delegate method on the main thread, we want to spin the main thread
1875 // run loop until the delegate method completes before taking the web thread
1876 // lock to prevent potentially re-entering WebCore.
1877 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1878 {
1879     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1880     WebThreadRun(^{
1881         dispatch_semaphore_signal(delegateSemaphore);
1882     });
1883
1884     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1885         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1886         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1887         [pool release];
1888     }
1889
1890     WebThreadLock();
1891     
1892     dispatch_release(delegateSemaphore);
1893 }
1894 #endif
1895
1896 static NSURL *computeTestURL(NSString *pathOrURLString, NSString **relativeTestPath)
1897 {
1898     *relativeTestPath = nil;
1899
1900     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1901         return [NSURL URLWithString:pathOrURLString];
1902
1903     NSString *absolutePath = [[[NSURL fileURLWithPath:pathOrURLString] absoluteURL] path];
1904
1905     NSRange layoutTestsRange = [absolutePath rangeOfString:@"/LayoutTests/"];
1906     if (layoutTestsRange.location == NSNotFound)
1907         return [NSURL fileURLWithPath:absolutePath];
1908
1909     *relativeTestPath = [absolutePath substringFromIndex:NSMaxRange(layoutTestsRange)];
1910
1911     // Convert file URLs in LayoutTests/http/tests to HTTP URLs, except for file URLs in LayoutTests/http/tests/local.
1912
1913     NSRange httpTestsRange = [absolutePath rangeOfString:@"/LayoutTests/http/tests/"];
1914     if (httpTestsRange.location == NSNotFound || [absolutePath rangeOfString:@"/LayoutTests/http/tests/local/"].location != NSNotFound)
1915         return [NSURL fileURLWithPath:absolutePath];
1916
1917     auto components = adoptNS([[NSURLComponents alloc] init]);
1918     [components setPath:[absolutePath substringFromIndex:NSMaxRange(httpTestsRange) - 1]];
1919     [components setHost:@"127.0.0.1"];
1920
1921     // Paths under /ssl/ should be loaded using HTTPS.
1922     BOOL isSecure = [[components path] hasPrefix:@"/ssl/"];
1923     if (isSecure) {
1924         [components setScheme:@"https"];
1925         [components setPort:@(8443)];
1926     } else {
1927         [components setScheme:@"http"];
1928         [components setPort:@(8000)];
1929     }
1930
1931     return [components URL];
1932 }
1933
1934 static void runTest(const string& inputLine)
1935 {
1936     ASSERT(!inputLine.empty());
1937
1938     TestCommand command = parseInputLine(inputLine);
1939     const string& pathOrURL = command.pathOrURL;
1940     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1941
1942     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1943     if (!pathOrURLString) {
1944         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1945         return;
1946     }
1947
1948     NSString *testPath;
1949     NSURL *url = computeTestURL(pathOrURLString, &testPath);
1950     if (!url) {
1951         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1952         return;
1953     }
1954     if (!testPath)
1955         testPath = [url absoluteString];
1956
1957     NSString *informationString = [@"CRASHING TEST: " stringByAppendingString:testPath];
1958     WKSetCrashReportApplicationSpecificInformation((CFStringRef)informationString);
1959
1960     TestOptions options(url, command);
1961     resetWebViewToConsistentStateBeforeTesting(options);
1962
1963     const char* testURL([[url absoluteString] UTF8String]);
1964
1965 #if !PLATFORM(IOS)
1966     changeWindowScaleIfNeeded(testURL);
1967 #endif
1968
1969     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
1970     gTestRunner->setAllowedHosts(allowedHosts);
1971     gTestRunner->setCustomTimeout(command.timeout);
1972     gTestRunner->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr);
1973     topLoadingFrame = nil;
1974 #if !PLATFORM(IOS)
1975     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1976     releaseAndZero(&draggingInfo);
1977 #endif
1978     done = NO;
1979
1980     sizeWebViewForCurrentTest();
1981     gTestRunner->setIconDatabaseEnabled(false);
1982     gTestRunner->clearAllApplicationCaches();
1983
1984     if (disallowedURLs)
1985         CFSetRemoveAllValues(disallowedURLs);
1986     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1987         gTestRunner->setDumpFrameLoadCallbacks(true);
1988
1989     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1990         [[mainFrame webView] setHistoryDelegate:historyDelegate];
1991     else
1992         [[mainFrame webView] setHistoryDelegate:nil];
1993
1994     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1995         gTestRunner->setDeveloperExtrasEnabled(true);
1996         if (shouldDumpAsText(pathOrURL.c_str())) {
1997             gTestRunner->setDumpAsText(true);
1998             gTestRunner->setGeneratePixelResults(false);
1999         }
2000     }
2001
2002 #if PLATFORM(IOS)
2003     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
2004         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
2005 #endif
2006
2007     if ([WebHistory optionalSharedHistory])
2008         [WebHistory setOptionalSharedHistory:nil];
2009
2010     lastMousePosition = NSZeroPoint;
2011     lastClickPosition = NSZeroPoint;
2012
2013     [prevTestBFItem release];
2014     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
2015
2016     auto& workQueue = WorkQueue::singleton();
2017     workQueue.clear();
2018     workQueue.setFrozen(false);
2019
2020     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
2021     if (ignoreWebCoreNodeLeaks)
2022         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
2023
2024     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2025     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
2026     [pool release];
2027
2028     while (!done) {
2029         pool = [[NSAutoreleasePool alloc] init];
2030         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
2031         [pool release];
2032     }
2033
2034 #if PLATFORM(IOS)
2035     [(DumpRenderTree *)UIApp _waitForWebThread];
2036     WebThreadLockAfterDelegateCallbacksHaveCompleted();
2037 #endif
2038     pool = [[NSAutoreleasePool alloc] init];
2039     [EventSendingController clearSavedEvents];
2040     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
2041
2042     workQueue.clear();
2043
2044     // If the test page could have possibly opened the Web Inspector frontend,
2045     // then try to close it in case it was accidentally left open.
2046     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2047         gTestRunner->closeWebInspector();
2048         gTestRunner->setDeveloperExtrasEnabled(false);
2049     }
2050
2051 #if PLATFORM(MAC)
2052     // Make sure the WebView is parented, since the test may have unparented it.
2053     WebView *webView = [mainFrame webView];
2054     if (![webView superview])
2055         [[mainWindow contentView] addSubview:webView];
2056 #endif
2057
2058     if (gTestRunner->closeRemainingWindowsWhenComplete()) {
2059         NSArray* array = [DumpRenderTreeWindow openWindows];
2060
2061         unsigned count = [array count];
2062         for (unsigned i = 0; i < count; i++) {
2063             NSWindow *window = [array objectAtIndex:i];
2064
2065             // Don't try to close the main window
2066             if (window == [[mainFrame webView] window])
2067                 continue;
2068             
2069 #if !PLATFORM(IOS)
2070             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
2071 #else
2072             ASSERT([[window contentView] isKindOfClass:[WebView class]]);
2073             WebView *webView = (WebView *)[window contentView];
2074 #endif
2075
2076             [webView close];
2077             [window close];
2078         }
2079     }
2080
2081     resetWebViewToConsistentStateBeforeTesting(options);
2082
2083     // Loading an empty request synchronously replaces the document with a blank one, which is necessary
2084     // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
2085     [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
2086
2087     [pool release];
2088
2089     // We should only have our main window left open when we're done
2090     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
2091     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
2092
2093     gTestRunner->cleanup();
2094     gTestRunner = nullptr;
2095
2096     if (ignoreWebCoreNodeLeaks)
2097         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
2098
2099     if (gcBetweenTests)
2100         [WebCoreStatistics garbageCollectJavaScriptObjects];
2101
2102     fputs("#EOF\n", stderr);
2103     fflush(stderr);
2104 }
2105
2106 void displayWebView()
2107 {
2108 #if !PLATFORM(IOS)
2109     WebView *webView = [mainFrame webView];
2110     [webView display];
2111
2112     // FIXME: Tracking repaints is not specific to Mac. We should enable such support on iOS.
2113     [webView setTracksRepaints:YES];
2114     [webView resetTrackedRepaints];
2115 #else
2116     [gDrtWindow layoutTilesNow];
2117     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
2118     [CATransaction flush];
2119 #endif
2120 }
2121
2122 #if !PLATFORM(IOS)
2123 @implementation DumpRenderTreeEvent
2124
2125 + (NSPoint)mouseLocation
2126 {
2127     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
2128 }
2129
2130 @end
2131
2132 @implementation DumpRenderTreeApplication
2133
2134 - (BOOL)isRunning
2135 {
2136     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
2137     return YES;
2138 }
2139
2140 @end
2141 #endif