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