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