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