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