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