Add logging to identify when the Page suspends scripted animations
[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/WKRetainPtr.h>
66 #import <WebKit/WKString.h>
67 #import <WebKit/WKStringCF.h>
68 #import <WebKit/WebArchive.h>
69 #import <WebKit/WebBackForwardList.h>
70 #import <WebKit/WebCache.h>
71 #import <WebKit/WebCoreStatistics.h>
72 #import <WebKit/WebDataSourcePrivate.h>
73 #import <WebKit/WebDatabaseManagerPrivate.h>
74 #import <WebKit/WebDeviceOrientationProviderMock.h>
75 #import <WebKit/WebDocumentPrivate.h>
76 #import <WebKit/WebEditingDelegate.h>
77 #import <WebKit/WebFrameView.h>
78 #import <WebKit/WebHistory.h>
79 #import <WebKit/WebHistoryItemPrivate.h>
80 #import <WebKit/WebInspector.h>
81 #import <WebKit/WebKitNSStringExtras.h>
82 #import <WebKit/WebPluginDatabase.h>
83 #import <WebKit/WebPreferenceKeysPrivate.h>
84 #import <WebKit/WebPreferences.h>
85 #import <WebKit/WebPreferencesPrivate.h>
86 #import <WebKit/WebResourceLoadDelegate.h>
87 #import <WebKit/WebStorageManagerPrivate.h>
88 #import <WebKit/WebViewPrivate.h>
89 #import <WebKitSystemInterface.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 <WebCore/CoreGraphicsSPI.h>
111 #import <WebKit/WAKWindow.h>
112 #import <WebKit/WebCoreThread.h>
113 #import <WebKit/WebCoreThreadRun.h>
114 #import <WebKit/WebDOMOperations.h>
115 #import <fcntl.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     [preferences setDisplayContentsEnabled:YES];
844     // FIXME: SpringTimingFunction
845     [preferences setGamepadsEnabled:YES];
846     [preferences setLinkPreloadEnabled:YES];
847     [preferences setMediaPreloadingEnabled:YES];
848     // FIXME: InputEvents
849     [preferences setWebAnimationsEnabled:YES];
850     [preferences setWebGL2Enabled:YES];
851     [preferences setWebGPUEnabled:YES];
852     // FIXME: AsyncFrameScrollingEnabled
853     [preferences setWebRTCLegacyAPIEnabled:YES];
854     [preferences setCredentialManagementEnabled:YES];
855     [preferences setReadableByteStreamAPIEnabled:YES];
856     [preferences setWritableStreamAPIEnabled:YES];
857 }
858
859 // Called before each test.
860 static void resetWebPreferencesToConsistentValues()
861 {
862     WebPreferences *preferences = [WebPreferences standardPreferences];
863     enableExperimentalFeatures(preferences);
864
865     [preferences setNeedsStorageAccessFromFileURLsQuirk: NO];
866     [preferences setAllowUniversalAccessFromFileURLs:YES];
867     [preferences setAllowFileAccessFromFileURLs:YES];
868     [preferences setStandardFontFamily:@"Times"];
869     [preferences setFixedFontFamily:@"Courier"];
870     [preferences setSerifFontFamily:@"Times"];
871     [preferences setSansSerifFontFamily:@"Helvetica"];
872     [preferences setCursiveFontFamily:@"Apple Chancery"];
873     [preferences setFantasyFontFamily:@"Papyrus"];
874     [preferences setPictographFontFamily:@"Apple Color Emoji"];
875     [preferences setDefaultFontSize:16];
876     [preferences setDefaultFixedFontSize:13];
877     [preferences setMinimumFontSize:0];
878     [preferences setDefaultTextEncodingName:@"ISO-8859-1"];
879     [preferences setJavaEnabled:NO];
880     [preferences setJavaScriptEnabled:YES];
881     [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
882 #if !PLATFORM(IOS)
883     [preferences setTabsToLinks:NO];
884 #endif
885     [preferences setDOMPasteAllowed:YES];
886 #if !PLATFORM(IOS)
887     [preferences setShouldPrintBackgrounds:YES];
888 #endif
889     [preferences setCacheModel:WebCacheModelDocumentBrowser];
890     [preferences setXSSAuditorEnabled:NO];
891     [preferences setExperimentalNotificationsEnabled:NO];
892     [preferences setPlugInsEnabled:YES];
893 #if !PLATFORM(IOS)
894     [preferences setTextAreasAreResizable:YES];
895 #endif
896
897     [preferences setPrivateBrowsingEnabled:NO];
898     [preferences setAuthorAndUserStylesEnabled:YES];
899     [preferences setShrinksStandaloneImagesToFit:YES];
900     [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
901     [preferences setJavaScriptCanAccessClipboard:YES];
902     [preferences setOfflineWebApplicationCacheEnabled:YES];
903     [preferences setDeveloperExtrasEnabled:NO];
904     [preferences setJavaScriptRuntimeFlags:WebKitJavaScriptRuntimeFlagsAllEnabled];
905     [preferences setLoadsImagesAutomatically:YES];
906     [preferences setLoadsSiteIconsIgnoringImageLoadingPreference:NO];
907     [preferences setFrameFlattening:WebKitFrameFlatteningDisabled];
908     [preferences setAsyncFrameScrollingEnabled:NO];
909     [preferences setSpatialNavigationEnabled:NO];
910     [preferences setMetaRefreshEnabled:YES];
911
912     if (persistentUserStyleSheetLocation) {
913         [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
914         [preferences setUserStyleSheetEnabled:YES];
915     } else
916         [preferences setUserStyleSheetEnabled:NO];
917
918     [preferences setMediaPlaybackAllowsInline:YES];
919     [preferences setVideoPlaybackRequiresUserGesture:NO];
920     [preferences setAudioPlaybackRequiresUserGesture:NO];
921     [preferences setMediaDataLoadsAutomatically:YES];
922     [preferences setInvisibleAutoplayNotPermitted:NO];
923     [preferences setSubpixelAntialiasedLayerTextEnabled:NO];
924
925 #if PLATFORM(IOS)
926     // Enable the tracker before creating the first WebView will
927     // cause initialization to use the correct database paths.
928     [preferences setStorageTrackerEnabled:YES];
929 #endif
930
931     [preferences _setTextAutosizingEnabled:NO];
932
933     // The back/forward cache is causing problems due to layouts during transition from one page to another.
934     // So, turn it off for now, but we might want to turn it back on some day.
935     [preferences setUsesPageCache:NO];
936     [preferences setAcceleratedCompositingEnabled:YES];
937 #if USE(CA)
938     [preferences setCanvasUsesAcceleratedDrawing:YES];
939     [preferences setAcceleratedDrawingEnabled:useAcceleratedDrawing];
940 #endif
941     [preferences setUsePreHTML5ParserQuirks:NO];
942     [preferences setAsynchronousSpellCheckingEnabled:NO];
943 #if !PLATFORM(IOS)
944     ASSERT([preferences mockScrollbarsEnabled]);
945 #endif
946
947     [preferences setWebAudioEnabled:YES];
948     [preferences setMediaSourceEnabled:YES];
949
950     [preferences setShadowDOMEnabled:YES];
951     [preferences setCustomElementsEnabled:YES];
952
953     [preferences setWebGL2Enabled:YES];
954     [preferences setWebGPUEnabled:YES];
955
956     [preferences setDownloadAttributeEnabled:YES];
957
958     [preferences setHiddenPageDOMTimerThrottlingEnabled:NO];
959     [preferences setHiddenPageCSSAnimationSuspensionEnabled:NO];
960
961     [preferences setMediaDevicesEnabled:YES];
962
963     [preferences setLargeImageAsyncDecodingEnabled:NO];
964
965     [preferences setModernMediaControlsEnabled:YES];
966     [preferences setResourceTimingEnabled:YES];
967     [preferences setUserTimingEnabled:YES];
968
969     [preferences setShouldLogScriptedAnimationControllerSuspensionChange:YES];
970
971     [WebPreferences _clearNetworkLoaderSession];
972     [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
973 }
974
975 static void setWebPreferencesForTestOptions(const TestOptions& options)
976 {
977     WebPreferences *preferences = [WebPreferences standardPreferences];
978
979     preferences.intersectionObserverEnabled = options.enableIntersectionObserver;
980     preferences.modernMediaControlsEnabled = options.enableModernMediaControls;
981     preferences.credentialManagementEnabled = options.enableCredentialManagement;
982     preferences.isSecureContextAttributeEnabled = options.enableIsSecureContextAttribute;
983 }
984
985 // Called once on DumpRenderTree startup.
986 static void setDefaultsToConsistentValuesForTesting()
987 {
988 #if PLATFORM(IOS)
989     WebThreadLock();
990 #endif
991
992     static const int NoFontSmoothing = 0;
993     static const int BlueTintedAppearance = 1;
994
995     NSString *libraryPath = libraryPathForDumpRenderTree();
996
997     NSDictionary *dict = @{
998         @"AppleKeyboardUIMode": @1,
999         @"AppleAntiAliasingThreshold": @4,
1000         @"AppleFontSmoothing": @(NoFontSmoothing),
1001         @"AppleAquaColorVariant": @(BlueTintedAppearance),
1002         @"AppleHighlightColor": @"0.709800 0.835300 1.000000",
1003         @"AppleOtherHighlightColor":@"0.500000 0.500000 0.500000",
1004         @"AppleLanguages": @[ @"en" ],
1005         WebKitEnableFullDocumentTeardownPreferenceKey: @YES,
1006         WebKitFullScreenEnabledPreferenceKey: @YES,
1007         WebKitAllowsInlineMediaPlaybackPreferenceKey: @YES,
1008         WebKitInlineMediaPlaybackRequiresPlaysInlineAttributeKey: @NO,
1009         @"UseWebKitWebInspector": @YES,
1010 #if !PLATFORM(IOS)
1011         @"NSPreferredSpellServerLanguage": @"en_US",
1012         @"NSUserDictionaryReplacementItems": @[],
1013         @"NSTestCorrectionDictionary": @{
1014             @"notationl": @"notational",
1015             @"mesage": @"message",
1016             @"wouldn": @"would",
1017             @"wellcome": @"welcome",
1018             @"hellolfworld": @"hello\nworld"
1019         },
1020 #endif
1021         @"AppleScrollBarVariant": @"DoubleMax",
1022 #if !PLATFORM(IOS)
1023         @"NSScrollAnimationEnabled": @NO,
1024 #endif
1025         @"NSOverlayScrollersEnabled": @NO,
1026         @"AppleShowScrollBars": @"Always",
1027         @"NSButtonAnimationsEnabled": @NO, // Ideally, we should find a way to test animations, but for now, make sure that the dumped snapshot matches actual state.
1028 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1029         @"AppleSystemFontOSSubversion": @(10),
1030 #endif
1031         @"NSWindowDisplayWithRunLoopObserver": @YES, // Temporary workaround, see <rdar://problem/20351297>.
1032         @"AppleEnableSwipeNavigateWithScrolls": @YES,
1033         @"com.apple.swipescrolldirection": @1,
1034     };
1035
1036     [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:dict];
1037
1038 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1039     // Make NSFont use the new defaults.
1040     [NSFont initialize];
1041 #endif
1042
1043     NSDictionary *processInstanceDefaults = @{
1044         WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
1045         WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1046         WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"],
1047         WebKitResourceLoadStatisticsDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1048 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1049         // This needs to also be added to argument domain because of <rdar://problem/20210002>.
1050         @"AppleSystemFontOSSubversion": @(10),
1051 #endif
1052     };
1053
1054     [[NSUserDefaults standardUserDefaults] setVolatileDomain:processInstanceDefaults forName:NSArgumentDomain];
1055 }
1056
1057 static void runThread(void* arg)
1058 {
1059     static ThreadIdentifier previousId = 0;
1060     ThreadIdentifier currentId = currentThread();
1061     // Verify 2 successive threads do not get the same Id.
1062     ASSERT(previousId != currentId);
1063     previousId = currentId;
1064 }
1065
1066 static void* runPthread(void* arg)
1067 {
1068     runThread(arg);
1069     return 0;
1070 }
1071
1072 static void testThreadIdentifierMap()
1073 {
1074     // Imitate 'foreign' threads that are not created by WTF.
1075     pthread_t pthread;
1076     pthread_create(&pthread, 0, &runPthread, 0);
1077     pthread_join(pthread, 0);
1078
1079     pthread_create(&pthread, 0, &runPthread, 0);
1080     pthread_join(pthread, 0);
1081
1082     // Now create another thread using WTF. On OSX, it will have the same pthread handle
1083     // but should get a different RefPtr<Thread>.
1084     Thread::create(runThread, 0, "DumpRenderTree: test");
1085 }
1086
1087 static void allocateGlobalControllers()
1088 {
1089     // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
1090     gNavigationController = [[NavigationController alloc] init];
1091     frameLoadDelegate = [[FrameLoadDelegate alloc] init];
1092     uiDelegate = [[UIDelegate alloc] init];
1093     editingDelegate = [[EditingDelegate alloc] init];
1094     resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
1095     policyDelegate = [[PolicyDelegate alloc] init];
1096     historyDelegate = [[HistoryDelegate alloc] init];
1097     defaultPolicyDelegate = [[DefaultPolicyDelegate alloc] init];
1098 #if PLATFORM(IOS)
1099     scrollViewResizerDelegate = [[ScrollViewResizerDelegate alloc] init];
1100 #endif
1101 }
1102
1103 // ObjC++ doens't seem to let me pass NSObject*& sadly.
1104 static inline void releaseAndZero(NSObject** object)
1105 {
1106     [*object release];
1107     *object = nil;
1108 }
1109
1110 static void releaseGlobalControllers()
1111 {
1112     releaseAndZero(&gNavigationController);
1113     releaseAndZero(&frameLoadDelegate);
1114     releaseAndZero(&editingDelegate);
1115     releaseAndZero(&resourceLoadDelegate);
1116     releaseAndZero(&uiDelegate);
1117     releaseAndZero(&policyDelegate);
1118 #if PLATFORM(IOS)
1119     releaseAndZero(&scrollViewResizerDelegate);
1120 #endif
1121 }
1122
1123 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
1124 {
1125     struct option options[] = {
1126         {"notree", no_argument, &dumpTree, NO},
1127         {"pixel-tests", no_argument, &dumpPixelsForAllTests, YES},
1128         {"tree", no_argument, &dumpTree, YES},
1129         {"threaded", no_argument, &threaded, YES},
1130         {"complex-text", no_argument, &forceComplexText, YES},
1131         {"accelerated-drawing", no_argument, &useAcceleratedDrawing, YES},
1132         {"gc-between-tests", no_argument, &gcBetweenTests, YES},
1133         {"no-timeout", no_argument, &useTimeoutWatchdog, NO},
1134         {"allowed-host", required_argument, nullptr, 'a'},
1135         {"show-webview", no_argument, &showWebView, YES},
1136         {"print-test-count", no_argument, &printTestCount, YES},
1137         {nullptr, 0, nullptr, 0}
1138     };
1139
1140     int option;
1141     while ((option = getopt_long(argc, (char * const *)argv, "", options, nullptr)) != -1) {
1142         switch (option) {
1143             case '?':   // unknown or ambiguous option
1144             case ':':   // missing argument
1145                 exit(1);
1146                 break;
1147             case 'a': // "allowed-host"
1148                 allowedHosts.insert(optarg);
1149                 break;
1150         }
1151     }
1152 }
1153
1154 static void addTestPluginsToPluginSearchPath(const char* executablePath)
1155 {
1156 #if !PLATFORM(IOS)
1157     NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
1158     [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
1159     [[WebPluginDatabase sharedDatabase] refresh];
1160 #endif
1161 }
1162
1163 static bool useLongRunningServerMode(int argc, const char *argv[])
1164 {
1165     // This assumes you've already called getopt_long
1166     return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
1167 }
1168
1169 static void runTestingServerLoop()
1170 {
1171     // When DumpRenderTree run in server mode, we just wait around for file names
1172     // to be passed to us and read each in turn, passing the results back to the client
1173     char filenameBuffer[2048];
1174     unsigned testCount = 0;
1175     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1176         char *newLineCharacter = strchr(filenameBuffer, '\n');
1177         if (newLineCharacter)
1178             *newLineCharacter = '\0';
1179
1180         if (strlen(filenameBuffer) == 0)
1181             continue;
1182
1183         runTest(filenameBuffer);
1184
1185         if (printTestCount) {
1186             ++testCount;
1187             printf("\nServer mode has completed %u tests.\n\n", testCount);
1188         }
1189     }
1190 }
1191
1192 static void prepareConsistentTestingEnvironment()
1193 {
1194 #if !PLATFORM(IOS)
1195     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1196     poseAsClass("DumpRenderTreeEvent", "NSEvent");
1197 #else
1198     poseAsClass("DumpRenderTreeEvent", "GSEvent");
1199 #endif
1200
1201     [[WebPreferences standardPreferences] setAutosaves:NO];
1202
1203     // +[WebPreferences _switchNetworkLoaderToNewTestingSession] calls +[NSURLCache sharedURLCache], which initializes a default cache on disk.
1204     // Making the shared cache memory-only avoids touching the file system.
1205     RetainPtr<NSURLCache> sharedCache =
1206         adoptNS([[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1207                                       diskCapacity:0
1208                                           diskPath:nil]);
1209     [NSURLCache setSharedURLCache:sharedCache.get()];
1210
1211     [WebPreferences _switchNetworkLoaderToNewTestingSession];
1212
1213 #if !PLATFORM(IOS)
1214     adjustFonts();
1215     registerMockScrollbars();
1216
1217     // The mock scrollbars setting cannot be modified after creating a view, so we have to do it now.
1218     [[WebPreferences standardPreferences] setMockScrollbarsEnabled:YES];
1219 #else
1220     activateFontsIOS();
1221 #endif
1222
1223     allocateGlobalControllers();
1224
1225 #if PLATFORM(MAC)
1226     NSActivityOptions options = (NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical) & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled);
1227     static id assertion = [[[NSProcessInfo processInfo] beginActivityWithOptions:options reason:@"DumpRenderTree should not be subject to process suppression"] retain];
1228     ASSERT_UNUSED(assertion, assertion);
1229 #endif
1230 }
1231
1232 const char crashedMessage[] = "#CRASHED\n";
1233
1234 void writeCrashedMessageOnFatalError(int signalCode)
1235 {
1236     // Reset the default action for the signal so that we run ReportCrash(8) on pending and
1237     // subsequent instances of the signal.
1238     signal(signalCode, SIG_DFL);
1239
1240     // WRITE(2) and FSYNC(2) are considered safe to call from a signal handler by SIGACTION(2).
1241     write(STDERR_FILENO, &crashedMessage[0], sizeof(crashedMessage) - 1);
1242     fsync(STDERR_FILENO);
1243 }
1244
1245 void dumpRenderTree(int argc, const char *argv[])
1246 {
1247 #if PLATFORM(IOS)
1248     setUpIOSLayoutTestCommunication();
1249     [UIApplication sharedApplication].idleTimerDisabled = YES;
1250     [[UIScreen mainScreen] _setScale:2.0];
1251 #endif
1252
1253     signal(SIGILL, &writeCrashedMessageOnFatalError);
1254     signal(SIGFPE, &writeCrashedMessageOnFatalError);
1255     signal(SIGBUS, &writeCrashedMessageOnFatalError);
1256     signal(SIGSEGV, &writeCrashedMessageOnFatalError);
1257
1258     initializeGlobalsFromCommandLineOptions(argc, argv);
1259     prepareConsistentTestingEnvironment();
1260     addTestPluginsToPluginSearchPath(argv[0]);
1261
1262     if (forceComplexText)
1263         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1264
1265 #if USE(APPKIT)
1266     [NSSound _setAlertType:0];
1267 #endif
1268
1269     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1270     [WebCache empty];
1271
1272     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1273     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1274
1275     // http://webkit.org/b/32689
1276     testThreadIdentifierMap();
1277
1278     if (threaded)
1279         startJavaScriptThreads();
1280
1281     if (useLongRunningServerMode(argc, argv)) {
1282         printSeparators = YES;
1283         runTestingServerLoop();
1284     } else {
1285         printSeparators = optind < argc - 1;
1286         for (int i = optind; i != argc; ++i)
1287             runTest(argv[i]);
1288     }
1289
1290     if (threaded)
1291         stopJavaScriptThreads();
1292
1293     destroyWebViewAndOffscreenWindow([mainFrame webView]);
1294
1295     releaseGlobalControllers();
1296
1297 #if !PLATFORM(IOS)
1298     [DumpRenderTreePasteboard releaseLocalPasteboards];
1299 #endif
1300
1301     // FIXME: This should be moved onto TestRunner and made into a HashSet
1302     if (disallowedURLs) {
1303         CFRelease(disallowedURLs);
1304         disallowedURLs = 0;
1305     }
1306
1307 #if PLATFORM(IOS)
1308     tearDownIOSLayoutTestCommunication();
1309 #endif
1310 }
1311
1312 #if PLATFORM(IOS)
1313 static int _argc;
1314 static const char **_argv;
1315
1316 @implementation DumpRenderTree
1317
1318 - (void)_runDumpRenderTree
1319 {
1320     dumpRenderTree(_argc, _argv);
1321 }
1322
1323 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1324 {
1325     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1326 }
1327
1328 - (void)applicationDidEnterBackground:(UIApplication *)application
1329 {
1330     RELEASE_ASSERT_NOT_REACHED();
1331 }
1332
1333 - (void)_webThreadEventLoopHasRun
1334 {
1335     ASSERT(!WebThreadIsCurrent());
1336     _hasFlushedWebThreadRunQueue = YES;
1337 }
1338
1339 - (void)_webThreadInvoked
1340 {
1341     ASSERT(WebThreadIsCurrent());
1342     dispatch_async(dispatch_get_main_queue(), ^{
1343         [self _webThreadEventLoopHasRun];
1344     });
1345 }
1346
1347 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1348 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1349 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1350 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1351 - (void)_waitForWebThread
1352 {
1353     ASSERT(!WebThreadIsCurrent());
1354     _hasFlushedWebThreadRunQueue = NO;
1355     WebThreadRun(^{
1356         [self _webThreadInvoked];
1357     });
1358     while (!_hasFlushedWebThreadRunQueue) {
1359         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1360         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1361         [pool release];
1362     }
1363 }
1364
1365 @end
1366 #endif
1367
1368 static bool returningFromMain = false;
1369
1370 void atexitFunction()
1371 {
1372     if (returningFromMain)
1373         return;
1374
1375     NSLog(@"DumpRenderTree is exiting unexpectedly. Generating a crash log.");
1376     __builtin_trap();
1377 }
1378
1379 int DumpRenderTreeMain(int argc, const char *argv[])
1380 {
1381     atexit(atexitFunction);
1382
1383 #if PLATFORM(IOS)
1384     _UIApplicationLoadWebKit();
1385 #endif
1386     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1387
1388     setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1389
1390 #if !PLATFORM(IOS)
1391     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1392
1393     dumpRenderTree(argc, argv);
1394 #else
1395     _argc = argc;
1396     _argv = argv;
1397     UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", @"DumpRenderTree");
1398 #endif
1399     [WebCoreStatistics garbageCollectJavaScriptObjects];
1400     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1401     JSC::finalizeStatsAtEndOfTesting();
1402     [pool release];
1403     returningFromMain = true;
1404     return 0;
1405 }
1406
1407 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1408 {
1409     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1410 }
1411
1412 static NSData *dumpAudio()
1413 {
1414     const vector<char>& dataVector = gTestRunner->audioResult();
1415
1416     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1417     return data;
1418 }
1419
1420 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1421 {
1422     int start = 0;
1423     if (current) {
1424         printf("curr->");
1425         start = 6;
1426     }
1427     for (int i = start; i < indent; i++)
1428         putchar(' ');
1429
1430     NSString *urlString = [item URLString];
1431     if ([[NSURL URLWithString:urlString] isFileURL]) {
1432         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1433         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1434     }
1435
1436     printf("%s", [urlString UTF8String]);
1437     NSString *target = [item target];
1438     if (target && [target length] > 0)
1439         printf(" (in frame \"%s\")", [target UTF8String]);
1440     if ([item isTargetItem])
1441         printf("  **nav target**");
1442     putchar('\n');
1443     NSArray *kids = [item children];
1444     if (kids) {
1445         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1446         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1447         for (unsigned i = 0; i < [kids count]; i++)
1448             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1449     }
1450 }
1451
1452 static void dumpFrameScrollPosition(WebFrame *f)
1453 {
1454     WebScriptObject* scriptObject = [f windowObject];
1455     NSPoint scrollPosition = NSMakePoint(
1456         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1457         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1458     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1459         if ([f parentFrame] != nil)
1460             printf("frame '%s' ", [[f name] UTF8String]);
1461         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1462     }
1463
1464     if (gTestRunner->dumpChildFrameScrollPositions()) {
1465         NSArray *kids = [f childFrames];
1466         if (kids)
1467             for (unsigned i = 0; i < [kids count]; i++)
1468                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1469     }
1470 }
1471
1472 static NSString *dumpFramesAsText(WebFrame *frame)
1473 {
1474     DOMDocument *document = [frame DOMDocument];
1475     DOMElement *documentElement = [document documentElement];
1476
1477     if (!documentElement)
1478         return @"";
1479
1480     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1481
1482     // Add header for all but the main frame.
1483     if ([frame parentFrame])
1484         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1485
1486     NSString *innerText = [documentElement innerText];
1487     // We use WKStringGetUTF8CStringNonStrict() to convert innerText to a WK String since
1488     // WKStringGetUTF8CStringNonStrict() can handle dangling surrogates and the NSString
1489     // conversion methods cannot. After the conversion to a buffer, we turn that buffer into
1490     // a CFString via fromUTF8WithLatin1Fallback().createCFString() which can be appended to
1491     // the result without any conversion.
1492     WKRetainPtr<WKStringRef> stringRef(AdoptWK, WKStringCreateWithCFString((CFStringRef)innerText));
1493     size_t bufferSize = WKStringGetMaximumUTF8CStringSize(stringRef.get());
1494     auto buffer = std::make_unique<char[]>(bufferSize);
1495     size_t stringLength = WKStringGetUTF8CStringNonStrict(stringRef.get(), buffer.get(), bufferSize);
1496     [result appendFormat:@"%@\n", String::fromUTF8WithLatin1Fallback(buffer.get(), stringLength - 1).createCFString().get()];
1497
1498     if (gTestRunner->dumpChildFramesAsText()) {
1499         NSArray *kids = [frame childFrames];
1500         if (kids) {
1501             for (unsigned i = 0; i < [kids count]; i++)
1502                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1503         }
1504     }
1505
1506     return result;
1507 }
1508
1509 static NSData *dumpFrameAsPDF(WebFrame *frame)
1510 {
1511 #if !PLATFORM(IOS)
1512     if (!frame)
1513         return nil;
1514
1515     // Sadly we have to dump to a file and then read from that file again
1516     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1517     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1518     // The goal of this function is to test "real" printing across multiple pages.
1519     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1520     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1521
1522     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1523     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1524     [printInfoDict setObject:path forKey:NSPrintSavePath];
1525
1526     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1527     [printInfo setHorizontalPagination:NSAutoPagination];
1528     [printInfo setVerticalPagination:NSAutoPagination];
1529     [printInfo setVerticallyCentered:NO];
1530
1531     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1532     [printOperation setShowPanels:NO];
1533     [printOperation runOperation];
1534
1535     [printInfo release];
1536
1537     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1538     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1539
1540     return pdfData;
1541 #else
1542     return nil;
1543 #endif
1544 }
1545
1546 static void dumpBackForwardListForWebView(WebView *view)
1547 {
1548     printf("\n============== Back Forward List ==============\n");
1549     WebBackForwardList *bfList = [view backForwardList];
1550
1551     // Print out all items in the list after prevTestBFItem, which was from the previous test
1552     // Gather items from the end of the list, the print them out from oldest to newest
1553     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1554     for (int i = [bfList forwardListCount]; i > 0; i--) {
1555         WebHistoryItem *item = [bfList itemAtIndex:i];
1556         // something is wrong if the item from the last test is in the forward part of the b/f list
1557         assert(item != prevTestBFItem);
1558         [itemsToPrint addObject:item];
1559     }
1560
1561     assert([bfList currentItem] != prevTestBFItem);
1562     [itemsToPrint addObject:[bfList currentItem]];
1563     int currentItemIndex = [itemsToPrint count] - 1;
1564
1565     for (int i = -1; i >= -[bfList backListCount]; i--) {
1566         WebHistoryItem *item = [bfList itemAtIndex:i];
1567         if (item == prevTestBFItem)
1568             break;
1569         [itemsToPrint addObject:item];
1570     }
1571
1572     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1573         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1574
1575     [itemsToPrint release];
1576     printf("===============================================\n");
1577 }
1578
1579 #if !PLATFORM(IOS)
1580 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1581 {
1582     WTF::String localPathOrUrl = String(testPathOrUR);
1583     float currentScaleFactor = [[[mainFrame webView] window] backingScaleFactor];
1584     float requiredScaleFactor = 1;
1585     if (localPathOrUrl.findIgnoringCase("/hidpi-3x-") != notFound)
1586         requiredScaleFactor = 3;
1587     else if (localPathOrUrl.findIgnoringCase("/hidpi-") != notFound)
1588         requiredScaleFactor = 2;
1589     if (currentScaleFactor == requiredScaleFactor)
1590         return;
1591     // 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.
1592     gTestRunner->setBackingScaleFactor(requiredScaleFactor);
1593     [[[mainFrame webView] window] _setWindowResolution:requiredScaleFactor displayIfChanged:YES];
1594 }
1595 #endif
1596
1597 static void sizeWebViewForCurrentTest()
1598 {
1599     [uiDelegate resetWindowOrigin];
1600
1601     // W3C SVG tests expect to be 480x360
1602     bool isSVGW3CTest = (gTestRunner->testURL().find("svg/W3C-SVG-1.1") != string::npos);
1603     if (isSVGW3CTest)
1604         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1605     else
1606         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1607 }
1608
1609 static const char *methodNameStringForFailedTest()
1610 {
1611     const char *errorMessage;
1612     if (gTestRunner->dumpAsText())
1613         errorMessage = "[documentElement innerText]";
1614     else if (gTestRunner->dumpDOMAsWebArchive())
1615         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1616     else if (gTestRunner->dumpSourceAsWebArchive())
1617         errorMessage = "[[mainFrame dataSource] webArchive]";
1618     else
1619         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1620
1621     return errorMessage;
1622 }
1623
1624 static void dumpBackForwardListForAllWindows()
1625 {
1626     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1627     unsigned count = CFArrayGetCount(openWindows);
1628     for (unsigned i = 0; i < count; i++) {
1629         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1630 #if !PLATFORM(IOS)
1631         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1632 #else
1633         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1634         WebView *webView = (WebView *)[window contentView];
1635 #endif
1636         dumpBackForwardListForWebView(webView);
1637     }
1638 }
1639
1640 static void invalidateAnyPreviousWaitToDumpWatchdog()
1641 {
1642     if (waitToDumpWatchdog) {
1643         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1644         CFRelease(waitToDumpWatchdog);
1645         waitToDumpWatchdog = 0;
1646     }
1647 }
1648
1649 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1650 {
1651     ASSERT(timer);
1652     ASSERT(shouldSetWaitToDumpWatchdog());
1653     waitToDumpWatchdog = timer;
1654     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1655 }
1656
1657 bool shouldSetWaitToDumpWatchdog()
1658 {
1659     return !waitToDumpWatchdog && useTimeoutWatchdog;
1660 }
1661
1662 static void updateDisplay()
1663 {
1664     WebView *webView = [mainFrame webView];
1665 #if PLATFORM(IOS)
1666     [gWebBrowserView layoutIfNeeded]; // Re-enables tile painting, which was disabled when committing the frame load.
1667     [gDrtWindow layoutTilesNow];
1668     [webView _flushCompositingChanges];
1669 #else
1670     if ([webView _isUsingAcceleratedCompositing])
1671         [webView display];
1672     else
1673         [webView displayIfNeeded];
1674 #endif
1675 }
1676
1677 void dump()
1678 {
1679 #if PLATFORM(IOS)
1680     WebThreadLock();
1681 #endif
1682
1683     updateDisplay();
1684
1685     invalidateAnyPreviousWaitToDumpWatchdog();
1686     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1687
1688     if (dumpTree) {
1689         NSString *resultString = nil;
1690         NSData *resultData = nil;
1691         NSString *resultMimeType = @"text/plain";
1692
1693         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1694             gTestRunner->setDumpAsText(true);
1695             gTestRunner->setGeneratePixelResults(false);
1696         }
1697         if (gTestRunner->dumpAsAudio()) {
1698             resultData = dumpAudio();
1699             resultMimeType = @"audio/wav";
1700         } else if (gTestRunner->dumpAsText()) {
1701             resultString = dumpFramesAsText(mainFrame);
1702         } else if (gTestRunner->dumpAsPDF()) {
1703             resultData = dumpFrameAsPDF(mainFrame);
1704             resultMimeType = @"application/pdf";
1705         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1706             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1707             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1708             resultMimeType = @"application/x-webarchive";
1709         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1710             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1711             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1712             resultMimeType = @"application/x-webarchive";
1713         } else
1714             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1715
1716         if (resultString && !resultData)
1717             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1718
1719         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1720
1721         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1722         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1723
1724         if (gTestRunner->dumpAsAudio())
1725             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1726
1727         if (resultData) {
1728             fwrite([resultData bytes], 1, [resultData length], stdout);
1729
1730             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1731                 dumpFrameScrollPosition(mainFrame);
1732
1733             if (gTestRunner->dumpBackForwardList())
1734                 dumpBackForwardListForAllWindows();
1735         } else
1736             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1737
1738         // Stop the watchdog thread before we leave this test to make sure it doesn't
1739         // fire in between tests causing the next test to fail.
1740         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1741         invalidateAnyPreviousWaitToDumpWatchdog();
1742
1743         if (printSeparators)
1744             puts("#EOF");       // terminate the content block
1745     }
1746
1747     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1748         // FIXME: when isPrinting is set, dump the image with page separators.
1749         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1750
1751     puts("#EOF");   // terminate the (possibly empty) pixels block
1752     fflush(stdout);
1753
1754     done = YES;
1755     CFRunLoopStop(CFRunLoopGetMain());
1756 }
1757
1758 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1759 {
1760     return strstr(pathOrURL, "loading/");
1761 }
1762
1763 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1764 {
1765     return strstr(pathOrURL, "globalhistory/");
1766 }
1767
1768 static bool shouldDumpAsText(const char* pathOrURL)
1769 {
1770     return strstr(pathOrURL, "dumpAsText/");
1771 }
1772
1773 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1774 {
1775     return true;
1776 }
1777
1778 #if PLATFORM(IOS)
1779 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1780 {
1781     return strstr(pathOrURL, "viewport/") && !strstr(pathOrURL, "visual-viewport/");
1782 }
1783 #endif
1784
1785 static void resetWebViewToConsistentStateBeforeTesting(const TestOptions& options)
1786 {
1787     WebView *webView = [mainFrame webView];
1788
1789 #if PLATFORM(IOS)
1790     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1791     [webView _setAllowsMessaging:YES];
1792 #endif
1793     [webView setEditable:NO];
1794     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1795     [webView makeTextStandardSize:nil];
1796     [webView resetPageZoom:nil];
1797     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1798 #if !PLATFORM(IOS)
1799     [webView _setCustomBackingScaleFactor:0];
1800 #endif
1801     [webView setTabKeyCyclesThroughElements:YES];
1802     [webView setPolicyDelegate:defaultPolicyDelegate];
1803     [policyDelegate setPermissive:NO];
1804     [policyDelegate setControllerToNotifyDone:0];
1805     [uiDelegate resetToConsistentStateBeforeTesting:options];
1806     [frameLoadDelegate resetToConsistentState];
1807 #if !PLATFORM(IOS)
1808     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1809 #endif
1810     [webView _clearMainFrameName];
1811     [[webView undoManager] removeAllActions];
1812     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1813 #if !PLATFORM(IOS)
1814     [[webView window] setAutodisplay:NO];
1815 #endif
1816     [webView setTracksRepaints:NO];
1817
1818     [WebCache clearCachedCredentials];
1819
1820     resetWebPreferencesToConsistentValues();
1821     setWebPreferencesForTestOptions(options);
1822 #if PLATFORM(MAC)
1823     [webView setWantsLayer:options.layerBackedWebView];
1824 #endif
1825
1826     TestRunner::setSerializeHTTPLoads(false);
1827     TestRunner::setAllowsAnySSLCertificate(false);
1828
1829     setlocale(LC_ALL, "");
1830
1831     if (gTestRunner) {
1832         gTestRunner->resetPageVisibility();
1833         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1834         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1835         gTestRunner->removeChromeInputField();
1836     }
1837
1838 #if !PLATFORM(IOS)
1839     if (WebCore::Frame* frame = [webView _mainCoreFrame])
1840         WebCoreTestSupport::clearWheelEventTestTrigger(*frame);
1841 #endif
1842
1843 #if !PLATFORM(IOS)
1844     [webView setContinuousSpellCheckingEnabled:YES];
1845     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1846     [webView setAutomaticLinkDetectionEnabled:NO];
1847     [webView setAutomaticDashSubstitutionEnabled:NO];
1848     [webView setAutomaticTextReplacementEnabled:NO];
1849     [webView setAutomaticSpellingCorrectionEnabled:YES];
1850     [webView setGrammarCheckingEnabled:YES];
1851
1852     [WebView _setUsesTestModeFocusRingColor:YES];
1853 #endif
1854     [WebView _resetOriginAccessWhitelists];
1855
1856     [[MockGeolocationProvider shared] stopTimer];
1857     [[MockWebNotificationProvider shared] reset];
1858
1859 #if !PLATFORM(IOS)
1860     // Clear the contents of the general pasteboard
1861     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1862 #endif
1863
1864     [mainFrame _clearOpener];
1865
1866     setSpellCheckerLoggingEnabled(false);
1867
1868     resetAccumulatedLogs();
1869     WebCoreTestSupport::initializeLogChannelsIfNecessary();
1870 }
1871
1872 #if PLATFORM(IOS)
1873 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1874 // the main thread is not thread safe. If the web thread is attempting to call
1875 // out to a delegate method on the main thread, we want to spin the main thread
1876 // run loop until the delegate method completes before taking the web thread
1877 // lock to prevent potentially re-entering WebCore.
1878 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1879 {
1880     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1881     WebThreadRun(^{
1882         dispatch_semaphore_signal(delegateSemaphore);
1883     });
1884
1885     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1886         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1887         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1888         [pool release];
1889     }
1890
1891     WebThreadLock();
1892
1893     dispatch_release(delegateSemaphore);
1894 }
1895 #endif
1896
1897 static NSURL *computeTestURL(NSString *pathOrURLString, NSString **relativeTestPath)
1898 {
1899     *relativeTestPath = nil;
1900
1901     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1902         return [NSURL URLWithString:pathOrURLString];
1903
1904     NSString *absolutePath = [[[NSURL fileURLWithPath:pathOrURLString] absoluteURL] path];
1905
1906     NSRange layoutTestsRange = [absolutePath rangeOfString:@"/LayoutTests/"];
1907     if (layoutTestsRange.location == NSNotFound)
1908         return [NSURL fileURLWithPath:absolutePath];
1909
1910     *relativeTestPath = [absolutePath substringFromIndex:NSMaxRange(layoutTestsRange)];
1911
1912     // Convert file URLs in LayoutTests/http/tests to HTTP URLs, except for file URLs in LayoutTests/http/tests/local.
1913
1914     NSRange httpTestsRange = [absolutePath rangeOfString:@"/LayoutTests/http/tests/"];
1915     if (httpTestsRange.location == NSNotFound || [absolutePath rangeOfString:@"/LayoutTests/http/tests/local/"].location != NSNotFound)
1916         return [NSURL fileURLWithPath:absolutePath];
1917
1918     auto components = adoptNS([[NSURLComponents alloc] init]);
1919     [components setPath:[absolutePath substringFromIndex:NSMaxRange(httpTestsRange) - 1]];
1920     [components setHost:@"127.0.0.1"];
1921
1922     // Paths under /ssl/ should be loaded using HTTPS.
1923     BOOL isSecure = [[components path] hasPrefix:@"/ssl/"];
1924     if (isSecure) {
1925         [components setScheme:@"https"];
1926         [components setPort:@(8443)];
1927     } else {
1928         [components setScheme:@"http"];
1929         [components setPort:@(8000)];
1930     }
1931
1932     return [components URL];
1933 }
1934
1935 static void runTest(const string& inputLine)
1936 {
1937     ASSERT(!inputLine.empty());
1938
1939     TestCommand command = parseInputLine(inputLine);
1940     const string& pathOrURL = command.pathOrURL;
1941     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1942
1943     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1944     if (!pathOrURLString) {
1945         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1946         return;
1947     }
1948
1949     NSString *testPath;
1950     NSURL *url = computeTestURL(pathOrURLString, &testPath);
1951     if (!url) {
1952         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1953         return;
1954     }
1955     if (!testPath)
1956         testPath = [url absoluteString];
1957
1958     NSString *informationString = [@"CRASHING TEST: " stringByAppendingString:testPath];
1959     WKSetCrashReportApplicationSpecificInformation((CFStringRef)informationString);
1960
1961     TestOptions options(url, command);
1962     if (!mainFrameTestOptions || !options.webViewIsCompatibleWithOptions(mainFrameTestOptions.value())) {
1963         if (mainFrame)
1964             destroyWebViewAndOffscreenWindow([mainFrame webView]);
1965         WebView *pristineWebView = createWebViewAndOffscreenWindow();
1966         mainFrame = [pristineWebView mainFrame];
1967     }
1968     mainFrameTestOptions = options;
1969
1970     resetWebViewToConsistentStateBeforeTesting(options);
1971
1972     const char* testURL([[url absoluteString] UTF8String]);
1973
1974 #if !PLATFORM(IOS)
1975     changeWindowScaleIfNeeded(testURL);
1976 #endif
1977
1978     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
1979     gTestRunner->setAllowedHosts(allowedHosts);
1980     gTestRunner->setCustomTimeout(command.timeout);
1981     gTestRunner->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr);
1982     topLoadingFrame = nil;
1983 #if !PLATFORM(IOS)
1984     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1985     releaseAndZero(&draggingInfo);
1986 #endif
1987     done = NO;
1988
1989     sizeWebViewForCurrentTest();
1990     gTestRunner->setIconDatabaseEnabled(false);
1991     gTestRunner->clearAllApplicationCaches();
1992
1993     if (disallowedURLs)
1994         CFSetRemoveAllValues(disallowedURLs);
1995     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1996         gTestRunner->setDumpFrameLoadCallbacks(true);
1997
1998     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1999         [[mainFrame webView] setHistoryDelegate:historyDelegate];
2000     else
2001         [[mainFrame webView] setHistoryDelegate:nil];
2002
2003     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2004         gTestRunner->setDeveloperExtrasEnabled(true);
2005         if (shouldDumpAsText(pathOrURL.c_str())) {
2006             gTestRunner->setDumpAsText(true);
2007             gTestRunner->setGeneratePixelResults(false);
2008         }
2009     }
2010
2011 #if PLATFORM(IOS)
2012     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
2013         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
2014 #endif
2015
2016     if ([WebHistory optionalSharedHistory])
2017         [WebHistory setOptionalSharedHistory:nil];
2018
2019     lastMousePosition = NSZeroPoint;
2020     lastClickPosition = NSZeroPoint;
2021
2022     [prevTestBFItem release];
2023     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
2024
2025     auto& workQueue = WorkQueue::singleton();
2026     workQueue.clear();
2027     workQueue.setFrozen(false);
2028
2029     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
2030     if (ignoreWebCoreNodeLeaks)
2031         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
2032
2033     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2034     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
2035     [pool release];
2036
2037     while (!done) {
2038         pool = [[NSAutoreleasePool alloc] init];
2039         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
2040         [pool release];
2041     }
2042
2043 #if PLATFORM(IOS)
2044     [(DumpRenderTree *)UIApp _waitForWebThread];
2045     WebThreadLockAfterDelegateCallbacksHaveCompleted();
2046 #endif
2047     pool = [[NSAutoreleasePool alloc] init];
2048     [EventSendingController clearSavedEvents];
2049     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
2050
2051     workQueue.clear();
2052
2053     // If the test page could have possibly opened the Web Inspector frontend,
2054     // then try to close it in case it was accidentally left open.
2055     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2056         gTestRunner->closeWebInspector();
2057         gTestRunner->setDeveloperExtrasEnabled(false);
2058     }
2059
2060 #if PLATFORM(MAC)
2061     // Make sure the WebView is parented, since the test may have unparented it.
2062     WebView *webView = [mainFrame webView];
2063     if (![webView superview])
2064         [[mainWindow contentView] addSubview:webView];
2065 #endif
2066
2067     if (gTestRunner->closeRemainingWindowsWhenComplete()) {
2068         NSArray* array = [DumpRenderTreeWindow openWindows];
2069
2070         unsigned count = [array count];
2071         for (unsigned i = 0; i < count; i++) {
2072             NSWindow *window = [array objectAtIndex:i];
2073
2074             // Don't try to close the main window
2075             if (window == [[mainFrame webView] window])
2076                 continue;
2077
2078 #if !PLATFORM(IOS)
2079             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
2080 #else
2081             ASSERT([[window contentView] isKindOfClass:[WebView class]]);
2082             WebView *webView = (WebView *)[window contentView];
2083 #endif
2084
2085             [webView close];
2086             [window close];
2087         }
2088     }
2089
2090     resetWebViewToConsistentStateBeforeTesting(options);
2091
2092     // Loading an empty request synchronously replaces the document with a blank one, which is necessary
2093     // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
2094     [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
2095
2096     [pool release];
2097
2098     // We should only have our main window left open when we're done
2099     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
2100     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
2101
2102     gTestRunner->cleanup();
2103     gTestRunner = nullptr;
2104
2105     if (ignoreWebCoreNodeLeaks)
2106         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
2107
2108     if (gcBetweenTests)
2109         [WebCoreStatistics garbageCollectJavaScriptObjects];
2110
2111     fputs("#EOF\n", stderr);
2112     fflush(stderr);
2113 }
2114
2115 void displayWebView()
2116 {
2117 #if !PLATFORM(IOS)
2118     WebView *webView = [mainFrame webView];
2119     [webView display];
2120 #else
2121     [gDrtWindow layoutTilesNow];
2122     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
2123     [CATransaction flush];
2124 #endif
2125 }
2126
2127 void displayAndTrackRepaintsWebView()
2128 {
2129     displayWebView();
2130 #if !PLATFORM(IOS)
2131     // FIXME: Tracking repaints is not specific to Mac. We should enable such support on iOS.
2132     WebView *webView = [mainFrame webView];
2133     [webView setTracksRepaints:YES];
2134     [webView resetTrackedRepaints];
2135 #endif
2136 }
2137
2138 #if !PLATFORM(IOS)
2139 @implementation DumpRenderTreeEvent
2140
2141 + (NSPoint)mouseLocation
2142 {
2143     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
2144 }
2145
2146 @end
2147
2148 @implementation DumpRenderTreeApplication
2149
2150 - (BOOL)isRunning
2151 {
2152     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
2153     return YES;
2154 }
2155
2156 @end
2157 #endif