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