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