Delete WebMetal implementation in favor of WebGPU
[WebKit-https.git] / Tools / DumpRenderTree / mac / DumpRenderTree.mm
1 /*
2  * Copyright (C) 2005-2019 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     // FIXME: AsyncFrameScrollingEnabled
864     [preferences setCacheAPIEnabled:NO];
865     [preferences setReadableByteStreamAPIEnabled:YES];
866     [preferences setWritableStreamAPIEnabled:YES];
867     preferences.encryptedMediaAPIEnabled = YES;
868     [preferences setAccessibilityObjectModelEnabled:YES];
869     [preferences setAriaReflectionEnabled:YES];
870     [preferences setVisualViewportAPIEnabled:YES];
871     [preferences setColorFilterEnabled:YES];
872     [preferences setServerTimingEnabled:YES];
873     [preferences setIntersectionObserverEnabled:YES];
874     preferences.sourceBufferChangeTypeEnabled = YES;
875     [preferences setCSSOMViewScrollingAPIEnabled:YES];
876     [preferences setMediaRecorderEnabled:YES];
877     [preferences setReferrerPolicyAttributeEnabled: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
980     [preferences setDownloadAttributeEnabled:YES];
981     [preferences setDirectoryUploadEnabled:YES];
982
983     [preferences setHiddenPageDOMTimerThrottlingEnabled:NO];
984     [preferences setHiddenPageCSSAnimationSuspensionEnabled:NO];
985
986     [preferences setMediaDevicesEnabled:YES];
987
988     [preferences setLargeImageAsyncDecodingEnabled:NO];
989
990     [preferences setModernMediaControlsEnabled:YES];
991     [preferences setResourceTimingEnabled:YES];
992     [preferences setUserTimingEnabled:YES];
993
994     [preferences setCacheAPIEnabled:NO];
995     preferences.mediaCapabilitiesEnabled = YES;
996
997     preferences.selectionAcrossShadowBoundariesEnabled = YES;
998
999     [WebPreferences _clearNetworkLoaderSession];
1000     [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
1001 }
1002
1003 static void setWebPreferencesForTestOptions(const TestOptions& options)
1004 {
1005     WebPreferences *preferences = [WebPreferences standardPreferences];
1006
1007     preferences.attachmentElementEnabled = options.enableAttachmentElement;
1008     preferences.acceleratedDrawingEnabled = options.useAcceleratedDrawing;
1009     preferences.menuItemElementEnabled = options.enableMenuItemElement;
1010     preferences.modernMediaControlsEnabled = options.enableModernMediaControls;
1011     preferences.isSecureContextAttributeEnabled = options.enableIsSecureContextAttribute;
1012     preferences.inspectorAdditionsEnabled = options.enableInspectorAdditions;
1013     preferences.allowCrossOriginSubresourcesToAskForCredentials = options.allowCrossOriginSubresourcesToAskForCredentials;
1014     preferences.webAnimationsCSSIntegrationEnabled = options.enableWebAnimationsCSSIntegration;
1015     preferences.colorFilterEnabled = options.enableColorFilter;
1016     preferences.selectionAcrossShadowBoundariesEnabled = options.enableSelectionAcrossShadowBoundaries;
1017     preferences.webGPUEnabled = options.enableWebGPU;
1018     preferences.CSSLogicalEnabled = options.enableCSSLogical;
1019     preferences.adClickAttributionEnabled = options.adClickAttributionEnabled;
1020     preferences.resizeObserverEnabled = options.enableResizeObserver;
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 (!strncmp("#CHECK FOR WORLD LEAKS", command, 22) || !strncmp("#LIST CHILD PROCESSES", command, 21)) {
1170         // DumpRenderTree does not support checking for world leaks or listing child processes.
1171         WTF::String result("\n");
1172         unsigned resultLength = result.length();
1173         printf("Content-Type: text/plain\n");
1174         printf("Content-Length: %u\n", resultLength);
1175         fwrite(result.utf8().data(), 1, resultLength, stdout);
1176         printf("#EOF\n");
1177         fprintf(stderr, "#EOF\n");
1178         fflush(stdout);
1179         fflush(stderr);
1180         return true;
1181     }
1182     return false;
1183 }
1184
1185 static void runTestingServerLoop()
1186 {
1187     // When DumpRenderTree run in server mode, we just wait around for file names
1188     // to be passed to us and read each in turn, passing the results back to the client
1189     char filenameBuffer[2048];
1190     unsigned testCount = 0;
1191     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1192         char *newLineCharacter = strchr(filenameBuffer, '\n');
1193         if (newLineCharacter)
1194             *newLineCharacter = '\0';
1195
1196         if (strlen(filenameBuffer) == 0)
1197             continue;
1198
1199         if (handleControlCommand(filenameBuffer))
1200             continue;
1201
1202         runTest(filenameBuffer);
1203
1204         if (printTestCount) {
1205             ++testCount;
1206             printf("\nServer mode has completed %u tests.\n\n", testCount);
1207         }
1208     }
1209 }
1210
1211 #if PLATFORM(IOS_FAMILY)
1212 static BOOL overrideIsInHardwareKeyboardMode()
1213 {
1214     return NO;
1215 }
1216 #endif
1217
1218 static void prepareConsistentTestingEnvironment()
1219 {
1220 #if !PLATFORM(IOS_FAMILY)
1221     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1222     poseAsClass("DumpRenderTreeEvent", "NSEvent");
1223 #else
1224     poseAsClass("DumpRenderTreeEvent", "GSEvent");
1225
1226     // Override the implementation of +[UIKeyboard isInHardwareKeyboardMode] to ensure that test runs are deterministic
1227     // regardless of whether a hardware keyboard is attached. We intentionally never restore the original implementation.
1228     method_setImplementation(class_getClassMethod([UIKeyboard class], @selector(isInHardwareKeyboardMode)), reinterpret_cast<IMP>(overrideIsInHardwareKeyboardMode));
1229 #endif
1230
1231     [[WebPreferences standardPreferences] setAutosaves:NO];
1232
1233     // +[WebPreferences _switchNetworkLoaderToNewTestingSession] calls +[NSURLCache sharedURLCache], which initializes a default cache on disk.
1234     // Making the shared cache memory-only avoids touching the file system.
1235     RetainPtr<NSURLCache> sharedCache =
1236         adoptNS([[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1237                                       diskCapacity:0
1238                                           diskPath:nil]);
1239     [NSURLCache setSharedURLCache:sharedCache.get()];
1240
1241     [WebPreferences _switchNetworkLoaderToNewTestingSession];
1242
1243 #if !PLATFORM(IOS_FAMILY)
1244     adjustFonts();
1245     registerMockScrollbars();
1246
1247     // The mock scrollbars setting cannot be modified after creating a view, so we have to do it now.
1248     [[WebPreferences standardPreferences] setMockScrollbarsEnabled:YES];
1249 #else
1250     activateFontsIOS();
1251 #endif
1252
1253     allocateGlobalControllers();
1254
1255 #if PLATFORM(MAC)
1256     NSActivityOptions options = (NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical) & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled);
1257     static id assertion = [[[NSProcessInfo processInfo] beginActivityWithOptions:options reason:@"DumpRenderTree should not be subject to process suppression"] retain];
1258     ASSERT_UNUSED(assertion, assertion);
1259 #endif
1260 }
1261
1262 const char crashedMessage[] = "#CRASHED\n";
1263
1264 void writeCrashedMessageOnFatalError(int signalCode)
1265 {
1266     // Reset the default action for the signal so that we run ReportCrash(8) on pending and
1267     // subsequent instances of the signal.
1268     signal(signalCode, SIG_DFL);
1269
1270     // WRITE(2) and FSYNC(2) are considered safe to call from a signal handler by SIGACTION(2).
1271     write(STDERR_FILENO, &crashedMessage[0], sizeof(crashedMessage) - 1);
1272     fsync(STDERR_FILENO);
1273 }
1274
1275 void dumpRenderTree(int argc, const char *argv[])
1276 {
1277 #if PLATFORM(IOS_FAMILY)
1278     setUpIOSLayoutTestCommunication();
1279     [UIApplication sharedApplication].idleTimerDisabled = YES;
1280     [[UIScreen mainScreen] _setScale:2.0];
1281 #endif
1282
1283     signal(SIGILL, &writeCrashedMessageOnFatalError);
1284     signal(SIGFPE, &writeCrashedMessageOnFatalError);
1285     signal(SIGBUS, &writeCrashedMessageOnFatalError);
1286     signal(SIGSEGV, &writeCrashedMessageOnFatalError);
1287
1288     initializeGlobalsFromCommandLineOptions(argc, argv);
1289     prepareConsistentTestingEnvironment();
1290     addTestPluginsToPluginSearchPath(argv[0]);
1291
1292     if (forceComplexText)
1293         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1294
1295 #if USE(APPKIT)
1296     [NSSound _setAlertType:0];
1297 #endif
1298
1299     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1300     [WebCache empty];
1301
1302     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1303     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1304     if (allowAnyHTTPSCertificateForAllowedHosts) {
1305         for (auto& host : allowedHosts)
1306             [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[NSString stringWithUTF8String:host.c_str()]];
1307     }
1308
1309     if (threaded)
1310         startJavaScriptThreads();
1311
1312     if (useLongRunningServerMode(argc, argv)) {
1313         printSeparators = YES;
1314         runTestingServerLoop();
1315     } else {
1316         printSeparators = optind < argc - 1;
1317         for (int i = optind; i != argc; ++i)
1318             runTest(argv[i]);
1319     }
1320
1321     if (threaded)
1322         stopJavaScriptThreads();
1323
1324     destroyWebViewAndOffscreenWindow([mainFrame webView]);
1325
1326     releaseGlobalControllers();
1327
1328 #if !PLATFORM(IOS_FAMILY)
1329     [DumpRenderTreePasteboard releaseLocalPasteboards];
1330 #endif
1331
1332     // FIXME: This should be moved onto TestRunner and made into a HashSet
1333     if (disallowedURLs) {
1334         CFRelease(disallowedURLs);
1335         disallowedURLs = 0;
1336     }
1337
1338 #if PLATFORM(IOS_FAMILY)
1339     tearDownIOSLayoutTestCommunication();
1340 #endif
1341 }
1342
1343 #if PLATFORM(IOS_FAMILY)
1344 static int _argc;
1345 static const char **_argv;
1346
1347 @implementation DumpRenderTree
1348
1349 - (void)_runDumpRenderTree
1350 {
1351     dumpRenderTree(_argc, _argv);
1352 }
1353
1354 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1355 {
1356     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1357 }
1358
1359 - (void)applicationDidEnterBackground:(UIApplication *)application
1360 {
1361     RELEASE_ASSERT_NOT_REACHED();
1362 }
1363
1364 - (void)_webThreadEventLoopHasRun
1365 {
1366     ASSERT(!WebThreadIsCurrent());
1367     _hasFlushedWebThreadRunQueue = YES;
1368 }
1369
1370 - (void)_webThreadInvoked
1371 {
1372     ASSERT(WebThreadIsCurrent());
1373     dispatch_async(dispatch_get_main_queue(), ^{
1374         [self _webThreadEventLoopHasRun];
1375     });
1376 }
1377
1378 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1379 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1380 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1381 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1382 - (void)_waitForWebThread
1383 {
1384     ASSERT(!WebThreadIsCurrent());
1385     _hasFlushedWebThreadRunQueue = NO;
1386     WebThreadRun(^{
1387         [self _webThreadInvoked];
1388     });
1389     while (!_hasFlushedWebThreadRunQueue) {
1390         @autoreleasepool {
1391             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1392         }
1393     }
1394 }
1395
1396 @end
1397 #endif
1398
1399 static bool returningFromMain = false;
1400
1401 void atexitFunction()
1402 {
1403     if (returningFromMain)
1404         return;
1405
1406     NSLog(@"DumpRenderTree is exiting unexpectedly. Generating a crash log.");
1407     __builtin_trap();
1408 }
1409
1410 int DumpRenderTreeMain(int argc, const char *argv[])
1411 {
1412     atexit(atexitFunction);
1413
1414     WTF::setProcessPrivileges(allPrivileges());
1415     WebCore::NetworkStorageSession::permitProcessToUseCookieAPI(true);
1416
1417 #if PLATFORM(IOS_FAMILY)
1418     _UIApplicationLoadWebKit();
1419 #endif
1420
1421     @autoreleasepool {
1422         setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1423
1424 #if !PLATFORM(IOS_FAMILY)
1425         [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1426
1427         dumpRenderTree(argc, argv);
1428 #else
1429         _argc = argc;
1430         _argv = argv;
1431         UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", @"DumpRenderTree");
1432 #endif
1433
1434         [WebCoreStatistics garbageCollectJavaScriptObjects];
1435         [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1436         JSC::finalizeStatsAtEndOfTesting();
1437     }
1438
1439     returningFromMain = true;
1440     return 0;
1441 }
1442
1443 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1444 {
1445     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1446 }
1447
1448 static NSData *dumpAudio()
1449 {
1450     const vector<char>& dataVector = gTestRunner->audioResult();
1451
1452     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1453     return data;
1454 }
1455
1456 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1457 {
1458     int start = 0;
1459     if (current) {
1460         printf("curr->");
1461         start = 6;
1462     }
1463     for (int i = start; i < indent; i++)
1464         putchar(' ');
1465
1466     NSString *urlString = [item URLString];
1467     if ([[NSURL URLWithString:urlString] isFileURL]) {
1468         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1469         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1470     }
1471
1472     printf("%s", [urlString UTF8String]);
1473     NSString *target = [item target];
1474     if (target && [target length] > 0)
1475         printf(" (in frame \"%s\")", [target UTF8String]);
1476     if ([item isTargetItem])
1477         printf("  **nav target**");
1478     putchar('\n');
1479     NSArray *kids = [item children];
1480     if (kids) {
1481         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1482         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1483         for (unsigned i = 0; i < [kids count]; i++)
1484             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1485     }
1486 }
1487
1488 static void dumpFrameScrollPosition(WebFrame *f)
1489 {
1490     WebScriptObject* scriptObject = [f windowObject];
1491     NSPoint scrollPosition = NSMakePoint(
1492         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1493         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1494     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1495         if ([f parentFrame] != nil)
1496             printf("frame '%s' ", [[f name] UTF8String]);
1497         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1498     }
1499
1500     if (gTestRunner->dumpChildFrameScrollPositions()) {
1501         NSArray *kids = [f childFrames];
1502         if (kids)
1503             for (unsigned i = 0; i < [kids count]; i++)
1504                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1505     }
1506 }
1507
1508 static NSString *dumpFramesAsText(WebFrame *frame)
1509 {
1510     DOMDocument *document = [frame DOMDocument];
1511     DOMElement *documentElement = [document documentElement];
1512
1513     if (!documentElement)
1514         return @"";
1515
1516     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1517
1518     // Add header for all but the main frame.
1519     if ([frame parentFrame])
1520         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1521
1522     NSString *innerText = [documentElement innerText];
1523     // We use WKStringGetUTF8CStringNonStrict() to convert innerText to a WK String since
1524     // WKStringGetUTF8CStringNonStrict() can handle dangling surrogates and the NSString
1525     // conversion methods cannot. After the conversion to a buffer, we turn that buffer into
1526     // a CFString via fromUTF8WithLatin1Fallback().createCFString() which can be appended to
1527     // the result without any conversion.
1528     WKRetainPtr<WKStringRef> stringRef(AdoptWK, WKStringCreateWithCFString((__bridge CFStringRef)innerText));
1529     size_t bufferSize = WKStringGetMaximumUTF8CStringSize(stringRef.get());
1530     auto buffer = std::make_unique<char[]>(bufferSize);
1531     size_t stringLength = WKStringGetUTF8CStringNonStrict(stringRef.get(), buffer.get(), bufferSize);
1532     [result appendFormat:@"%@\n", String::fromUTF8WithLatin1Fallback(buffer.get(), stringLength - 1).createCFString().get()];
1533
1534     if (gTestRunner->dumpChildFramesAsText()) {
1535         NSArray *kids = [frame childFrames];
1536         if (kids) {
1537             for (unsigned i = 0; i < [kids count]; i++)
1538                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1539         }
1540     }
1541
1542     return result;
1543 }
1544
1545 static NSData *dumpFrameAsPDF(WebFrame *frame)
1546 {
1547 #if !PLATFORM(IOS_FAMILY)
1548     if (!frame)
1549         return nil;
1550
1551     // Sadly we have to dump to a file and then read from that file again
1552     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1553     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1554     // The goal of this function is to test "real" printing across multiple pages.
1555     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1556     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1557
1558     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1559     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1560     [printInfoDict setObject:path forKey:NSPrintSavePath];
1561
1562     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1563     [printInfo setHorizontalPagination:NSAutoPagination];
1564     [printInfo setVerticalPagination:NSAutoPagination];
1565     [printInfo setVerticallyCentered:NO];
1566
1567     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1568     [printOperation setShowPanels:NO];
1569     [printOperation runOperation];
1570
1571     [printInfo release];
1572
1573     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1574     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1575
1576     return pdfData;
1577 #else
1578     return nil;
1579 #endif
1580 }
1581
1582 static void dumpBackForwardListForWebView(WebView *view)
1583 {
1584     printf("\n============== Back Forward List ==============\n");
1585     WebBackForwardList *bfList = [view backForwardList];
1586
1587     // Print out all items in the list after prevTestBFItem, which was from the previous test
1588     // Gather items from the end of the list, the print them out from oldest to newest
1589     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1590     for (int i = [bfList forwardListCount]; i > 0; i--) {
1591         WebHistoryItem *item = [bfList itemAtIndex:i];
1592         // something is wrong if the item from the last test is in the forward part of the b/f list
1593         assert(item != prevTestBFItem);
1594         [itemsToPrint addObject:item];
1595     }
1596
1597     assert([bfList currentItem] != prevTestBFItem);
1598     [itemsToPrint addObject:[bfList currentItem]];
1599     int currentItemIndex = [itemsToPrint count] - 1;
1600
1601     for (int i = -1; i >= -[bfList backListCount]; i--) {
1602         WebHistoryItem *item = [bfList itemAtIndex:i];
1603         if (item == prevTestBFItem)
1604             break;
1605         [itemsToPrint addObject:item];
1606     }
1607
1608     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1609         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1610
1611     [itemsToPrint release];
1612     printf("===============================================\n");
1613 }
1614
1615 #if !PLATFORM(IOS_FAMILY)
1616 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1617 {
1618     WTF::String localPathOrUrl = String(testPathOrUR);
1619     float currentScaleFactor = [[[mainFrame webView] window] backingScaleFactor];
1620     float requiredScaleFactor = 1;
1621     if (localPathOrUrl.containsIgnoringASCIICase("/hidpi-3x-"))
1622         requiredScaleFactor = 3;
1623     else if (localPathOrUrl.containsIgnoringASCIICase("/hidpi-"))
1624         requiredScaleFactor = 2;
1625     if (currentScaleFactor == requiredScaleFactor)
1626         return;
1627     // 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.
1628     gTestRunner->setBackingScaleFactor(requiredScaleFactor);
1629     NSWindow *window = [[mainFrame webView] window];
1630     if ([window respondsToSelector:@selector(_setWindowResolution:)])
1631         [window _setWindowResolution:requiredScaleFactor];
1632     else
1633         [window _setWindowResolution:requiredScaleFactor displayIfChanged:YES];
1634 }
1635 #endif
1636
1637 static void sizeWebViewForCurrentTest()
1638 {
1639     [uiDelegate resetWindowOrigin];
1640
1641     // W3C SVG tests expect to be 480x360
1642     bool isSVGW3CTest = (gTestRunner->testURL().find("svg/W3C-SVG-1.1") != string::npos);
1643     NSSize frameSize = isSVGW3CTest ? NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight) : NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight);
1644     [[mainFrame webView] setFrameSize:frameSize];
1645     [[mainFrame frameView] setFrame:NSMakeRect(0, 0, frameSize.width, frameSize.height)];
1646 }
1647
1648 static const char *methodNameStringForFailedTest()
1649 {
1650     const char *errorMessage;
1651     if (gTestRunner->dumpAsText())
1652         errorMessage = "[documentElement innerText]";
1653     else if (gTestRunner->dumpDOMAsWebArchive())
1654         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1655     else if (gTestRunner->dumpSourceAsWebArchive())
1656         errorMessage = "[[mainFrame dataSource] webArchive]";
1657     else
1658         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1659
1660     return errorMessage;
1661 }
1662
1663 static void dumpBackForwardListForAllWindows()
1664 {
1665     for (NSWindow *window in [DumpRenderTreeWindow openWindows]) {
1666 #if !PLATFORM(IOS_FAMILY)
1667         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1668 #else
1669         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1670         WebView *webView = (WebView *)[window contentView];
1671 #endif
1672         dumpBackForwardListForWebView(webView);
1673     }
1674 }
1675
1676 static void invalidateAnyPreviousWaitToDumpWatchdog()
1677 {
1678     if (waitToDumpWatchdog) {
1679         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1680         CFRelease(waitToDumpWatchdog);
1681         waitToDumpWatchdog = 0;
1682     }
1683 }
1684
1685 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1686 {
1687     ASSERT(timer);
1688     ASSERT(shouldSetWaitToDumpWatchdog());
1689     waitToDumpWatchdog = timer;
1690     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1691 }
1692
1693 bool shouldSetWaitToDumpWatchdog()
1694 {
1695     return !waitToDumpWatchdog && useTimeoutWatchdog;
1696 }
1697
1698 static void updateDisplay()
1699 {
1700     WebView *webView = [mainFrame webView];
1701 #if PLATFORM(IOS_FAMILY)
1702     [gWebBrowserView layoutIfNeeded]; // Re-enables tile painting, which was disabled when committing the frame load.
1703     [gDrtWindow layoutTilesNow];
1704     [webView _flushCompositingChanges];
1705 #else
1706     if ([webView _isUsingAcceleratedCompositing])
1707         [webView display];
1708     else
1709         [webView displayIfNeeded];
1710 #endif
1711 }
1712
1713 void dump()
1714 {
1715 #if PLATFORM(IOS_FAMILY)
1716     WebThreadLock();
1717 #endif
1718
1719     updateDisplay();
1720
1721     invalidateAnyPreviousWaitToDumpWatchdog();
1722     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1723
1724     if (dumpTree) {
1725         NSString *resultString = nil;
1726         NSData *resultData = nil;
1727         NSString *resultMimeType = @"text/plain";
1728
1729         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1730             gTestRunner->setDumpAsText(true);
1731             gTestRunner->setGeneratePixelResults(false);
1732         }
1733         if (gTestRunner->dumpAsAudio()) {
1734             resultData = dumpAudio();
1735             resultMimeType = @"audio/wav";
1736         } else if (gTestRunner->dumpAsText()) {
1737             resultString = dumpFramesAsText(mainFrame);
1738         } else if (gTestRunner->dumpAsPDF()) {
1739             resultData = dumpFrameAsPDF(mainFrame);
1740             resultMimeType = @"application/pdf";
1741         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1742             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1743             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((__bridge CFDataRef)[webArchive data]));
1744             resultMimeType = @"application/x-webarchive";
1745         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1746             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1747             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((__bridge CFDataRef)[webArchive data]));
1748             resultMimeType = @"application/x-webarchive";
1749         } else
1750             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1751
1752         if (resultString && !resultData)
1753             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1754
1755         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1756
1757         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1758         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1759
1760         if (gTestRunner->dumpAsAudio())
1761             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1762
1763         if (resultData) {
1764             fwrite([resultData bytes], 1, [resultData length], stdout);
1765
1766             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1767                 dumpFrameScrollPosition(mainFrame);
1768
1769             if (gTestRunner->dumpBackForwardList())
1770                 dumpBackForwardListForAllWindows();
1771         } else
1772             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1773
1774         // Stop the watchdog thread before we leave this test to make sure it doesn't
1775         // fire in between tests causing the next test to fail.
1776         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1777         invalidateAnyPreviousWaitToDumpWatchdog();
1778
1779         if (printSeparators)
1780             puts("#EOF");       // terminate the content block
1781     }
1782
1783     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1784         // FIXME: when isPrinting is set, dump the image with page separators.
1785         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1786
1787     puts("#EOF");   // terminate the (possibly empty) pixels block
1788     fflush(stdout);
1789
1790     done = YES;
1791     CFRunLoopStop(CFRunLoopGetMain());
1792 }
1793
1794 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1795 {
1796     return strstr(pathOrURL, "loading/");
1797 }
1798
1799 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1800 {
1801     return strstr(pathOrURL, "globalhistory/");
1802 }
1803
1804 static bool shouldDumpAsText(const char* pathOrURL)
1805 {
1806     return strstr(pathOrURL, "dumpAsText/");
1807 }
1808
1809 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1810 {
1811     return true;
1812 }
1813
1814 #if PLATFORM(IOS_FAMILY)
1815 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1816 {
1817     return strstr(pathOrURL, "viewport/") && !strstr(pathOrURL, "visual-viewport/");
1818 }
1819 #endif
1820
1821 static void setJSCOptions(const TestOptions& options)
1822 {
1823     static WTF::StringBuilder savedOptions;
1824
1825     if (!savedOptions.isEmpty()) {
1826         JSC::Options::setOptions(savedOptions.toString().ascii().data());
1827         savedOptions.clear();
1828     }
1829
1830     if (options.jscOptions.length()) {
1831         JSC::Options::dumpAllOptionsInALine(savedOptions);
1832         JSC::Options::setOptions(options.jscOptions.c_str());
1833     }
1834 }
1835
1836 static void resetWebViewToConsistentStateBeforeTesting(const TestOptions& options)
1837 {
1838     WebView *webView = [mainFrame webView];
1839
1840 #if PLATFORM(IOS_FAMILY)
1841     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1842     [webView _setAllowsMessaging:YES];
1843 #endif
1844     [webView setEditable:NO];
1845     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1846     [webView makeTextStandardSize:nil];
1847     [webView resetPageZoom:nil];
1848     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1849 #if !PLATFORM(IOS_FAMILY)
1850     [webView _setCustomBackingScaleFactor:0];
1851 #endif
1852     [webView setTabKeyCyclesThroughElements:YES];
1853     [webView setPolicyDelegate:defaultPolicyDelegate];
1854     [policyDelegate setPermissive:NO];
1855     [policyDelegate setControllerToNotifyDone:0];
1856     [uiDelegate resetToConsistentStateBeforeTesting:options];
1857     [frameLoadDelegate resetToConsistentState];
1858 #if !PLATFORM(IOS_FAMILY)
1859     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1860 #endif
1861     [webView _clearMainFrameName];
1862     [[webView undoManager] removeAllActions];
1863     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1864 #if !PLATFORM(IOS_FAMILY)
1865     [[webView window] setAutodisplay:NO];
1866 #endif
1867     [webView setTracksRepaints:NO];
1868
1869     [WebCache clearCachedCredentials];
1870
1871     resetWebPreferencesToConsistentValues();
1872     setWebPreferencesForTestOptions(options);
1873 #if PLATFORM(MAC)
1874     [webView setWantsLayer:options.layerBackedWebView];
1875 #endif
1876
1877     TestRunner::setSerializeHTTPLoads(false);
1878     TestRunner::setAllowsAnySSLCertificate(false);
1879
1880     setlocale(LC_ALL, "");
1881
1882     if (gTestRunner) {
1883         gTestRunner->resetPageVisibility();
1884         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1885         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1886         gTestRunner->removeChromeInputField();
1887     }
1888
1889 #if !PLATFORM(IOS_FAMILY)
1890     if (WebCore::Frame* frame = [webView _mainCoreFrame])
1891         WebCoreTestSupport::clearWheelEventTestTrigger(*frame);
1892 #endif
1893
1894 #if !PLATFORM(IOS_FAMILY)
1895     [webView setContinuousSpellCheckingEnabled:YES];
1896     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1897     [webView setAutomaticLinkDetectionEnabled:NO];
1898     [webView setAutomaticDashSubstitutionEnabled:NO];
1899     [webView setAutomaticTextReplacementEnabled:NO];
1900     [webView setAutomaticSpellingCorrectionEnabled:YES];
1901     [webView setGrammarCheckingEnabled:YES];
1902
1903     [WebView _setUsesTestModeFocusRingColor:YES];
1904 #endif
1905     [WebView _resetOriginAccessWhitelists];
1906
1907     [[MockGeolocationProvider shared] stopTimer];
1908     [[MockWebNotificationProvider shared] reset];
1909
1910 #if !PLATFORM(IOS_FAMILY)
1911     // Clear the contents of the general pasteboard
1912     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1913 #endif
1914
1915     setJSCOptions(options);
1916
1917     [mainFrame _clearOpener];
1918
1919 #if PLATFORM(MAC)
1920     [LayoutTestSpellChecker uninstallAndReset];
1921 #endif
1922
1923     resetAccumulatedLogs();
1924     WebCoreTestSupport::initializeLogChannelsIfNecessary();
1925 }
1926
1927 #if PLATFORM(IOS_FAMILY)
1928 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1929 // the main thread is not thread safe. If the web thread is attempting to call
1930 // out to a delegate method on the main thread, we want to spin the main thread
1931 // run loop until the delegate method completes before taking the web thread
1932 // lock to prevent potentially re-entering WebCore.
1933 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1934 {
1935     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1936     WebThreadRun(^{
1937         dispatch_semaphore_signal(delegateSemaphore);
1938     });
1939
1940     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1941         @autoreleasepool {
1942             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1943         }
1944     }
1945
1946     WebThreadLock();
1947
1948     dispatch_release(delegateSemaphore);
1949 }
1950 #endif
1951
1952 static NSURL *computeTestURL(NSString *pathOrURLString, NSString **relativeTestPath)
1953 {
1954     *relativeTestPath = nil;
1955
1956     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1957         return [NSURL URLWithString:pathOrURLString];
1958
1959     NSString *absolutePath = [[[NSURL fileURLWithPath:pathOrURLString] absoluteURL] path];
1960
1961     NSRange layoutTestsRange = [absolutePath rangeOfString:@"/LayoutTests/"];
1962     if (layoutTestsRange.location == NSNotFound)
1963         return [NSURL fileURLWithPath:absolutePath];
1964
1965     *relativeTestPath = [absolutePath substringFromIndex:NSMaxRange(layoutTestsRange)];
1966     return [NSURL fileURLWithPath:absolutePath];
1967 }
1968
1969 static void runTest(const string& inputLine)
1970 {
1971     ASSERT(!inputLine.empty());
1972
1973     TestCommand command = parseInputLine(inputLine);
1974     const string& pathOrURL = command.pathOrURL;
1975     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1976
1977     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1978     if (!pathOrURLString) {
1979         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1980         return;
1981     }
1982
1983     NSString *testPath;
1984     NSURL *url = computeTestURL(pathOrURLString, &testPath);
1985     if (!url) {
1986         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1987         return;
1988     }
1989     if (!testPath)
1990         testPath = [url absoluteString];
1991
1992     NSString *informationString = [@"CRASHING TEST: " stringByAppendingString:testPath];
1993     WebKit::setCrashReportApplicationSpecificInformation((__bridge CFStringRef)informationString);
1994
1995     TestOptions options { [url isFileURL] ? [url fileSystemRepresentation] : pathOrURL, command.absolutePath };
1996
1997     if (!mainFrameTestOptions || !options.webViewIsCompatibleWithOptions(mainFrameTestOptions.value())) {
1998         if (mainFrame)
1999             destroyWebViewAndOffscreenWindow([mainFrame webView]);
2000         WebView *pristineWebView = createWebViewAndOffscreenWindow();
2001         mainFrame = [pristineWebView mainFrame];
2002     }
2003     mainFrameTestOptions = options;
2004
2005     resetWebViewToConsistentStateBeforeTesting(options);
2006
2007     const char* testURL([[url absoluteString] UTF8String]);
2008
2009 #if !PLATFORM(IOS_FAMILY)
2010     changeWindowScaleIfNeeded(testURL);
2011 #endif
2012
2013     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
2014     gTestRunner->setAllowedHosts(allowedHosts);
2015     gTestRunner->setCustomTimeout(command.timeout);
2016     gTestRunner->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr || options.dumpJSConsoleLogInStdErr);
2017     topLoadingFrame = nil;
2018 #if !PLATFORM(IOS_FAMILY)
2019     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
2020     releaseAndZero(&draggingInfo);
2021 #endif
2022     done = NO;
2023
2024     sizeWebViewForCurrentTest();
2025     gTestRunner->setIconDatabaseEnabled(false);
2026     gTestRunner->clearAllApplicationCaches();
2027
2028     gTestRunner->clearAllDatabases();
2029     gTestRunner->setIDBPerOriginQuota(50 * MB);
2030
2031     if (disallowedURLs)
2032         CFSetRemoveAllValues(disallowedURLs);
2033     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
2034         gTestRunner->setDumpFrameLoadCallbacks(true);
2035
2036     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
2037         [[mainFrame webView] setHistoryDelegate:historyDelegate];
2038     else
2039         [[mainFrame webView] setHistoryDelegate:nil];
2040
2041     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2042         gTestRunner->setDeveloperExtrasEnabled(true);
2043         if (shouldDumpAsText(pathOrURL.c_str())) {
2044             gTestRunner->setDumpAsText(true);
2045             gTestRunner->setGeneratePixelResults(false);
2046         }
2047     }
2048
2049 #if PLATFORM(IOS_FAMILY)
2050     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
2051         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
2052 #endif
2053
2054     if ([WebHistory optionalSharedHistory])
2055         [WebHistory setOptionalSharedHistory:nil];
2056
2057     lastMousePosition = NSZeroPoint;
2058     lastClickPosition = NSZeroPoint;
2059
2060     [prevTestBFItem release];
2061     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
2062
2063     auto& workQueue = DRT::WorkQueue::singleton();
2064     workQueue.clear();
2065     workQueue.setFrozen(false);
2066
2067     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
2068     if (ignoreWebCoreNodeLeaks)
2069         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
2070
2071     @autoreleasepool {
2072         [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
2073     }
2074
2075     while (!done) {
2076         @autoreleasepool {
2077             CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
2078         }
2079     }
2080
2081 #if PLATFORM(IOS_FAMILY)
2082     [(DumpRenderTree *)UIApp _waitForWebThread];
2083     WebThreadLockAfterDelegateCallbacksHaveCompleted();
2084 #endif
2085
2086     @autoreleasepool {
2087         [EventSendingController clearSavedEvents];
2088         [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
2089
2090         workQueue.clear();
2091
2092         // If the test page could have possibly opened the Web Inspector frontend,
2093         // then try to close it in case it was accidentally left open.
2094         if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2095             gTestRunner->closeWebInspector();
2096             gTestRunner->setDeveloperExtrasEnabled(false);
2097         }
2098
2099 #if PLATFORM(MAC)
2100         // Make sure the WebView is parented, since the test may have unparented it.
2101         WebView *webView = [mainFrame webView];
2102         if (![webView superview])
2103             [[mainWindow contentView] addSubview:webView];
2104 #endif
2105
2106         if (gTestRunner->closeRemainingWindowsWhenComplete()) {
2107             NSArray* array = [DumpRenderTreeWindow openWindows];
2108
2109             unsigned count = [array count];
2110             for (unsigned i = 0; i < count; i++) {
2111                 NSWindow *window = [array objectAtIndex:i];
2112
2113                 // Don't try to close the main window
2114                 if (window == [[mainFrame webView] window])
2115                     continue;
2116
2117 #if !PLATFORM(IOS_FAMILY)
2118                 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
2119 #else
2120                 ASSERT([[window contentView] isKindOfClass:[WebView class]]);
2121                 WebView *webView = (WebView *)[window contentView];
2122 #endif
2123
2124                 [webView close];
2125                 [window close];
2126             }
2127         }
2128
2129         resetWebViewToConsistentStateBeforeTesting(options);
2130
2131         // Loading an empty request synchronously replaces the document with a blank one, which is necessary
2132         // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
2133         [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
2134     }
2135
2136     // We should only have our main window left open when we're done
2137     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
2138     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == (__bridge CFTypeRef)[[mainFrame webView] window]);
2139
2140     gTestRunner->cleanup();
2141     gTestRunner = nullptr;
2142
2143 #if PLATFORM(MAC)
2144     [DumpRenderTreeDraggingInfo clearAllFilePromiseReceivers];
2145 #endif
2146
2147     if (ignoreWebCoreNodeLeaks)
2148         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
2149
2150     if (gcBetweenTests)
2151         [WebCoreStatistics garbageCollectJavaScriptObjects];
2152     
2153     JSC::waitForVMDestruction();
2154
2155     fputs("#EOF\n", stderr);
2156     fflush(stderr);
2157 }
2158
2159 void displayWebView()
2160 {
2161 #if !PLATFORM(IOS_FAMILY)
2162     WebView *webView = [mainFrame webView];
2163     [webView display];
2164 #else
2165     [gDrtWindow layoutTilesNow];
2166     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
2167     [CATransaction flush];
2168 #endif
2169 }
2170
2171 void displayAndTrackRepaintsWebView()
2172 {
2173     displayWebView();
2174 #if !PLATFORM(IOS_FAMILY)
2175     // FIXME: Tracking repaints is not specific to Mac. We should enable such support on iOS.
2176     WebView *webView = [mainFrame webView];
2177     [webView setTracksRepaints:YES];
2178     [webView resetTrackedRepaints];
2179 #endif
2180 }
2181
2182 #if !PLATFORM(IOS_FAMILY)
2183 @implementation DumpRenderTreeEvent
2184
2185 + (NSPoint)mouseLocation
2186 {
2187     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
2188 }
2189
2190 @end
2191
2192 @implementation DumpRenderTreeApplication
2193
2194 - (BOOL)isRunning
2195 {
2196     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
2197     return YES;
2198 }
2199
2200 @end
2201 #endif