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