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