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