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