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