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