[WTF] Add environment variable helpers
[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/Environment.h>
95 #import <wtf/FastMalloc.h>
96 #import <wtf/LoggingAccumulator.h>
97 #import <wtf/ObjCRuntimeExtras.h>
98 #import <wtf/ProcessPrivilege.h>
99 #import <wtf/RetainPtr.h>
100 #import <wtf/Threading.h>
101 #import <wtf/text/StringBuilder.h>
102 #import <wtf/text/WTFString.h>
103
104 #if !PLATFORM(IOS_FAMILY)
105 #import <Carbon/Carbon.h>
106 #import <WebKit/WebDynamicScrollBarsView.h>
107 #endif
108
109 #if PLATFORM(IOS_FAMILY)
110 #import "DumpRenderTreeBrowserView.h"
111 #import "IOSLayoutTestCommunication.h"
112 #import "UIKitSPI.h"
113 #import <QuartzCore/QuartzCore.h>
114 #import <WebKit/WAKWindow.h>
115 #import <WebKit/WebCoreThread.h>
116 #import <WebKit/WebCoreThreadRun.h>
117 #import <WebKit/WebDOMOperations.h>
118 #import <fcntl.h>
119 #import <pal/spi/cg/CoreGraphicsSPI.h>
120 #endif
121
122 extern "C" {
123 #import <mach-o/getsect.h>
124 }
125
126 using namespace std;
127
128 #if !PLATFORM(IOS_FAMILY)
129 @interface DumpRenderTreeApplication : NSApplication
130 @end
131
132 @interface DumpRenderTreeEvent : NSEvent
133 @end
134 #else
135 @interface ScrollViewResizerDelegate : NSObject
136 @end
137
138 @implementation ScrollViewResizerDelegate
139 - (void)view:(UIWebDocumentView *)view didSetFrame:(CGRect)newFrame oldFrame:(CGRect)oldFrame asResultOfZoom:(BOOL)wasResultOfZoom
140 {
141     UIView *scrollView = [view superview];
142     while (![scrollView isKindOfClass:[UIWebScrollView class]])
143         scrollView = [scrollView superview];
144
145     ASSERT(scrollView && [scrollView isKindOfClass:[UIWebScrollView class]]);
146     const CGSize scrollViewSize = [scrollView bounds].size;
147     CGSize contentSize = newFrame.size;
148     contentSize.height = CGRound(max(CGRectGetMaxY(newFrame), scrollViewSize.height));
149     [(UIWebScrollView *)scrollView setContentSize:contentSize];
150 }
151 @end
152 #endif
153
154 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
155 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
156 @end
157
158 #if USE(APPKIT)
159 @interface NSSound ()
160 + (void)_setAlertType:(NSUInteger)alertType;
161 @end
162 #endif
163
164 @interface WebView ()
165 - (BOOL)_flushCompositingChanges;
166 @end
167
168 #if !PLATFORM(IOS_FAMILY)
169 @interface WebView (WebViewInternalForTesting)
170 - (WebCore::Frame*)_mainCoreFrame;
171 @end
172 #endif
173
174 static void runTest(const string& testURL);
175
176 // Deciding when it's OK to dump out the state is a bit tricky.  All these must be true:
177 // - There is no load in progress
178 // - There is no work queued up (see workQueue var, below)
179 // - waitToDump==NO.  This means either waitUntilDone was never called, or it was called
180 //       and notifyDone was called subsequently.
181 // Note that the call to notifyDone and the end of the load can happen in either order.
182
183 volatile bool done;
184
185 NavigationController* gNavigationController = nullptr;
186 RefPtr<TestRunner> gTestRunner;
187
188 Optional<TestOptions> mainFrameTestOptions;
189 WebFrame *mainFrame = nil;
190 // This is the topmost frame that is loading, during a given load, or nil when no load is 
191 // in progress.  Usually this is the same as the main frame, but not always.  In the case
192 // where a frameset is loaded, and then new content is loaded into one of the child frames,
193 // that child frame is the "topmost frame that is loading".
194 WebFrame *topLoadingFrame = nil; // !nil iff a load is in progress
195
196 #if PLATFORM(MAC)
197 NSWindow *mainWindow = nil;
198 #endif
199
200 CFMutableSetRef disallowedURLs= nullptr;
201 static CFRunLoopTimerRef waitToDumpWatchdog;
202
203 // Delegates
204 static FrameLoadDelegate *frameLoadDelegate;
205 static UIDelegate *uiDelegate;
206 static EditingDelegate *editingDelegate;
207 static ResourceLoadDelegate *resourceLoadDelegate;
208 static HistoryDelegate *historyDelegate;
209 PolicyDelegate *policyDelegate = nullptr;
210 DefaultPolicyDelegate *defaultPolicyDelegate = nullptr;
211 #if PLATFORM(IOS_FAMILY)
212 static ScrollViewResizerDelegate *scrollViewResizerDelegate;
213 #endif
214
215 static int dumpPixelsForAllTests;
216 static bool dumpPixelsForCurrentTest;
217 static int threaded;
218 static int dumpTree = YES;
219 static int useTimeoutWatchdog = YES;
220 static int forceComplexText;
221 static int useAcceleratedDrawing;
222 static int gcBetweenTests;
223 static int allowAnyHTTPSCertificateForAllowedHosts;
224 static int showWebView;
225 static int printTestCount;
226 static int checkForWorldLeaks;
227 static BOOL printSeparators;
228 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
229 static std::set<std::string> allowedHosts;
230
231 static WebHistoryItem *prevTestBFItem; // current b/f item at the end of the previous test
232
233 #if PLATFORM(IOS_FAMILY)
234 const CGRect layoutTestViewportRect = { {0, 0}, {static_cast<CGFloat>(TestRunner::viewWidth), static_cast<CGFloat>(TestRunner::viewHeight)} };
235 DumpRenderTreeBrowserView *gWebBrowserView = nil;
236 DumpRenderTreeWebScrollView *gWebScrollView = nil;
237 DumpRenderTreeWindow *gDrtWindow = nil;
238 #endif
239
240 #ifdef __OBJC2__
241 static void swizzleAllMethods(Class imposter, Class original)
242 {
243     unsigned int imposterMethodCount;
244     Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
245
246     unsigned int originalMethodCount;
247     Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
248
249     for (unsigned int i = 0; i < imposterMethodCount; i++) {
250         SEL imposterMethodName = method_getName(imposterMethods[i]);
251
252         // Attempt to add the method to the original class.  If it fails, the method already exists and we should
253         // instead exchange the implementations.
254         if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
255             continue;
256
257         unsigned int j = 0;
258         for (; j < originalMethodCount; j++) {
259             SEL originalMethodName = method_getName(originalMethods[j]);
260             if (sel_isEqual(imposterMethodName, originalMethodName))
261                 break;
262         }
263
264         // If class_addMethod failed above then the method must exist on the original class.
265         ASSERT(j < originalMethodCount);
266         method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
267     }
268
269     free(imposterMethods);
270     free(originalMethods);
271 }
272 #endif
273
274 static void poseAsClass(const char* imposter, const char* original)
275 {
276     Class imposterClass = objc_getClass(imposter);
277     Class originalClass = objc_getClass(original);
278
279 #ifndef __OBJC2__
280     class_poseAs(imposterClass, originalClass);
281 #else
282
283     // Swizzle instance methods
284     swizzleAllMethods(imposterClass, originalClass);
285     // and then class methods
286     swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
287 #endif
288 }
289
290 void setPersistentUserStyleSheetLocation(CFStringRef url)
291 {
292     persistentUserStyleSheetLocation = url;
293 }
294
295 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
296 {
297     static char* const ignoreSet[] = {
298         // Keeping this infrastructure around in case we ever need it again.
299     };
300     static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
301
302     for (int i = 0; i < ignoreSetCount; i++) {
303         // FIXME: ignore case
304         string curIgnore(ignoreSet[i]);
305         // Match at the end of the URLString
306         if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
307             return true;
308     }
309     return false;
310 }
311
312 #if !PLATFORM(IOS_FAMILY)
313 static NSSet *allowedFontFamilySet()
314 {
315     static NSSet *fontFamilySet = [[NSSet setWithObjects:
316         @"Ahem",
317         @"Al Bayan",
318         @"American Typewriter",
319         @"Andale Mono",
320         @"Apple Braille",
321         @"Apple Color Emoji",
322         @"Apple Chancery",
323         @"Apple Garamond BT",
324         @"Apple LiGothic",
325         @"Apple LiSung",
326         @"Apple Symbols",
327         @"AppleGothic",
328         @"AppleMyungjo",
329         @"Arial Black",
330         @"Arial Hebrew",
331         @"Arial Narrow",
332         @"Arial Rounded MT Bold",
333         @"Arial Unicode MS",
334         @"Arial",
335         @"Avenir Next",
336         @"Ayuthaya",
337         @"Baghdad",
338         @"Baskerville",
339         @"BiauKai",
340         @"Big Caslon",
341         @"Brush Script MT",
342         @"Chalkboard",
343         @"Chalkduster",
344         @"Charcoal CY",
345         @"Cochin",
346         @"Comic Sans MS",
347         @"Copperplate",
348         @"Corsiva Hebrew",
349         @"Courier New",
350         @"Courier",
351         @"DecoType Naskh",
352         @"Devanagari MT",
353         @"Didot",
354         @"Euphemia UCAS",
355         @"Futura",
356         @"GB18030 Bitmap",
357         @"Geeza Pro",
358         @"Geneva CY",
359         @"Geneva",
360         @"Georgia",
361         @"Gill Sans",
362         @"Gujarati MT",
363         @"GungSeo",
364         @"Gurmukhi MT",
365         @"HeadLineA",
366         @"Hei",
367         @"Heiti SC",
368         @"Heiti TC",
369         @"Helvetica CY",
370         @"Helvetica Neue",
371         @"Helvetica",
372         @"Herculanum",
373         @"Hiragino Kaku Gothic Pro",
374         @"Hiragino Kaku Gothic ProN",
375         @"Hiragino Kaku Gothic Std",
376         @"Hiragino Kaku Gothic StdN",
377         @"Hiragino Maru Gothic Pro",
378         @"Hiragino Maru Gothic ProN",
379         @"Hiragino Mincho Pro",
380         @"Hiragino Mincho ProN",
381         @"Hiragino Sans",
382         @"Hiragino Sans GB",
383         @"Hoefler Text",
384         @"Impact",
385         @"InaiMathi",
386         @"Kai",
387         @"Kailasa",
388         @"Kokonor",
389         @"Krungthep",
390         @"KufiStandardGK",
391         @"Lao Sangam MN",
392         @"LastResort",
393         @"LiHei Pro",
394         @"LiSong Pro",
395         @"Lucida Grande",
396         @"Marker Felt",
397         @"Menlo",
398         @"Microsoft Sans Serif",
399         @"Monaco",
400         @"Mshtakan",
401         @"Nadeem",
402         @"New Peninim MT",
403         @"Optima",
404         @"Osaka",
405         @"Palatino",
406         @"Papyrus",
407         @"PCMyungjo",
408         @"PilGi",
409         @"PingFang HK",
410         @"PingFang SC",
411         @"PingFang TC",
412         @"Plantagenet Cherokee",
413         @"Raanana",
414         @"Sathu",
415         @"Silom",
416         @"Skia",
417         @"Snell Roundhand",
418         @"Songti SC",
419         @"Songti TC",
420         @"STFangsong",
421         @"STHeiti",
422         @"STIXGeneral",
423         @"STIXSizeOneSym",
424         @"STKaiti",
425         @"STSong",
426         @"Symbol",
427         @"Tahoma",
428         @"Thonburi",
429         @"Times New Roman",
430         @"Times",
431         @"Trebuchet MS",
432         @"Verdana",
433         @"Webdings",
434         @"WebKit WeightWatcher",
435         @"FontWithFeaturesOTF",
436         @"FontWithFeaturesTTF",
437         @"Wingdings 2",
438         @"Wingdings 3",
439         @"Wingdings",
440         @"Zapf Dingbats",
441         @"Zapfino",
442         nil] retain];
443
444     return fontFamilySet;
445 }
446
447 static NSArray *fontWhitelist()
448 {
449     static NSArray *availableFonts;
450     if (availableFonts)
451         return availableFonts;
452
453     NSMutableArray *availableFontList = [[NSMutableArray alloc] init];
454     for (NSString *fontFamily in allowedFontFamilySet()) {
455         NSArray* fontsForFamily = [[NSFontManager sharedFontManager] availableMembersOfFontFamily:fontFamily];
456         [availableFontList addObject:fontFamily];
457         for (NSArray* fontInfo in fontsForFamily) {
458             // Font name is the first entry in the array.
459             [availableFontList addObject:[fontInfo objectAtIndex:0]];
460         }
461     }
462
463     availableFonts = availableFontList;
464     return availableFonts;
465 }
466
467 // Activating system copies of these fonts overrides any others that could be preferred, such as ones
468 // in /Library/Fonts/Microsoft, and which don't always have the same metrics.
469 // FIXME: Switch to a solution from <rdar://problem/19553550> once it's available.
470 static void activateSystemCoreWebFonts()
471 {
472     NSArray *coreWebFontNames = @[
473         @"Andale Mono",
474         @"Arial",
475         @"Arial Black",
476         @"Comic Sans MS",
477         @"Courier New",
478         @"Georgia",
479         @"Impact",
480         @"Times New Roman",
481         @"Trebuchet MS",
482         @"Verdana",
483         @"Webdings"
484     ];
485
486     NSArray *fontFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL fileURLWithPath:@"/Library/Fonts" isDirectory:YES]
487         includingPropertiesForKeys:@[NSURLFileResourceTypeKey, NSURLNameKey] options:0 error:0];
488
489     for (NSURL *fontURL in fontFiles) {
490         NSString *resourceType;
491         NSString *fileName;
492         if (![fontURL getResourceValue:&resourceType forKey:NSURLFileResourceTypeKey error:0]
493             || ![fontURL getResourceValue:&fileName forKey:NSURLNameKey error:0])
494             continue;
495         if (![resourceType isEqualToString:NSURLFileResourceTypeRegular])
496             continue;
497
498         // Activate all font variations, such as Arial Bold Italic.ttf. This algorithm is not 100% precise, as it
499         // also activates e.g. Arial Unicode, which is not a variation of Arial.
500         for (NSString *coreWebFontName in coreWebFontNames) {
501             if ([fileName hasPrefix:coreWebFontName]) {
502                 CTFontManagerRegisterFontsForURL((CFURLRef)fontURL, kCTFontManagerScopeProcess, 0);
503                 break;
504             }
505         }
506     }
507 }
508
509 static void activateTestingFonts()
510 {
511     static const char* fontFileNames[] = {
512         "AHEM____.TTF",
513         "WebKitWeightWatcher100.ttf",
514         "WebKitWeightWatcher200.ttf",
515         "WebKitWeightWatcher300.ttf",
516         "WebKitWeightWatcher400.ttf",
517         "WebKitWeightWatcher500.ttf",
518         "WebKitWeightWatcher600.ttf",
519         "WebKitWeightWatcher700.ttf",
520         "WebKitWeightWatcher800.ttf",
521         "WebKitWeightWatcher900.ttf",
522         "FontWithFeatures.ttf",
523         "FontWithFeatures.otf",
524         0
525     };
526
527     NSMutableArray *fontURLs = [NSMutableArray array];
528     NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
529     for (unsigned i = 0; fontFileNames[i]; ++i) {
530         NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]] isDirectory:NO];
531         [fontURLs addObject:[fontURL absoluteURL]];
532     }
533
534     CFArrayRef errors = 0;
535     if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
536         NSLog(@"Failed to activate fonts: %@", errors);
537         CFRelease(errors);
538         exit(1);
539     }
540 }
541
542 static void adjustFonts()
543 {
544     activateSystemCoreWebFonts();
545     activateTestingFonts();
546 }
547 #else
548 static void activateFontIOS(const uint8_t* fontData, unsigned long length, std::string sectionName)
549 {
550     CGDataProviderRef data = CGDataProviderCreateWithData(nullptr, fontData, length, nullptr);
551     if (!data) {
552         fprintf(stderr, "Failed to create CGDataProviderRef for the %s font.\n", sectionName.c_str());
553         exit(1);
554     }
555
556     CGFontRef cgFont = CGFontCreateWithDataProvider(data);
557     CGDataProviderRelease(data);
558     if (!cgFont) {
559         fprintf(stderr, "Failed to create CGFontRef for the %s font.\n", sectionName.c_str());
560         exit(1);
561     }
562
563     CFErrorRef error = nullptr;
564     CTFontManagerRegisterGraphicsFont(cgFont, &error);
565     if (error) {
566         fprintf(stderr, "Failed to add CGFont to CoreText for the %s font: %s.\n", sectionName.c_str(), CFStringGetCStringPtr(CFErrorCopyDescription(error), kCFStringEncodingUTF8));
567         exit(1);
568     }
569     CGFontRelease(cgFont);
570 }
571
572 static void activateFontsIOS()
573 {
574     // __asm() requires a string literal, so we can't do this as either local variables or template parameters.
575 #define fontData(sectionName) \
576 { \
577     extern const uint8_t start##sectionName __asm("section$start$__DATA$" # sectionName); \
578     extern const uint8_t end##sectionName __asm("section$end$__DATA$" # sectionName); \
579     activateFontIOS(&start##sectionName, &end##sectionName - &start##sectionName, #sectionName); \
580 }
581     fontData(Ahem);
582     fontData(WeightWatcher100);
583     fontData(WeightWatcher200);
584     fontData(WeightWatcher300);
585     fontData(WeightWatcher400);
586     fontData(WeightWatcher500);
587     fontData(WeightWatcher600);
588     fontData(WeightWatcher700);
589     fontData(WeightWatcher800);
590     fontData(WeightWatcher900);
591     fontData(FWFTTF);
592     fontData(FWFOTF);
593 }
594 #endif // !PLATFORM(IOS_FAMILY)
595
596
597 #if PLATFORM(IOS_FAMILY)
598 static void adjustWebDocumentForFlexibleViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
599 {
600     // These values match MobileSafari's, see -[TabDocument _createDocumentView].
601     [webBrowserView setMinimumScale:0.25f forDocumentTypes:UIEveryDocumentMask];
602     [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
603     [webBrowserView setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:UIEveryDocumentMask];
604     [webBrowserView setViewportSize:CGSizeMake(UIWebViewStandardViewportWidth, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:UIEveryDocumentMask];
605
606     // Adjust the viewport view and viewport to have similar behavior
607     // as the browser.
608     [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:YES];
609     [webBrowserView setDelegate:scrollViewResizerDelegate];
610
611     CGRect screenBounds = [UIScreen mainScreen].bounds;
612     CGRect viewportRect = CGRectMake(0, 0, screenBounds.size.width, screenBounds.size.height);
613
614     [scrollView setBounds:viewportRect];
615     [scrollView setFrame:viewportRect];
616
617     [webBrowserView setMinimumSize:viewportRect.size];
618     [webBrowserView setAutoresizes:YES];
619     [webBrowserView setFrame:screenBounds];
620
621     // This just affects text autosizing.
622     [mainFrame _setVisibleSize:CGSizeMake(screenBounds.size.width, screenBounds.size.height)];
623 }
624
625 static void adjustWebDocumentForStandardViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
626 {
627     [webBrowserView setMinimumScale:1.0f forDocumentTypes:UIEveryDocumentMask];
628     [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
629     [webBrowserView setInitialScale:1.0f forDocumentTypes:UIEveryDocumentMask];
630
631     [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:NO];
632     [webBrowserView setDelegate: nil];
633
634     [scrollView setBounds:layoutTestViewportRect];
635     [scrollView setFrame:layoutTestViewportRect];
636
637     [webBrowserView setMinimumSize:layoutTestViewportRect.size];
638     [webBrowserView setAutoresizes:NO];
639     [webBrowserView setFrame:layoutTestViewportRect];
640
641     // This just affects text autosizing.
642     [mainFrame _setVisibleSize:CGSizeMake(layoutTestViewportRect.size.width, layoutTestViewportRect.size.height)];
643
644 }
645 #endif
646
647 #if !PLATFORM(IOS_FAMILY)
648 @interface DRTMockScroller : NSScroller
649 @end
650
651 @implementation DRTMockScroller
652
653 - (NSRect)rectForPart:(NSScrollerPart)partCode
654 {
655     if (partCode != NSScrollerKnob)
656         return [super rectForPart:partCode];
657
658     NSRect frameRect = [self frame];
659     NSRect bounds = [self bounds];
660     BOOL isHorizontal = frameRect.size.width > frameRect.size.height;
661     CGFloat trackLength = isHorizontal ? bounds.size.width : bounds.size.height;
662     CGFloat minKnobSize = isHorizontal ? bounds.size.height : bounds.size.width;
663     CGFloat knobLength = max(minKnobSize, static_cast<CGFloat>(round(trackLength * [self knobProportion])));
664     CGFloat knobPosition = static_cast<CGFloat>((round([self doubleValue] * (trackLength - knobLength))));
665
666     if (isHorizontal)
667         return NSMakeRect(bounds.origin.x + knobPosition, bounds.origin.y, knobLength, bounds.size.height);
668
669     return NSMakeRect(bounds.origin.x, bounds.origin.y +  + knobPosition, bounds.size.width, knobLength);
670 }
671
672 - (void)drawKnob
673 {
674     if (![self isEnabled])
675         return;
676
677     NSRect knobRect = [self rectForPart:NSScrollerKnob];
678
679     static NSColor *knobColor = [[NSColor colorWithDeviceRed:0x80 / 255.0 green:0x80 / 255.0 blue:0x80 / 255.0 alpha:1] retain];
680     [knobColor set];
681
682     NSRectFill(knobRect);
683 }
684
685 - (void)drawRect:(NSRect)dirtyRect
686 {
687     static NSColor *trackColor = [[NSColor colorWithDeviceRed:0xC0 / 255.0 green:0xC0 / 255.0 blue:0xC0 / 255.0 alpha:1] retain];
688     static NSColor *disabledTrackColor = [[NSColor colorWithDeviceRed:0xE0 / 255.0 green:0xE0 / 255.0 blue:0xE0 / 255.0 alpha:1] retain];
689
690     if ([self isEnabled])
691         [trackColor set];
692     else
693         [disabledTrackColor set];
694
695     NSRectFill(dirtyRect);
696
697     [self drawKnob];
698 }
699
700 @end
701
702 static void registerMockScrollbars()
703 {
704     [WebDynamicScrollBarsView setCustomScrollerClass:[DRTMockScroller class]];
705 }
706 #endif
707
708 WebView *createWebViewAndOffscreenWindow()
709 {
710 #if !PLATFORM(IOS_FAMILY)
711     NSRect rect = NSMakeRect(0, 0, TestRunner::viewWidth, TestRunner::viewHeight);
712     WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
713 #else
714     DumpRenderTreeBrowserView *webBrowserView = [[[DumpRenderTreeBrowserView alloc] initWithFrame:layoutTestViewportRect] autorelease];
715     [webBrowserView setInputViewObeysDOMFocus:YES];
716     WebView *webView = [[webBrowserView webView] retain];
717     [webView setGroupName:@"org.webkit.DumpRenderTree"];
718 #endif
719
720     [webView setUIDelegate:uiDelegate];
721     [webView setFrameLoadDelegate:frameLoadDelegate];
722     [webView setEditingDelegate:editingDelegate];
723     [webView setResourceLoadDelegate:resourceLoadDelegate];
724     [webView _setGeolocationProvider:[MockGeolocationProvider shared]];
725     [webView _setDeviceOrientationProvider:[WebDeviceOrientationProviderMock shared]];
726     [webView _setNotificationProvider:[MockWebNotificationProvider shared]];
727
728     // Register the same schemes that Safari does
729     [WebView registerURLSchemeAsLocal:@"feed"];
730     [WebView registerURLSchemeAsLocal:@"feeds"];
731     [WebView registerURLSchemeAsLocal:@"feedsearch"];
732
733 #if PLATFORM(MAC)
734     [webView setWindowOcclusionDetectionEnabled:NO];
735     [WebView _setFontWhitelist:fontWhitelist()];
736 #endif
737
738 #if !PLATFORM(IOS_FAMILY)
739     [webView setContinuousSpellCheckingEnabled:YES];
740     [webView setAutomaticQuoteSubstitutionEnabled:NO];
741     [webView setAutomaticLinkDetectionEnabled:NO];
742     [webView setAutomaticDashSubstitutionEnabled:NO];
743     [webView setAutomaticTextReplacementEnabled:NO];
744     [webView setAutomaticSpellingCorrectionEnabled:YES];
745     [webView setGrammarCheckingEnabled:YES];
746
747     [webView setDefersCallbacks:NO];
748     [webView setInteractiveFormValidationEnabled:YES];
749     [webView setValidationMessageTimerMagnification:-1];
750
751     // 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.
752     // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
753     NSScreen *firstScreen = [[NSScreen screens] firstObject];
754     NSRect windowRect = (showWebView) ? NSOffsetRect(rect, 100, 100) : NSOffsetRect(rect, -10000, [firstScreen frame].size.height - rect.size.height + 10000);
755     DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
756     mainWindow = window;
757
758     [window setColorSpace:[firstScreen colorSpace]];
759     [window setCollectionBehavior:NSWindowCollectionBehaviorStationary];
760     [[window contentView] addSubview:webView];
761     if (showWebView)
762         [window orderFront:nil];
763     else
764         [window orderBack:nil];
765     [window setAutodisplay:NO];
766
767     [window startListeningForAcceleratedCompositingChanges];
768 #else
769     DumpRenderTreeWindow *drtWindow = [[DumpRenderTreeWindow alloc] initWithLayer:[webBrowserView layer]];
770     [drtWindow setContentView:webView];
771     [webBrowserView setWAKWindow:drtWindow];
772
773     [[webView window] makeFirstResponder:[[[webView mainFrame] frameView] documentView]];
774
775     CGRect uiWindowRect = layoutTestViewportRect;
776     uiWindowRect.origin.y += [UIApp statusBarHeight];
777     UIWindow *uiWindow = [[[UIWindow alloc] initWithFrame:uiWindowRect] autorelease];
778
779     UIViewController *viewController = [[UIViewController alloc] init];
780     [uiWindow setRootViewController:viewController];
781     [viewController release];
782
783     // The UIWindow and UIWebBrowserView are released when the DumpRenderTreeWindow is closed.
784     drtWindow.uiWindow = uiWindow;
785     drtWindow.browserView = webBrowserView;
786
787     DumpRenderTreeWebScrollView *scrollView = [[DumpRenderTreeWebScrollView alloc] initWithFrame:layoutTestViewportRect];
788     [scrollView addSubview:webBrowserView];
789
790     [viewController.view addSubview:scrollView];
791     [scrollView release];
792
793     adjustWebDocumentForStandardViewport(webBrowserView, scrollView);
794 #endif
795
796 #if !PLATFORM(IOS_FAMILY)
797     // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
798     // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
799     NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
800     [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
801 #else
802     [[webView preferences] _setTelephoneNumberParsingEnabled:NO];
803
804     // Initialize the global UIViews, and set the key UIWindow to be painted.
805     if (!gWebBrowserView) {
806         gWebBrowserView = [webBrowserView retain];
807         gWebScrollView = [scrollView retain];
808         gDrtWindow = [drtWindow retain];
809         [uiWindow makeKeyAndVisible];
810         [uiWindow retain];
811     }
812 #endif
813
814     [webView setMediaVolume:0];
815
816     return webView;
817 }
818
819 static void destroyWebViewAndOffscreenWindow(WebView *webView)
820 {
821     ASSERT(webView == [mainFrame webView]);
822 #if !PLATFORM(IOS_FAMILY)
823     NSWindow *window = [webView window];
824 #endif
825     [webView close];
826     mainFrame = nil;
827
828 #if !PLATFORM(IOS_FAMILY)
829     // Work around problem where registering drag types leaves an outstanding
830     // "perform selector" on the window, which retains the window. It's a bit
831     // inelegant and perhaps dangerous to just blow them all away, but in practice
832     // it probably won't cause any trouble (and this is just a test tool, after all).
833     [NSObject cancelPreviousPerformRequestsWithTarget:window];
834
835     [window close]; // releases when closed
836 #else
837     UIWindow *uiWindow = [gWebBrowserView window];
838     [uiWindow removeFromSuperview];
839     [uiWindow release];
840 #endif
841
842     [webView release];
843 }
844
845 static NSString *libraryPathForDumpRenderTree()
846 {
847     if (const char* dumpRenderTreeTemp = Environment::getRaw("DUMPRENDERTREE_TEMP"))
848         return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
849
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