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