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